diff --git a/.github/workflows/affinity-corpus.yml b/.github/workflows/affinity-corpus.yml index b3e0178f56..c6c130a5ba 100644 --- a/.github/workflows/affinity-corpus.yml +++ b/.github/workflows/affinity-corpus.yml @@ -17,25 +17,25 @@ concurrency: jobs: affinity3: - runs-on: ubuntu-latest - timeout-minutes: 30 - env: - AFFINITY_CORPUS_REQUIRED: "1" - CARGO_PROFILE_DEV_DEBUG: "0" - CARGO_PROFILE_TEST_DEBUG: "0" - steps: - - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 - with: - egress-policy: audit - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - name: Install Rust - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 - with: - toolchain: "1.95" - - name: Fetch pinned and checksum-verified corpus - run: cargo xtask corpus --affinity - - name: Parse every file and freeze actual Affinity 3 feature retention - run: cargo test -p vectorcraft-affinity --all-features -- --nocapture - - name: Check every artboard, native save, SVG, PDF and PSD exports - run: cargo test -p vectorcraft-engine --test affinity_artboards --test affinity_text --test affinity_corpus -- --nocapture + # Tracks @main so suite-wide CI fixes reach every app without a PR in each repository. + uses: storytold/craft-common-actions/.github/workflows/gate.yml@main + with: + timeout-minutes: 30 + toolchain: "1.95" + # As before: no craft-fonts, apt packages, wasm target or nextest. + craft-fonts-ref: "" + targets: "" + tools: "" + dev-debug: "0" + env: | + AFFINITY_CORPUS_REQUIRED=1 + CARGO_PROFILE_TEST_DEBUG=0 + # Its own cache, apart from ci.yml's gate. + cache-version: v1-affinity + command: | + # Pinned and checksum-verified corpus. + cargo xtask corpus --affinity + # Parse every file and freeze actual Affinity 3 feature retention. + cargo test -p vectorcraft-affinity --all-features -- --nocapture + # Every artboard, native save, SVG, PDF and PSD export. + cargo test -p vectorcraft-engine --test affinity_artboards --test affinity_text --test affinity_corpus -- --nocapture diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index fd836de6c7..32043bf033 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -30,51 +30,9 @@ jobs: contents: read pull-requests: read uses: storytold/craft-common-actions/.github/workflows/refresh-contributors.yml@main - git-sources: - name: Git dependencies come from storytold - runs-on: ubuntu-latest - permissions: - contents: read - steps: - - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 - with: - egress-policy: audit - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - name: Git dependencies come from storytold - run: | - set -euo pipefail - test -f Cargo.lock || { echo "Cargo.lock is missing"; exit 1; } - # Source replacement, patches and path overrides in cargo config never show up - # in Cargo.lock. Parsed rather than grepped: TOML has many spellings of one key. - # Cargo still reads the legacy .cargo/config. - python3 - <<'PY' - import os, sys, tomllib - for path in (".cargo/config", ".cargo/config.toml"): - if not os.path.exists(path): - continue - config = tomllib.load(open(path, "rb")) - replaced = [name for name, source in config.get("source", {}).items() - if isinstance(source, dict) and "replace-with" in source] - if replaced or "patch" in config or "paths" in config: - print(f"{path} replaces, patches or overrides a source") - sys.exit(1) - PY - # Fails when Cargo.lock is out of date with the manifests. - cargo metadata --locked --format-version 1 > /dev/null - python3 - <<'PY' - import sys, tomllib - lock = tomllib.load(open("Cargo.lock", "rb")) - bad = sorted({p["source"] for p in lock.get("package", []) - if p.get("source", "").startswith("git+") - and not p["source"].startswith("git+https://github.com/storytold/")}) - if bad: - print("Git dependencies outside github.com/storytold:", *bad, sep="\n") - sys.exit(1) - PY release: - needs: [git-sources, credits] + needs: credits permissions: contents: write packages: write diff --git a/ASSETS.md b/ASSETS.md index 27bbcfc5e7..dbdd8b84d8 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -20,7 +20,7 @@ Every non-code asset in this repository (icons, images, fonts, example art, colo **Policy (mandatory):** VectorCraft contains **no Adobe iconography, images, artwork, presets, swatch/brush/symbol/pattern libraries or ICC profiles**. Every asset is either original work by VectorCraft contributors, or third-party material under an open licence (OSI open source, public domain / CC0, or Creative Commons that allows redistribution), and it is attributed below. Screenshots of Adobe software are never committed. The one exception is the ArtCraft name, wordmark and logos in `docs/brand/`: ArtCraft trademarks, not open source, usable only under [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt). -Generated-in-code art is original and has no file to list. This covers the default swatches, brushes, symbols, patterns, graphic styles, image-trace presets and the vector tool cursors (`crates/ui-egui/src/cursors.rs`). +Generated-in-code art is original and has no file to list. This covers the default swatches, brushes, symbols, patterns, graphic styles, image-trace presets, the vector tool cursors (`crates/ui-egui/src/cursors.rs`) and the Learn panel's practice samples (`crates/ui-egui/src/panels/learn/samples.rs`). **Font files are never committed here.** Fonts shared by the Crafting Apps live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts). The small Latin UI/document fonts below predate that rule and stay. @@ -160,6 +160,7 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-fx.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-gamut.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-grad-conic.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-grad-diamond.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-grad-freeform.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-grad-linear.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-grad-radial.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | @@ -266,6 +267,7 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/flip-vertical-2.svg` | Lucide Icons and Contributors | https://lucide.dev (lucide-static v1.49.0; header kept in file) | ISC (`assets/icons/LICENSE-lucide.txt`) | | | `assets/icons/folder-open.svg` | Lucide Icons and Contributors | https://lucide.dev (lucide-static v1.49.0; header kept in file) | ISC (`assets/icons/LICENSE-lucide.txt`) | | | `assets/icons/frame.svg` | Lucide Icons and Contributors | https://lucide.dev (lucide-static v1.49.0; header kept in file) | ISC (`assets/icons/LICENSE-lucide.txt`) | | +| `assets/icons/graduation-cap.svg` | Lucide Icons and Contributors | https://lucide.dev (lucide-static v1.49.0; header kept in file) | ISC (`assets/icons/LICENSE-lucide.txt`) | Learn panel, Explore tutorials button | | `assets/icons/grid-3x3.svg` | Lucide Icons and Contributors | https://lucide.dev (lucide-static v1.49.0; header kept in file) | ISC (`assets/icons/LICENSE-lucide.txt`) | | | `assets/icons/group.svg` | Lucide Icons and Contributors | https://lucide.dev (lucide-static v1.49.0; header kept in file) | ISC (`assets/icons/LICENSE-lucide.txt`) | | | `assets/icons/hand.svg` | Lucide Icons and Contributors | https://lucide.dev (lucide-static v1.49.0; header kept in file) | ISC (`assets/icons/LICENSE-lucide.txt`) | | diff --git a/Cargo.lock b/Cargo.lock index d018aa027f..dc08d4542e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -217,7 +217,7 @@ dependencies = [ "objc2-foundation 0.3.2", "parking_lot", "percent-encoding", - "windows-sys 0.61.2", + "windows-sys 0.52.0", "wl-clipboard-rs", "x11rb", ] @@ -967,6 +967,17 @@ dependencies = [ "libc", ] +[[package]] +name = "craft-affinity" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=228f6d0c50f1fdee4c5124603602993fc79d4c9d#228f6d0c50f1fdee4c5124603602993fc79d4c9d" +dependencies = [ + "crc32fast", + "flate2", + "image", + "ruzstd", +] + [[package]] name = "craft-docpath" version = "0.1.0" @@ -975,12 +986,12 @@ source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7 [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bb8320f5fa5d20fa78a026d0de06fe4e2f08a099#bb8320f5fa5d20fa78a026d0de06fe4e2f08a099" +source = "git+https://github.com/storytold/craft-libs?rev=c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6#c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6" [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bb8320f5fa5d20fa78a026d0de06fe4e2f08a099#bb8320f5fa5d20fa78a026d0de06fe4e2f08a099" +source = "git+https://github.com/storytold/craft-libs?rev=c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6#c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6" dependencies = [ "fixed_decimal", "icu_decimal", @@ -1049,7 +1060,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bb8320f5fa5d20fa78a026d0de06fe4e2f08a099#bb8320f5fa5d20fa78a026d0de06fe4e2f08a099" +source = "git+https://github.com/storytold/craft-libs?rev=c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6#c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -1070,7 +1081,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280" dependencies = [ "chrono", "dunce", @@ -1097,7 +1108,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280" dependencies = [ "flate2", "serde", @@ -1609,7 +1620,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -3858,7 +3869,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -4380,7 +4391,7 @@ dependencies = [ "once_cell", "socket2", "tracing", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -4758,7 +4769,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.12.1", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -4817,7 +4828,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -4879,9 +4890,6 @@ name = "ruzstd" version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "69e4ce4a039f42bf25920b95667e4d789e98749ab11bbb8d2c2936f788421bb5" -dependencies = [ - "twox-hash", -] [[package]] name = "ryu" @@ -5679,7 +5687,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix 1.1.6", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -6066,12 +6074,6 @@ dependencies = [ "core_maths", ] -[[package]] -name = "twox-hash" -version = "2.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86a801b3cea342a06d468c8710662aa29e5e05e4f5c0d62f00bbb7f2ad7941c2" - [[package]] name = "type-map" version = "0.5.1" @@ -6313,7 +6315,7 @@ dependencies = [ [[package]] name = "vectorcraft" -version = "0.24.0" +version = "0.24.1" dependencies = [ "arboard", "block2 0.6.2", @@ -6324,6 +6326,7 @@ dependencies = [ "craft-window", "eframe", "egui", + "futures-lite", "image", "log", "muda", @@ -6338,7 +6341,6 @@ dependencies = [ "raw-window-handle", "rfd", "serde_json", - "smithay-clipboard", "socket2", "tempfile", "vectorcraft-engine", @@ -6353,31 +6355,31 @@ dependencies = [ "winit", "winresource", "winsafe", + "wl-clipboard-rs", "x11rb", "zbus", ] [[package]] name = "vectorcraft-affinity" -version = "0.24.0" +version = "0.24.1" dependencies = [ + "craft-affinity", "crc32fast", - "flate2", "image", "proptest", - "ruzstd", ] [[package]] name = "vectorcraft-apischema" -version = "0.24.0" +version = "0.24.1" dependencies = [ "serde_json", ] [[package]] name = "vectorcraft-brush" -version = "0.24.0" +version = "0.24.1" dependencies = [ "kurbo 0.13.1", "serde", @@ -6389,7 +6391,7 @@ dependencies = [ [[package]] name = "vectorcraft-cad" -version = "0.24.0" +version = "0.24.1" dependencies = [ "image", "kurbo 0.13.1", @@ -6405,7 +6407,7 @@ dependencies = [ [[package]] name = "vectorcraft-cli" -version = "0.24.0" +version = "0.24.1" dependencies = [ "log", "objc2-core-foundation", @@ -6428,7 +6430,7 @@ dependencies = [ [[package]] name = "vectorcraft-color" -version = "0.24.0" +version = "0.24.1" dependencies = [ "kurbo 0.13.1", "moxcms", @@ -6440,7 +6442,7 @@ dependencies = [ [[package]] name = "vectorcraft-doc" -version = "0.24.0" +version = "0.24.1" dependencies = [ "chrono", "hayro-ccitt", @@ -6459,7 +6461,7 @@ dependencies = [ [[package]] name = "vectorcraft-effects" -version = "0.24.0" +version = "0.24.1" dependencies = [ "image", "kurbo 0.13.1", @@ -6473,11 +6475,13 @@ dependencies = [ "vectorcraft-plugins", "vectorcraft-text", "vectorcraft-three-d", + "vectorcraft-trace", + "wat", ] [[package]] name = "vectorcraft-engine" -version = "0.24.0" +version = "0.24.1" dependencies = [ "cfb", "chrono", @@ -6498,6 +6502,7 @@ dependencies = [ "roxmltree 0.21.2", "rustix 1.1.6", "ruzstd", + "same-file", "serde", "serde_json", "skrifa 0.47.0", @@ -6530,7 +6535,7 @@ dependencies = [ [[package]] name = "vectorcraft-eps" -version = "0.24.0" +version = "0.24.1" dependencies = [ "craft-pdf", "encoding_rs", @@ -6558,7 +6563,7 @@ dependencies = [ [[package]] name = "vectorcraft-format" -version = "0.24.0" +version = "0.24.1" dependencies = [ "craft-vectorcraft-format", "flate2", @@ -6574,7 +6579,7 @@ dependencies = [ [[package]] name = "vectorcraft-geom" -version = "0.24.0" +version = "0.24.1" dependencies = [ "kurbo 0.13.1", "proptest", @@ -6586,17 +6591,17 @@ dependencies = [ [[package]] name = "vectorcraft-js" -version = "0.24.0" +version = "0.24.1" dependencies = [ "chrono", "getrandom 0.4.3", "proptest", - "unicode-general-category", + "unicode-properties", ] [[package]] name = "vectorcraft-mcp" -version = "0.24.0" +version = "0.24.1" dependencies = [ "image", "log", @@ -6615,7 +6620,7 @@ dependencies = [ [[package]] name = "vectorcraft-metafile" -version = "0.24.0" +version = "0.24.1" dependencies = [ "image", "kurbo 0.13.1", @@ -6629,7 +6634,7 @@ dependencies = [ [[package]] name = "vectorcraft-pathops" -version = "0.24.0" +version = "0.24.1" dependencies = [ "kurbo 0.13.1", "linesweeper", @@ -6641,7 +6646,7 @@ dependencies = [ [[package]] name = "vectorcraft-pdf" -version = "0.24.0" +version = "0.24.1" dependencies = [ "aes", "chrono", @@ -6660,6 +6665,7 @@ dependencies = [ "serde", "serde_json", "sha2", + "siphasher", "skrifa 0.47.0", "smallvec", "thiserror 2.0.21", @@ -6675,7 +6681,7 @@ dependencies = [ [[package]] name = "vectorcraft-plugins" -version = "0.24.0" +version = "0.24.1" dependencies = [ "craft-vectorcraft-format", "image", @@ -6694,7 +6700,7 @@ dependencies = [ [[package]] name = "vectorcraft-render" -version = "0.24.0" +version = "0.24.1" dependencies = [ "flate2", "gif 0.14.2", @@ -6724,15 +6730,15 @@ dependencies = [ [[package]] name = "vectorcraft-scriptcheck" -version = "0.24.0" +version = "0.24.1" dependencies = [ "proptest", - "unicode-general-category", + "unicode-properties", ] [[package]] name = "vectorcraft-svg" -version = "0.24.0" +version = "0.24.1" dependencies = [ "craft-docpath", "flate2", @@ -6759,7 +6765,7 @@ dependencies = [ [[package]] name = "vectorcraft-testkit" -version = "0.24.0" +version = "0.24.1" dependencies = [ "fax", "image", @@ -6777,7 +6783,7 @@ dependencies = [ [[package]] name = "vectorcraft-text" -version = "0.24.0" +version = "0.24.1" dependencies = [ "harfrust 0.13.3", "icu_segmenter", @@ -6798,7 +6804,7 @@ dependencies = [ [[package]] name = "vectorcraft-three-d" -version = "0.24.0" +version = "0.24.1" dependencies = [ "vectorcraft-geom", "vectorcraft-pathops", @@ -6806,7 +6812,7 @@ dependencies = [ [[package]] name = "vectorcraft-tools" -version = "0.24.0" +version = "0.24.1" dependencies = [ "image", "kurbo 0.13.1", @@ -6823,7 +6829,7 @@ dependencies = [ [[package]] name = "vectorcraft-trace" -version = "0.24.0" +version = "0.24.1" dependencies = [ "image", "kurbo 0.13.1", @@ -6835,7 +6841,7 @@ dependencies = [ [[package]] name = "vectorcraft-ui-egui" -version = "0.24.0" +version = "0.24.1" dependencies = [ "bytemuck", "craft-keymap", @@ -6850,6 +6856,7 @@ dependencies = [ "serde", "serde_json", "toml", + "vectorcraft-apischema", "vectorcraft-brush", "vectorcraft-cad", "vectorcraft-color", @@ -6873,7 +6880,7 @@ dependencies = [ [[package]] name = "vectorcraft-web" -version = "0.24.0" +version = "0.24.1" dependencies = [ "craft-web-api", "eframe", @@ -7513,7 +7520,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -8005,7 +8012,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee" [[package]] name = "xtask" -version = "0.24.0" +version = "0.24.1" dependencies = [ "serde_json", ] diff --git a/Cargo.toml b/Cargo.toml index 606c34f8b7..5bed166e17 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"] default-members = ["crates/*", "apps/vectorcraft", "apps/vectorcraft-cli", "xtask"] [workspace.package] -version = "0.24.0" +version = "0.24.1" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" @@ -14,16 +14,18 @@ repository = "https://github.com/storytold/vectorcraft" craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", default-features = false, features = ["interpret", "write"] } craft-print = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" } craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" } -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "bb8320f5fa5d20fa78a026d0de06fe4e2f08a099", features = ["serde"] } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6", features = ["serde"] } craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" } craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" } # Decides who draws the window frame (desktop vs. app) so the suite shares one native titlebar per # desktop. The `egui` feature adds `craft_window::decorate`. (craft-libs#217.) craft-window = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", features = ["egui"] } # The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON. -craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280" } # craft-update: app-specific pretend versions apply to startup and manual checks. -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } +# Native Affinity documents (craft-libs#914). +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "228f6d0c50f1fdee4c5124603602993fc79d4c9d" } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", features = ["egui"] } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } diff --git a/README.md b/README.md index dc7a1cfa5f..7e49943a31 100644 --- a/README.md +++ b/README.md @@ -237,7 +237,7 @@ and what's next; [`docs/target-app-parity.md`](docs/target-app-parity.md) the fu (92.5% of menu items do something), feature depth is ~75%, and we estimate ~65% ready for real work for a mainstream illustrator (~62% across all tracked features): everyday vector illustration is close to usable: drawing and path tools, Pathfinder and Shape Builder, paint, gradients, appearance and transparency, type with styles, threading and Hebrew/Arabic bidirectional layout, and -files (SVG, PDF and PDF-compatible `.ai` with PDF/X, legacy version 7 `.ai` keeping layers, groups and type, EPS, DXF, EMF/WMF, raster formats, PSD out and PSD/PSB in as their merged image, JPEG XL in, Print, Package). +files (SVG, PDF and PDF-compatible `.ai` with PDF/X, legacy version 7 `.ai` keeping layers, groups and type, EPS, DXF, EMF/WMF, raster formats, PSD out, PSD/PSB opened with their layers and placed as their merged image, JPEG XL in, Print, Package). Affinity documents (`.af` from Affinity 3, `.afdesign`, `.afpub` and, by their content, `.afphoto` from Affinity 1 and 2) open and place natively: layers, groups, artboards and pages, curves and shapes, fills, gradients and strokes, clipping and masks, text with each paragraph's indents, spacing and leading, tables (as text frames and lines), master diff --git a/ROADMAP.md b/ROADMAP.md index 327036c371..fe325ff849 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -122,10 +122,13 @@ 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-12: Stencil Bridges in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): strips of a set width are cut out of the selected art so that every island of a stencil cut from it (the inside of an O, a hole in a shape) stays attached to the sheet, by the shortest crossings first, vertical, horizontal or the shortest among 12 directions 15° apart, with up to 16 bridges per island; type is measured by its glyph outlines and stays type, and the original goes to a hidden layer or is replaced. One undo step (`addon.cutting.bridges`). A VectorCraft addition: 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. - 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`). +- 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. +- 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. - 2026-11-01: Find Nearest Swatch joins the Color Effects add-on (Object › Plug-ins › Color Effects): for each colour of the selection, the closest swatches of the document, a built-in library or a library or colour book the user loaded, with their CIEDE2000 difference; Apply gives each colour its nearest swatch as one undo step, linking global and spot swatches and adding a library's to the document first, so a process colour becomes the closest spot colour (`addon.color.nearestSwatch`, `addon.color.applyNearestSwatch`, #4923). - 2026-11-01: Expand Dashes into Paths joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): each selected path's dashed stroke becomes separate open paths, one per dash, laid out exactly as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off, so the gaps are real gaps for cutters and plotters, as one undo step (`addon.pathtools.expandDashes`, #4922). - 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925). @@ -137,6 +140,9 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-01: Group Overlapping Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap or touch, chains included, go into one group each, within their own layer or group, at the stacking place of their frontmost member; objects that overlap nothing stay as they are. One undo step, a sweep along x so thousands of loose pieces group quickly (at most 20000 objects). A VectorCraft addition: headline numbers unchanged. - 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged. - 2026-10-31: Arrange Tools, a built-in add-on (Object › Plug-ins › Arrange Tools): Arrange in Grid lays the selected objects out in rows and columns, a row or a column with gaps, from the selection's top-left or centred on the artboard; Swap Objects swaps two objects' places (and, with Swap Objects and Sizes, their sizes); Replace with Top Object puts a copy of the topmost selected object in place of each of the others, kept, stretched or fitted in proportion; Set Size of Each gives every selected object an exact width and/or height about a reference point; Zoom to Selection fits the view to the selection. Each is one undo step with a previewed dialog where it has options. A VectorCraft addition: headline numbers unchanged. +- 2026-11-11: Window › Swatch Libraries › Gradients › Organic Fades: fifteen soft fades (ten linear, five radial) through three to five unevenly spaced stops with off-center midpoints, mixed with the Perceptual method, that thin out to transparent at the end of a linear one and at the edge of a radial one; they also list in the Swatches panel's library menu, `swatch.library.list` and the Gradient panel's Presets. +- 2026-11-13: Gradient panel › Method: Hue Clockwise and Hue Counterclockwise mix a linear, radial, conic or diamond gradient's colors around the hue wheel in one direction, so red to blue passes through magenta one way and through yellow and green the other (`paint.editGradient` `method`: `hue-clockwise`, `hue-counterclockwise`); SVG and PDF exports write such a gradient as an image. +- 2026-11-11: Window › Swatch Libraries › Gradients › Holographic: seven foils (opaque linear gradients of six narrow pastel and pearl bands with off-center midpoints) and seven glows (radial gradients from a bright center out to a clear edge), mixed with the Perceptual method; they also list in the Swatches panel's library menu, `swatch.library.list` and the Gradient panel's Presets. - 2026-10-30: Gradient panel presets: a Presets menu applies one of the built-in gradient libraries' presets (grouped by theme) or a saved one to the gradient behind the active proxy, keeping its placement, as one undo step; the panel menu saves the current gradient as a preset, kept with the preferences, and deletes saved ones (`gradient.presets.list/apply/save/delete`). - 2026-10-23: Pathfinder › Trap: the Pathfinder panel's Trap… and Effect › Pathfinder › Trap… add a thin overprinting strip of the lighter colour inside the darker one where two solid colours meet, so misregistered plates leave no gap ([trapping](https://helpx.adobe.com/illustrator/using/trapping.html)), with Thickness, Height/Width, Tint Reduction, Traps with Process Color and Reverse Traps. Illustrator effects 49/50 (SVG Filters remains); Live vector effects hours 6–10 → 4–8; headline numbers unchanged. - 2026-10-23: OpenType SVG colour fonts draw as vector art: each glyph's SVG document is read by the SVG importer, in the text's colours where it asks for them, and draws, exports and outlines as COLR glyphs do; all colour font formats are now drawn. diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index 57ab103590..b66c15070f 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -238,14 +238,17 @@ fn main() -> ExitCode { /// A headless session that remembers what the user keeps between runs: the PDF presets saved, the /// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541), the custom dictionary's words (#4936) and the Color Settings (#6335), in the folders /// and files next to the preferences that the desktop app uses too, and lists the scripts of the Scripts folder there -/// (`script.listInstalled`). `VECTORCRAFT_NO_PREFS` and `VECTORCRAFT_CONFIG_DIR` apply as they do there. +/// (`script.listInstalled`) and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and +/// `VECTORCRAFT_CONFIG_DIR` apply as they do there. fn with_stores(mut h: Headless) -> Headless { prefs_dir::attach_scripts_dir(&mut h.session); + prefs_dir::attach_new_doc_profiles(&mut h.session); prefs_dir::attach_profile_store(&mut h.session); prefs_dir::attach_color_settings(&mut h.session); prefs_dir::attach_plugin_store(&mut h.session); prefs_dir::attach_pdf_preset_store(&mut h.session); prefs_dir::attach_custom_dictionary(&mut h.session); + prefs_dir::attach_arrowheads(&mut h.session); h } @@ -415,10 +418,18 @@ fn convert(args: &[String]) -> Result<(), String> { // Save as Template writes every artboard, with the .ai options. ("file.saveAsTemplate", json!({"path": output, "format": "ait", "outlineText": outline_text, "acknowledgeLoss": replace_lossy})) } else { - // A conversion keeps hidden layers and objects, written hidden, where the format can (SVG, - // PSD). - let params = json!({"path": output, "artboard": artboard, "range": range, "outlineText": outline_text, "hiddenLayers": true, "acknowledgeLoss": replace_lossy}); + let params = json!({"path": output, "artboard": artboard, "range": range, "acknowledgeLoss": replace_lossy}); let mut params = with_pixel_scale(params, &output, scale, ppi); + // An option the format doesn't read comes back in the warnings, so each goes out only + // when it was asked for: `outlineText` with --outline-text, and `hiddenLayers` to the + // formats that have it (SVG, PSD), where a conversion keeps hidden layers and objects, + // written hidden. + if outline_text { + params["outlineText"] = json!(true); + } + if vectorcraft_engine::cmd::fileio::writable_format(None, Some(&output)).is_ok_and(|f| f.options.iter().any(|o| o.name == "hiddenLayers")) { + params["hiddenLayers"] = json!(true); + } if let Some(decimals) = decimals { params["decimals"] = json!(decimals); } diff --git a/apps/vectorcraft-cli/tests/it/cli.rs b/apps/vectorcraft-cli/tests/it/cli.rs index 5bdd2bf631..0b1c560901 100644 --- a/apps/vectorcraft-cli/tests/it/cli.rs +++ b/apps/vectorcraft-cli/tests/it/cli.rs @@ -3,8 +3,6 @@ use std::process::{Command, Stdio}; use serde_json::{Value, json}; -const BIN: &str = env!("CARGO_BIN_EXE_vectorcraft-cli"); - /// Returns the path of `name` in `vectorcraft-cli-test-` in the temp folder. The first call removes /// that folder and creates it again empty. fn tmp(name: &str) -> std::path::PathBuf { @@ -27,7 +25,12 @@ fn approval_param_needs_the_start_up_flag(key: &str, value: Value) { std::fs::write(&steps, json!([{"command": "plugin.install", "params": {"dataBase64": module, key: value}}]).to_string()).unwrap(); let config = empty_dir(std::env::temp_dir().join(format!("vectorcraft-cli-test-{key}-{}", std::process::id()))); let run = |extra: &[&str]| { - Command::new(BIN).env("VECTORCRAFT_CONFIG_DIR", &config).args(["run", "--commands", steps.to_str().unwrap()]).args(extra).output().unwrap() + Command::new(crate::bin()) + .env("VECTORCRAFT_CONFIG_DIR", &config) + .args(["run", "--commands", steps.to_str().unwrap()]) + .args(extra) + .output() + .unwrap() }; let out = run(&[]); assert!(!out.status.success()); @@ -38,7 +41,7 @@ fn approval_param_needs_the_start_up_flag(key: &str, value: Value) { let mcp_config = empty_dir(std::env::temp_dir().join(format!("vectorcraft-cli-test-mcp-{key}-{}", std::process::id()))); let mcp_install = |extra: &[&str]| -> Value { - let mut child = Command::new(BIN) + let mut child = Command::new(crate::bin()) .env("VECTORCRAFT_CONFIG_DIR", &mcp_config) .args(["mcp", "--headless"]) .args(extra) @@ -77,22 +80,23 @@ fn plugin_grants_need_the_start_up_flag() { approval_param_needs_the_start_up_flag("grant", json!(["doc.read"])); approval_param_needs_the_start_up_flag("allowHeavy", json!(true)); - let out = Command::new(BIN).args(["mcp", "--allow-plugin-grants", "--connect", "127.0.0.1:1"]).output().unwrap(); + let out = Command::new(crate::bin()).args(["mcp", "--allow-plugin-grants", "--connect", "127.0.0.1:1"]).output().unwrap(); assert!(!out.status.success()); assert!(String::from_utf8_lossy(&out.stderr).contains("--allow-plugin-grants applies to the headless server")); let root = std::env::temp_dir(); for flag in ["--automation-read-root", "--automation-write-root"] { - let out = Command::new(BIN).args(["mcp", "--allow-plugin-grants", flag, root.to_str().unwrap()]).stdin(Stdio::null()).output().unwrap(); + let out = + Command::new(crate::bin()).args(["mcp", "--allow-plugin-grants", flag, root.to_str().unwrap()]).stdin(Stdio::null()).output().unwrap(); assert!(!out.status.success(), "{flag}"); assert!(String::from_utf8_lossy(&out.stderr).contains("--allow-plugin-grants can't be used with"), "{flag}"); } - let usage = Command::new(BIN).arg("help").output().unwrap(); + let usage = Command::new(crate::bin()).arg("help").output().unwrap(); assert!(String::from_utf8_lossy(&usage.stdout).contains("--allow-plugin-grants lets plugin.install's grant and allowHeavy take effect")); } #[test] fn commands_prints_catalogue() { - let out = Command::new(BIN).arg("commands").output().unwrap(); + let out = Command::new(crate::bin()).arg("commands").output().unwrap(); assert!(out.status.success()); let v: Value = serde_json::from_slice(&out.stdout).unwrap(); let ids: Vec<&str> = v.as_array().unwrap().iter().filter_map(|c| c["id"].as_str()).collect(); @@ -104,7 +108,7 @@ fn run_batch_exports() { let svg = tmp("batch.svg"); let png = tmp("batch.png"); let dc = tmp("batch.vectorcraft"); - let out = Command::new(BIN) + let out = Command::new(crate::bin()) .args(["run", "--cmd", "file.new", "--params", r#"{"width":200,"height":100}"#]) .args(["--cmd", "shape.ellipse", "--params", r#"{"x":10,"y":10,"width":80,"height":60}"#]) .args(["--cmd", "paint.setFill", "--params", r##"{"color":"#3366ff"}"##]) @@ -121,7 +125,7 @@ fn run_batch_exports() { assert_eq!(u32::from_be_bytes(png_bytes[16..20].try_into().unwrap()), 400); // Re-open the native file and inspect. - let out = Command::new(BIN).args(["run", "--in", dc.to_str().unwrap(), "--cmd", "document.inspect"]).output().unwrap(); + let out = Command::new(crate::bin()).args(["run", "--in", dc.to_str().unwrap(), "--cmd", "document.inspect"]).output().unwrap(); assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); let last: Value = serde_json::from_str(String::from_utf8(out.stdout).unwrap().lines().last().unwrap()).unwrap(); assert_eq!(last["result"]["artboards"][0]["width"], 200.0); @@ -137,7 +141,7 @@ fn scale_sizes_raster_exports_only() { let svg = svg.to_str().unwrap(); let (plain, scaled, png) = (tmp("plain.dxf"), tmp("scaled.dxf"), tmp("scaled.png")); let ok = |args: &[&str]| { - let out = Command::new(BIN).args(args).output().unwrap(); + let out = Command::new(crate::bin()).args(args).output().unwrap(); assert!(out.status.success(), "{args:?}: {}", String::from_utf8_lossy(&out.stderr)); }; ok(&["convert", svg, plain.to_str().unwrap()]); @@ -151,11 +155,11 @@ fn scale_sizes_raster_exports_only() { #[test] fn run_reports_errors() { - let out = Command::new(BIN).args(["run", "--cmd", "nope.nothing"]).output().unwrap(); + let out = Command::new(crate::bin()).args(["run", "--cmd", "nope.nothing"]).output().unwrap(); assert!(!out.status.success()); let stderr = String::from_utf8_lossy(&out.stderr).to_string(); assert!(stderr.contains("step 0 (nope.nothing)"), "{stderr}"); - let out = Command::new(BIN).args(["run", "--params", "{}"]).output().unwrap(); + let out = Command::new(crate::bin()).args(["run", "--params", "{}"]).output().unwrap(); assert!(!out.status.success()); } @@ -184,7 +188,7 @@ fn run_reads_steps_from_a_commands_file() { {"id": "object.setProps", "params": {"id": "$2.ids.0", "name": "barcode"}}, ]); std::fs::write(&steps, serde_json::to_string_pretty(&file).unwrap()).unwrap(); - let out = Command::new(BIN) + let out = Command::new(crate::bin()) .args(["run", "--cmd", "file.new", "--params", r#"{"width":200,"height":100}"#, "--commands", steps.to_str().unwrap()]) .args(["--cmd", "document.node", "--params", r#"{"id":"$2.ids.0"}"#, "--export", svg.to_str().unwrap()]) .output() @@ -204,7 +208,7 @@ fn run_reads_steps_from_a_commands_file() { #[test] fn run_reads_json_lines_from_standard_input() { let svg = tmp("stdin.svg"); - let mut child = Command::new(BIN) + let mut child = Command::new(crate::bin()) .args(["run", "--commands", "-", "--export", svg.to_str().unwrap()]) .stdin(Stdio::piped()) .stdout(Stdio::piped()) @@ -227,7 +231,7 @@ fn run_reads_json_lines_from_standard_input() { #[test] fn run_refuses_malformed_commands_naming_the_step() { let fails = |args: &[&str]| { - let out = Command::new(BIN).args(args).stdin(Stdio::null()).output().unwrap(); + let out = Command::new(crate::bin()).args(args).stdin(Stdio::null()).output().unwrap(); assert!(!out.status.success(), "{args:?}"); (String::from_utf8_lossy(&out.stderr).to_string(), json_lines(&out.stdout).len()) }; @@ -275,11 +279,11 @@ fn run_refuses_malformed_commands_naming_the_step() { /// `--help` and `-h` right after a subcommand print the usage that `vectorcraft-cli help` prints. #[test] fn help_after_a_subcommand_prints_the_usage() { - let usage = Command::new(BIN).arg("help").output().unwrap(); + let usage = Command::new(crate::bin()).arg("help").output().unwrap(); assert!(usage.status.success() && String::from_utf8_lossy(&usage.stdout).contains("USAGE:")); for sub in ["mcp", "run", "commands", "convert", "info", "bench", "perf"] { for flag in ["--help", "-h"] { - let out = Command::new(BIN).args([sub, flag]).stdin(Stdio::null()).output().unwrap(); + let out = Command::new(crate::bin()).args([sub, flag]).stdin(Stdio::null()).output().unwrap(); assert!(out.status.success(), "{sub} {flag}: {}", String::from_utf8_lossy(&out.stderr)); assert!(out.stdout == usage.stdout, "{sub} {flag}: {}", String::from_utf8_lossy(&out.stdout)); } @@ -290,7 +294,7 @@ fn help_after_a_subcommand_prints_the_usage() { /// with them. #[test] fn help_later_in_the_line_prints_the_usage() { - let usage = Command::new(BIN).arg("help").output().unwrap(); + let usage = Command::new(crate::bin()).arg("help").output().unwrap(); let mut wrong = vec![]; for args in [ &["mcp", "--headless", "--help"][..], @@ -311,7 +315,7 @@ fn help_later_in_the_line_prints_the_usage() { &["perf", "--paths", "many", "-h"], &["convert", "--decimals", "many", "--help"], ] { - let out = Command::new(BIN).args(args).stdin(Stdio::null()).output().unwrap(); + let out = Command::new(crate::bin()).args(args).stdin(Stdio::null()).output().unwrap(); if !out.status.success() || out.stdout != usage.stdout { wrong.push(format!("{args:?}: {}{}", String::from_utf8_lossy(&out.stderr), String::from_utf8_lossy(&out.stdout))); } @@ -322,17 +326,18 @@ fn help_later_in_the_line_prints_the_usage() { /// Further along the line, `-h` is the value of the option before it. #[test] fn help_as_an_option_value_goes_to_the_option() { - let out = Command::new(BIN).args(["run", "--cmd", "-h"]).output().unwrap(); + let out = Command::new(crate::bin()).args(["run", "--cmd", "-h"]).output().unwrap(); let err = String::from_utf8_lossy(&out.stderr); assert!(!out.status.success() && err.contains("vectorcraft-cli: step 0 (-h):") && out.stdout.is_empty(), "{err}"); - let out = Command::new(BIN).args(["convert", "in.svg", "--range", "-h"]).output().unwrap(); + let out = Command::new(crate::bin()).args(["convert", "in.svg", "--range", "-h"]).output().unwrap(); let err = String::from_utf8_lossy(&out.stderr); assert!(!out.status.success() && err.contains("convert needs IN and OUT") && out.stdout.is_empty(), "{err}"); } #[test] fn mcp_headless_over_stdio() { - let mut child = Command::new(BIN).args(["mcp", "--headless"]).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn().unwrap(); + let mut child = + Command::new(crate::bin()).args(["mcp", "--headless"]).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn().unwrap(); { let mut stdin = child.stdin.take().unwrap(); for m in [ @@ -359,13 +364,13 @@ fn mcp_headless_over_stdio() { /// 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 out = Command::new(crate::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 out = Command::new(crate::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}"); } @@ -402,7 +407,7 @@ fn mcp_automation_roots_take_several_folders() { } let dir = |d: &str| base.join(d).to_string_lossy().into_owned(); let file = |d: &str, f: &str| base.join(d).join(f).to_string_lossy().into_owned(); - let mut child = Command::new(BIN) + let mut child = Command::new(crate::bin()) .args(["mcp", "--automation-read-root", &dir("in"), &format!("--automation-read-root={}", dir("in2"))]) .args(["--automation-write-root", &dir("out"), "--automation-write-root", &dir("out2")]) .stdin(Stdio::piped()) @@ -457,7 +462,7 @@ fn automation_roots(base: &std::path::Path) { } let dir = |d: &str| base.join(d).to_string_lossy().into_owned(); let fails = |args: &[&str], why: &str| { - let out = Command::new(BIN).args(args).stdin(Stdio::null()).output().unwrap(); + let out = Command::new(crate::bin()).args(args).stdin(Stdio::null()).output().unwrap(); let err = String::from_utf8_lossy(&out.stderr); assert!(!out.status.success() && err.contains(why), "{args:?}: {err}"); }; @@ -469,7 +474,7 @@ fn automation_roots(base: &std::path::Path) { "a running app enforces its own roots: start it with `vectorcraft --control ", ); - let mut child = Command::new(BIN) + let mut child = Command::new(crate::bin()) .args(["mcp", "--automation-read-root", &dir("in"), &format!("--automation-write-root={}", dir("out"))]) .stdin(Stdio::piped()) .stdout(Stdio::piped()) @@ -530,7 +535,7 @@ fn automation_roots(base: &std::path::Path) { fn mcp_protocol_over_stdio() { use std::io::{BufRead, BufReader}; let mut child = - Command::new(BIN).args(["mcp", "--headless"]).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap(); + Command::new(crate::bin()).args(["mcp", "--headless"]).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap(); let mut stdin = child.stdin.take().unwrap(); let mut lines = BufReader::new(child.stdout.take().unwrap()).lines(); let mut notes = vec![]; @@ -711,7 +716,7 @@ fn run_command(id: u64, command: &str, params: Value) -> Value { #[test] fn closed_stdout_ends_quietly() { use std::io::Read; - let mut child = Command::new(BIN).arg("commands").stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap(); + let mut child = Command::new(crate::bin()).arg("commands").stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap(); let mut first = [0u8; 16]; child.stdout.as_mut().unwrap().read_exact(&mut first).unwrap(); drop(child.stdout.take()); @@ -728,13 +733,13 @@ fn run_with_a_closed_stdout_ends_quietly_and_finishes_the_batch() { let _ = std::fs::remove_file(&svg); let rect = r#"{"x":1,"y":1,"width":5,"height":5}"#; let args = ["run", "--cmd", "document.json", "--cmd", "shape.rectangle", "--params", rect, "--export", svg.to_str().unwrap()]; - let mut child = Command::new(BIN).args(args).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap(); + let mut child = Command::new(crate::bin()).args(args).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap(); drop(child.stdout.take()); let out = child.wait_with_output().unwrap(); let err = String::from_utf8_lossy(&out.stderr); assert!(out.status.success() && err.is_empty(), "{:?}: {err}", out.status); assert!(svg.is_file(), "the export after the closed reader still ran"); - let out = Command::new(BIN).args(["run", "--cmd", "not-a-command"]).stdout(Stdio::null()).output().unwrap(); + let out = Command::new(crate::bin()).args(["run", "--cmd", "not-a-command"]).stdout(Stdio::null()).output().unwrap(); assert!(!out.status.success()); } @@ -749,7 +754,7 @@ fn config_dir(name: &str) -> std::path::PathBuf { /// One `vectorcraft-cli run` with `steps` ((command, params)) against the settings folder `config`; /// the result of each step. fn run_in(config: &std::path::Path, steps: &[(&str, Value)]) -> Vec { - let mut cmd = Command::new(BIN); + let mut cmd = Command::new(crate::bin()); cmd.arg("run").env("VECTORCRAFT_CONFIG_DIR", config).env_remove("VECTORCRAFT_NO_PREFS"); for (id, params) in steps { cmd.args(["--cmd", id, "--params", ¶ms.to_string()]); @@ -820,7 +825,7 @@ fn saved_pdf_presets_and_loaded_profiles_survive_a_restart() { #[test] fn runs_without_preferences_remember_nothing() { let config = config_dir("noprefs"); - let out = Command::new(BIN) + let out = Command::new(crate::bin()) .args(["run", "--cmd", "pdf.preset.save", "--params", r#"{"name":"Press"}"#]) .env("VECTORCRAFT_CONFIG_DIR", &config) .env("VECTORCRAFT_NO_PREFS", "1") diff --git a/apps/vectorcraft-cli/tests/it/fileio.rs b/apps/vectorcraft-cli/tests/it/fileio.rs index c60357b5f8..cdb16d28d3 100644 --- a/apps/vectorcraft-cli/tests/it/fileio.rs +++ b/apps/vectorcraft-cli/tests/it/fileio.rs @@ -4,8 +4,6 @@ use std::process::Command; use serde_json::Value; -const BIN: &str = env!("CARGO_BIN_EXE_vectorcraft-cli"); - /// Returns the path of `name` in `vectorcraft-cli-fileio-` in the temp folder. The first call /// removes that folder and creates it again empty. fn tmp(name: &str) -> String { @@ -20,7 +18,7 @@ fn tmp(name: &str) -> String { } fn ok(args: &[&str]) -> String { - let out = Command::new(BIN).args(args).output().unwrap(); + let out = Command::new(crate::bin()).args(args).output().unwrap(); assert!(out.status.success(), "{args:?}: {}", String::from_utf8_lossy(&out.stderr)); String::from_utf8(out.stdout).unwrap() } @@ -130,7 +128,7 @@ fn raster_exports_use_document_resolution_unless_overridden() { fn raster_export_rejects_invalid_ppi() { for ppi in ["0", "-150", "NaN", "inf", "high"] { for args in [vec!["run", "--export", "unused.png", "--ppi", ppi], vec!["convert", "unused.svg", "unused.png", "--ppi", ppi]] { - let out = Command::new(BIN).args(&args).output().unwrap(); + let out = Command::new(crate::bin()).args(&args).output().unwrap(); assert!(!out.status.success(), "{args:?}"); assert!(String::from_utf8_lossy(&out.stderr).contains("positive finite number"), "{args:?}: {out:?}"); } @@ -179,6 +177,27 @@ fn convert_reports_import_warnings() { assert!(w.iter().any(|w| w.as_str().unwrap().contains("nowhere-to-be-found.png")), "{out}"); } +/// A conversion sends each format only the options it reads, so its warnings name an unused +/// option only when the command line gave one: `--outline-text` for a format without it. +#[test] +fn convert_warns_about_an_unused_option_only_when_one_was_given() { + let svg = tmp("unused-option.svg"); + std::fs::write(&svg, r#""#).unwrap(); + let unused = |out: &Value| -> Vec { + let w = out["warnings"].as_array().unwrap_or_else(|| panic!("{out}")); + w.iter().filter_map(Value::as_str).filter(|w| w.contains("was not used")).map(str::to_string).collect() + }; + for ext in ["png", "jpg", "pdf", "ai", "eps", "psd", "dxf", "svg", "txt", "vectorcraft", "vctemplate"] { + let path = tmp(&format!("unused-option.{ext}")); + let out: Value = serde_json::from_str(ok(&["convert", &svg, &path]).trim()).unwrap(); + assert!(unused(&out).is_empty(), "{ext}: {out}"); + } + let out: Value = serde_json::from_str(ok(&["convert", &svg, &tmp("unused-option-outlined.svg"), "--outline-text"]).trim()).unwrap(); + assert!(unused(&out).is_empty(), "{out}"); + let out: Value = serde_json::from_str(ok(&["convert", &svg, &tmp("unused-option-outlined.png"), "--outline-text"]).trim()).unwrap(); + assert_eq!(unused(&out), ["`outlineText` was not used: PNG files don't read it"], "{out}"); +} + #[test] fn convert_writes_legacy_ai_with_its_options() { // Two artboards, a shown rectangle and a hidden one. @@ -228,7 +247,7 @@ fn convert_writes_legacy_ai_with_its_options() { assert!(r["warnings"].to_string().contains("hidden objects are left out"), "{r}"); assert!(std::fs::read(&one).unwrap().starts_with(b"%!PS-Adobe-3.0")); // A value the engine doesn't take is an error. - let bad = Command::new(BIN).args(["convert", &src, &tmp("bad.ai"), "--ai-version", "7", "--hidden-objects", "behind"]).output().unwrap(); + let bad = Command::new(crate::bin()).args(["convert", &src, &tmp("bad.ai"), "--ai-version", "7", "--hidden-objects", "behind"]).output().unwrap(); assert!(!bad.status.success()); assert!(String::from_utf8_lossy(&bad.stderr).contains("hiddenObjects"), "{}", String::from_utf8_lossy(&bad.stderr)); } @@ -253,7 +272,7 @@ fn convert_and_run_write_ait_templates() { assert_eq!(info(ait)["artboards"].as_array().unwrap().len(), 2, "{ait}"); } // A template holds every artboard: one can't be picked. - let one = Command::new(BIN).args(["convert", &pdf, &tmp("one.ait"), "--artboard", "0"]).output().unwrap(); + let one = Command::new(crate::bin()).args(["convert", &pdf, &tmp("one.ait"), "--artboard", "0"]).output().unwrap(); assert!(!one.status.success()); assert!(String::from_utf8_lossy(&one.stderr).contains("every artboard"), "{}", String::from_utf8_lossy(&one.stderr)); } diff --git a/apps/vectorcraft-cli/tests/it/main.rs b/apps/vectorcraft-cli/tests/it/main.rs index 07e5a3a70d..d898dda20a 100644 --- a/apps/vectorcraft-cli/tests/it/main.rs +++ b/apps/vectorcraft-cli/tests/it/main.rs @@ -6,3 +6,11 @@ mod cli; mod fileio; mod mcp_e2e; mod script; + +/// Nextest relocates archived binaries; Cargo's compile-time path still names the build runner. +fn bin() -> std::path::PathBuf { + std::env::var_os("NEXTEST_BIN_EXE_vectorcraft_cli") + .or_else(|| std::env::var_os("CARGO_BIN_EXE_vectorcraft-cli")) + .map(std::path::PathBuf::from) + .unwrap_or_else(|| env!("CARGO_BIN_EXE_vectorcraft-cli").into()) +} diff --git a/apps/vectorcraft-cli/tests/it/mcp_e2e.rs b/apps/vectorcraft-cli/tests/it/mcp_e2e.rs index 5a353070ae..4931602ec8 100644 --- a/apps/vectorcraft-cli/tests/it/mcp_e2e.rs +++ b/apps/vectorcraft-cli/tests/it/mcp_e2e.rs @@ -6,8 +6,6 @@ use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio}; use serde_json::{Value, json}; use vectorcraft_testkit::raster::Image; -const BIN: &str = env!("CARGO_BIN_EXE_vectorcraft-cli"); - struct Mcp { child: Child, stdin: Option, @@ -17,7 +15,7 @@ struct Mcp { impl Mcp { fn spawn() -> Self { - let mut child = Command::new(BIN) + let mut child = Command::new(crate::bin()) .args(["mcp", "--headless"]) .stdin(Stdio::piped()) .stdout(Stdio::piped()) diff --git a/apps/vectorcraft-cli/tests/it/script.rs b/apps/vectorcraft-cli/tests/it/script.rs index d68716f7b3..3652e585d0 100644 --- a/apps/vectorcraft-cli/tests/it/script.rs +++ b/apps/vectorcraft-cli/tests/it/script.rs @@ -2,11 +2,9 @@ use std::process::Command; use serde_json::{Value, json}; -const BIN: &str = env!("CARGO_BIN_EXE_vectorcraft-cli"); - /// `run` with `script.run` after `file.new`, with `params`. fn run_script(params: &Value) -> std::process::Output { - Command::new(BIN).args(["run", "--cmd", "file.new", "--cmd", "script.run", "--params", ¶ms.to_string()]).output().unwrap() + Command::new(crate::bin()).args(["run", "--cmd", "file.new", "--cmd", "script.run", "--params", ¶ms.to_string()]).output().unwrap() } /// `run` runs a script headless: the reply holds the report, with what the script logged and the diff --git a/apps/vectorcraft-web/src/main.rs b/apps/vectorcraft-web/src/main.rs index f7dd201af2..3808c281f9 100644 --- a/apps/vectorcraft-web/src/main.rs +++ b/apps/vectorcraft-web/src/main.rs @@ -7,7 +7,7 @@ //! Differences from the desktop app: //! - no TCP control server (browsers can't listen on sockets); //! - File → Open uses the browser file picker; bytes arrive asynchronously through -//! `Services::inbox`; +//! `Services::picked_inbox`; //! - Save / Export trigger a browser download; //! - dropped files are read asynchronously by `web::WebShell` and delivered through the inbox; //! - pen and finger input is read from Pointer Events by `pencil` (Apple Pencil pressure and diff --git a/apps/vectorcraft-web/src/web.rs b/apps/vectorcraft-web/src/web.rs index b4ca434d90..2de7f3b481 100644 --- a/apps/vectorcraft-web/src/web.rs +++ b/apps/vectorcraft-web/src/web.rs @@ -17,7 +17,7 @@ use vectorcraft_ui_egui::i18n; use vectorcraft_ui_egui::place::{DropTarget, PlaceArrival, PlaceInbox}; use vectorcraft_ui_egui::print::{PrintJob, PrintService, Printer}; use vectorcraft_ui_egui::stylus::StylusFeed; -use vectorcraft_ui_egui::{Services, VectorcraftApp}; +use vectorcraft_ui_egui::{PickedInbox, Services, VectorcraftApp}; use wasm_bindgen::JsCast as _; use crate::locks::WebLocks; @@ -25,6 +25,18 @@ use crate::pencil::SharedPointers; pub(crate) type Inbox = Arc)>>>; +/// The files waiting to open, by where they came from (`Services::inbox`, `picked_inbox` and +/// `page_inbox`). +#[derive(Clone, Default)] +struct OpenInboxes { + /// Dropped on the page. + dropped: Inbox, + /// The open picker's answers. + picked: PickedInbox, + /// Handed over by the page's script (`window.vectorcraft.openFile`). + page: Inbox, +} + /// Where the pointer was over the canvas during the last file drag (CSS px from its top-left) and /// whether Shift was held: where dropped files land. type DragPos = Rc>>; @@ -48,7 +60,7 @@ const MAX_RESTARTS: u32 = 3; #[derive(Clone)] struct Host { runner: eframe::WebRunner, - inbox: Inbox, + inbox: OpenInboxes, place_inbox: PlaceInbox, script_inbox: ScriptInbox, drag: DragPos, @@ -77,7 +89,7 @@ pub fn start() { crate::fonts::load_startup_fonts().await; let host = Host { runner: eframe::WebRunner::new(), - inbox: Arc::default(), + inbox: OpenInboxes::default(), place_inbox: Arc::default(), script_inbox: Arc::default(), drag: DragPos::default(), @@ -132,13 +144,13 @@ async fn run(host: Host, canvas: web_sys::HtmlCanvasElement, moving: Option { // `window.vectorcraft`: the page's control channel (crate::api). let (control_tx, control_rx) = std::sync::mpsc::channel(); - crate::api::connect(Some(control_tx), host.inbox.clone(), ctx.clone()); + crate::api::connect(Some(control_tx), host.inbox.page.clone(), ctx.clone()); if let Err(e) = crate::api::install() { log::error!("vectorcraft-web: couldn't install window.vectorcraft: {}", js_err(e)); } @@ -409,7 +421,7 @@ impl eframe::App for WebShell { for f in dropped { let name = f.path().file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "dropped".into()); let target = app.drop_target(&name, pos, shift); - let (inbox, place_inbox, repaint) = (self.host.inbox.clone(), self.host.place_inbox.clone(), ctx.clone()); + let (inbox, place_inbox, repaint) = (self.host.inbox.dropped.clone(), self.host.place_inbox.clone(), ctx.clone()); wasm_bindgen_futures::spawn_local(async move { match f.bytes_async().await { Ok(bytes) => { @@ -432,14 +444,14 @@ impl eframe::App for WebShell { } fn services( - inbox: Inbox, + inbox: OpenInboxes, place_inbox: PlaceInbox, script_inbox: ScriptInbox, ctx: egui::Context, locks: Option, stylus: StylusFeed, ) -> Services { - let open_inbox = inbox.clone(); + let open_inbox = inbox.picked.clone(); let picked = place_inbox.clone(); let place_ctx = ctx.clone(); let screen_color = eye_dropper(ctx.clone()); @@ -488,11 +500,12 @@ fn services( let dialog = fileio::open_filters().fold(rfd::AsyncFileDialog::new(), |d, (name, exts)| { d.add_filter(vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name), exts) }); - let Some(file) = dialog.pick_file().await else { - return; + // A canceled pick answers `None`. + let answer = match dialog.pick_file().await { + Some(file) => Some((file.file_name(), file.read().await)), + None => None, }; - let bytes = file.read().await; - inbox.lock().unwrap_or_else(|e| e.into_inner()).push((file.file_name(), bytes)); + inbox.lock().unwrap_or_else(|e| e.into_inner()).push(answer); ctx.request_repaint(); }); })), @@ -500,7 +513,9 @@ fn services( screen_color, // A download that couldn't be started fails the save or export it is for (#1693). download: Some(Box::new(|name: &str, bytes: &[u8]| download(name, bytes).inspect_err(|e| log::error!("download of {name} failed: {e}")))), - inbox: Some(inbox), + inbox: Some(inbox.dropped), + picked_inbox: Some(inbox.picked), + page_inbox: Some(inbox.page), recovery_store: Some(Arc::new(BrowserStore { locks })), // File → Print: the browser's print dialog. print: Some(Box::new(BrowserPrint)), diff --git a/apps/vectorcraft/Cargo.toml b/apps/vectorcraft/Cargo.toml index dfd9b16719..ffa1d2a5e8 100644 --- a/apps/vectorcraft/Cargo.toml +++ b/apps/vectorcraft/Cargo.toml @@ -96,12 +96,11 @@ winit = { version = "0.30", default-features = false, features = ["wayland-csd-a x11rb = { version = "0.13", default-features = false, features = ["xinput", "xkb"] } # Asks the Wayland compositor which GPU it draws with (linux-dmabuf feedback, src/compositor_gpu.rs), -# so Automatic draws on that one. Both are already in the build through winit. +# so Automatic draws on that one, and copies and pastes text, SVG and PNG through the compositor's +# core data-device protocol on the window's connection (src/clipboard.rs), where arboard has neither +# data-control (GNOME) nor X11 (a Flatpak on a Wayland session). Both are already in the build +# through winit. wayland-client = "0.31" -# Copy and Paste of text through the compositor's core data-device protocol on the window's -# connection (src/clipboard.rs), where arboard has neither data-control (GNOME) nor X11 (a Flatpak -# on a Wayland session). MIT, already in the build through egui-winit. -smithay-clipboard = "0.7" wayland-protocols = { version = "0.32", features = ["client", "unstable"] } # The save dialog's parent window on Wayland (src/portal_save.rs): an xdg-foreign handle (in # wayland-protocols' `unstable` set) made on the window's own connection. MIT, already in the build @@ -113,6 +112,14 @@ wayland-backend = { version = "0.3", features = ["client_system"] } # exactly: review the diff before bumping. [target.'cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))'.dependencies] zbus = "=5.19.0" +# Waits for a portal answer (the save dialog's and the screen color sampler's) and for the portal +# leaving the bus at the same time (src/portal_request.rs). Apache-2.0 OR MIT, already in the build +# through zbus. +futures-lite = "2" +# Tells whether arboard reads through the compositor's data-control protocol or through X11, the +# same check arboard makes (src/clipboard.rs). MIT OR Apache-2.0, already in the build through +# arboard. +wl-clipboard-rs = "0.9" [build-dependencies] # Icon + VERSIONINFO for vectorcraft.exe; build.rs only uses it when targeting Windows. diff --git a/apps/vectorcraft/src/app.rs b/apps/vectorcraft/src/app.rs index fa0f0dca29..4827772444 100644 --- a/apps/vectorcraft/src/app.rs +++ b/apps/vectorcraft/src/app.rs @@ -9,6 +9,7 @@ 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; +use vectorcraft_ui_egui::hang_beacon::{self, BEACON, FrameTime, Stage}; /// 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 @@ -34,12 +35,16 @@ impl eframe::App for App { // control channel asks for, and the frames carrying input it injected, to the automation roots // (`VectorcraftApp::with_automation_roots`), which are in force elsewhere in the process. fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) { + let _timed = BEACON.enter_timed(Stage::Logic); file_access::unconfined(|| self.logic_frame(ctx, frame)); self.app.finish_ime_logic(ctx); + BEACON.enter(Stage::Idle); } /// Restore the borderless caption, apply platform menu and pen input, and hand the frame to the /// app's raw-input hook while the keyboard user is unconfined. fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) { + let _timed = BEACON.enter_timed(Stage::Input); + self.frame_start = Some(std::time::Instant::now()); // winit gives the window its caption back when it changes the window's flags (maximize, // restore, …): take it off again before the frame is laid out (#1758). if let Some(window_frame) = self.window_frame.as_mut() { @@ -60,9 +65,10 @@ impl eframe::App for App { // that no mouse button is down. #[cfg(target_os = "macos")] self.app.release_lost_buttons(ctx, raw, objc2_app_kit::NSEvent::pressedMouseButtons() != 0); + BEACON.enter(Stage::Idle); } - #[cfg_attr(not(target_os = "macos"), allow(unused_variables))] fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { + let _timed = BEACON.enter_timed(Stage::Interface); #[cfg(target_os = "macos")] { let bar = vectorcraft_ui_egui::chrome::APP_BAR_HEIGHT; @@ -89,19 +95,80 @@ impl eframe::App for App { if !self.app.file_dialog_open() && self.app.take_ime_discard() { discard_marked_text(); } + self.end_frame(ui.ctx(), frame); } fn on_exit(&mut self) { + // The window is closing: saving and teardown are not timed for the hang report, and a report + // of a stall the interface came back from is removed. + let log_dir = super::prefs::log_dir().filter(|_| super::prefs::prefs_enabled()); + super::hang_watch::closing(log_dir.as_deref(), &super::hang_watch::CLOSING, &BEACON); file_access::unconfined(|| save_prefs(&self.app)); // A ready update installs once the process has exited. The macOS exit below skips // dropping the app, so the helper is started here. self.app.start_pending_update(); #[cfg(target_os = "macos")] super::mac_cursor::release(); + #[cfg(not(any(target_os = "macos", windows)))] + hide_before_teardown(self.winit_window.as_deref()); end_before_teardown(self.frames); } } +/// The main window as [`hide_before_teardown`] sees it. +#[cfg(not(any(target_os = "macos", windows)))] +pub(crate) trait QuittingWindow { + fn hide(&self); +} + +#[cfg(not(any(target_os = "macos", windows)))] +impl QuittingWindow for winit::window::Window { + fn hide(&self) { + self.set_visible(false); + } +} + +/// On Linux and the BSDs, hide the main window before eframe drops the app. Dropping the app waits +/// up to [`vectorcraft_ui_egui::CLIPBOARD_PROBE_STOP_WAIT`] for the clipboard handles to let go, and +/// the window would stay on screen for that time. The window is hidden, not closed: the Wayland +/// clipboard reads text on the window's connection. winit hides X11 windows (XWayland included) and +/// cannot hide a Wayland window. +#[cfg(not(any(target_os = "macos", windows)))] +pub(crate) fn hide_before_teardown(window: Option<&W>) { + if let Some(window) = window { + window.hide(); + } +} + impl App { + /// The frame's times for the hang report, and its last stage ([`hang_beacon::after_frame`]): a + /// focused, shown window whose windows had input waits for the renderer and the next frame, + /// which the input asks for at once; any other frame leaves the interface thread idle + /// (`hang_watch`). + fn end_frame(&mut self, ctx: &egui::Context, frame: &eframe::Frame) { + // A pass egui discards and runs again is not the frame's end: the pass after it is. + if ctx.will_discard() { + return; + } + if let Some(start) = self.frame_start.take() { + let work_ms = start.elapsed().as_secs_f32() * 1000.0; + let previous_total_ms = frame.info().cpu_usage.map(|s| s * 1000.0); + BEACON.frame(FrameTime { work_ms, previous_total_ms }, self.app.session.documents().len()); + } + // Hide on macOS hides the window at once, before the window reports losing focus. + let main_shown = ctx.input(|i| i.focused && i.viewport().minimized != Some(true)) + && self.winit_window.as_ref().is_none_or(|w| w.is_visible() != Some(false)); + // A floating panel or document window with the focus counts as well, with the commands it + // was sent after its pass, and those its pass sent (`hang_beacon::watch_input`). + let shown = ctx.input(|i| hang_beacon::shown_window(main_shown, &i.raw.viewports)); + let handed_off = BEACON.take_handed_off(); + let input = BEACON.take_input(); + let stage = match shown { + Some(id) => ctx.viewport_for(id, |vp| hang_beacon::after_frame(input && !handed_off.contains(&id), true, &vp.commands)), + None => hang_beacon::after_frame(input, false, &[]), + }; + BEACON.enter(stage); + } + fn logic_frame(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { #[cfg(target_os = "macos")] if self.winit_window.as_ref().is_some_and(|w| !w.has_focus() || w.is_visible() == Some(false) || w.is_minimized() == Some(true)) { diff --git a/apps/vectorcraft/src/clipboard.rs b/apps/vectorcraft/src/clipboard.rs index b9be306898..77a96442c4 100644 --- a/apps/vectorcraft/src/clipboard.rs +++ b/apps/vectorcraft/src/clipboard.rs @@ -10,9 +10,12 @@ //! Linux arboard reads no other formats). On Wayland, arboard's data-control //! backend reads the compositor's clipboard (X11 through XWayland only sees what X11 apps //! copied), falling back to X11 where the compositor lacks the protocol, and where there is no -//! X11 either (a Flatpak on GNOME) to the compositor's core protocol on the window's connection, -//! text only. A clipboard that can't be opened is tried again after a wait that grows to a -//! minute, not each time Paste asks. +//! X11 either (a Flatpak on GNOME) to the compositor's core protocol on the window's connection: +//! Copy offers SVG (`image/svg+xml`), PNG (`image/png`) and text together, and Paste reads SVG, +//! text and PNG. A clipboard that can't be opened is tried again after a wait that grows to a +//! minute, not each time Paste asks. On Linux and the BSDs a read waits 2 s at most for the app +//! that copied to send its data (a bitmap 10 s), and until that app answers, later reads fail at +//! once; a paste then waits for that read's answer off the UI thread. //! - Everywhere: files copied in a file manager paste as the first one that is art (SVG, PDF, EPS, //! a metafile or a bitmap), before the clipboard's other formats (the files' paths as text). @@ -22,8 +25,8 @@ use std::path::PathBuf; use vectorcraft_engine::cmd::clipboard::{BITMAP, EPS, FILE_HEAD, Flavour, PDF, PNG, SVG, TEXT, file_flavour}; use vectorcraft_ui_egui::{ClipboardRead, SystemClipboard}; -/// This platform's system clipboard. On Linux, `window`'s Wayland connection carries text where -/// arboard can't open (GNOME has no data-control protocol, a Flatpak there no X11). +/// This platform's system clipboard. On Linux, `window`'s Wayland connection carries text, SVG and +/// PNG where arboard can't open (GNOME has no data-control protocol, a Flatpak there no X11). pub fn system_clipboard(window: Option>) -> Box { #[cfg(windows)] let cb = { @@ -332,11 +335,290 @@ mod win { } } +/// Reads made on a worker thread and waited for a bounded time: a clipboard owner that never sends +/// its data holds the worker, not the caller. On Linux and the BSDs arboard's reads go through one, +/// and on Linux the Wayland core protocol's reads through another. Built everywhere so it is +/// tested everywhere. +#[cfg_attr( + not(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd")), + allow(dead_code) +)] +mod loads { + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::{Arc, Mutex, PoisonError, Weak, mpsc}; + use std::time::{Duration, Instant}; + + /// The longest a read waits for the clipboard's owner to send its data. + pub(super) const LOAD_WAIT: Duration = Duration::from_secs(2); + /// What a read says once its worker has stopped. + pub(super) const GONE: &str = "the clipboard's reader stopped"; + + /// Requests of type `R` answered with `A` on a worker thread. + pub(super) struct Loads { + /// The worker's requests; the worker stops once this is dropped. + line: Arc>, + /// Disconnected once the worker has let go of what its `load` holds. + done: mpsc::Receiver<()>, + /// How long after it was sent dropping `Loads` waits for an unanswered read to end. + finish: Duration, + } + + /// Where requests go to a [`Loads`] worker. + struct Line { + /// Each request goes with the channel its answer is sent on. + requests: mpsc::Sender<(R, mpsc::Sender)>, + /// Requests sent and not answered yet, counted down by the worker: while one is open, + /// reads don't queue behind it. + open: Arc, + /// When the last request was sent, and whether the `Loads` has stopped taking requests: + /// requests are sent with this locked. + sent: Mutex, + } + + #[derive(Default)] + struct Sent { + at: Option, + closed: bool, + } + + impl Line { + /// A line whose worker has stopped. + fn dead() -> Arc { + Arc::new(Self { requests: mpsc::channel().0, open: Arc::default(), sent: Mutex::default() }) + } + + /// `request` sent to the worker ([`Loads::ask`]). + fn ask(&self, request: R) -> Result, String> { + let mut sent = self.sent.lock().unwrap_or_else(PoisonError::into_inner); + if sent.closed { + return Err(GONE.into()); + } + if self.open.compare_exchange(0, 1, Ordering::SeqCst, Ordering::SeqCst).is_err() { + return Err("the clipboard's owner hasn't answered an earlier read".into()); + } + let (reply, answer) = mpsc::channel(); + sent.at = Some(Instant::now()); + if self.requests.send((request, reply)).is_err() { + self.open.fetch_sub(1, Ordering::SeqCst); + return Err(GONE.into()); + } + Ok(answer) + } + + /// Stops taking requests → when the one still unanswered was sent. + fn close(&self) -> Option { + let mut sent = self.sent.lock().unwrap_or_else(PoisonError::into_inner); + sent.closed = true; + sent.at.filter(|_| self.open.load(Ordering::SeqCst) > 0) + } + } + + /// Sends requests to a [`Loads`] worker from another thread while the `Loads` is open. + pub(super) struct Asker(Weak>); + + impl Asker { + /// [`Loads::ask`]; Err also once the `Loads` has been dropped. + pub(super) fn ask(&self, request: R) -> Result, String> { + self.0.upgrade().ok_or_else(|| GONE.to_string())?.ask(request) + } + } + + /// When dropping `Loads` stops waiting for its worker: `finish` after the unanswered read + /// `pending` was sent (at once if that time has passed), and with no read unanswered + /// [`LOAD_WAIT`] from `now` at most (an idle worker ends at once). + fn stop_by(pending: Option, now: Instant, finish: Duration) -> Instant { + pending.map_or(now + LOAD_WAIT, |sent| sent + finish) + } + + impl Loads { + /// A worker thread named `name` that answers each request with `load`; dropping the result + /// waits up to `finish` after an unanswered read was sent for that read to end. None when the + /// worker can't start. + pub(super) fn spawn(name: &str, finish: Duration, mut load: impl FnMut(R) -> A + Send + 'static) -> Option { + let (requests, asked) = mpsc::channel::<(R, mpsc::Sender)>(); + let (alive, done) = mpsc::channel::<()>(); + let open = Arc::new(AtomicUsize::new(0)); + let answered = open.clone(); + let work = move || { + while let Ok((request, reply)) = asked.recv() { + let answer = load(request); + // Counted down before the answer goes, so its reader can ask again at once. + answered.fetch_sub(1, Ordering::SeqCst); + // A read that timed out no longer waits: its late answer is dropped. + let _ = reply.send(answer); + } + // `load` and the clipboard it holds go first: dropping `Loads` waits for `alive`. + drop(load); + drop(alive); + }; + std::thread::Builder::new().name(name.into()).spawn(work).ok()?; + Some(Self { line: Arc::new(Line { requests, open, sent: Mutex::default() }), done, finish }) + } + + /// `request` sent to the worker; its answer comes on the channel returned, for + /// [`wait_for_answer`] here or on another thread. Err when an earlier request is still + /// unanswered or the worker has stopped. + pub(super) fn ask(&mut self, request: R) -> Result, String> { + self.line.ask(request) + } + + /// Whether a request sent is still unanswered. + pub(super) fn waiting(&self) -> bool { + self.line.open.load(Ordering::SeqCst) > 0 + } + + /// A handle that sends requests from another thread until this is dropped. + pub(super) fn asker(&self) -> Asker { + Asker(Arc::downgrade(&self.line)) + } + + /// The answer to `request`, or why there is none, after `wait` at most. + #[cfg(test)] + pub(super) fn get(&mut self, request: R, wait: Duration) -> Result { + wait_for_answer(&self.ask(request)?, wait) + } + } + + /// The answer that comes on `answer` ([`Loads::ask`]), or why there is none, after `wait` at most. + pub(super) fn wait_for_answer(answer: &mpsc::Receiver, wait: Duration) -> Result { + match answer.recv_timeout(wait) { + Ok(answer) => Ok(answer), + Err(mpsc::RecvTimeoutError::Timeout) => Err(format!("the clipboard's owner didn't send its data within {wait:?}")), + Err(mpsc::RecvTimeoutError::Disconnected) => Err(GONE.into()), + } + } + + impl Drop for Loads { + /// Stops the worker and waits until it has let go of what its `load` holds, until + /// [`stop_by`] at most: on X11 the last arboard handle dropped hands what the app copied to + /// the clipboard manager, and the app's own handle must be that one. + fn drop(&mut self) { + // No `Asker` sends after this, and one that holds the line lets go once it has sent. + let pending = self.line.close(); + drop(std::mem::replace(&mut self.line, Line::dead())); + let end = stop_by(pending, Instant::now(), self.finish); + // Nothing is sent on `done`: this ends when the worker drops `alive`, or at `end`. + let _ = self.done.recv_timeout(end.saturating_duration_since(Instant::now())); + } + } + + #[cfg(test)] + mod tests { + use std::sync::Arc; + + use super::*; + + #[test] + fn a_read_that_answers_in_time_gives_the_text() { + let mut loads = Loads::spawn("test", Duration::ZERO, |()| "".to_string()).unwrap(); + assert_eq!(loads.get((), Duration::from_secs(5)), Ok("".to_string())); + assert_eq!(loads.get((), Duration::from_secs(5)), Ok("".to_string())); + } + + #[test] + fn an_owner_that_never_answers_holds_the_worker_not_the_caller() { + let (release, gate) = mpsc::channel::<()>(); + let mut calls = 0; + let mut loads = Loads::spawn("test", Duration::ZERO, move |()| { + calls += 1; + if calls == 1 { + // The first owner sends nothing until released. + let _ = gate.recv(); + return "stale".to_string(); + } + "fresh".to_string() + }) + .unwrap(); + assert!(loads.get((), Duration::ZERO).is_err(), "the first read times out"); + // While it is unanswered, a read doesn't queue behind it or wait at all. + assert!(loads.get((), Duration::from_secs(600)).is_err()); + release.send(()).unwrap(); + // Once the late answer is in, it is dropped and a new read is made. + let text = loop { + match loads.get((), Duration::from_secs(600)) { + Ok(text) => break text, + Err(why) => { + // The late answer isn't in yet. + assert_ne!(why, GONE); + std::thread::yield_now(); + } + } + }; + assert_eq!(text, "fresh"); + } + + #[test] + fn a_read_after_the_worker_stops_says_so() { + let mut loads = Loads::spawn("test", Duration::ZERO, |()| String::new()).unwrap(); + // The worker ends when its requests stop: cut them off by hand. + drop(std::mem::replace(&mut loads.line, Line::dead())); + assert_eq!(loads.get((), Duration::from_millis(50)), Err(GONE.to_string())); + } + + #[test] + fn another_threads_reads_stop_with_the_reads() { + let loads = Loads::spawn("test", Duration::ZERO, |()| 1).unwrap(); + let asker = loads.asker(); + assert_eq!(asker.ask(()).and_then(|a| wait_for_answer(&a, Duration::from_secs(600))), Ok(1)); + drop(loads); + assert_eq!(asker.ask(()).err(), Some(GONE.to_string())); + // Closed while an asker still holds the line: nothing more is sent. + let line = Line::<(), ()>::dead(); + assert_eq!(line.close(), None); + assert_eq!(line.ask(()).err(), Some(GONE.to_string())); + } + + #[test] + fn an_answer_waited_for_on_another_thread_holds_back_the_next_read() { + let (release, gate) = mpsc::channel::<()>(); + let mut loads = Loads::spawn("test", Duration::ZERO, move |n: u32| { + if n == 1 { + let _ = gate.recv(); + } + n + }) + .unwrap(); + let answer = loads.ask(1).unwrap(); + // The caller doesn't wait: the answer is waited for wherever the channel goes. + let waiter = std::thread::spawn(move || wait_for_answer(&answer, Duration::from_secs(600))); + // Until it comes, a read fails at once instead of queuing behind it. + assert!(loads.get(2, Duration::from_secs(600)).is_err()); + release.send(()).unwrap(); + assert_eq!(waiter.join().ok(), Some(Ok(1))); + assert_eq!(loads.get(3, Duration::from_secs(600)), Ok(3)); + } + + #[test] + fn dropping_the_reads_waits_until_the_worker_lets_go_of_its_clipboard() { + let clipboard = Arc::new(()); + let held = clipboard.clone(); + let mut loads = Loads::spawn("test", Duration::ZERO, move |()| Arc::strong_count(&held)).unwrap(); + assert_eq!(loads.get((), Duration::from_secs(600)), Ok(2)); + drop(loads); + assert_eq!(Arc::strong_count(&clipboard), 1, "the worker's handle is gone before the app's"); + } + + #[test] + fn dropping_the_reads_waits_for_an_unanswered_read_up_to_its_limit() { + let now = Instant::now(); + let limit = Duration::from_secs(25); + // No read unanswered: the idle worker ends at once, LOAD_WAIT is only the bound. + assert_eq!(stop_by(None, now, limit), now + LOAD_WAIT); + // A read sent 2 s ago that timed out: wait for it until 25 s after it was sent. + assert_eq!(stop_by(Some(now - Duration::from_secs(2)), now, limit), now + Duration::from_secs(23)); + // Its limit already over, or no limit (data-control, the core protocol): no wait. + assert!(stop_by(Some(now - Duration::from_secs(30)), now, limit) <= now); + assert_eq!(stop_by(Some(now), now, Duration::ZERO), now); + } + } +} + /// arboard, or on a Wayland compositor without its data-control protocol the core protocol's text /// clipboard: one format at a time. Built everywhere so it is checked everywhere. #[cfg_attr(windows, allow(dead_code))] mod portable { use std::borrow::Cow; + use std::path::PathBuf; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use std::time::{Duration, Instant}; @@ -344,32 +626,365 @@ mod portable { use super::{BITMAP, ClipboardRead, Flavour, PNG, SystemClipboard, TEXT, copied_file, decode_png, png_flavour, text_of}; /// What our last write put on the clipboard. + #[derive(Clone)] enum Ours { Text(String), Image(usize, usize), + /// A Copy through the Wayland core protocol, whose data source tells whether the + /// clipboard still holds it. + #[cfg(target_os = "linux")] + Source, } + /// A read of arboard's clipboard. + #[derive(Clone, Copy, PartialEq, Eq)] + enum Request { + Text, + Image, + Files, + } + + /// What a [`Request`] read. + enum Answer { + Text(Result), + Image(Result, String>), + Files(Vec), + } + + /// What a read says when it gets the answer to another request. + const MIXED: &str = "the clipboard answered another read"; + + impl Answer { + /// The answer to `request` when it couldn't be read: `why`, or no files. + #[cfg(any(test, target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + fn failed(request: Request, why: String) -> Self { + match request { + Request::Text => Self::Text(Err(why)), + Request::Image => Self::Image(Err(why)), + Request::Files => Self::Files(vec![]), + } + } + + /// The request this answers. + #[cfg_attr( + not(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd")), + allow(dead_code) + )] + fn request(&self) -> Request { + match self { + Self::Text(_) => Request::Text, + Self::Image(_) => Request::Image, + Self::Files(_) => Request::Files, + } + } + + fn text(self) -> Result { + match self { + Self::Text(text) => text, + _ => Err(MIXED.into()), + } + } + + fn image(self) -> Result, String> { + match self { + Self::Image(image) => image, + _ => Err(MIXED.into()), + } + } + + fn files(self) -> Vec { + match self { + Self::Files(files) => files, + _ => vec![], + } + } + } + + /// `request` read through `cb`. + fn answer(cb: &mut arboard::Clipboard, request: Request) -> Answer { + match request { + Request::Text => Answer::Text(cb.get_text().map_err(|e| e.to_string())), + Request::Image => Answer::Image(cb.get_image().map_err(|e| e.to_string())), + Request::Files => Answer::Files(cb.get().file_list().unwrap_or_default()), + } + } + + /// `request` read on `reads`' worker, waiting `wait` at most. + #[cfg(test)] + fn read_within(reads: &mut super::loads::Loads, request: Request, wait: Duration) -> Answer { + reads.get(request, wait).unwrap_or_else(|why| Answer::failed(request, why)) + } + + /// The longest a paste's bitmap read of arboard's waits for the app that copied, off the UI + /// thread: the bitmap's transfer and its PNG decoding happen within the read. A paste waits as + /// long, from when it was sent, for a read that got no answer in its wait, the core protocol's + /// text read included. Text, file lists and the UI thread's bitmap check wait + /// [`LOAD_WAIT`](super::loads::LOAD_WAIT). + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + const IMAGE_WAIT: Duration = Duration::from_secs(10); + + /// How long a read of `request` waits for the app that copied. + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + fn wait_for(request: Request) -> Duration { + match request { + Request::Image => IMAGE_WAIT, + Request::Text | Request::Files => super::loads::LOAD_WAIT, + } + } + + /// How long a paste's read of `request` after a late answer waits at `now`: as long as any read + /// of `request`, or until [`IMAGE_WAIT`] after the unanswered read was `sent` when that is later. + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + fn follow_up_wait(request: Request, sent: Instant, now: Instant) -> Duration { + wait_for(request).max((sent + IMAGE_WAIT).saturating_duration_since(now)) + } + + /// The longest an X11 read of arboard's lasts while the owner sends nothing: a text read tries + /// six formats and waits up to 4 s for each, and a second more covers the rest of the read. + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + const X11_READ_LIMIT: Duration = Duration::from_secs(25); + + /// Whether arboard's handles use the compositor's data-control protocol rather than X11. arboard + /// 3.7 makes the same check when it opens: data-control where `WAYLAND_DISPLAY` is set and + /// wl-clipboard-rs finds the protocol, X11 otherwise. + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + fn on_data_control() -> bool { + std::env::var_os("WAYLAND_DISPLAY").is_some() && wl_clipboard_rs::utils::is_primary_selection_supported().is_ok() + } + + /// How long after an unanswered read was sent dropping the reads waits for it to end: on X11 + /// the last handle dropped hands what the app copied to a clipboard manager, and on + /// data-control, where a read may never end, nothing is handed over. + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + fn finish(data_control: bool) -> Duration { + if data_control { Duration::ZERO } else { X11_READ_LIMIT } + } + + /// arboard's clipboard, with `C` for writes (arboard's handle; a stand-in in tests). On Linux + /// and the BSDs its reads run on a worker with a handle of its own and wait + /// [`LOAD_WAIT`](super::loads::LOAD_WAIT) at most, a paste's bitmap 10 s off the UI thread: arboard's Wayland + /// data-control read waits for the app that copied to send its data with no limit, and its X11 + /// read waits up to 4 s for each format it tries. + struct Arboard { + /// Dropped before `cb`, and waits for its worker's handle to go, on X11 up to + /// [`X11_READ_LIMIT`] after an unanswered read was sent: there the last handle dropped + /// hands what the app copied to the clipboard manager. + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + reads: super::loads::Loads, + /// The last read that got no answer in its wait, until a paste takes it or the next read + /// is sent. + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + unanswered: Option, + /// Writes, and elsewhere reads. + cb: C, + } + + /// A read on arboard's worker that got no answer in its wait. + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + struct Unanswered { + request: Request, + answer: std::sync::mpsc::Receiver, + sent: Instant, + /// The worker, for the paste's other reads. + reads: super::loads::Asker, + } + + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + impl Unanswered { + /// Whether a paste of one of `mimes` can take this read's answer: files paste as any of + /// them. + fn fits(&self, mimes: &[&'static str]) -> bool { + match self.request { + Request::Text => mimes.contains(&TEXT), + Request::Image => mimes.contains(&BITMAP), + Request::Files => true, + } + } + + /// What a paste of one of `mimes` takes, once this read's answer comes, waiting for it until + /// [`IMAGE_WAIT`] after it was sent, as long as a paste's bitmap read waits. Once it comes, + /// the same read is made again, since the clipboard may have changed hands meanwhile. + /// `None`, so the paste takes the internal clipboard, when that answer doesn't come or the + /// new one is what `ours` put on the clipboard. Otherwise the clipboard is read as + /// [`Clipboard::read_now_or_later`] and the paste read it, the new answer standing in for + /// the read it answers: copied files, else + /// text, else the bitmap, and the bitmap when it is asked for and the text is blank or only + /// names a picture (`adopt_system_clipboard_or_defer` in `vectorcraft-ui-egui`). Those reads + /// wait as [`follow_up_wait`] says. + fn paste(self, ours: Option<&Ours>, mimes: &[&'static str]) -> Option { + let wait = (self.sent + IMAGE_WAIT).saturating_duration_since(Instant::now()); + super::loads::wait_for_answer(&self.answer, wait).ok()?; + let fresh = |request: Request| { + self.reads + .ask(request) + .and_then(|a| super::loads::wait_for_answer(&a, follow_up_wait(request, self.sent, Instant::now()))) + .unwrap_or_else(|why| Answer::failed(request, why)) + }; + // The late answer may come from an app that lost the clipboard while it was awaited. + let answer = fresh(self.request); + let held = match (&answer, ours) { + (Answer::Text(Ok(now)), Some(Ours::Text(t))) => now == t, + (Answer::Image(Ok(now)), Some(Ours::Image(w, h))) => (now.width, now.height) == (*w, *h), + _ => false, + }; + if held { + return None; + } + let mut answer = Some(answer); + let mut read = |request: Request| match answer.take_if(|a| a.request() == request) { + Some(answer) => answer, + None => fresh(request), + }; + if let Some(f) = copied_file(read(Request::Files).files(), mimes) { + return Some(f); + } + let text = if mimes.contains(&TEXT) { read(Request::Text).text().ok().filter(|t| !t.is_empty()) } else { None }; + let bitmap = |read: &mut dyn FnMut(Request) -> Answer| image_flavour(read(Request::Image).image().ok()?); + match text { + Some(t) if mimes.contains(&BITMAP) && (t.trim().is_empty() || vectorcraft_engine::cmd::clipboard::names_a_picture(&t)) => { + bitmap(&mut read).or(Some(Flavour { mime: TEXT, data: t.into_bytes() })) + } + Some(t) => Some(Flavour { mime: TEXT, data: t.into_bytes() }), + None if mimes.contains(&BITMAP) => bitmap(&mut read), + None => None, + } + } + } + + /// A read that got no answer in its wait, for a paste to wait for off the UI thread. + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + enum Late { + Arboard(Unanswered), + /// The core protocol's text read. + #[cfg(target_os = "linux")] + Wayland(super::wayland::Unanswered), + } + + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + impl Late { + /// What a paste of one of `mimes` takes once the answer comes ([`Unanswered::paste`]). The + /// core protocol's answer is waited for as long, until [`IMAGE_WAIT`] after its read was + /// sent; then the clipboard is read again and pasted as at once, unless it holds the Copy + /// made here ([`super::wayland::Unanswered::paste`]). + fn paste(self, ours: Option<&Ours>, mimes: &[&'static str]) -> Option { + match self { + Self::Arboard(unanswered) => unanswered.paste(ours, mimes), + #[cfg(target_os = "linux")] + Self::Wayland(unanswered) => unanswered.paste(mimes, IMAGE_WAIT), + } + } + } + + /// arboard's bitmap as a PNG flavour. + fn image_flavour(img: arboard::ImageData<'static>) -> Option { + let (width, height) = (u32::try_from(img.width).ok()?, u32::try_from(img.height).ok()?); + png_flavour(&image::RgbaImage::from_raw(width, height, img.bytes.into_owned())?) + } + + impl Arboard { + fn open() -> Result { + let cb = arboard::Clipboard::new().map_err(|e| e.to_string())?; + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + { + let mut reader = arboard::Clipboard::new().map_err(|e| e.to_string())?; + let reads = super::loads::Loads::spawn("clipboard-read", finish(on_data_control()), move |request| answer(&mut reader, request)) + .ok_or("the clipboard's reader didn't start")?; + Ok(Self { reads, unanswered: None, cb }) + } + #[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd")))] + Ok(Self { cb }) + } + + #[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd")))] + fn read(&mut self, request: Request) -> Answer { + answer(&mut self.cb, request) + } + } + + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + impl Arboard { + /// Reads on the worker; the write handle `C` is not used. + fn read(&mut self, request: Request) -> Answer { + self.read_waiting(request, wait_for(request)) + } + + /// A bitmap read on the worker that waits [`LOAD_WAIT`](super::loads::LOAD_WAIT) at most, for + /// a check on the UI thread. + fn image_now(&mut self) -> Result, String> { + self.read_waiting(Request::Image, super::loads::LOAD_WAIT).image() + } + + /// `request` read on the worker, waiting `wait` at most. A read that gets no answer in that + /// time is kept ([`Self::unanswered`]) for a paste to wait for off the UI thread. + fn read_waiting(&mut self, request: Request, wait: Duration) -> Answer { + let sent = Instant::now(); + let answer = match self.ask(request) { + Ok(answer) => answer, + Err(why) => return Answer::failed(request, why), + }; + match super::loads::wait_for_answer(&answer, wait) { + Ok(answer) => answer, + Err(why) => { + if why != super::loads::GONE { + self.unanswered = Some(Unanswered { request, answer, sent, reads: self.reads.asker() }); + } + Answer::failed(request, why) + } + } + } + + /// `request` sent to the worker. A read sent means the one kept unanswered has been + /// answered, and its answer is dropped. + fn ask(&mut self, request: Request) -> Result, String> { + let answer = self.reads.ask(request)?; + self.unanswered = None; + Ok(answer) + } + + /// A bitmap read sent to the worker now; the work returned waits [`IMAGE_WAIT`] at most for + /// it, so the caller can wait off the UI thread. Err when the read can't be sent. + fn image_later(&mut self) -> Result { + let answer = self.ask(Request::Image)?; + Ok(Box::new(move || super::loads::wait_for_answer(&answer, IMAGE_WAIT).and_then(Answer::image))) + } + + /// The read that got no answer in its wait, while its answer has still not come and a paste + /// of one of `mimes` can take it: what the clipboard holds is not known until it comes. Once + /// it has come the answer may be old, and it is dropped: a new read is made. + fn unanswered(&mut self, mimes: &[&'static str]) -> Option { + let unanswered = self.unanswered.take_if(|u| u.fits(mimes))?; + self.reads.waiting().then_some(unanswered) + } + } + + /// A bitmap read whose answer is waited for when it runs. + type ImageWork = Box Result, String> + Send>; + /// An open clipboard connection. enum Backend { - Arboard(arboard::Clipboard), - /// The compositor's core data-device protocol on the window's connection (text only). + Arboard(Arboard), + /// The compositor's core data-device protocol on the window's connection. #[cfg(target_os = "linux")] - Wayland(super::wayland::TextClipboard), + Wayland(super::wayland::DataClipboard), } - /// What a write of a picture says where the clipboard carries text only. + /// What a bitmap read or write says on the core protocol, which carries pictures as PNG data + /// only ([`Clipboard::write`], [`Clipboard::read_now_or_later`]). #[cfg(target_os = "linux")] - const TEXT_ONLY: &str = "this clipboard carries text only"; + const PNG_ONLY: &str = "this clipboard carries pictures as PNG data"; impl Backend { /// arboard (Wayland data-control, else X11), else the core protocol on `window`'s /// Wayland connection. Err: why each failed. fn open(window: Option<&Arc>) -> Result { first_open( - || arboard::Clipboard::new().map(Self::Arboard).map_err(|e| e.to_string()), + || Arboard::open().map(Self::Arboard), || { #[cfg(target_os = "linux")] - return window.and_then(|w| super::wayland::TextClipboard::new(w.clone())).map(Self::Wayland).ok_or("not a Wayland window"); + return window + .and_then(|w| super::wayland::DataClipboard::new(w.clone())) + .map(Self::Wayland) + .ok_or("not a Wayland window with a seat and a data-device manager"); #[cfg(not(target_os = "linux"))] { let _ = window; @@ -383,60 +998,106 @@ mod portable { match self { Self::Arboard(_) => "arboard", #[cfg(target_os = "linux")] - Self::Wayland(_) => "the Wayland core protocol (text only)", + Self::Wayland(_) => "the Wayland core protocol", } } fn get_text(&mut self) -> Result { match self { - Self::Arboard(cb) => cb.get_text().map_err(|e| e.to_string()), + Self::Arboard(cb) => cb.read(Request::Text).text(), #[cfg(target_os = "linux")] - Self::Wayland(cb) => cb.get_text(), + Self::Wayland(cb) => cb.text(), } } fn set_text(&mut self, text: &str) -> Result<(), String> { match self { - Self::Arboard(cb) => cb.set_text(text).map_err(|e| e.to_string()), + Self::Arboard(cb) => cb.cb.set_text(text).map_err(|e| e.to_string()), #[cfg(target_os = "linux")] - Self::Wayland(cb) => { - cb.set_text(text); - Ok(()) - } + Self::Wayland(cb) => cb.copy(&[Flavour { mime: TEXT, data: text.as_bytes().to_vec() }]), } } - fn get_image(&mut self) -> Result, String> { + /// Whether the clipboard holds the core protocol's last Copy made here (never for arboard, + /// whose writes are checked by what they wrote). + #[cfg(target_os = "linux")] + fn holds_source(&mut self) -> bool { match self { - Self::Arboard(cb) => cb.get_image().map_err(|e| e.to_string()), + Self::Arboard(_) => false, + Self::Wayland(cb) => cb.holds_ours(), + } + } + + /// The bitmap, for a check on the UI thread: on Linux and the BSDs it waits + /// [`LOAD_WAIT`](super::loads::LOAD_WAIT) at most, as text does. + fn image_now(&mut self) -> Result, String> { + match self { + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + Self::Arboard(cb) => cb.image_now(), + #[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd")))] + Self::Arboard(cb) => cb.read(Request::Image).image(), #[cfg(target_os = "linux")] - Self::Wayland(_) => Err(TEXT_ONLY.into()), + Self::Wayland(_) => Err(PNG_ONLY.into()), + } + } + + /// The bitmap as work for another thread: on Linux and the BSDs the wait for the app + /// that copied happens when the work runs, elsewhere the bitmap is read here. + fn image_later(&mut self) -> Result { + match self { + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + Self::Arboard(cb) => cb.image_later(), + #[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd")))] + Self::Arboard(cb) => { + let image = cb.read(Request::Image).image()?; + Ok(Box::new(move || Ok(image))) + } + #[cfg(target_os = "linux")] + Self::Wayland(_) => Err(PNG_ONLY.into()), } } fn set_image(&mut self, img: arboard::ImageData<'_>) -> Result<(), String> { match self { - Self::Arboard(cb) => cb.set_image(img).map_err(|e| e.to_string()), + Self::Arboard(cb) => cb.cb.set_image(img).map_err(|e| e.to_string()), #[cfg(target_os = "linux")] - Self::Wayland(_) => Err(TEXT_ONLY.into()), + Self::Wayland(_) => Err(PNG_ONLY.into()), } } fn clear(&mut self) -> Result<(), String> { match self { - Self::Arboard(cb) => cb.clear().map_err(|e| e.to_string()), + Self::Arboard(cb) => cb.cb.clear().map_err(|e| e.to_string()), #[cfg(target_os = "linux")] - Self::Wayland(cb) => { - cb.set_text(""); - Ok(()) - } + Self::Wayland(cb) => cb.copy(&[]), + } + } + + /// The read that got no answer in its wait, when a paste of one of `mimes` can take its + /// answer ([`Arboard::unanswered`], [`Reads::unanswered`](super::wayland::Reads::unanswered)). + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + fn unanswered(&mut self, mimes: &[&'static str]) -> Option { + match self { + Self::Arboard(cb) => cb.unanswered(mimes).map(Late::Arboard), + #[cfg(target_os = "linux")] + Self::Wayland(cb) => cb.unanswered(mimes).map(Late::Wayland), + } + } + + /// Drops the read that got no answer in its wait: a paste no longer takes its answer. + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + fn forget_unanswered(&mut self) { + match self { + Self::Arboard(cb) => cb.unanswered = None, + #[cfg(target_os = "linux")] + Self::Wayland(cb) => cb.forget_unanswered(), } } /// Files copied in a file manager (none where the backend can't read a file list). - fn file_list(&mut self) -> Vec { + fn file_list(&mut self) -> Vec { match self { - Self::Arboard(cb) => cb.get().file_list().unwrap_or_default(), + Self::Arboard(cb) => cb.read(Request::Files).files(), #[cfg(target_os = "linux")] Self::Wayland(_) => vec![], } @@ -560,16 +1221,64 @@ mod portable { let window = self.window.as_ref(); self.cb.get(asker, Instant::now(), || Backend::open(window), Backend::name).ok_or_else(|| "no system clipboard".to_string()) } + + /// The work that pastes the answer to a read that got no answer in its wait + /// ([`Late::paste`]), while that answer has not come. + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + fn paste_unanswered(&mut self, mimes: &[&'static str]) -> Option { + let ours = self.ours.clone(); + let unanswered = self.cb(Asker::User).ok()?.unanswered(mimes)?; + let mimes = mimes.to_vec(); + Some(ClipboardRead::Later(Box::new(move || unanswered.paste(ours.as_ref(), &mimes)))) + } + + /// Text and copied files are read here, and work that reads arboard's image comes back. On + /// the Wayland core protocol the first of `mimes` the clipboard offers is read: text here, + /// SVG and PNG by the work that comes back, which waits [`IMAGE_WAIT`] at most. + fn read_now_or_later(&mut self, mimes: &[&'static str]) -> Option { + let cb = self.cb(Asker::User).ok()?; + #[cfg(target_os = "linux")] + if let Backend::Wayland(cb) = cb { + return cb.read(mimes, IMAGE_WAIT); + } + if let Some(f) = copied_file(cb.file_list(), mimes) { + return Some(ClipboardRead::Now(f)); + } + mimes.iter().find_map(|m| { + #[cfg(target_os = "macos")] + if let Some(f) = super::mac::read(m) { + return Some(ClipboardRead::Now(f)); + } + match *m { + TEXT => cb.get_text().ok().filter(|t| !t.is_empty()).map(|t| ClipboardRead::Now(Flavour { mime: TEXT, data: t.into_bytes() })), + BITMAP => { + let read = cb.image_later().ok()?; + Some(ClipboardRead::Later(Box::new(move || image_flavour(read().ok()?)))) + } + _ => None, + } + }) + } } impl SystemClipboard for Clipboard { + /// arboard takes the text, else the PNG as a bitmap; the Wayland core protocol offers the + /// SVG, PNG and text together ([`DataClipboard::copy`](super::wayland::DataClipboard::copy)). fn write(&mut self, flavours: &[Flavour]) -> Result<(), String> { + let cb = self.cb(Asker::User)?; + #[cfg(target_os = "linux")] + if let Backend::Wayland(wl) = cb { + wl.copy(flavours)?; + // What a read got late was on the clipboard before this write. + wl.forget_unanswered(); + self.ours = wl.holds_ours().then_some(Ours::Source); + return Ok(()); + } let text = text_of(flavours); let image = match &text { Some(_) => None, None => flavours.iter().find(|f| f.mime == PNG).and_then(|f| decode_png(&f.data)), }; - let cb = self.cb(Asker::User)?; let ours = match (text, image) { (Some(t), _) => { cb.set_text(t.as_str())?; @@ -585,6 +1294,9 @@ mod portable { None } }; + // What a read got late was on the clipboard before this write. + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + cb.forget_unanswered(); self.ours = ours; Ok(()) } @@ -593,40 +1305,37 @@ mod portable { let Some(cb) = self.cb.opened() else { return false }; match &self.ours { Some(Ours::Text(t)) => cb.get_text().is_ok_and(|now| now == *t), - Some(Ours::Image(w, h)) => cb.get_image().is_ok_and(|now| (now.width, now.height) == (*w, *h)), + Some(Ours::Image(w, h)) => cb.image_now().is_ok_and(|now| (now.width, now.height) == (*w, *h)), + #[cfg(target_os = "linux")] + Some(Ours::Source) => cb.holds_source(), None => false, } } fn read(&mut self, mimes: &[&'static str]) -> Option { - self.read_deferred(mimes)?.flavour() + self.read_now_or_later(mimes)?.flavour() } - /// arboard's image is read here and encoded as PNG by the work that comes back. + /// arboard's image is read here and encoded as PNG by the work that comes back. On Linux and + /// the BSDs, after a read that got no answer in its wait (such as the check whether the + /// clipboard still holds what was copied here, or one of the reads here), the work waits for + /// that read's answer instead and pastes from it, or nothing when it is what was copied here. fn read_deferred(&mut self, mimes: &[&'static str]) -> Option { - let cb = self.cb(Asker::User).ok()?; - if let Some(f) = copied_file(cb.file_list(), mimes) { - return Some(ClipboardRead::Now(f)); + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + if let Some(read) = self.paste_unanswered(mimes) { + return Some(read); } - mimes.iter().find_map(|m| { - #[cfg(target_os = "macos")] - if let Some(f) = super::mac::read(m) { - return Some(ClipboardRead::Now(f)); - } - match *m { - TEXT => cb.get_text().ok().filter(|t| !t.is_empty()).map(|t| ClipboardRead::Now(Flavour { mime: TEXT, data: t.into_bytes() })), - BITMAP => { - let img = cb.get_image().ok()?; - let (width, height) = (u32::try_from(img.width).ok()?, u32::try_from(img.height).ok()?); - let bytes = img.bytes.into_owned(); - Some(ClipboardRead::Later(Box::new(move || png_flavour(&image::RgbaImage::from_raw(width, height, bytes)?)))) - } - _ => None, - } - }) + let read = self.read_now_or_later(mimes); + // One of these reads got no answer in its wait, and the ones after it failed at once. + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + if read.is_none() { + return self.paste_unanswered(mimes); + } + read } - /// Text, and on macOS vector art or a bitmap (by the pasteboard's types). Linux has no + /// Text, on macOS vector art or a bitmap (by the pasteboard's types), and on the Wayland + /// core protocol SVG, text or PNG (by the types offered, nothing read). arboard has no /// cheap way to ask for a bitmap (reading one costs as much as pasting it): the paste keys /// take it, the menu item waits for text. fn has(&mut self, mimes: &[&'static str]) -> bool { @@ -634,7 +1343,12 @@ mod portable { if super::mac::has(mimes) { return true; } - mimes.contains(&TEXT) && self.cb(Asker::Probe).is_ok_and(|cb| cb.get_text().is_ok_and(|t| !t.is_empty())) + let Ok(cb) = self.cb(Asker::Probe) else { return false }; + #[cfg(target_os = "linux")] + if let Backend::Wayland(wl) = cb { + return wl.has(mimes); + } + mimes.contains(&TEXT) && cb.get_text().is_ok_and(|t| !t.is_empty()) } } @@ -642,6 +1356,7 @@ mod portable { mod tests { use std::cell::Cell; + use super::super::loads::Loads; use super::*; /// A clock that starts now and moves only when told. @@ -763,6 +1478,293 @@ mod portable { ); } + #[test] + fn reads_return_while_the_clipboard_owner_sends_nothing() { + let (release, gate) = std::sync::mpsc::channel::<()>(); + // The app that copied never sends its data until released. + let mut reads = Loads::spawn("test", Duration::ZERO, move |request| { + let _ = gate.recv(); + Answer::failed(request, "late".into()) + }) + .unwrap(); + // Copy's look at the text, Paste's file list and its bitmap: none waits for the owner. + assert!(read_within(&mut reads, Request::Text, Duration::ZERO).text().is_err()); + assert!(read_within(&mut reads, Request::Files, Duration::from_secs(600)).files().is_empty()); + assert!(read_within(&mut reads, Request::Image, Duration::from_secs(600)).image().is_err()); + drop(release); + } + + #[test] + fn each_read_takes_its_own_answer() { + let mut reads = Loads::spawn("test", Duration::ZERO, |request| match request { + Request::Text => Answer::Text(Ok("".into())), + Request::Image => Answer::Image(Ok(arboard::ImageData { width: 2, height: 1, bytes: Cow::Owned(vec![0; 8]) })), + Request::Files => Answer::Files(vec![PathBuf::from("art.svg")]), + }) + .unwrap(); + let wait = Duration::from_secs(600); + assert_eq!(read_within(&mut reads, Request::Text, wait).text(), Ok("".to_string())); + assert_eq!(read_within(&mut reads, Request::Image, wait).image().map(|i| (i.width, i.height)), Ok((2, 1))); + assert_eq!(read_within(&mut reads, Request::Files, wait).files(), [PathBuf::from("art.svg")]); + // The answer to another read is not taken for this one. + assert_eq!(Answer::Files(vec![]).text(), Err(MIXED.to_string())); + assert!(Answer::Text(Ok(String::new())).image().is_err()); + assert!(Answer::Text(Ok("art.svg".into())).files().is_empty()); + } + + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + #[test] + fn arboards_reads_run_on_its_reader_and_wait_by_kind() { + let reads = Loads::spawn("test", Duration::ZERO, |request| match request { + Request::Text => Answer::Text(Ok("read on the worker".into())), + _ => Answer::failed(request, "not asked".into()), + }) + .unwrap(); + // `()` for writes: a read made through the write handle wouldn't build. + let mut cb = Arboard { reads, unanswered: None, cb: () }; + assert_eq!(cb.read(Request::Text).text(), Ok("read on the worker".to_string())); + assert_eq!(wait_for(Request::Text), super::super::loads::LOAD_WAIT); + assert_eq!(wait_for(Request::Files), super::super::loads::LOAD_WAIT); + assert_eq!(wait_for(Request::Image), Duration::from_secs(10)); + // A paste's reads after a late answer wait until 10 s after the unanswered read was + // sent, and never less than any read of their kind. + let sent = Instant::now(); + assert_eq!(follow_up_wait(Request::Text, sent, sent + Duration::from_secs(3)), Duration::from_secs(7)); + assert_eq!(follow_up_wait(Request::Files, sent, sent + Duration::from_secs(9)), super::super::loads::LOAD_WAIT); + assert_eq!(follow_up_wait(Request::Image, sent, sent + Duration::from_secs(20)), IMAGE_WAIT); + // X11 waits for an unanswered read when the clipboard closes; data-control doesn't. + assert_eq!(finish(false), X11_READ_LIMIT); + assert_eq!(finish(true), Duration::ZERO); + } + + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + #[test] + fn quitting_waits_for_the_paste_checks_handle_as_long_as_its_reads_last() { + // The Paste check's handle is one of these: when the app quits, its unanswered X11 read + // ends `X11_READ_LIMIT` after it was sent, and an idle worker stops within `LOAD_WAIT`. + // Quitting waits for that handle until both are over. + assert!(vectorcraft_ui_egui::CLIPBOARD_PROBE_STOP_WAIT >= finish(false) + super::super::loads::LOAD_WAIT); + assert!(vectorcraft_ui_egui::CLIPBOARD_PROBE_STOP_WAIT >= finish(true) + super::super::loads::LOAD_WAIT); + } + + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + #[test] + fn a_bitmap_paste_waits_for_the_owner_off_the_ui_thread() { + let (release, gate) = std::sync::mpsc::channel::<()>(); + // The app that copied sends its bitmap only when released. + let reads = Loads::spawn("test", Duration::ZERO, move |request| match request { + Request::Image => { + let _ = gate.recv(); + Answer::Image(Ok(arboard::ImageData { width: 2, height: 1, bytes: Cow::Owned(vec![0; 8]) })) + } + _ => Answer::failed(request, "not asked".into()), + }) + .unwrap(); + let mut cb = Arboard { reads, unanswered: None, cb: () }; + // The read is sent and the UI thread goes on without its answer. + let work = cb.image_later().unwrap(); + // A check on the UI thread meanwhile fails at once instead of waiting behind it. + assert!(cb.read(Request::Text).text().is_err()); + let paste = std::thread::spawn(work); + release.send(()).unwrap(); + assert_eq!(paste.join().ok().and_then(Result::ok).map(|i| (i.width, i.height)), Some((2, 1))); + } + + /// An arboard clipboard whose owner answers each read with `answer` only once the sender + /// returned is used or dropped. + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + fn slow_owner(answer: impl Fn(Request) -> Answer + Send + 'static) -> (Arboard<()>, std::sync::mpsc::Sender<()>) { + let (release, gate) = std::sync::mpsc::channel::<()>(); + let reads = Loads::spawn("test", Duration::ZERO, move |request| { + let _ = gate.recv(); + answer(request) + }) + .unwrap(); + (Arboard { reads, unanswered: None, cb: () }, release) + } + + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + #[test] + fn a_paste_after_an_unanswered_ownership_check_waits_for_its_answer() { + let image = |width: usize| Answer::Image(Ok(arboard::ImageData { width, height: 1, bytes: Cow::Owned(vec![0; width * 4]) })); + // A 2×1 bitmap was copied here; the clipboard's owner sends a `width`×1 one late. + let paste_after_check = |width: usize| { + let (mut cb, release) = slow_owner(move |_| image(width)); + // The check whether the clipboard still holds what was copied here gets no answer + // in its wait (2 s on the UI thread, none here). + assert!(cb.read_waiting(Request::Image, Duration::ZERO).image().is_err()); + // The paste's own reads fail at once while the owner hasn't answered. + assert!(cb.read(Request::Files).files().is_empty()); + assert!(cb.read(Request::Text).text().is_err()); + assert!(cb.image_later().is_err()); + // The paste waits for the check's answer off the UI thread instead. + let unanswered = cb.unanswered(&vectorcraft_engine::cmd::clipboard::PASTE_ORDER).expect("the check's read is kept for the paste"); + let paste = std::thread::spawn(move || unanswered.paste(Some(&Ours::Image(2, 1)), &[BITMAP])); + drop(release); + paste.join().ok().flatten() + }; + // Another app's bitmap is pasted, not the art copied here. + let pasted = paste_after_check(3).expect("the new bitmap is pasted"); + assert_eq!((pasted.mime, decode_png(&pasted.data).map(|i| i.dimensions())), (PNG, Some((3, 1)))); + // The bitmap copied here: the paste takes the internal clipboard. + assert!(paste_after_check(2).is_none()); + } + + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + #[test] + fn a_late_answer_to_an_ownership_check_is_pasted_only_while_it_is_awaited() { + // Text was copied here; the clipboard's owner answers the check with `text` late, and + // has a 3×1 bitmap. + let paste_after_check = |text: &'static str| { + let (mut cb, release) = slow_owner(move |request| match request { + Request::Text => Answer::Text(Ok(text.into())), + Request::Image => Answer::Image(Ok(arboard::ImageData { width: 3, height: 1, bytes: Cow::Owned(vec![0; 12]) })), + Request::Files => Answer::Files(vec![]), + }); + assert!(cb.read_waiting(Request::Text, Duration::ZERO).text().is_err()); + // A paste of a bitmap alone can't take a text read's answer: the read stays kept. + assert!(cb.unanswered(&[BITMAP]).is_none()); + let unanswered = cb.unanswered(&vectorcraft_engine::cmd::clipboard::PASTE_ORDER).expect("the check's read is kept for the paste"); + let ours = Ours::Text("copied here".into()); + let paste = std::thread::spawn(move || unanswered.paste(Some(&ours), &vectorcraft_engine::cmd::clipboard::PASTE_ORDER)); + drop(release); + paste.join().ok().flatten() + }; + let pasted = paste_after_check("copied elsewhere").expect("the other app's text is pasted"); + assert_eq!((pasted.mime, pasted.data), (TEXT, b"copied elsewhere".to_vec())); + // Text that only names a picture goes with it: the picture is pasted, as at once. + let pasted = paste_after_check("").expect("the picture is pasted"); + assert_eq!((pasted.mime, decode_png(&pasted.data).map(|i| i.dimensions())), (PNG, Some((3, 1)))); + // The text copied here: the paste takes the internal clipboard. + assert!(paste_after_check("copied here").is_none()); + + // A paste's own file-list read that gets no answer: once it comes, the text is read. + let (mut cb, release) = slow_owner(|request| match request { + Request::Text => Answer::Text(Ok("late text".into())), + _ => Answer::failed(request, "none".into()), + }); + assert!(cb.read_waiting(Request::Files, Duration::ZERO).files().is_empty()); + let unanswered = cb.unanswered(&[TEXT]).expect("the file-list read is kept for the paste"); + let paste = std::thread::spawn(move || unanswered.paste(None, &[TEXT])); + drop(release); + assert_eq!(paste.join().ok().flatten().map(|f| f.data), Some(b"late text".to_vec())); + + // A paste of text alone pastes text that names a picture, not the picture. + let (mut cb, release) = slow_owner(|request| match request { + Request::Text => Answer::Text(Ok("".into())), + Request::Image => Answer::Image(Ok(arboard::ImageData { width: 3, height: 1, bytes: Cow::Owned(vec![0; 12]) })), + Request::Files => Answer::Files(vec![]), + }); + assert!(cb.read_waiting(Request::Text, Duration::ZERO).text().is_err()); + let unanswered = cb.unanswered(&[TEXT]).expect("the text read is kept for the paste"); + let paste = std::thread::spawn(move || unanswered.paste(None, &[TEXT])); + drop(release); + let pasted = paste.join().ok().flatten().expect("the text is pasted"); + assert_eq!((pasted.mime, pasted.data), (TEXT, b"".to_vec())); + + // The app that answers late may have lost the clipboard meanwhile: the paste reads it + // again and takes the new owner's text. + let texts_read = std::sync::atomic::AtomicUsize::new(0); + let (mut cb, release) = slow_owner(move |request| match request { + Request::Text if texts_read.fetch_add(1, std::sync::atomic::Ordering::SeqCst) == 0 => Answer::Text(Ok("old owner".into())), + Request::Text => Answer::Text(Ok("new owner".into())), + _ => Answer::failed(request, "none".into()), + }); + assert!(cb.read_waiting(Request::Text, Duration::ZERO).text().is_err()); + let unanswered = cb.unanswered(&[TEXT]).expect("the text read is kept for the paste"); + let paste = std::thread::spawn(move || unanswered.paste(None, &[TEXT])); + drop(release); + assert_eq!(paste.join().ok().flatten().map(|f| f.data), Some(b"new owner".to_vec())); + + // An answer that came before the paste may be old: it is dropped, not pasted. + let (mut cb, release) = slow_owner(|request| Answer::failed(request, "not asked".into())); + assert!(cb.read_waiting(Request::Text, Duration::ZERO).text().is_err()); + drop(release); + while cb.reads.waiting() { + std::thread::yield_now(); + } + assert!(cb.unanswered(&[TEXT]).is_none()); + } + + #[cfg(target_os = "linux")] + #[test] + fn a_paste_after_an_unanswered_core_protocol_text_read_waits_for_its_answer() { + use std::sync::{Arc, Mutex}; + + use super::super::wayland::{Reads, Seen}; + use vectorcraft_engine::cmd::clipboard::PASTE_ORDER; + + /// Core protocol reads of a clipboard offering `types`, whose owner answers each read + /// of a text type with `text` and of `image/png` with `png`, only once the sender + /// returned is used or dropped. + fn slow_owner(types: &[&str], text: &'static str, png: &'static [u8]) -> (Reads, Arc>, std::sync::mpsc::Sender<()>) { + let (release, gate) = std::sync::mpsc::channel::<()>(); + let loads = Loads::spawn("test", Duration::ZERO, move |wire: String| { + let _ = gate.recv(); + Ok(if wire == PNG { png.to_vec() } else { text.as_bytes().to_vec() }) + }) + .unwrap(); + let seen = Arc::new(Mutex::new(Seen::offering(types))); + (Reads::new(loads, seen.clone()), seen, release) + } + // The clipboard's owner answers the check with `text` late; `copied_here` when the + // clipboard holds the Copy made here meanwhile. + let paste_after_check = |text: &'static str, copied_here: bool| { + let (mut reads, seen, release) = slow_owner(&["text/plain;charset=utf-8", PNG], text, b"\x89PNG"); + // The check whether the clipboard still holds what was copied here gets no answer + // in its wait (2 s on the UI thread, none here). + assert!(reads.text(Duration::ZERO).is_err()); + // The paste's own read fails at once while the owner hasn't answered. + assert!(reads.text(Duration::from_secs(600)).is_err()); + // A paste of a bitmap alone can't take text: the read stays kept. + assert!(reads.unanswered(&[BITMAP]).is_none()); + let late = Late::Wayland(reads.unanswered(&PASTE_ORDER).expect("the check's read is kept for the paste")); + if copied_here { + let mut seen = seen.lock().unwrap(); + seen.copy(vec!["text/plain;charset=utf-8", PNG]); + seen.selection(vec!["text/plain;charset=utf-8".into(), PNG.into()]); + } + let paste = std::thread::spawn(move || late.paste(None, &PASTE_ORDER)); + drop(release); + paste.join().ok().flatten() + }; + let pasted = paste_after_check("copied elsewhere", false).expect("the other app's text is pasted"); + assert_eq!((pasted.mime, pasted.data), (TEXT, b"copied elsewhere".to_vec())); + // Text that only names a picture goes with it: the picture is pasted, as at once. + let pasted = paste_after_check("https://example.com/art.png", false).expect("the picture is pasted"); + assert_eq!((pasted.mime, pasted.data), (PNG, b"\x89PNG".to_vec())); + // The Copy made here, by its data source: the paste takes the internal clipboard. + assert!(paste_after_check("copied elsewhere", true).is_none()); + // Empty text is not pasted: the picture beside it is. + assert_eq!(paste_after_check("", false).map(|f| f.mime), Some(PNG)); + + // An answer that came before the paste may be old: it is dropped, not pasted. + let (mut reads, _, release) = slow_owner(&["text/plain"], "old", b""); + assert!(reads.text(Duration::ZERO).is_err()); + drop(release); + while reads.waiting() { + std::thread::yield_now(); + } + assert!(reads.unanswered(&[TEXT]).is_none()); + + // The app that answers late may have lost the clipboard meanwhile: the paste reads it + // again and takes the new owner's text. + let (release, gate) = std::sync::mpsc::channel::<()>(); + let mut texts_read = 0; + let loads = Loads::spawn("test", Duration::ZERO, move |_: String| { + let _ = gate.recv(); + texts_read += 1; + Ok(if texts_read == 1 { "old owner" } else { "new owner" }.as_bytes().to_vec()) + }) + .unwrap(); + let mut reads = Reads::new(loads, Arc::new(Mutex::new(Seen::offering(&["UTF8_STRING"])))); + assert!(reads.text(Duration::ZERO).is_err()); + let late = Late::Wayland(reads.unanswered(&[TEXT]).expect("the read is kept for the paste")); + let paste = std::thread::spawn(move || late.paste(None, &[TEXT])); + drop(release); + assert_eq!(paste.join().ok().flatten().map(|f| f.data), Some(b"new owner".to_vec())); + } + #[test] fn one_outage_is_logged_once_across_handles() { static LOGGED: AtomicBool = AtomicBool::new(false); @@ -781,162 +1783,915 @@ mod portable { /// The compositor's clipboard through the core data-device protocol (`wl_data_device`), on the /// window's own Wayland connection: what Copy and Paste use where the compositor lacks the /// data-control protocol arboard needs (GNOME) and there is no X11 to fall back on (the Flatpak on -/// a Wayland session). Text only (smithay-clipboard), and only while the window has focus, as the -/// protocol has it. A read waits [`LOAD_WAIT`] at most: smithay-clipboard waits for the owner's -/// data with no limit, so reads run on a worker of their own. +/// a Wayland session). A Copy offers its SVG as `image/svg+xml`, its PNG as `image/png` and its +/// text under each of [`TEXT_TYPES`]; Paste reads the clipboard's SVG, text and PNG, and the paste +/// check looks at the types offered without reading any data. The protocol gives the clipboard to +/// the window with the keyboard focus only. A worker thread handles the protocol's events and +/// starts a thread for each paste of a Copy's data by another app ([`MAX_SENDS`] at once). Reads +/// run on another worker and take [`MAX_BYTES`] at most; text waits [`LOAD_WAIT`] at most, SVG and +/// PNG as long as a paste's bitmap from arboard. A read that gets no answer in its wait is kept for +/// a paste to wait for off the UI thread, as arboard's are. #[cfg(target_os = "linux")] mod wayland { - use std::sync::Arc; - use std::sync::mpsc; - use std::time::Duration; + use std::io::{Read, Write}; + use std::os::fd::AsFd as _; + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + use std::sync::{Arc, Mutex, MutexGuard, PoisonError, mpsc}; + use std::time::{Duration, Instant}; - /// The longest a read waits for the selection's owner to send its text. - const LOAD_WAIT: Duration = Duration::from_secs(2); - /// What a read says once its worker has stopped. - const GONE: &str = "the clipboard's reader stopped"; + use vectorcraft_engine::cmd::clipboard::names_a_picture; + use vectorcraft_ui_egui::ClipboardRead; + use wayland_client::backend::ObjectData; + use wayland_client::globals::{GlobalListContents, registry_queue_init}; + use wayland_client::protocol::wl_callback::{self, WlCallback}; + use wayland_client::protocol::wl_data_device::{self, WlDataDevice}; + use wayland_client::protocol::wl_data_device_manager::{self, WlDataDeviceManager}; + use wayland_client::protocol::wl_data_offer::{self, WlDataOffer}; + use wayland_client::protocol::wl_data_source::{self, WlDataSource}; + use wayland_client::protocol::wl_keyboard::{self, WlKeyboard}; + use wayland_client::protocol::wl_pointer::{self, WlPointer}; + use wayland_client::protocol::wl_registry::{self, WlRegistry}; + use wayland_client::protocol::wl_seat::{self, WlSeat}; + use wayland_client::{Connection, Dispatch, Proxy, QueueHandle, WEnum}; - pub struct TextClipboard { - /// Writes: a store only hands the text to smithay-clipboard's thread. - cb: smithay_clipboard::Clipboard, - /// Reads, on a worker with a second clipboard on the same connection. - loads: Loads, - /// Held as long as the clipboards: their connection is the window's. - _window: Arc, + use super::loads::{Asker, GONE, LOAD_WAIT, Loads, wait_for_answer}; + use super::{BITMAP, Flavour, PNG, SVG, TEXT}; + + /// The types text is offered under and read from, best first: `text/plain;charset=utf-8` (GTK + /// and Qt apps), `UTF8_STRING` (X11 apps through XWayland) and `text/plain`. + const TEXT_TYPES: [&str; 3] = ["text/plain;charset=utf-8", "UTF8_STRING", "text/plain"]; + /// The most bytes a read takes from the app that copied (untrusted data), VectorCraft's own + /// limit: a read of more fails. + const MAX_BYTES: usize = 64 << 20; + /// The most pastes of a Copy's data that are sent at once; a paste beyond them gets nothing. + const MAX_SENDS: usize = 8; + /// The most types of an offer that are kept (untrusted data). + const MAX_TYPES: usize = 256; + + /// What a read gives: the bytes, or why there are none. + type Got = Result, String>; + + fn lock(m: &Mutex) -> MutexGuard<'_, T> { + m.lock().unwrap_or_else(PoisonError::into_inner) } - /// The read worker's clipboard and the window whose connection it uses, dropped in that order. - struct Loader { - cb: smithay_clipboard::Clipboard, - _window: Arc, + /// The types a Copy of `flavours` offers, each with its data: SVG as `image/svg+xml`, PNG as + /// `image/png` and text under each of [`TEXT_TYPES`]. Flavours with no data and other flavours + /// (PDF) are not offered. + fn copy_types(flavours: &[Flavour]) -> Vec<(&'static str, Arc<[u8]>)> { + let mut out: Vec<(&'static str, Arc<[u8]>)> = vec![]; + for f in flavours.iter().filter(|f| !f.data.is_empty()) { + let types: &[&'static str] = match f.mime { + SVG => &[SVG], + PNG => &[PNG], + TEXT => &TEXT_TYPES, + _ => &[], + }; + let data: Arc<[u8]> = f.data.as_slice().into(); + for &t in types { + if !out.iter().any(|(o, _)| *o == t) { + out.push((t, data.clone())); + } + } + } + out } - impl Loader { - fn load(&self) -> Result { - self.cb.load().map_err(|e| e.to_string()) + /// The type among `offered` that a read of `mime` asks for, in any letter case: SVG as + /// `image/svg+xml`, text as the first of [`TEXT_TYPES`] offered, a bitmap as `image/png`. + fn wire_type<'a>(mime: &str, offered: &'a [String]) -> Option<&'a str> { + let wanted: &[&str] = match mime { + SVG => &[SVG], + TEXT => &TEXT_TYPES, + BITMAP | PNG => &[PNG], + _ => &[], + }; + wanted.iter().find_map(|w| offered.iter().find(|o| o.eq_ignore_ascii_case(w))).map(String::as_str) + } + + /// The flavour a read of `mime` makes of `data`: SVG as it is, a bitmap as PNG, text with its + /// line ends as `\n`. None when `data` is empty. + fn flavour(mime: &'static str, data: Vec) -> Option { + if data.is_empty() { + return None; + } + Some(match mime { + TEXT => Flavour { mime: TEXT, data: String::from_utf8_lossy(&data).replace("\r\n", "\n").replace('\r', "\n").into_bytes() }, + BITMAP | PNG => Flavour { mime: PNG, data }, + _ => Flavour { mime, data }, + }) + } + + /// What a paste of one of `mimes` takes from a clipboard offering `offered`, `read` reading the + /// offer's type for each one tried: the first of `mimes` offered with data, except that text + /// that is blank or only names a picture gives way to the PNG when `mimes` has a bitmap + /// (`adopt_system_clipboard_or_defer` in `vectorcraft-ui-egui`). + fn pick(offered: &[String], mimes: &[&'static str], mut read: impl FnMut(&str) -> Option>) -> Option { + let mut take = |mime: &'static str| flavour(mime, read(wire_type(mime, offered)?)?); + let first = mimes.iter().find_map(|&m| take(m))?; + if first.mime == TEXT && mimes.contains(&BITMAP) { + let text = String::from_utf8_lossy(&first.data); + if text.trim().is_empty() || names_a_picture(&text) { + return take(BITMAP).or(Some(first)); + } + } + Some(first) + } + + /// `from` read to its end, `cap` bytes at most: more is an error, as is a failed read. + fn read_capped(from: impl Read, cap: usize) -> Got { + let mut data = vec![]; + from.take(cap as u64 + 1).read_to_end(&mut data).map_err(|e| format!("couldn't read the clipboard's data: {e}"))?; + if data.len() > cap { + return Err(format!("the clipboard's data is larger than {} MiB", cap >> 20)); + } + Ok(data) + } + + /// The threads that send a Copy's data to the apps that paste it, counted. + #[derive(Clone, Default)] + struct Sends(Arc); + + impl Sends { + /// `data` written to `to` on a thread of its own, which then closes `to`; an app that + /// closes its end early ends the write (the process ignores `SIGPIPE`). While + /// [`MAX_SENDS`] are being written `to` is closed at once with nothing written → false. + fn start(&self, mut to: impl Write + Send + 'static, data: Arc<[u8]>) -> bool { + if self.0.fetch_add(1, Ordering::SeqCst) >= MAX_SENDS { + self.0.fetch_sub(1, Ordering::SeqCst); + return false; + } + let count = self.0.clone(); + let send = move || { + let _ = to.write_all(&data); + drop(to); + count.fetch_sub(1, Ordering::SeqCst); + }; + if std::thread::Builder::new().name("wayland-clipboard-send".into()).spawn(send).is_err() { + self.0.fetch_sub(1, Ordering::SeqCst); + return false; + } + true + } + + /// How many are being written. + #[cfg(test)] + fn running(&self) -> usize { + self.0.load(Ordering::SeqCst) } } - impl TextClipboard { - /// None when `window` isn't a Wayland window or the read worker can't start. - #[allow(unsafe_code)] - pub fn new(window: Arc) -> Option { - use winit::raw_window_handle::{HasDisplayHandle as _, RawDisplayHandle}; - let RawDisplayHandle::Wayland(d) = window.display_handle().ok()?.as_raw() else { return None }; - let display = d.display.as_ptr(); - // SAFETY: the display is winit's open `wl_display`, which outlives `window`; each - // clipboard is held beside a clone of `window` and dropped before it. smithay-clipboard - // makes its own event queue on the display and doesn't close it. - let (cb, reader) = unsafe { (smithay_clipboard::Clipboard::new(display), smithay_clipboard::Clipboard::new(display)) }; - let loader = Loader { cb: reader, _window: window.clone() }; - // `loader.load()`, not `loader.cb.load()`: a closure moves only the fields it names, - // and the worker must hold the window as long as its clipboard. - let loads = Loads::spawn(move || loader.load())?; - Some(Self { cb, loads, _window: window }) + /// What the protocol worker has seen of the clipboard. + #[derive(Default)] + pub(super) struct Seen { + /// The types of the clipboard's offer, none when it is empty. + offered: Vec, + /// The types of this connection's last Copy, until its data source is canceled. + copied: Option>, + /// Whether the clipboard holds that Copy. + ours: bool, + } + + impl Seen { + /// A clipboard offering `types`, copied elsewhere. + #[cfg(test)] + pub(super) fn offering(types: &[&str]) -> Self { + Self { offered: types.iter().map(|t| t.to_string()).collect(), ..Self::default() } } - pub fn get_text(&mut self) -> Result { - self.loads.get(LOAD_WAIT) + /// A Copy of `types` (none: the clipboard emptied) was given the clipboard. + pub(super) fn copy(&mut self, types: Vec<&'static str>) { + self.ours = !types.is_empty(); + self.copied = Some(types).filter(|t| !t.is_empty()); } - pub fn set_text(&self, text: &str) { - self.cb.store(text); + /// The clipboard's offer has `offered` now. It holds the last Copy while that Copy's data + /// source is not canceled and the offer has the Copy's types, no more and no fewer, as the + /// compositor offers a source's types. An offer made before the Copy and handled after it + /// makes the Copy not ours until the Copy's own offer comes. + pub(super) fn selection(&mut self, offered: Vec) { + self.ours = self.copied.as_ref().is_some_and(|c| c.len() == offered.len() && c.iter().all(|t| offered.iter().any(|o| o == t))); + self.offered = offered; + } + + /// The last Copy's data source was canceled: another app holds the clipboard. + pub(super) fn cancelled(&mut self) { + self.copied = None; + self.ours = false; } } - /// Reads made on a worker thread and waited for a bounded time: a selection owner that never - /// sends its data holds the worker, not the caller. - struct Loads { - requests: mpsc::Sender<()>, - answers: mpsc::Receiver>, - /// A read that timed out and hasn't answered yet: until it does, reads don't queue behind it. - pending: bool, + /// Reads of the clipboard's offer on a worker, and the last one that got no answer in its wait. + pub(super) struct Reads { + /// Each request is the offer's type to read. + loads: Loads, + seen: Arc>, + /// The last text read that got no answer in its wait, until a paste takes it or the next + /// read is sent. + unanswered: Option, } - impl Loads { - fn spawn(mut load: impl FnMut() -> Result + Send + 'static) -> Option { - let (requests, asked) = mpsc::channel::<()>(); - let (answer, answers) = mpsc::channel(); - let work = move || { - while asked.recv().is_ok() { - if answer.send(load()).is_err() { - break; + /// A text read that got no answer in its wait. + pub(super) struct Unanswered { + answer: mpsc::Receiver, + sent: Instant, + /// The worker, for the reads made once the answer comes. + reads: Asker, + seen: Arc>, + } + + impl Unanswered { + /// What a paste of one of `mimes` takes once this read's answer comes, waiting for it until + /// `limit` after the read was sent: the clipboard read again as [`pick`] reads it, each read + /// waiting as long, [`LOAD_WAIT`] at least, since the app that answers late may have lost the + /// clipboard meanwhile. None when the answer doesn't come or the clipboard holds this + /// connection's Copy. + pub(super) fn paste(self, mimes: &[&'static str], limit: Duration) -> Option { + let left = |now: Instant| (self.sent + limit).saturating_duration_since(now); + let _late = wait_for_answer(&self.answer, left(Instant::now())).ok()?; + let offered = { + let seen = lock(&self.seen); + if seen.ours { + return None; + } + seen.offered.clone() + }; + pick(&offered, mimes, |wire| wait_for_answer(&self.reads.ask(wire.to_string()).ok()?, LOAD_WAIT.max(left(Instant::now()))).ok()?.ok()) + } + } + + impl Reads { + pub(super) fn new(loads: Loads, seen: Arc>) -> Self { + Self { loads, seen, unanswered: None } + } + + /// The offer's type for `mime`, when it has one. + fn wire(&self, mime: &str) -> Option { + wire_type(mime, &lock(&self.seen).offered).map(str::to_string) + } + + /// The text, waiting `wait` at most; empty when the clipboard has none. A read that gets no + /// answer in that time is kept ([`Self::unanswered`]) for a paste to wait for off the UI + /// thread; a read sent means the one kept has been answered, and its answer is dropped. + pub(super) fn text(&mut self, wait: Duration) -> Result { + let Some(wire) = self.wire(TEXT) else { return Ok(String::new()) }; + let sent = Instant::now(); + let answer = self.loads.ask(wire)?; + self.unanswered = None; + match wait_for_answer(&answer, wait) { + Ok(got) => Ok(flavour(TEXT, got?).map(|f| String::from_utf8_lossy(&f.data).into_owned()).unwrap_or_default()), + Err(why) => { + if why != GONE { + self.unanswered = Some(Unanswered { answer, sent, reads: self.loads.asker(), seen: self.seen.clone() }); + } + Err(why) + } + } + } + + /// What a paste of one of `mimes` reads: the first the clipboard offers. Text is read here, + /// [`LOAD_WAIT`] at most, and pasted unless it is empty; SVG and PNG are asked for here and + /// waited for, `wait` at most, by the work that comes back. When that read fails or is + /// empty, the work reads the rest of `mimes` as [`pick`] does, each read waiting until + /// `wait` after the first was sent, [`LOAD_WAIT`] at least. + pub(super) fn read(&mut self, mimes: &[&'static str], wait: Duration) -> Option { + mimes.iter().enumerate().find_map(|(i, &mime)| { + let wire = self.wire(mime)?; + if mime == TEXT { + let text = self.text(LOAD_WAIT).ok().filter(|t| !t.is_empty())?; + return Some(ClipboardRead::Now(Flavour { mime: TEXT, data: text.into_bytes() })); + } + let sent = Instant::now(); + let answer = self.loads.ask(wire).ok()?; + self.unanswered = None; + let (reads, seen, rest) = (self.loads.asker(), self.seen.clone(), mimes.get(i + 1..).unwrap_or_default().to_vec()); + Some(ClipboardRead::Later(Box::new(move || { + if let Some(f) = wait_for_answer(&answer, wait).ok().and_then(Result::ok).and_then(|data| flavour(mime, data)) { + return Some(f); + } + let offered = lock(&seen).offered.clone(); + let left = || LOAD_WAIT.max((sent + wait).saturating_duration_since(Instant::now())); + pick(&offered, &rest, |wire| wait_for_answer(&reads.ask(wire.to_string()).ok()?, left()).ok()?.ok()) + }))) + }) + } + + /// Whether the clipboard offers one of `mimes`; nothing is read. + pub(super) fn has(&self, mimes: &[&'static str]) -> bool { + let seen = lock(&self.seen); + mimes.iter().any(|m| wire_type(m, &seen.offered).is_some()) + } + + /// Whether the clipboard holds this connection's last Copy. + pub(super) fn holds_ours(&self) -> bool { + lock(&self.seen).ours + } + + /// The text read that got no answer in its wait, while its answer has still not come and a + /// paste of one of `mimes` can take text. Once it has come the answer may be old, and it is + /// dropped: a new read is made. + pub(super) fn unanswered(&mut self, mimes: &[&'static str]) -> Option { + let unanswered = self.unanswered.take_if(|_| mimes.contains(&TEXT))?; + self.loads.waiting().then_some(unanswered) + } + + /// Drops the read that got no answer in its wait: a paste no longer takes its answer. + pub(super) fn forget_unanswered(&mut self) { + self.unanswered = None; + } + + /// Whether a read sent is still unanswered. + #[cfg(test)] + pub(super) fn waiting(&self) -> bool { + self.loads.waiting() + } + } + + /// The protocol objects of a [`DataClipboard`], kept up to date by its worker. + #[derive(Default)] + struct Objects { + device: Option, + keyboard: Option, + pointer: Option, + /// The serial of the last key press, click or keyboard focus, which a Copy takes the + /// clipboard with. + serial: Option, + /// The clipboard's offer. + selection: Option, + /// The offer of a drag over the window. + drag: Option, + /// The last Copy's data source. + source: Option, + } + + /// An offer's types, as its events give them. + #[derive(Default)] + struct OfferData(Mutex>); + + /// A Copy's types with their data. + struct SourceData(Vec<(&'static str, Arc<[u8]>)>); + + /// What the protocol worker's event handlers change. + struct State { + objects: Arc>, + seen: Arc>, + sends: Sends, + } + + impl State { + /// Lets go of every object, once the clipboard is dropped. + fn close(&mut self, seat: &WlSeat) { + let mut o = lock(&self.objects); + for offer in [o.selection.take(), o.drag.take()].into_iter().flatten() { + offer.destroy(); + } + if let Some(source) = o.source.take() { + source.destroy(); + } + if let Some(device) = o.device.take().filter(|d| d.version() >= 2) { + device.release(); + } + if let Some(keyboard) = o.keyboard.take().filter(|k| k.version() >= 3) { + keyboard.release(); + } + if let Some(pointer) = o.pointer.take().filter(|p| p.version() >= 3) { + pointer.release(); + } + if seat.version() >= 5 { + seat.release(); + } + } + } + + impl Dispatch for State { + fn event(_: &mut Self, _: &WlRegistry, _: wl_registry::Event, _: &GlobalListContents, _: &Connection, _: &QueueHandle) {} + } + + impl Dispatch for State { + fn event(_: &mut Self, _: &WlCallback, _: wl_callback::Event, _: &(), _: &Connection, _: &QueueHandle) {} + } + + impl Dispatch for State { + fn event(_: &mut Self, _: &WlDataDeviceManager, _: wl_data_device_manager::Event, _: &(), _: &Connection, _: &QueueHandle) {} + } + + impl Dispatch for State { + fn event(state: &mut Self, seat: &WlSeat, event: wl_seat::Event, _: &(), _: &Connection, qh: &QueueHandle) { + let wl_seat::Event::Capabilities { capabilities: WEnum::Value(caps) } = event else { return }; + let mut o = lock(&state.objects); + if !caps.contains(wl_seat::Capability::Keyboard) { + if let Some(keyboard) = o.keyboard.take().filter(|k| k.version() >= 3) { + keyboard.release(); + } + } else if o.keyboard.is_none() { + o.keyboard = Some(seat.get_keyboard(qh, ())); + } + if !caps.contains(wl_seat::Capability::Pointer) { + if let Some(pointer) = o.pointer.take().filter(|p| p.version() >= 3) { + pointer.release(); + } + } else if o.pointer.is_none() { + o.pointer = Some(seat.get_pointer(qh, ())); + } + } + } + + /// The serial a Copy takes the clipboard with after the keyboard event `event`, `serial` before + /// it: a key or the keyboard focus coming in sets it, the focus leaving clears it, and other + /// events leave it. A modifier change's serial is not an input event's, and the release of Ctrl + /// after Ctrl+C comes before the Copy's data is ready. + fn keyboard_serial(event: &wl_keyboard::Event, serial: Option) -> Option { + match event { + wl_keyboard::Event::Enter { serial, .. } | wl_keyboard::Event::Key { serial, .. } => Some(*serial), + wl_keyboard::Event::Leave { .. } => None, + _ => serial, + } + } + + impl Dispatch for State { + fn event(state: &mut Self, _: &WlKeyboard, event: wl_keyboard::Event, _: &(), _: &Connection, _: &QueueHandle) { + let mut o = lock(&state.objects); + o.serial = keyboard_serial(&event, o.serial); + } + } + + impl Dispatch for State { + fn event(state: &mut Self, _: &WlPointer, event: wl_pointer::Event, _: &(), _: &Connection, _: &QueueHandle) { + if let wl_pointer::Event::Button { serial, .. } = event { + lock(&state.objects).serial = Some(serial); + } + } + } + + impl Dispatch for State { + fn event(state: &mut Self, _: &WlDataDevice, event: wl_data_device::Event, _: &(), _: &Connection, _: &QueueHandle) { + let mut o = lock(&state.objects); + match event { + wl_data_device::Event::Selection { id } => { + let mut offered = id.as_ref().and_then(|offer| offer.data::()).map(|d| lock(&d.0).clone()).unwrap_or_default(); + offered.dedup(); + if let Some(old) = std::mem::replace(&mut o.selection, id) { + old.destroy(); + } + lock(&state.seen).selection(offered); + } + wl_data_device::Event::Enter { id, .. } => { + if let Some(old) = std::mem::replace(&mut o.drag, id) { + old.destroy(); } } - }; - std::thread::Builder::new().name("wayland-clipboard-read".into()).spawn(work).ok()?; - Some(Self { requests, answers, pending: false }) + wl_data_device::Event::Leave | wl_data_device::Event::Drop => { + if let Some(old) = o.drag.take() { + old.destroy(); + } + } + _ => {} + } } - /// The text, or why there is none, after `wait` at most. - fn get(&mut self, wait: Duration) -> Result { - if self.pending { - match self.answers.try_recv() { - // The late answer of the read that timed out: stale by now. - Ok(_) => self.pending = false, - Err(mpsc::TryRecvError::Empty) => return Err("the clipboard's owner hasn't answered an earlier read".into()), - Err(mpsc::TryRecvError::Disconnected) => return Err(GONE.into()), + /// The one event of a data device that makes an object is `data_offer`. + fn event_created_child(_: u16, qh: &QueueHandle) -> Arc { + qh.make_data::(OfferData::default()) + } + } + + impl Dispatch for State { + fn event(_: &mut Self, _: &WlDataOffer, event: wl_data_offer::Event, data: &OfferData, _: &Connection, _: &QueueHandle) { + if let wl_data_offer::Event::Offer { mime_type } = event { + let mut types = lock(&data.0); + if types.len() < MAX_TYPES { + types.push(mime_type); } } - self.requests.send(()).map_err(|_| GONE.to_string())?; - match self.answers.recv_timeout(wait) { - Ok(text) => text, - Err(mpsc::RecvTimeoutError::Timeout) => { - self.pending = true; - Err(format!("the clipboard's owner didn't send its text within {wait:?}")) - } - Err(mpsc::RecvTimeoutError::Disconnected) => Err(GONE.into()), - } } } + impl Dispatch for State { + fn event(state: &mut Self, source: &WlDataSource, event: wl_data_source::Event, data: &SourceData, _: &Connection, _: &QueueHandle) { + match event { + // A type the Copy doesn't offer gets nothing: dropping `fd` closes it. + wl_data_source::Event::Send { mime_type, fd } => { + if let Some((_, bytes)) = data.0.iter().find(|(t, _)| t.eq_ignore_ascii_case(&mime_type)) { + state.sends.start(std::fs::File::from(fd), bytes.clone()); + } + } + wl_data_source::Event::Cancelled => { + source.destroy(); + let mut o = lock(&state.objects); + if o.source.as_ref() == Some(source) { + o.source = None; + lock(&state.seen).cancelled(); + } + } + _ => {} + } + } + } + + /// Reads the clipboard's offer for the read worker. + struct Receiver { + conn: Connection, + objects: Arc>, + /// Held as long as the connection, which is the window's. + _window: Arc, + } + + impl Receiver { + /// The clipboard's data of type `wire`, read until the app that copied closes the pipe, + /// [`MAX_BYTES`] at most. + fn receive(&self, wire: String) -> Got { + let offer = lock(&self.objects).selection.clone().ok_or("the clipboard is empty")?; + let (from, to) = std::io::pipe().map_err(|e| format!("couldn't open a pipe for the clipboard's data: {e}"))?; + offer.receive(wire, to.as_fd()); + // The request carries a copy of the write end: once it is sent, the app that copied + // holds the only one, and the read ends when that app closes it. + drop(to); + self.conn.flush().map_err(|e| format!("couldn't reach the compositor: {e}"))?; + read_capped(from, MAX_BYTES) + } + } + + pub struct DataClipboard { + reads: Reads, + objects: Arc>, + manager: WlDataDeviceManager, + conn: Connection, + qh: QueueHandle, + /// Tells the protocol worker to stop. + stop: Arc, + /// Held as long as the connection, which is the window's. + _window: Arc, + } + + impl DataClipboard { + /// None when `window` isn't a Wayland window, the compositor has no data-device manager or + /// seat, or a worker can't start. + pub fn new(window: Arc) -> Option { + let conn = connection(&window)?; + let (globals, mut queue) = registry_queue_init::(&conn).ok()?; + let qh = queue.handle(); + let manager: WlDataDeviceManager = globals.bind(&qh, 1..=3, ()).ok()?; + let seat: WlSeat = globals.bind(&qh, 1..=5, ()).ok()?; + let (objects, seen) = (Arc::>::default(), Arc::>::default()); + lock(&objects).device = Some(manager.get_data_device(&seat, &qh, ())); + let mut state = State { objects: objects.clone(), seen: seen.clone(), sends: Sends::default() }; + // The seat's keyboard and pointer, and the clipboard's offer when the window has focus. + queue.roundtrip(&mut state).ok()?; + let receiver = Receiver { conn: conn.clone(), objects: objects.clone(), _window: window.clone() }; + // Dropping doesn't wait for an unanswered read: only arboard's X11 handles hand what the + // app copied on when the last one goes. + let loads = Loads::spawn("wayland-clipboard-read", Duration::ZERO, move |wire| receiver.receive(wire))?; + let stop = Arc::new(AtomicBool::new(false)); + let (stopped, held) = (stop.clone(), window.clone()); + let work = move || { + while !stopped.load(Ordering::SeqCst) && queue.blocking_dispatch(&mut state).is_ok() {} + state.close(&seat); + let _ = queue.flush(); + drop(held); + }; + std::thread::Builder::new().name("wayland-clipboard".into()).spawn(work).ok()?; + Some(Self { reads: Reads::new(loads, seen), objects, manager, conn, qh, stop, _window: window }) + } + + /// Gives the clipboard to a Copy of `flavours` ([`copy_types`]); none empties it. Err when + /// the seat has no data device or the window has had no input to take the clipboard with. + pub fn copy(&mut self, flavours: &[Flavour]) -> Result<(), String> { + let offered = copy_types(flavours); + let mut o = lock(&self.objects); + let device = o.device.clone().ok_or("the seat has no clipboard")?; + let serial = o.serial.ok_or("the window has had no key press or click to copy with")?; + let types: Vec<&'static str> = offered.iter().map(|(t, _)| *t).collect(); + let source = (!offered.is_empty()).then(|| { + let source = self.manager.create_data_source(&self.qh, SourceData(offered)); + for t in &types { + source.offer(t.to_string()); + } + source + }); + device.set_selection(source.as_ref(), serial); + if let Some(old) = std::mem::replace(&mut o.source, source) { + old.destroy(); + } + lock(&self.reads.seen).copy(types); + drop(o); + self.conn.flush().map_err(|e| format!("couldn't reach the compositor: {e}")) + } + + pub fn text(&mut self) -> Result { + self.reads.text(LOAD_WAIT) + } + + /// What a paste of one of `mimes` reads ([`Reads::read`]), SVG and PNG waited for `wait` at + /// most. + pub fn read(&mut self, mimes: &[&'static str], wait: Duration) -> Option { + self.reads.read(mimes, wait) + } + + pub fn has(&self, mimes: &[&'static str]) -> bool { + self.reads.has(mimes) + } + + pub fn holds_ours(&self) -> bool { + self.reads.holds_ours() + } + + /// The read that got no answer in its wait, when a paste of one of `mimes` can take its + /// answer ([`Reads::unanswered`]). + pub(super) fn unanswered(&mut self, mimes: &[&'static str]) -> Option { + self.reads.unanswered(mimes) + } + + /// Drops the read that got no answer in its wait: a paste no longer takes its answer. + pub fn forget_unanswered(&mut self) { + self.reads.forget_unanswered(); + } + } + + impl Drop for DataClipboard { + /// Stops the protocol worker, which a sync request's answer wakes. + fn drop(&mut self) { + self.stop.store(true, Ordering::SeqCst); + let _ = self.conn.display().sync(&self.qh, ()); + let _ = self.conn.flush(); + } + } + + /// A connection on `window`'s Wayland display. + #[allow(unsafe_code)] + fn connection(window: &winit::window::Window) -> Option { + use wayland_backend::sys::client::Backend; + use winit::raw_window_handle::{HasDisplayHandle as _, RawDisplayHandle}; + let RawDisplayHandle::Wayland(d) = window.display_handle().ok()?.as_raw() else { return None }; + // SAFETY: the display is winit's open `wl_display`, which outlives `window`; every user of + // the connection holds a clone of `window`. A backend made from a foreign display does not + // close it when dropped. + let backend = unsafe { Backend::from_foreign_display(d.display.as_ptr().cast()) }; + Some(Connection::from_backend(backend)) + } + #[cfg(test)] mod tests { - use std::time::Instant; - use super::*; - #[test] - fn a_read_that_answers_in_time_gives_the_text() { - let mut loads = Loads::spawn(|| Ok("".into())).unwrap(); - assert_eq!(loads.get(Duration::from_secs(5)), Ok("".to_string())); - assert_eq!(loads.get(Duration::from_secs(5)), Ok("".to_string())); + fn flavour_of(mime: &'static str, data: &[u8]) -> Flavour { + Flavour { mime, data: data.to_vec() } + } + + fn offered(types: &[&str]) -> Vec { + types.iter().map(|t| t.to_string()).collect() } #[test] - fn an_owner_that_never_answers_holds_the_worker_not_the_caller() { - let (release, gate) = mpsc::channel::<()>(); - let mut calls = 0; - let mut loads = Loads::spawn(move || { - calls += 1; - if calls == 1 { - // The first owner sends nothing until released. - let _ = gate.recv(); - return Ok("stale".into()); + fn a_copy_offers_its_svg_png_and_text_each_with_its_own_data() { + let flavours = [flavour_of(TEXT, b""), flavour_of(SVG, b""), flavour_of(super::super::PDF, b"%PDF"), flavour_of(PNG, b"png")]; + let types: Vec<(&str, Vec)> = copy_types(&flavours).into_iter().map(|(t, d)| (t, d.to_vec())).collect(); + assert_eq!( + types, + [ + ("text/plain;charset=utf-8", b"".to_vec()), + ("UTF8_STRING", b"".to_vec()), + ("text/plain", b"".to_vec()), + (SVG, b"".to_vec()), + (PNG, b"png".to_vec()), + ] + ); + // With Include SVG Code off the engine makes no SVG flavour, and none is offered; a + // flavour with no data is not offered either. + let types: Vec<&str> = copy_types(&[flavour_of(PNG, b"png"), flavour_of(TEXT, b"")]).into_iter().map(|(t, _)| t).collect(); + assert_eq!(types, [PNG]); + assert!(copy_types(&[]).is_empty()); + } + + #[test] + fn a_read_asks_for_the_offers_own_type() { + let all = offered(&["text/plain", "TEXT", "UTF8_STRING", "Image/PNG", "image/svg+xml", "application/pdf"]); + assert_eq!(wire_type(TEXT, &all), Some("UTF8_STRING")); + assert_eq!(wire_type(TEXT, &offered(&["text/plain", "text/plain;charset=UTF-8"])), Some("text/plain;charset=UTF-8")); + assert_eq!(wire_type(BITMAP, &all), Some("Image/PNG")); + assert_eq!(wire_type(SVG, &all), Some("image/svg+xml")); + // PDF, EPS and metafiles are not read here, nor types no reader knows. + assert_eq!(wire_type(super::super::PDF, &all), None); + assert_eq!(wire_type(TEXT, &offered(&["text/html", "image/jpeg"])), None); + assert_eq!(wire_type(SVG, &[]), None); + } + + /// What a paste of `mimes` takes from a clipboard holding `data` by type, and the types read. + fn pasted(data: &[(&str, &[u8])], mimes: &[&'static str]) -> (Option, Vec) { + let types: Vec = data.iter().map(|(t, _)| t.to_string()).collect(); + let mut read = vec![]; + let f = pick(&types, mimes, |wire| { + read.push(wire.to_string()); + data.iter().find(|(t, _)| *t == wire).map(|(_, d)| d.to_vec()) + }); + (f, read) + } + + #[test] + fn a_paste_takes_svg_then_text_then_png() { + use vectorcraft_engine::cmd::clipboard::PASTE_ORDER; + let svg: (&str, &[u8]) = (SVG, b""); + let text: (&str, &[u8]) = ("text/plain;charset=utf-8", b"a\r\nb"); + let png: (&str, &[u8]) = (PNG, b"\x89PNG"); + let (f, read) = pasted(&[text, png, svg], &PASTE_ORDER); + assert_eq!(f.map(|f| (f.mime, f.data)), Some((SVG, svg.1.to_vec()))); + assert_eq!(read, [SVG]); + // Text before a bitmap, its line ends made `\n`. + let (f, _) = pasted(&[png, text], &PASTE_ORDER); + assert_eq!(f.map(|f| (f.mime, f.data)), Some((TEXT, b"a\nb".to_vec()))); + // An offer of a PNG or SVG alone pastes it. + assert_eq!(pasted(&[png], &PASTE_ORDER).0.map(|f| (f.mime, f.data)), Some((PNG, png.1.to_vec()))); + assert_eq!(pasted(&[svg], &PASTE_ORDER).0.map(|f| f.mime), Some(SVG)); + // Blank text, or text that only names a picture, gives way to the picture. + for beside in [&b" \n"[..], b"https://example.com/art.png", b""] { + let (f, read) = pasted(&[("UTF8_STRING", beside), png], &PASTE_ORDER); + assert_eq!(f.map(|f| f.mime), Some(PNG)); + assert_eq!(read, ["UTF8_STRING", PNG]); + } + // With no picture, or a paste of text alone, the text is what there is. + assert_eq!(pasted(&[("text/plain", &b"https://example.com/art.png"[..])], &PASTE_ORDER).0.map(|f| f.mime), Some(TEXT)); + assert_eq!(pasted(&[("text/plain", &b" "[..]), png], &[TEXT]).0.map(|f| f.mime), Some(TEXT)); + // An empty clipboard, a type no reader knows, data that doesn't come or is empty. + assert_eq!(pasted(&[], &PASTE_ORDER).0, None); + assert_eq!(pasted(&[("application/x-other", &b"x"[..])], &PASTE_ORDER).0, None); + assert_eq!(pasted(&[(PNG, &b""[..])], &PASTE_ORDER).0, None); + let types = offered(&[PNG]); + assert_eq!(pick(&types, &PASTE_ORDER, |_| None), None); + } + + #[test] + fn the_clipboard_holds_a_copy_until_another_app_takes_it() { + let mut seen = Seen::default(); + let types = vec!["text/plain;charset=utf-8", SVG, PNG]; + seen.copy(types.clone()); + assert!(seen.ours, "a Copy holds the clipboard before its offer comes"); + // An offer made before the Copy and handled after it. + seen.selection(offered(&[PNG])); + assert!(!seen.ours); + // The Copy's own offer, its types in another order. + seen.selection(offered(&[PNG, SVG, "text/plain;charset=utf-8"])); + assert!(seen.ours); + // Another app's copy: an offer with other types, then the source canceled. + seen.selection(offered(&[PNG, SVG, "text/plain;charset=utf-8", "text/html"])); + assert!(!seen.ours); + seen.selection(offered(&[PNG, SVG, "text/plain;charset=utf-8"])); + seen.cancelled(); + assert!(!seen.ours, "a canceled source no longer holds the clipboard"); + // Another app's offer with the same types after that is not ours. + seen.selection(offered(&[PNG, SVG, "text/plain;charset=utf-8"])); + assert!(!seen.ours); + // An empty Copy empties the clipboard. + seen.copy(vec![]); + assert!(!seen.ours); + seen.selection(vec![]); + assert!(!seen.ours && seen.offered.is_empty()); + } + + #[test] + fn a_copy_takes_the_clipboard_with_a_key_press_not_a_modifier_change() { + let key = |serial| wl_keyboard::Event::Key { serial, time: 0, key: 46, state: WEnum::Value(wl_keyboard::KeyState::Pressed) }; + let modifiers = |serial| wl_keyboard::Event::Modifiers { serial, mods_depressed: 0, mods_latched: 0, mods_locked: 0, group: 0 }; + // Ctrl+C, then Ctrl released before the Copy's data is ready. + let serial = keyboard_serial(&key(7), None); + assert_eq!(keyboard_serial(&modifiers(8), serial), Some(7)); + assert_eq!(keyboard_serial(&wl_keyboard::Event::RepeatInfo { rate: 25, delay: 600 }, Some(7)), Some(7)); + assert_eq!(keyboard_serial(&modifiers(9), None), None); + } + + #[test] + fn a_read_stops_at_its_limit() { + assert_eq!(MAX_BYTES, 64 * 1024 * 1024); + assert_eq!(read_capped(&b"12345678"[..], 8), Ok(b"12345678".to_vec())); + assert_eq!(read_capped(&b""[..], 8), Ok(vec![])); + assert_eq!(read_capped(&[0u8; 9][..], 8), Err("the clipboard's data is larger than 0 MiB".to_string())); + assert_eq!(read_capped(&vec![0u8; (2 << 20) + 1][..], 2 << 20), Err("the clipboard's data is larger than 2 MiB".to_string())); + /// A pipe that breaks. + struct Broken; + impl Read for Broken { + fn read(&mut self, _: &mut [u8]) -> std::io::Result { + Err(std::io::ErrorKind::BrokenPipe.into()) } - Ok("fresh".into()) + } + assert!(read_capped(Broken, 8).is_err_and(|e| e.starts_with("couldn't read the clipboard's data"))); + } + + #[test] + fn a_copys_data_is_sent_through_the_pipe_and_closed() { + let sends = Sends::default(); + let (from, to) = std::io::pipe().unwrap(); + let data: Arc<[u8]> = vec![7u8; 300_000].into(); + assert!(sends.start(to, data.clone())); + // More than a pipe holds: the write ends once all of it is read, then the pipe closes. + assert_eq!(read_capped(from, MAX_BYTES).as_deref(), Ok(&data[..])); + // An app that closes its end before reading ends the send. + let (from, to) = std::io::pipe().unwrap(); + drop(from); + assert!(sends.start(to, data.clone())); + while sends.running() > 0 { + std::thread::yield_now(); + } + } + + #[test] + fn pastes_that_read_nothing_hold_a_few_sends_at_most() { + let sends = Sends::default(); + let data: Arc<[u8]> = vec![1u8; 300_000].into(); + // Apps that ask for the data and never read it. + let stalled: Vec<_> = (0..MAX_SENDS) + .map(|_| { + let (from, to) = std::io::pipe().unwrap(); + assert!(sends.start(to, data.clone())); + from + }) + .collect(); + // The next paste gets its pipe closed at once, with nothing written. + let (from, to) = std::io::pipe().unwrap(); + assert!(!sends.start(to, data.clone())); + assert_eq!(read_capped(from, MAX_BYTES), Ok(vec![])); + // Once those apps close their pipes, the sends end and others are sent again. + drop(stalled); + while sends.running() > 0 { + std::thread::yield_now(); + } + let (from, to) = std::io::pipe().unwrap(); + assert!(sends.start(to, data.clone())); + assert_eq!(read_capped(from, MAX_BYTES).map(|d| d.len()), Ok(data.len())); + } + + /// What a clipboard holds, by type. + type Held = &'static [(&'static str, &'static [u8])]; + const PNG_ONLY: Held = &[(PNG, b"\x89PNG")]; + const SVG_ONLY: Held = &[(SVG, b"")]; + const TEXT_ONLY: Held = &[("text/plain;charset=utf-8", b"words")]; + const EMPTY_TEXT: Held = &[("text/plain", b"")]; + const NOTHING: Held = &[]; + const UNKNOWN: Held = &[("application/x-other", b"x")]; + + /// Reads of a clipboard holding `data`, answered at once. + fn reads_of(data: Held) -> Reads { + let loads = Loads::spawn("test", Duration::ZERO, move |wire: String| { + data.iter().find(|(t, _)| *t == wire).map(|(_, d)| d.to_vec()).ok_or_else(|| "not offered".to_string()) }) .unwrap(); - let start = Instant::now(); - assert!(loads.get(Duration::from_millis(50)).is_err(), "the first read times out"); - // While it is unanswered, a read doesn't queue behind it or wait at all. - assert!(loads.get(Duration::from_secs(60)).is_err()); - assert!(start.elapsed() < Duration::from_secs(30), "no read waited past its bound"); - release.send(()).unwrap(); - // Once the late answer is in, it is dropped and a new read is made. - let text = (0..200).find_map(|_| { - std::thread::sleep(Duration::from_millis(10)); - loads.get(Duration::from_secs(5)).ok() - }); - assert_eq!(text.as_deref(), Some("fresh")); + let types: Vec<&str> = data.iter().map(|(t, _)| *t).collect(); + Reads::new(loads, Arc::new(Mutex::new(Seen::offering(&types)))) } #[test] - fn a_read_after_the_worker_stops_says_so() { - let mut loads = Loads::spawn(|| Ok(String::new())).unwrap(); - // The worker ends when its answers can't be sent: drop them by hand. - let (_, dead) = mpsc::channel(); - drop(std::mem::replace(&mut loads.answers, dead)); - assert_eq!(loads.get(Duration::from_millis(50)), Err(GONE.to_string())); + fn a_picture_or_svg_alone_can_be_pasted_and_is() { + use vectorcraft_engine::cmd::clipboard::PASTE_ORDER; + let wait = Duration::from_secs(600); + for (data, mime) in [(PNG_ONLY, PNG), (SVG_ONLY, SVG)] { + let mut reads = reads_of(data); + // The paste check enables Paste from the types alone. + assert!(reads.has(&PASTE_ORDER)); + let Some(ClipboardRead::Later(work)) = reads.read(&PASTE_ORDER, wait) else { panic!("{mime} is read off the UI thread") }; + assert_eq!(work().map(|f| (f.mime, f.data)), Some((mime, data[0].1.to_vec()))); + } + let mut reads = reads_of(TEXT_ONLY); + assert!(reads.has(&[TEXT]) && !reads.has(&[BITMAP, SVG])); + let Some(ClipboardRead::Now(f)) = reads.read(&PASTE_ORDER, wait) else { panic!("text is read at once") }; + assert_eq!((f.mime, f.data), (TEXT, b"words".to_vec())); + // An empty clipboard, or one with no type a paste reads, enables nothing and pastes nothing. + for data in [NOTHING, UNKNOWN] { + let mut reads = reads_of(data); + assert!(!reads.has(&PASTE_ORDER)); + assert!(reads.read(&PASTE_ORDER, wait).is_none()); + assert_eq!(reads.text(wait), Ok(String::new())); + } + // Empty text is not pasted. + assert!(reads_of(EMPTY_TEXT).read(&[TEXT], wait).is_none()); + } + + #[test] + fn an_svg_that_sends_nothing_gives_way_to_the_text_or_png_beside_it() { + use vectorcraft_engine::cmd::clipboard::PASTE_ORDER; + const EMPTY_SVG_TEXT: Held = &[(SVG, b""), ("text/plain", b"words"), (PNG, b"\x89PNG")]; + const EMPTY_SVG_PNG: Held = &[(SVG, b""), (PNG, b"\x89PNG")]; + const EMPTY_SVG_URL: Held = &[(SVG, b""), ("text/plain", b"https://example.com/art.png"), (PNG, b"\x89PNG")]; + let wait = Duration::from_secs(600); + const EMPTY_PNG: Held = &[(PNG, b"")]; + for (data, mime, bytes) in + [(EMPTY_SVG_TEXT, TEXT, &b"words"[..]), (EMPTY_SVG_PNG, PNG, &b"\x89PNG"[..]), (EMPTY_SVG_URL, PNG, &b"\x89PNG"[..])] + { + // Held while the work runs, as the clipboard is. + let mut reads = reads_of(data); + let Some(ClipboardRead::Later(work)) = reads.read(&PASTE_ORDER, wait) else { panic!("the SVG is asked for") }; + assert_eq!(work().map(|f| (f.mime, f.data)), Some((mime, bytes.to_vec()))); + } + // A failed PNG read, last of all, pastes nothing. + let mut reads = reads_of(EMPTY_PNG); + let Some(ClipboardRead::Later(work)) = reads.read(&PASTE_ORDER, wait) else { panic!("the PNG is asked for") }; + assert!(work().is_none()); + } + + #[test] + fn a_read_that_fails_pastes_nothing() { + let loads = Loads::spawn("test", Duration::ZERO, |_: String| Err::, _>("the clipboard's data is larger than 64 MiB".to_string())) + .unwrap(); + let mut reads = Reads::new(loads, Arc::new(Mutex::new(Seen::offering(&[PNG, "text/plain"])))); + assert_eq!(reads.text(Duration::from_secs(600)), Err("the clipboard's data is larger than 64 MiB".to_string())); + let Some(ClipboardRead::Later(work)) = reads.read(&[BITMAP], Duration::from_secs(600)) else { panic!("the PNG is asked for") }; + assert!(work().is_none()); } } } diff --git a/apps/vectorcraft/src/hang_watch.rs b/apps/vectorcraft/src/hang_watch.rs new file mode 100644 index 0000000000..e5adb77dfa --- /dev/null +++ b/apps/vectorcraft/src/hang_watch.rs @@ -0,0 +1,445 @@ +//! The hang report. A thread reads the interface thread's marks +//! ([`vectorcraft_ui_egui::hang_beacon`]) every [`POLL`]. When the interface thread has made no +//! mark for [`STALL`] while inside a stage of its frame, the thread writes what the app knows to the +//! log (`logs/vectorcraft.log`) and to `logs/hang-report-.txt`: the stage, a clipboard +//! call in progress, the last commands, the last frames' times, the platform, the window system, the +//! graphics processor and the present mode the app asked for, and how long the session has run with +//! how many documents open. The process holds a lock on the file until the interface thread answers +//! again; then the log says after how long and the file is removed. A file nobody holds at a later +//! launch was left by a session that was closed while it did not answer, and a locked one belongs to +//! another instance that is stalled now and is left alone. That launch writes the report to the log, +//! moves the newest abandoned file to `hang-report.1.txt` and removes the others, says so in the +//! status bar, and Help › Copy Troubleshooting Info copies the reports. Where the file system has no +//! file locks, the file is written and taken without one. +//! +//! No native stack is recorded: the marks are what the report has. The report holds command ids and +//! counts, never document contents or file paths. [`STALL`] is VectorCraft's own value. +//! +//! A stall in the renderer is timed only after a frame that had input in any window: input asks for +//! the next frame at once, so a frame that does not start then is late. After a frame without +//! input, the window waiting for input looks the same as one stuck drawing, so that time is not +//! timed. Nor is the time after a frame that minimizes or hides the main window or hands it to the +//! system to move or resize. A window the system stops redrawing while it is hidden can still look +//! like a stall after a frame with input; the report's stage says so. A system file dialog shown in +//! line (on Windows and Linux) and an open menu of the macOS menu bar wait for the user and are not +//! timed. + +use std::fs::File; +use std::io::{Read as _, Write as _}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, PoisonError}; +use std::time::{Duration, Instant, SystemTime}; + +#[cfg(target_os = "macos")] +use vectorcraft_ui_egui::hang_beacon::Activity; +use vectorcraft_ui_egui::hang_beacon::{BEACON, Beacon, FrameTime, Sample, Stage}; + +use super::logging::timestamp; + +/// How long the interface thread may stay in one stage before the report is written. +pub const STALL: Duration = Duration::from_secs(3); +/// How often the watching thread reads the marks. +pub const POLL: Duration = Duration::from_millis(500); +/// The report of a stall that has not ended, in the log folder: this, the process id, `.txt`. +pub const REPORT_PREFIX: &str = "hang-report-"; +/// At most this many report files are taken when a launch looks for abandoned ones; older abandoned +/// ones are removed. +const MAX_REPORT_FILES: usize = 16; +/// At most this many entries of the log folder are looked at for report files. +const MAX_SCANNED_ENTRIES: usize = 1024; +/// The report the last session left, moved here at launch. +pub const PREVIOUS_FILE: &str = "hang-report.1.txt"; +/// A report file larger than this is not read. +pub const MAX_REPORT_BYTES: u64 = 64 * 1024; +/// Environment values in the report are cut to this many characters. +const MAX_VALUE_CHARS: usize = 64; + +/// What [`Watch::check`] found. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Event { + /// The interface thread has been in the sample's stage, without a mark, for this long. + Stalled(Duration), + /// The interface thread made a mark again after a [`Event::Stalled`], about this long after + /// the stall began. + Answered(Duration), +} + +/// Decides from successive samples when the interface thread has stalled and when it answers +/// again. Time comes from the caller, so tests drive it without waiting. +#[derive(Debug)] +pub struct Watch { + stall: Duration, + /// The step seen in a busy stage and when it was first seen. + seen: Option<(u64, Duration)>, + reported: bool, +} + +impl Watch { + pub fn new(stall: Duration) -> Watch { + Watch { stall, seen: None, reported: false } + } + + /// The marks read at `now` (any monotonic clock that started before the first call). + pub fn check(&mut self, now: Duration, sample: Sample) -> Option { + let same = self.seen.is_some_and(|(step, _)| step == sample.step); + if same && sample.busy() { + let since = self.seen.map_or(now, |(_, since)| since); + let stalled = now.saturating_sub(since); + if !self.reported && stalled >= self.stall { + self.reported = true; + return Some(Event::Stalled(stalled)); + } + return None; + } + let answered = match (self.reported, self.seen) { + (true, Some((_, since))) => Some(Event::Answered(now.saturating_sub(since))), + _ => None, + }; + self.reported = false; + self.seen = sample.busy().then_some((sample.step, now)); + answered + } +} + +/// What the report says about the platform. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Facts { + /// The window system the window opened on: Wayland, X11, AppKit, Win32, other or unknown. + pub window_system: String, + /// `XDG_CURRENT_DESKTOP`. + pub desktop: Option, + /// `XDG_SESSION_TYPE`. + pub session_type: Option, + /// Running in a Flatpak sandbox. + pub flatpak: bool, + /// The graphics processor the window draws with. + pub graphics: Option, + /// The present mode and frame queue the app asked the window surface for. + pub surface: String, +} + +impl Facts { + /// The facts from the environment (`env`, `flatpak_info`: whether `/.flatpak-info` exists) and + /// what the app knows. + pub fn new(env: impl Fn(&str) -> Option, flatpak_info: bool, window_system: &str, graphics: Option, surface: String) -> Facts { + let value = |name: &str| env(name).map(|v| clean(&v)).filter(|v| !v.is_empty()); + Facts { + window_system: window_system.to_string(), + desktop: value("XDG_CURRENT_DESKTOP"), + session_type: value("XDG_SESSION_TYPE"), + flatpak: flatpak_info || env("FLATPAK_ID").is_some_and(|v| !v.is_empty()), + graphics, + surface, + } + } + + /// The facts as report lines. + pub fn lines(&self) -> String { + let or_unknown = |v: &Option| v.clone().unwrap_or_else(|| "unknown".to_string()); + format!( + "VectorCraft {} on {} {}\nWindow system: {}; desktop: {}; session type: {}; Flatpak: {}\nGraphics: {}; {}\n", + env!("CARGO_PKG_VERSION"), + std::env::consts::OS, + std::env::consts::ARCH, + self.window_system, + or_unknown(&self.desktop), + or_unknown(&self.session_type), + if self.flatpak { "yes" } else { "no" }, + or_unknown(&self.graphics), + self.surface, + ) + } +} + +/// `v` with control characters removed, cut to [`MAX_VALUE_CHARS`] characters. +fn clean(v: &str) -> String { + v.chars().filter(|c| !c.is_control()).take(MAX_VALUE_CHARS).collect::().trim().to_string() +} + +/// The marks other than the stage: the last commands, the last frames and the session. +fn activity_lines(beacon: &Beacon, uptime: Duration) -> String { + let commands = match beacon.recent_commands() { + Some(c) if c.is_empty() => "none".to_string(), + Some(c) => c.join(", "), + None => "unavailable (being written)".to_string(), + }; + let (work, total) = match beacon.recent_frames() { + Some(frames) => { + let list = |f: &dyn Fn(&FrameTime) -> Option| { + let times: Vec = frames.iter().filter_map(f).map(|ms| format!("{ms:.1}")).collect(); + if times.is_empty() { "none".to_string() } else { times.join(", ") } + }; + (list(&|t| Some(t.work_ms)), list(&|t| t.previous_total_ms)) + } + None => ("unavailable (being written)".to_string(), "unavailable (being written)".to_string()), + }; + format!( + "Recent commands, oldest first: {commands}\nApp work per frame (ms), oldest first: {work}\nWork and drawing per frame, without waiting for the display (ms), oldest first: {total}\nSession: running for {} s, {} documents open\n", + uptime.as_secs(), + beacon.documents(), + ) +} + +/// The report of a stall that has lasted `stalled` in `sample`'s stage, written at `at`. +pub fn report(at: SystemTime, stalled: Duration, sample: Sample, beacon: &Beacon, uptime: Duration, facts: &Facts) -> String { + let waiting = sample.activity.describe().map(|a| format!("Waiting on: {a}\n")).unwrap_or_default(); + format!( + "VectorCraft hang report, {}\nThe interface thread has not moved on for {:.1} s.\nStage: {}\n{waiting}{}{}No native stack is recorded: the stage and the activity are what the app marks.\n", + timestamp(at), + stalled.as_secs_f64(), + sample.stage.describe(), + activity_lines(beacon, uptime), + facts.lines(), + ) +} + +/// What the watching thread and Help › Copy Troubleshooting Info share. +pub struct Shared { + pub facts: Facts, + pub started: Instant, + /// This session's last report. + pub last: Mutex>, + /// The report the last session left ([`take_previous`]). + pub previous: Option, +} + +/// The text Help › Copy Troubleshooting Info copies. +pub fn troubleshooting(shared: &Shared, beacon: &Beacon, at: SystemTime) -> String { + let last = shared.last.lock().unwrap_or_else(PoisonError::into_inner).clone(); + format!( + "VectorCraft troubleshooting info, {}\n{}{}\nThis session's last hang report:\n{}\nThe hang report the last session left (it was closed while it did not answer):\n{}\n", + timestamp(at), + shared.facts.lines(), + activity_lines(beacon, shared.started.elapsed()), + last.as_deref().unwrap_or("none\n"), + shared.previous.as_deref().unwrap_or("none\n"), + ) +} + +/// The report file of this process in `dir`. +fn report_path(dir: &Path) -> PathBuf { + dir.join(format!("{REPORT_PREFIX}{}.txt", std::process::id())) +} + +/// A report file this process wrote and holds locked until the interface answers again. +#[derive(Debug)] +pub struct Held { + path: PathBuf, + _file: File, +} + +/// Write `text` to this process's report file in `dir` and lock it. Where the file system has no +/// file locks, the file is written unlocked and the log says so. +fn write_report(dir: &Path, text: &str) -> std::io::Result { + std::fs::create_dir_all(dir)?; + let path = report_path(dir); + let mut file = File::create(&path)?; + if let Err(e) = file.lock() { + log::warn!("the hang report file is written without a lock: {e}"); + } + file.write_all(text.as_bytes())?; + Ok(Held { path, _file: file }) +} + +/// Whether a report file whose `try_lock` gave `locked` was abandoned: nobody holds it. A file +/// system without file locks answers [`std::io::ErrorKind::Unsupported`], and its files count as +/// abandoned; any other error leaves the file alone. +fn abandoned(locked: Result<(), std::fs::TryLockError>) -> bool { + match locked { + Ok(()) => true, + Err(std::fs::TryLockError::Error(e)) => e.kind() == std::io::ErrorKind::Unsupported, + Err(std::fs::TryLockError::WouldBlock) => false, + } +} + +/// The report file at `path`, opened and locked, with its length, when it was abandoned +/// ([`abandoned`]) and is not empty (an empty one may be being written). +fn open_abandoned(path: &Path) -> Option<(File, u64)> { + let file = File::options().read(true).write(true).open(path).ok()?; + if !abandoned(file.try_lock()) { + return None; + } + let len = file.metadata().map_or(0, |m| m.len()); + (len > 0).then_some((file, len)) +} + +/// The reports that sessions closed while they did not answer left in `dir`, oldest first; `None` +/// when there are none. The newest file is moved to [`PREVIOUS_FILE`] and the others are removed +/// once read. Of more than [`MAX_REPORT_FILES`], the newest are taken and the older ones removed +/// unread; the first [`MAX_SCANNED_ENTRIES`] entries of `dir` are looked at. A report file another +/// process holds locked, or one still empty, is left alone. A file over [`MAX_REPORT_BYTES`] is +/// taken without being read. A file that can't be moved is removed, so no later launch offers it +/// again: the caller writes the reports to the log. Each file is opened once. +pub fn take_previous(dir: &Path) -> Option { + let mut found: Vec<(SystemTime, PathBuf)> = std::fs::read_dir(dir) + .ok()? + .take(MAX_SCANNED_ENTRIES) + .filter_map(Result::ok) + .filter(|e| { + e.file_name() + .to_str() + .and_then(|n| n.strip_prefix(REPORT_PREFIX)?.strip_suffix(".txt")) + .is_some_and(|pid| !pid.is_empty() && pid.bytes().all(|b| b.is_ascii_digit())) + }) + .map(|e| (e.metadata().and_then(|m| m.modified()).unwrap_or(SystemTime::UNIX_EPOCH), e.path())) + .collect(); + found.sort(); + // Newest first: only abandoned reports count toward the limit. + let mut texts = Vec::new(); + for (_, path) in found.into_iter().rev() { + let Some((file, len)) = open_abandoned(&path) else { continue }; + if texts.len() == MAX_REPORT_FILES { + drop(file); + remove_quietly(&path); + continue; + } + let mut bytes = Vec::new(); + let text = if len <= MAX_REPORT_BYTES && (&file).take(MAX_REPORT_BYTES).read_to_end(&mut bytes).is_ok() { + String::from_utf8_lossy(&bytes).into_owned() + } else { + format!("The report was larger than {MAX_REPORT_BYTES} bytes and was not read.\n") + }; + // Closed (and unlocked) before it is moved: Windows moves no open file. + drop(file); + if !texts.is_empty() { + remove_quietly(&path); + } else if let Err(e) = std::fs::rename(&path, dir.join(PREVIOUS_FILE)) { + log::warn!("couldn't move the hang report file to {PREVIOUS_FILE}: {e}"); + remove_quietly(&path); + } + texts.push(text); + } + texts.reverse(); + (!texts.is_empty()).then(|| texts.join("\n")) +} + +/// Remove the report file at `path`; a failure goes to the log. +fn remove_quietly(path: &Path) { + if let Err(e) = std::fs::remove_file(path) { + log::warn!("couldn't remove the hang report file: {e}"); + } +} + +/// Set when the app closes normally ([`closing`]): the watching thread writes no report file after it. +pub static CLOSING: AtomicBool = AtomicBool::new(false); + +/// Remove `held`'s file, closing it first. → the error message; a file already gone is none. +fn remove(held: Held) -> Option { + let Held { path, _file: file } = held; + drop(file); + match std::fs::remove_file(&path) { + Err(e) if e.kind() != std::io::ErrorKind::NotFound => Some(e.to_string()), + _ => None, + } +} + +/// Act on what [`Watch::check`] found: write (and hold) or remove this process's report file in +/// `dir`, then log it. The file comes first: logging can wait on what the interface thread waits on. +#[allow(clippy::too_many_arguments)] +pub fn record( + event: Event, + sample: Sample, + beacon: &Beacon, + shared: &Shared, + dir: Option<&Path>, + held: &mut Option, + closing: &AtomicBool, + at: SystemTime, +) { + match event { + Event::Stalled(stalled) => { + let text = report(at, stalled, sample, beacon, shared.started.elapsed(), &shared.facts); + let mut failed = None; + if let Some(dir) = dir.filter(|_| !closing.load(Ordering::Acquire)) { + match write_report(dir, &text) { + Ok(file) => *held = Some(file), + Err(e) => failed = Some(e.to_string()), + } + // The app began to close while the file was written: it is not a report to leave. + if closing.load(Ordering::Acquire) { + failed = held.take().and_then(remove).or(failed); + } + } + *shared.last.lock().unwrap_or_else(PoisonError::into_inner) = Some(text.clone()); + log::warn!("the interface stopped answering:\n{}", text.trim_end()); + if let Some(e) = failed { + log::warn!("couldn't write or remove the hang report file: {e}"); + } + } + Event::Answered(after) => { + let failed = held.take().and_then(remove); + log::warn!("the interface answered again about {:.1} s after it stopped", after.as_secs_f64()); + if let Some(e) = failed { + log::warn!("couldn't remove the hang report file: {e}"); + } + } + } +} + +/// The app is closing normally: mark the interface thread idle on `beacon` (saving and teardown are +/// not timed), remove this process's report file in `dir` and have the watching thread write no +/// more. It does not wait for the watching thread. The file can be removed while that thread holds +/// it open and locked: the standard library opens files with `FILE_SHARE_DELETE` on Windows, and a +/// byte-range lock does not prevent deletion. Where Windows deletes a file only once its last +/// handle closes, the name goes when the process ends. +pub fn closing(dir: Option<&Path>, closing: &AtomicBool, beacon: &Beacon) { + beacon.enter(Stage::Idle); + closing.store(true, Ordering::Release); + if let Some(dir) = dir { + match std::fs::remove_file(report_path(dir)) { + Err(e) if e.kind() != std::io::ErrorKind::NotFound => log::warn!("couldn't remove the hang report file: {e}"), + _ => {} + } + } +} + +/// The window system `window` opened on, for [`Facts::window_system`]. +pub fn window_system(window: Option<&winit::window::Window>) -> &'static str { + use winit::raw_window_handle::{HasWindowHandle as _, RawWindowHandle}; + match window.and_then(|w| w.window_handle().ok()).map(|h| h.as_raw()) { + Some(RawWindowHandle::Wayland(_)) => "Wayland", + Some(RawWindowHandle::Xlib(_) | RawWindowHandle::Xcb(_)) => "X11", + Some(RawWindowHandle::AppKit(_)) => "AppKit", + Some(RawWindowHandle::Win32(_)) => "Win32", + Some(_) => "other", + None => "unknown", + } +} + +/// The present mode and frame queue the app asked the window surface for, for [`Facts::surface`]; +/// `None` when the window has no wgpu renderer. +pub fn surface(config: Option<(String, Option)>) -> String { + match config { + Some((mode, Some(frames))) => format!("requested present mode {mode}, frame latency {frames}"), + Some((mode, None)) => format!("requested present mode {mode}"), + None => "no wgpu renderer".to_string(), + } +} + +/// Start the watching thread; the report file goes in `dir` (none: the log only). +pub fn start(dir: Option, shared: Arc) { + let spawned = std::thread::Builder::new().name("hang-watch".into()).spawn(move || { + let mut watch = Watch::new(STALL); + let mut held = None; + loop { + std::thread::sleep(POLL); + #[cfg_attr(not(target_os = "macos"), allow(unused_mut))] + let mut sample = BEACON.sample(); + // An open menu of the menu bar waits for the user. + #[cfg(target_os = "macos")] + if super::mac_menu::is_tracking() { + sample.activity = Activity::Menu; + } + if let Some(event) = watch.check(shared.started.elapsed(), sample) { + record(event, sample, &BEACON, &shared, dir.as_deref(), &mut held, &CLOSING, SystemTime::now()); + } + } + }); + if let Err(e) = spawned { + log::warn!("no hang report this session: the watching thread didn't start: {e}"); + } +} + +#[cfg(test)] +mod tests; diff --git a/apps/vectorcraft/src/hang_watch/tests.rs b/apps/vectorcraft/src/hang_watch/tests.rs new file mode 100644 index 0000000000..09cf74e403 --- /dev/null +++ b/apps/vectorcraft/src/hang_watch/tests.rs @@ -0,0 +1,270 @@ +use super::*; +use std::time::UNIX_EPOCH; +use vectorcraft_ui_egui::hang_beacon::{Activity, Stage}; + +fn ms(n: u64) -> Duration { + Duration::from_millis(n) +} + +fn sample(step: u64, stage: Stage) -> Sample { + Sample { step, stage, activity: Activity::None } +} + +fn facts() -> Facts { + let env = |name: &str| match name { + "XDG_CURRENT_DESKTOP" => Some("KDE".to_string()), + "XDG_SESSION_TYPE" => Some("wayland\u{7}".to_string()), + _ => None, + }; + Facts::new(env, true, "Wayland", Some("Test GPU (Vulkan, DiscreteGpu)".to_string()), surface(Some(("AutoVsync".to_string(), Some(1))))) +} + +fn shared(previous: Option) -> Shared { + Shared { facts: facts(), started: Instant::now(), last: Mutex::new(None), previous } +} + +#[test] +fn a_stage_held_for_the_stall_time_is_reported_once_and_its_end_after_it() { + let mut w = Watch::new(STALL); + assert_eq!(w.check(ms(0), sample(5, Stage::Interface)), None); + assert_eq!(w.check(ms(2_999), sample(5, Stage::Interface)), None); + assert_eq!(w.check(ms(3_000), sample(5, Stage::Interface)), Some(Event::Stalled(ms(3_000)))); + assert_eq!(w.check(ms(9_000), sample(5, Stage::Interface)), None); + assert_eq!(w.check(ms(9_500), sample(6, Stage::Idle)), Some(Event::Answered(ms(9_500)))); + assert_eq!(w.check(ms(20_000), sample(6, Stage::Idle)), None); +} + +#[test] +fn frames_that_keep_moving_and_an_idle_window_are_never_reported() { + let mut w = Watch::new(STALL); + // A long animation: the step changes at every read. + for n in 0..100 { + assert_eq!(w.check(ms(n * 500), sample(n, Stage::Drawing)), None); + } + // A window waiting for input for a minute. + for n in 0..120 { + assert_eq!(w.check(ms(50_000 + n * 500), sample(1_000, Stage::Idle)), None); + } +} + +#[test] +fn a_file_dialog_shown_in_line_is_waiting_for_the_user_not_stalled() { + let mut w = Watch::new(STALL); + let dialog = Sample { step: 7, stage: Stage::Interface, activity: Activity::Dialog }; + for n in 0..60 { + assert_eq!(w.check(ms(n * 500), dialog), None); + } + // Back from the dialog, the command goes on and is timed again. + assert_eq!(w.check(ms(30_000), sample(8, Stage::Interface)), None); + assert_eq!(w.check(ms(33_000), sample(8, Stage::Interface)), Some(Event::Stalled(ms(3_000)))); +} + +#[test] +fn an_open_menu_bar_menu_is_waiting_for_the_user_not_stalled() { + let mut w = Watch::new(STALL); + let menu = Sample { step: 3, stage: Stage::Drawing, activity: Activity::Menu }; + for n in 0..60 { + assert_eq!(w.check(ms(n * 500), menu), None); + } +} + +#[test] +fn a_new_busy_step_starts_the_time_again() { + let mut w = Watch::new(STALL); + assert_eq!(w.check(ms(0), sample(1, Stage::Logic)), None); + assert_eq!(w.check(ms(2_500), sample(2, Stage::Interface)), None); + assert_eq!(w.check(ms(5_000), sample(2, Stage::Interface)), None); + assert_eq!(w.check(ms(5_500), sample(2, Stage::Interface)), Some(Event::Stalled(ms(3_000)))); + // A mark inside the stall (a clipboard read ending) is an answer. + assert_eq!(w.check(ms(6_000), sample(3, Stage::Interface)), Some(Event::Answered(ms(3_500)))); +} + +#[test] +fn the_report_names_the_stage_the_activity_the_commands_and_the_platform() { + let beacon = Beacon::new(); + beacon.command("edit.copy"); + beacon.command("edit.paste"); + beacon.frame(FrameTime { work_ms: 1.24, previous_total_ms: Some(3.5) }, 2); + let s = Sample { step: 9, stage: Stage::Interface, activity: Activity::ClipboardRead }; + let text = report(UNIX_EPOCH + Duration::from_secs(1_794_385_145), ms(3_240), s, &beacon, Duration::from_secs(754), &facts()); + for want in [ + "VectorCraft hang report, 2026-11-11T08:19:05.000Z", + "has not moved on for 3.2 s", + "Stage: running the interface", + "Waiting on: reading the system clipboard", + "Recent commands, oldest first: edit.copy, edit.paste", + "App work per frame (ms), oldest first: 1.2", + "without waiting for the display (ms), oldest first: 3.5", + "Session: running for 754 s, 2 documents open", + "Window system: Wayland; desktop: KDE; session type: wayland; Flatpak: yes", + "Graphics: Test GPU (Vulkan, DiscreteGpu); requested present mode AutoVsync, frame latency 1", + ] { + assert!(text.contains(want), "{want:?} missing from:\n{text}"); + } +} + +#[test] +fn environment_values_lose_control_characters_and_are_cut_short() { + let long = "x".repeat(500); + let env = |name: &str| (name == "XDG_CURRENT_DESKTOP").then(|| format!("A\nB{long}")); + let f = Facts::new(env, false, "X11", None, String::new()); + assert_eq!(f.desktop.as_deref().map(str::len), Some(MAX_VALUE_CHARS)); + assert!(f.desktop.as_deref().is_some_and(|d| d.starts_with("ABx"))); + assert!(!f.flatpak); + assert!(f.lines().contains("Graphics: unknown")); +} + +#[test] +fn a_stall_writes_the_report_file_and_its_end_removes_it() { + let dir = tempfile::tempdir().unwrap(); + let shared = shared(None); + let beacon = Beacon::new(); + let s = sample(4, Stage::Drawing); + let (mut held, open) = (None, AtomicBool::new(false)); + record(Event::Stalled(ms(3_000)), s, &beacon, &shared, Some(dir.path()), &mut held, &open, UNIX_EPOCH); + let path = report_path(dir.path()); + // Windows refuses reads through another handle while the file is locked: the length is read. + let last = shared.last.lock().unwrap().clone().unwrap_or_default(); + assert!(last.contains("Stage: after a frame with input went to the renderer")); + assert_eq!(std::fs::metadata(&path).unwrap().len(), last.len() as u64); + // While the stall lasts, a launch of another instance leaves the file alone. + assert_eq!(take_previous(dir.path()), None); + assert!(path.exists()); + record(Event::Answered(ms(4_000)), s, &beacon, &shared, Some(dir.path()), &mut held, &open, UNIX_EPOCH); + assert!(!path.exists()); + // This session's report stays for Copy Troubleshooting Info. + assert!(shared.last.lock().unwrap().is_some()); +} + +#[test] +fn closing_normally_removes_the_report_and_writes_no_more() { + let dir = tempfile::tempdir().unwrap(); + let shared = shared(None); + let beacon = Beacon::new(); + let (mut held, flag) = (None, AtomicBool::new(false)); + record(Event::Stalled(ms(3_000)), sample(4, Stage::Interface), &beacon, &shared, Some(dir.path()), &mut held, &flag, UNIX_EPOCH); + let path = report_path(dir.path()); + assert!(path.exists()); + // The interface answered after a frame with input, and the app quit before the watching thread + // looked again: saving and teardown are not timed. + beacon.enter(Stage::Drawing); + closing(Some(dir.path()), &flag, &beacon); + assert_eq!(beacon.sample().stage, Stage::Idle); + assert!(!path.exists()); + assert_eq!(take_previous(dir.path()), None); + // The watching thread then sees the answer. + record(Event::Answered(ms(3_500)), sample(5, Stage::Idle), &beacon, &shared, Some(dir.path()), &mut held, &flag, UNIX_EPOCH); + assert!(held.is_none()); + // A stall the watching thread finds while the app closes goes to the log only. + record(Event::Stalled(ms(3_000)), sample(9, Stage::Interface), &beacon, &shared, Some(dir.path()), &mut held, &flag, UNIX_EPOCH); + assert!(!path.exists()); + assert!(held.is_none()); +} + +#[test] +fn the_next_launch_takes_a_left_report_once_and_keeps_a_copy() { + let dir = tempfile::tempdir().unwrap(); + assert_eq!(take_previous(dir.path()), None); + let left = dir.path().join(format!("{REPORT_PREFIX}4242.txt")); + std::fs::write(&left, "VectorCraft hang report, then\n").unwrap(); + // Other files in the log folder are not reports. + std::fs::write(dir.path().join(format!("{REPORT_PREFIX}notes.txt")), "x").unwrap(); + std::fs::write(dir.path().join(format!("{REPORT_PREFIX}17.txt")), "").unwrap(); + assert_eq!(take_previous(dir.path()).as_deref(), Some("VectorCraft hang report, then\n")); + assert!(!left.exists()); + assert_eq!(std::fs::read_to_string(dir.path().join(PREVIOUS_FILE)).unwrap(), "VectorCraft hang report, then\n"); + assert_eq!(take_previous(dir.path()), None); + // An empty file may be one being written: it stays. + assert!(dir.path().join(format!("{REPORT_PREFIX}17.txt")).exists()); +} + +#[test] +fn of_several_left_reports_the_newest_is_kept_and_all_are_offered_oldest_first() { + let dir = tempfile::tempdir().unwrap(); + for (pid, text, secs) in [(9, "newer\n", 2_000), (10, "older\n", 1_000)] { + let path = dir.path().join(format!("{REPORT_PREFIX}{pid}.txt")); + std::fs::write(&path, text).unwrap(); + let file = std::fs::File::options().write(true).open(&path).unwrap(); + file.set_modified(UNIX_EPOCH + Duration::from_secs(secs)).unwrap(); + } + assert_eq!(take_previous(dir.path()).as_deref(), Some("older\n\nnewer\n")); + assert_eq!(std::fs::read_to_string(dir.path().join(PREVIOUS_FILE)).unwrap(), "newer\n"); +} + +#[test] +fn a_report_that_cannot_be_moved_is_offered_once() { + let dir = tempfile::tempdir().unwrap(); + // Something that is not a file is in the way. + std::fs::create_dir_all(dir.path().join(PREVIOUS_FILE).join("x")).unwrap(); + let left = dir.path().join(format!("{REPORT_PREFIX}5.txt")); + std::fs::write(&left, "kept\n").unwrap(); + assert_eq!(take_previous(dir.path()).as_deref(), Some("kept\n")); + assert!(!left.exists()); + assert_eq!(take_previous(dir.path()), None); +} + +#[test] +fn reports_beyond_the_newest_are_removed_not_left_for_a_later_launch() { + let dir = tempfile::tempdir().unwrap(); + let count = MAX_REPORT_FILES + 3; + for n in 0..count { + let path = dir.path().join(format!("{REPORT_PREFIX}{}.txt", 100 + n)); + std::fs::write(&path, format!("report {n}\n")).unwrap(); + let file = std::fs::File::options().write(true).open(&path).unwrap(); + file.set_modified(UNIX_EPOCH + Duration::from_secs(1_000 + n as u64)).unwrap(); + } + let text = take_previous(dir.path()).unwrap(); + assert!(text.starts_with("report 3\n"), "{text}"); + assert!(text.ends_with(&format!("report {}\n", count - 1)), "{text}"); + assert!(!text.contains("report 2\n")); + assert_eq!(take_previous(dir.path()), None); + let left: Vec<_> = std::fs::read_dir(dir.path()).unwrap().filter_map(Result::ok).map(|e| e.file_name()).collect(); + assert_eq!(left, vec![std::ffi::OsString::from(PREVIOUS_FILE)]); +} + +#[test] +fn newer_empty_files_do_not_push_out_an_abandoned_report() { + let dir = tempfile::tempdir().unwrap(); + let old = dir.path().join(format!("{REPORT_PREFIX}1.txt")); + std::fs::write(&old, "old\n").unwrap(); + std::fs::File::options().write(true).open(&old).unwrap().set_modified(UNIX_EPOCH + Duration::from_secs(1_000)).unwrap(); + for n in 0..MAX_REPORT_FILES + 1 { + let path = dir.path().join(format!("{REPORT_PREFIX}{}.txt", 100 + n)); + std::fs::write(&path, "").unwrap(); + std::fs::File::options().write(true).open(&path).unwrap().set_modified(UNIX_EPOCH + Duration::from_secs(2_000)).unwrap(); + } + assert_eq!(take_previous(dir.path()).as_deref(), Some("old\n")); +} + +#[test] +fn a_file_system_without_locks_does_not_hide_a_report() { + use std::io::{Error, ErrorKind}; + assert!(abandoned(Ok(()))); + assert!(!abandoned(Err(std::fs::TryLockError::WouldBlock))); + assert!(abandoned(Err(std::fs::TryLockError::Error(Error::from(ErrorKind::Unsupported))))); + // Any other error may hide a live session's lock: the file is left alone. + assert!(!abandoned(Err(std::fs::TryLockError::Error(Error::from(ErrorKind::PermissionDenied))))); +} + +#[test] +fn an_oversized_report_file_is_not_read() { + let dir = tempfile::tempdir().unwrap(); + let big = vec![b'x'; usize::try_from(MAX_REPORT_BYTES).unwrap() + 1]; + let left = dir.path().join(format!("{REPORT_PREFIX}7.txt")); + std::fs::write(&left, big).unwrap(); + let text = take_previous(dir.path()).unwrap(); + assert!(text.starts_with("The report was larger than")); + assert!(!left.exists()); +} + +#[test] +fn troubleshooting_info_holds_both_sessions_reports() { + let shared = shared(Some("VectorCraft hang report, last session\n".to_string())); + *shared.last.lock().unwrap() = Some("VectorCraft hang report, this session\n".to_string()); + let beacon = Beacon::new(); + let text = troubleshooting(&shared, &beacon, UNIX_EPOCH); + assert!(text.starts_with("VectorCraft troubleshooting info, 1970-01-01T00:00:00.000Z\n")); + assert!(text.contains("This session's last hang report:\nVectorCraft hang report, this session\n")); + assert!(text.contains("(it was closed while it did not answer):\nVectorCraft hang report, last session\n")); + assert!(text.contains("Recent commands, oldest first: none")); +} diff --git a/apps/vectorcraft/src/host_services.rs b/apps/vectorcraft/src/host_services.rs index 187c42cde7..94419b1049 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -1,10 +1,10 @@ #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] use super::portal_save; -#[cfg(target_os = "linux")] -use super::tablet; #[cfg(all(windows, not(target_vendor = "win7")))] use super::windows_stylus; use super::{ClipboardProbeFactory, FilePick, PickRequest, Services, clipboard, cursor_theme, fileio, printing}; +#[cfg(target_os = "linux")] +use super::{linux_screen_color, tablet}; #[cfg(target_os = "macos")] use super::{mac_save_format, mac_screen_color, mac_tablet}; @@ -120,7 +120,6 @@ fn make_folder(request: &PickRequest) { #[cfg(not(target_os = "macos"))] #[cfg_attr(windows, allow(unused_variables))] fn show_dialog(dialog: rfd::FileDialog, request: &PickRequest, parent: &Parent) -> Vec { - make_folder(request); #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] if let PickRequest::Save(pick) = request && let Some(answer) = portal_save::pick(pick, parent.as_deref()) @@ -139,7 +138,30 @@ fn show_dialog(dialog: rfd::FileDialog, request: &PickRequest, parent: &Parent) /// Show the dialog for `request` over `parent` now → the paths picked. #[cfg(not(target_os = "macos"))] fn pick_now(request: PickRequest, parent: &Parent) -> Vec { - show_dialog(file_dialog(&request, parent), &request, parent) + let beacon = &vectorcraft_ui_egui::hang_beacon::BEACON; + marked_dialog(beacon, || make_folder(&request), || show_dialog(file_dialog(&request, parent), &request, parent)) +} + +/// Run `prepare` (making the dialog's folder), then `show`, marked on `beacon` as a dialog: the +/// dialog waits for the user and is not a stall for the hang report (`hang_watch`), while `prepare` +/// is still timed. +#[cfg(not(target_os = "macos"))] +fn marked_dialog(beacon: &vectorcraft_ui_egui::hang_beacon::Beacon, prepare: impl FnOnce(), show: impl FnOnce() -> T) -> T { + prepare(); + let _mark = beacon.activity(vectorcraft_ui_egui::hang_beacon::Activity::Dialog); + show() +} + +#[cfg(all(test, not(target_os = "macos")))] +#[test] +fn making_a_dialogs_folder_is_timed_and_the_dialog_is_not() { + use vectorcraft_ui_egui::hang_beacon::{Activity, Beacon}; + let beacon = Beacon::new(); + let mut preparing = None; + let showing = marked_dialog(&beacon, || preparing = Some(beacon.sample().activity), || beacon.sample().activity); + assert_eq!(preparing, Some(Activity::None), "making the folder is timed"); + assert_eq!(showing, Activity::Dialog, "the dialog is not"); + assert_eq!(beacon.sample().activity, Activity::None, "the mark ends with the dialog"); } /// macOS shows no dialog in line: its modal loop would run inside winit's event handler, and an @@ -239,6 +261,7 @@ fn start_pick(request: PickRequest, parent: &Parent, ui: &egui::Context) -> Opti std::thread::Builder::new() .name("file-dialog".into()) .spawn(move || { + make_folder(&request); // The app gone meanwhile has no use for the answer. let _ = tx.send(show_dialog(dialog, &request, &parent)); ui.request_repaint(); @@ -331,8 +354,10 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services { .is_some_and(|h| matches!(h.as_raw(), RawWindowHandle::Xlib(_) | RawWindowHandle::Xcb(_))); let (clip, clip_probe) = (parent.clone(), parent.clone()); let (p1, p2, p3, p4, p5) = (parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent); - #[cfg(target_os = "macos")] + #[cfg(any(target_os = "macos", target_os = "linux"))] let sampled_ui = ui.clone(); + #[cfg(target_os = "linux")] + let sampled_parent = p1.clone(); Services { pick_open: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::Open(pick.clone()), &p1).into_iter().next())), pick_open_multi: Some(Box::new(move || pick_now(PickRequest::OpenMany, &p2))), @@ -355,18 +380,22 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services { // Load Actions… refuses a file over its size limit without reading all of it. read_head: Some(Box::new(read_file_head)), write: Some(Box::new(write_file)), - exists: Some(Box::new(|p: &str| std::path::Path::new(p).exists())), + exists: Some(std::sync::Arc::new(|p: &str| std::path::Path::new(p).exists())), // Background Save and Export write from a worker thread. write_shared: Some(std::sync::Arc::new(write_file)), + save_write: Some(std::sync::Arc::new(fileio::write_save_file)), + save_stream: Some(std::sync::Arc::new(fileio::write_save_file_with)), // Native saves stream into the file as they are encoded. stream_shared: Some(std::sync::Arc::new(|p: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>| { fileio::write_file_with(p, fill).map_err(|e| e.to_string()) })), // Every format Copy offers and Paste reads (menu-bar Paste never sees egui's Paste event). - system_clipboard: Some(clipboard::system_clipboard(clip)), + // Its calls are marked for the hang report (`hang_watch`). + system_clipboard: Some(Box::new(vectorcraft_ui_egui::hang_beacon::Marked(clipboard::system_clipboard(clip)))), // Linux checks whether Paste has something to take on a background thread: an X11 clipboard - // owner that never answers holds a read for up to 4 s. Windows only asks which formats the - // clipboard holds and macOS asks the pasteboard server, so they check in line. + // owner that never answers holds a text read for up to 4 s for each format it tries, and + // quitting waits up to `CLIPBOARD_PROBE_STOP_WAIT` for that thread. Windows only asks which + // formats the clipboard holds and macOS asks the pasteboard server, so they check in line. // The probe's handle is made on its own thread, from the window (`Send`), not its raw display. clipboard_probe: cfg!(target_os = "linux").then(|| Box::new(move || clipboard::system_clipboard(clip_probe)) as ClipboardProbeFactory), // Help → Discord / website / GitHub, the Discord button, About and Home links. @@ -382,6 +411,8 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services { // Sample Color from Screen: the system's color sampler. #[cfg(target_os = "macos")] screen_color: Some(mac_screen_color::sampler(sampled_ui)), + #[cfg(target_os = "linux")] + screen_color: Some(linux_screen_color::sampler(sampled_ui, sampled_parent)), // File → Print: the system's printers and print queue. print: Some(Box::new(printing::SystemPrint)), ..Default::default() diff --git a/apps/vectorcraft/src/linux_screen_color.rs b/apps/vectorcraft/src/linux_screen_color.rs new file mode 100644 index 0000000000..cfb8d7d69f --- /dev/null +++ b/apps/vectorcraft/src/linux_screen_color.rs @@ -0,0 +1,41 @@ +//! Linux: Sample Color from Screen (`vectorcraft_ui_egui::screen_color`) through the XDG desktop +//! portal's color sampler ([`portal`]). A thread of its own asks the portal and waits for the +//! person, so the UI keeps drawing; it sends the color to the UI and wakes the window. The dialog's +//! parent is the window, named on that thread as for the portal's save dialog (`portal_save`). + +mod portal; + +/// The portal's color sampler over the window `parent` holds; `ui` is woken when it answers. +pub fn sampler(ui: egui::Context, parent: super::host_services::Parent) -> vectorcraft_ui_egui::screen_color::StartSampler { + Box::new(move || { + let (tx, rx) = std::sync::mpsc::channel(); + let (ui, window) = (ui.clone(), parent.clone()); + std::thread::Builder::new() + .name("screen-color".into()) + .spawn(move || { + // The thread names the window and holds it until the export that names it is dropped. + let (handle, export) = match window.as_deref() { + Some(window) => { + let (handle, export) = super::portal_save::exported_parent(window); + (handle, Some(export)) + } + None => (String::new(), None), + }; + let picked = portal::connect(zbus::blocking::connection::Builder::session()).and_then(|conn| portal::pick(&conn, &handle)); + drop(export); + drop(window); + let answer = picked.map_err(|failure| { + log::warn!("the portal's screen color sampler gave no color: {}", failure.detail()); + failure.message().to_string() + }); + // The UI may be gone (the app quitting): nothing waits for the color then. + let _ = tx.send(answer); + ui.request_repaint(); + }) + .map_err(|e| { + log::warn!("could not start the screen color sampler's thread: {e}"); + "the screen color sampler failed".to_string() + })?; + Ok(rx) + }) +} diff --git a/apps/vectorcraft/src/linux_screen_color/portal.rs b/apps/vectorcraft/src/linux_screen_color/portal.rs new file mode 100644 index 0000000000..21bcb34da5 --- /dev/null +++ b/apps/vectorcraft/src/linux_screen_color/portal.rs @@ -0,0 +1,291 @@ +//! The XDG desktop portal's `Screenshot.PickColor` +//! (): +//! the call returns a request path at once, and the request's `Response` signal later carries the +//! color the person picked, as sRGB components from 0 to 1, or a code for a cancel or another end. + +use std::collections::HashMap; + +use zbus::blocking::{Connection, Proxy}; +use zbus::zvariant::{OwnedValue, Value}; + +/// How long the portal has to return a request path for `PickColor`. VectorCraft's own limit, +/// 25 seconds as libdbus's default for a method call. The portal returns the path before it shows +/// the sampler, so the person's time with the sampler does not count. +const CALL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(25); + +/// Why no color came back, as the status bar shows it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(super) enum Failure { + /// No session bus, no portal, or a portal without the Screenshot interface's `PickColor`. + Unavailable(String), + /// The portal did not return a request path in time, or it left the bus before it answered. + NoAnswer(String), + /// The portal ended the request without a color, or its answer can't be read. + Failed(String), +} + +impl Failure { + /// The status bar's message (English; the status bar translates it). + pub(super) fn message(&self) -> &'static str { + match self { + Failure::Unavailable(_) => "this system has no screen color sampler", + Failure::NoAnswer(_) => "the screen color sampler did not answer", + Failure::Failed(_) => "the screen color sampler failed", + } + } + + /// What went wrong, for the log. + pub(super) fn detail(&self) -> &str { + match self { + Failure::Unavailable(d) | Failure::NoAnswer(d) | Failure::Failed(d) => d, + } + } +} + +/// D-Bus errors that mean the session has no portal, or none that answers `PickColor`. +const UNAVAILABLE: &[&str] = &[ + "org.freedesktop.DBus.Error.ServiceUnknown", + "org.freedesktop.DBus.Error.NameHasNoOwner", + "org.freedesktop.DBus.Error.UnknownMethod", + "org.freedesktop.DBus.Error.UnknownInterface", + "org.freedesktop.DBus.Error.UnknownObject", +]; + +/// The connection `builder` makes, with [`CALL_TIMEOUT`] for its method calls. +pub(super) fn connect(builder: zbus::Result>) -> Result { + builder.and_then(|b| b.method_timeout(CALL_TIMEOUT).build()).map_err(|e| Failure::Unavailable(e.to_string())) +} + +/// Shows the portal's color sampler over the window `parent` names and waits for the color, `None` +/// when the person canceled it. `conn`'s method timeout bounds the call; the wait for the person +/// after it has no bound, and ends when the portal answers or leaves the bus. +pub(super) fn pick(conn: &Connection, parent: &str) -> Result, Failure> { + const DESKTOP: &str = "org.freedesktop.portal.Desktop"; + let token = crate::portal_request::token("vectorcraft_color").map_err(Failure::Failed)?; + // Made before the call: a portal can send its answer before the call returns. + let replies = crate::portal_request::Responses::new(conn).map_err(Failure::Failed)?; + let proxy = Proxy::new(conn, DESKTOP, "/org/freedesktop/portal/desktop", "org.freedesktop.portal.Screenshot") + .map_err(|e| Failure::Failed(e.to_string()))?; + let options = HashMap::from([("handle_token", Value::from(token.as_str()))]); + let call = proxy.call_method("PickColor", &(parent, options)).map_err(|e| call_failure(&e))?; + let reply = replies.wait(&call).map_err(Failure::NoAnswer)?; + let (code, results): (u32, HashMap) = reply.body().deserialize().map_err(|e| Failure::Failed(e.to_string()))?; + answer(code, &results) +} + +/// The [`Failure`] for an error the `PickColor` call returned. zbus reports a call that outlives +/// the connection's method timeout as an `InputOutput` error of kind `TimedOut`. +fn call_failure(e: &zbus::Error) -> Failure { + match e { + zbus::Error::MethodError(name, ..) if UNAVAILABLE.contains(&name.as_str()) => Failure::Unavailable(e.to_string()), + zbus::Error::InputOutput(io) if io.kind() == std::io::ErrorKind::TimedOut => Failure::NoAnswer(e.to_string()), + _ => Failure::Failed(e.to_string()), + } +} + +/// The color in a `Response` with `code` and `results`: response 0 carries it, 1 is a cancel, and +/// any other code ends the request without one. The components are passed on as given; +/// `screen_color::sampled` clamps them to 0 to 1, as for the other systems' samplers. +fn answer(code: u32, results: &HashMap) -> Result, Failure> { + match code { + 0 => {} + 1 => return Ok(None), + _ => return Err(Failure::Failed(format!("the portal ended the request (response {code})"))), + } + let color = results.get("color").ok_or_else(|| Failure::Failed("no color in the portal's answer".into()))?; + // Matched field by field: zvariant's tuple conversion panics on a structure with fewer fields. + match &**color { + Value::Structure(s) => match s.fields() { + [Value::F64(r), Value::F64(g), Value::F64(b)] => Ok(Some([*r, *g, *b].map(|v| v as f32))), + _ => Err(Failure::Failed(format!("the portal's color is not three numbers: {color:?}"))), + }, + _ => Err(Failure::Failed(format!("the portal's color is not three numbers: {color:?}"))), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::portal_request::test_bus::private_bus; + + fn color(rgb: (f64, f64, f64)) -> HashMap { + HashMap::from([("color".into(), OwnedValue::try_from(Value::from(rgb)).unwrap())]) + } + + fn failed(r: Result) -> bool { + matches!(r, Err(Failure::Failed(_))) + } + + #[test] + fn a_picked_color_keeps_its_srgb_values() { + assert_eq!(answer(0, &color((0.25, 0.5, 0.75))), Ok(Some([0.25, 0.5, 0.75]))); + assert_eq!(answer(0, &color((0.0, 1.0, 0.0))), Ok(Some([0.0, 1.0, 0.0]))); + // Outside 0 to 1: passed on for `screen_color::sampled` to clamp. + assert_eq!(answer(0, &color((-0.5, 1.5, 1.0))), Ok(Some([-0.5, 1.5, 1.0]))); + } + + #[test] + fn a_cancel_needs_no_color() { + assert_eq!(answer(1, &HashMap::new()), Ok(None)); + assert_eq!(answer(1, &color((0.25, 0.5, 0.75))), Ok(None)); + } + + #[test] + fn other_response_codes_are_failures() { + for code in [2, 3, u32::MAX] { + assert!(failed(answer(code, &color((0.25, 0.5, 0.75)))), "{code}"); + } + } + + #[test] + fn a_success_without_a_valid_color_is_a_failure() { + assert!(failed(answer(0, &HashMap::new()))); + let wrong = HashMap::from([("color".into(), OwnedValue::from(1_u32))]); + assert!(failed(answer(0, &wrong))); + // Fewer fields, more fields, and fields of another type: an error, not a panic. + for wrong in [Value::from((0.5, 0.5)), Value::from((0.5, 0.5, 0.5, 0.5)), Value::from((1_u32, 0.5, 0.5)), Value::from(vec![0.5, 0.5, 0.5])] { + let wrong = HashMap::from([("color".into(), OwnedValue::try_from(wrong).unwrap())]); + assert!(failed(answer(0, &wrong))); + } + } + + #[test] + fn call_errors_say_whether_the_system_has_a_sampler() { + let reply = |name: &str| { + let call = zbus::Message::method_call("/org/freedesktop/portal/desktop", "PickColor").unwrap().build(&()).unwrap(); + let error = zbus::Message::error(&call.header(), name).unwrap().build(&("detail",)).unwrap(); + zbus::Error::from(error) + }; + for name in UNAVAILABLE { + assert!(matches!(call_failure(&reply(name)), Failure::Unavailable(_)), "{name}"); + } + assert!(matches!(call_failure(&reply("org.freedesktop.portal.Error.NotAllowed")), Failure::Failed(_))); + let timed_out = zbus::Error::InputOutput(std::sync::Arc::new(std::io::ErrorKind::TimedOut.into())); + assert!(matches!(call_failure(&timed_out), Failure::NoAnswer(_))); + let broken = zbus::Error::InputOutput(std::sync::Arc::new(std::io::ErrorKind::BrokenPipe.into())); + assert!(matches!(call_failure(&broken), Failure::Failed(_))); + let messages = [Failure::Unavailable(String::new()), Failure::NoAnswer(String::new()), Failure::Failed(String::new())].map(|f| f.message()); + assert_eq!( + messages, + ["this system has no screen color sampler", "the screen color sampler did not answer", "the screen color sampler failed"] + ); + assert_eq!(call_failure(&broken).detail(), broken.to_string()); + } + + /// Every language that translates the sampler's other messages translates these too. The + /// i18n tests of `vectorcraft-ui-egui` do not read this crate's messages. + #[test] + fn the_messages_are_translated_where_the_sampler_is() { + use vectorcraft_ui_egui::i18n::{Lang, message}; + const OPEN: &str = "the screen color sampler is already open"; + let langs: Vec = Lang::all().filter(|&lang| message(lang, OPEN) != OPEN).collect(); + assert!(!langs.is_empty(), "no language translates {OPEN:?}"); + for lang in langs { + for failure in [Failure::Unavailable(String::new()), Failure::NoAnswer(String::new()), Failure::Failed(String::new())] { + assert_ne!(message(lang, failure.message()), failure.message(), "{}", lang.code()); + } + } + } + + /// The client's connection to the private bus at `address`, made as the sampler makes its own. + fn client(address: &str) -> Connection { + connect(zbus::blocking::connection::Builder::address(address)).unwrap() + } + + /// The portal's name, owned on the private bus at `address` before any call, so the bus never + /// starts an installed portal in its place. + fn portal(address: &str) -> Connection { + zbus::blocking::connection::Builder::address(address).unwrap().name("org.freedesktop.portal.Desktop").unwrap().build().unwrap() + } + + /// Through a real D-Bus: an answer that comes before the call returns is kept; answers on + /// other request paths or from other connections are ignored; a cancel gives no color; and a + /// portal that leaves the bus while the person picks ends the wait. + #[test] + fn the_answer_is_the_portals_response_on_the_returned_path() { + use zbus::blocking::MessageIterator; + use zbus::zvariant::OwnedObjectPath; + + let Some((_daemon, address)) = private_bus() else { return }; + let address = address.as_str(); + let server = portal(address); + let impostor = zbus::blocking::connection::Builder::address(address).unwrap().build().unwrap(); + let incoming = MessageIterator::from(&server); + let worker = std::thread::spawn(move || { + let mut calls = Vec::new(); + for msg in incoming { + let msg = msg.unwrap(); + let header = msg.header(); + if header.message_type() != zbus::message::Type::MethodCall || header.member().map(|m| m.as_str()) != Some("PickColor") { + continue; + } + let (parent, options): (String, HashMap) = msg.body().deserialize().unwrap(); + let token = String::try_from(options.get("handle_token").unwrap().try_clone().unwrap()).unwrap(); + assert!(token.starts_with("vectorcraft_color_")); + assert!(token.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'_')); + assert!(!calls.iter().any(|(_, old)| old == &token)); + calls.push((parent, token)); + // A portal older than version 0.9 answers on a path of its own, not the token's. + let path = format!("/org/freedesktop/portal/desktop/request/independent/pick_{}", calls.len()); + let handle = OwnedObjectPath::try_from(path.as_str()).unwrap(); + if calls.len() == 4 { + server.reply(&header, &handle).unwrap(); + assert!(server.release_name("org.freedesktop.portal.Desktop").unwrap()); + break; + } + let to = header.sender().cloned().map(zbus::names::BusName::from); + // Another connection can't end the wait by claiming the portal left. + impostor + .emit_signal( + to.clone(), + "/org/freedesktop/DBus", + "org.freedesktop.DBus", + "NameOwnerChanged", + &("org.freedesktop.portal.Desktop", server.unique_name().unwrap().as_str(), ""), + ) + .unwrap(); + let wrong = color((1.0, 0.0, 0.0)); + impostor.emit_signal(to.clone(), path.as_str(), "org.freedesktop.portal.Request", "Response", &(0_u32, &wrong)).unwrap(); + let unrelated = "/org/freedesktop/portal/desktop/request/unrelated"; + server.emit_signal(to.clone(), unrelated, "org.freedesktop.portal.Request", "Response", &(0_u32, &wrong)).unwrap(); + let code = if calls.len() == 2 { 1_u32 } else { 0_u32 }; + server.emit_signal(to, path.as_str(), "org.freedesktop.portal.Request", "Response", &(code, &color((0.25, 0.5, 0.75)))).unwrap(); + // The reply that names the path goes last: every answer above came before it. + server.reply(&header, &handle).unwrap(); + } + calls + }); + let client = client(address); + assert_eq!(pick(&client, "x11:12"), Ok(Some([0.25, 0.5, 0.75]))); + assert_eq!(pick(&client, "wayland:example"), Ok(None)); + assert_eq!(pick(&client, ""), Ok(Some([0.25, 0.5, 0.75]))); + assert!(matches!(pick(&client, ""), Err(Failure::NoAnswer(_)))); + let calls = worker.join().unwrap(); + assert_eq!(calls.iter().map(|(parent, _)| parent.as_str()).collect::>(), ["x11:12", "wayland:example", "", ""]); + } + + /// Through a real D-Bus: a portal without `PickColor` ends the request as a system without a + /// sampler, and the sampler's connection gives the call [`CALL_TIMEOUT`]. + #[test] + fn a_portal_without_pick_color_ends_the_request() { + let Some((_daemon, address)) = private_bus() else { return }; + let address = address.as_str(); + let server = portal(address); + let incoming = zbus::blocking::MessageIterator::from(&server); + let worker = std::thread::spawn(move || { + for msg in incoming { + let msg = msg.unwrap(); + let header = msg.header(); + if header.member().map(|m| m.as_str()) == Some("PickColor") { + server.reply_error(&header, "org.freedesktop.DBus.Error.UnknownMethod", &("no PickColor",)).unwrap(); + break; + } + } + }); + let client = client(address); + assert_eq!(client.method_timeout(), Some(CALL_TIMEOUT)); + let failure = pick(&client, ""); + assert!(matches!(failure, Err(Failure::Unavailable(_))), "{failure:?}"); + worker.join().unwrap(); + } +} diff --git a/apps/vectorcraft/src/mac_cursor.rs b/apps/vectorcraft/src/mac_cursor.rs index 85fea6c78a..69685a35b5 100644 --- a/apps/vectorcraft/src/mac_cursor.rs +++ b/apps/vectorcraft/src/mac_cursor.rs @@ -35,7 +35,6 @@ trait Backend { fn suspend(&mut self, window: &Self::Window); fn restore(&mut self, window: &Self::Window); fn build(&mut self, request: &Request) -> Option; - fn current(&self) -> Option; fn set(&mut self, cursor: &Self::Cursor); } @@ -73,9 +72,10 @@ impl State { && *key == request.key && *owned == window { - if self.backend.current().as_ref() != Some(cursor) { - self.backend.set(cursor); - } + // AppKit can show the system arrow when the pointer moves while + // `NSCursor.currentCursor` (the app's last set cursor) still reads as ours, so a + // comparison would keep the arrow. Setting the cursor again costs nothing. + self.backend.set(cursor); return; } self.release(); @@ -135,9 +135,6 @@ impl Backend for AppKit { fn build(&mut self, request: &Request) -> Option { build(&request.bitmap) } - fn current(&self) -> Option { - Some(NSCursor::currentCursor()) - } fn set(&mut self, cursor: &Self::Cursor) { cursor.set(); } diff --git a/apps/vectorcraft/src/mac_cursor/tests.rs b/apps/vectorcraft/src/mac_cursor/tests.rs index 648492c4b2..ad13a11336 100644 --- a/apps/vectorcraft/src/mac_cursor/tests.rs +++ b/apps/vectorcraft/src/mac_cursor/tests.rs @@ -6,7 +6,6 @@ use std::cell::Cell; struct Fake { window: Option, suspended: Vec, - current: Option, sets: usize, builds: usize, restores: Vec, @@ -27,17 +26,12 @@ impl Backend for Fake { fn restore(&mut self, w: &u8) { self.suspended.retain(|v| v != w); self.restores.push(*w); - self.current = None; } fn build(&mut self, r: &Request) -> Option { self.builds += 1; (!self.fail).then_some(r.key) } - fn current(&self) -> Option { - self.current - } - fn set(&mut self, cursor: &Key) { - self.current = Some(*cursor); + fn set(&mut self, _: &Key) { self.sets += 1; } } @@ -66,19 +60,16 @@ fn deliver(state: &mut State, request: Option) { } #[test] -fn mac_cursor_ownership_deduplicates_reasserts_and_restores() { +fn mac_cursor_ownership_reasserts_every_pass_and_restores() { let req = request(1.0); let mut state = fake_state(); deliver(&mut state, Some(req.clone())); assert_eq!(state.backend.suspended, [1]); assert_eq!((state.backend.builds, state.backend.sets), (1, 1)); + // The pointer moves and AppKit shows the system arrow, but the app's current cursor + // still reads as ours. The next pass sets it again without rebuilding or re-suspending. deliver(&mut state, Some(req.clone())); - assert_eq!(state.backend.sets, 1); - // Simulate a platform fallback replacing the cursor after finalization. The next pass - // reasserts; this proves the protocol, not AppKit timing or absence of transient flicker. - state.backend.current = None; - deliver(&mut state, Some(req.clone())); - assert_eq!(state.backend.sets, 2); + assert_eq!((state.backend.builds, state.backend.sets, state.backend.suspended.len()), (1, 2, 1)); deliver(&mut state, None); assert_eq!(state.backend.restores, [1]); deliver(&mut state, Some(req.clone())); diff --git a/apps/vectorcraft/src/mac_menu.rs b/apps/vectorcraft/src/mac_menu.rs index f90e4f7304..53b610a210 100644 --- a/apps/vectorcraft/src/mac_menu.rs +++ b/apps/vectorcraft/src/mac_menu.rs @@ -30,6 +30,9 @@ use vectorcraft_ui_egui::native_menu::{self, Backend, Event, MenuBar, MenuRole, // AppKit can deliver window input while its system menu is still tracking (especially with // asynchronous menu presentation). Keep the native tracking state separate from egui popups. static TRACKING: AtomicBool = AtomicBool::new(false); +/// A tracking session began since the last [`Backend::drain`], which reports it as +/// [`Event::Opened`]. +static OPENED: AtomicBool = AtomicBool::new(false); pub(crate) fn is_tracking() -> bool { TRACKING.load(Ordering::Relaxed) @@ -46,9 +49,11 @@ fn observe_tracking(ctx: &egui::Context) { let block = RcBlock::new(move |_: std::ptr::NonNull| { TRACKING.store(tracking, Ordering::Relaxed); if tracking { + OPENED.store(true, Ordering::Relaxed); super::mac_cursor::release(); } - // Apply any deferred menu updates as soon as the tracking session ends. + // Report the opened menu and apply any deferred menu updates as soon as the + // tracking session ends. if !tracking { repaint.request_repaint(); } @@ -267,6 +272,9 @@ impl Backend for MacMenu { fn drain(&mut self) -> Vec { let mut out = Vec::new(); + if OPENED.swap(false, Ordering::Relaxed) { + out.push(Event::Opened); + } while let Ok(chosen) = self.rx.try_recv() { cancel_tracking(); // Ids that aren't ours are AppKit's own items (Services, Zoom…), already handled. diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index bb94bad1cc..cd3ea7cd36 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -30,6 +30,9 @@ mod control_server; mod cursor_theme; #[cfg(feature = "wgpu")] mod gpu; +mod hang_watch; +#[cfg(target_os = "linux")] +mod linux_screen_color; #[cfg(target_os = "linux")] mod linux_stylus; mod logging; @@ -50,6 +53,8 @@ mod mac_tablet; mod mac_window; #[cfg(target_os = "macos")] mod open_documents; +#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] +mod portal_request; #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd", test))] mod portal_save; mod prefs_dir; @@ -84,6 +89,8 @@ mod titlebar; use app::bring_window_forward; use app::native_input_hook; use app::open_or_hold; +#[cfg(all(test, not(any(target_os = "macos", windows))))] +use app::{QuittingWindow, hide_before_teardown}; use host_services::services; #[cfg(all(test, feature = "wgpu"))] use prefs::{KEEP_UI_PREFS, decode_saved_prefs, keep_prefs_copy, prefs_bytes}; @@ -113,7 +120,8 @@ struct App { frames: u64, /// Keeps the custom title bar's window borderless (Windows, #1758). window_frame: Option, - /// The main window; used to read and set maximized state the UI layer does not see on Linux (#3635). + /// The main window; used to read and set maximized state the UI layer does not see on Linux (#3635), + /// and to hide the window on quit before the clipboard handles let go (`app::hide_before_teardown`). winit_window: Option>, /// A saved or fitted geometry asked for maximize once the window is mapped (Linux). pending_maximize: bool, @@ -123,6 +131,8 @@ struct App { held_files: Vec, /// The time and UI zoom of the last monitor list ([`window::monitors_due`]). monitors_listed: Option<(f64, f32)>, + /// When this frame's input hook started, for the hang report's frame times (`hang_watch`). + frame_start: Option, } /// `vectorcraft --help`. Headless work (convert, run, MCP) is `vectorcraft-cli`'s. @@ -293,6 +303,11 @@ fn main() -> std::process::ExitCode { None => logger.no_file(), } } + // The report a session left when it was closed while it did not answer (`hang_watch`). + let previous_hang = log_dir().filter(|_| prefs_enabled()).and_then(|dir| hang_watch::take_previous(&dir)); + if let Some(report) = &previous_hang { + log::warn!("the last session was closed while it did not answer; its report:\n{}", report.trim_end()); + } // The roots confine the control channel: a bad one keeps the app from starting rather than // leaving agents unconfined. Without a control port there is nothing to confine. let roots = if control_port.is_none() { @@ -437,6 +452,9 @@ fn main() -> std::process::ExitCode { open_documents::install(); #[cfg(feature = "wgpu")] let created = startup.clone(); + // For the hang report (`hang_watch`). + #[cfg(feature = "wgpu")] + let requested_surface = options.wgpu_options.surface; // A panic that ends the window (egui-wgpu's own, #502) is caught here: never a crash. let run = |options: eframe::NativeOptions, app_creator: eframe::AppCreator<'_>| { #[cfg(target_os = "linux")] @@ -465,6 +483,7 @@ fn main() -> std::process::ExitCode { prefs_dir::attach_plugin_store(&mut session); // File › Scripts lists the scripts of the Scripts folder next to the preferences. prefs_dir::attach_scripts_dir(&mut session); + prefs_dir::attach_new_doc_profiles(&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); @@ -474,6 +493,8 @@ fn main() -> std::process::ExitCode { prefs_dir::attach_pdf_preset_store(&mut app.session); // The custom dictionary's words, kept in their own file next to the preferences. prefs_dir::attach_custom_dictionary(&mut app.session); + // The custom arrowheads, kept in their own file next to the preferences. + prefs_dir::attach_arrowheads(&mut app.session); // Fit the window to its monitor, or put it back where it was (still hidden). let winit_window = cc.winit_window().cloned(); if let Some(w) = &winit_window { @@ -537,6 +558,36 @@ 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}"))); } + // The hang report and Help › Copy Troubleshooting Info (`hang_watch`). + // The surface settings the options asked for; the driver resolves the present mode. + #[cfg(feature = "wgpu")] + let surface = cc + .wgpu_render_state + .as_ref() + .map(|_| (format!("{:?}", requested_surface.present_mode), requested_surface.desired_maximum_frame_latency)); + #[cfg(not(feature = "wgpu"))] + let surface = None; + let hang = std::sync::Arc::new(hang_watch::Shared { + facts: hang_watch::Facts::new( + |name| std::env::var(name).ok(), + std::path::Path::new("/.flatpak-info").exists(), + hang_watch::window_system(winit_window.as_deref()), + app.graphics_adapter.clone(), + hang_watch::surface(surface), + ), + started: std::time::Instant::now(), + last: std::sync::Mutex::new(None), + previous: previous_hang.clone(), + }); + vectorcraft_ui_egui::hang_beacon::watch_input(&vectorcraft_ui_egui::hang_beacon::BEACON, &cc.egui_ctx); + hang_watch::start(log_dir().filter(|_| prefs_enabled()), hang.clone()); + app.services.troubleshooting = Some(Box::new(move || { + hang_watch::troubleshooting(&hang, &vectorcraft_ui_egui::hang_beacon::BEACON, std::time::SystemTime::now()) + })); + // A message about the graphics processor, or a stopped plug-in, comes first. + if previous_hang.is_some() && app.ui.status.is_empty() { + vectorcraft_ui_egui::troubleshooting::last_session_stopped(&mut app); + } app.titlebar_from_env = titlebar_from_env(); app.custom_titlebar = custom_titlebar; app.desktop_frame = !custom_titlebar; @@ -583,6 +634,7 @@ fn main() -> std::process::ExitCode { maximize_tries: 8, held_files, monitors_listed: None, + frame_start: None, })) }), ) diff --git a/apps/vectorcraft/src/portal_request.rs b/apps/vectorcraft/src/portal_request.rs new file mode 100644 index 0000000000..da4cb9ad23 --- /dev/null +++ b/apps/vectorcraft/src/portal_request.rs @@ -0,0 +1,231 @@ +//! Linux and the BSDs: the answer to an XDG desktop portal request +//! (), +//! for the save dialog (`portal_save`) and, on Linux, the screen color sampler +//! (`linux_screen_color`). The wait ends with the request's `Response`, or with an error when the +//! portal leaves the bus first. + +use futures_lite::{StreamExt as _, future}; +use zbus::blocking::{Connection, MessageIterator}; +use zbus::zvariant::OwnedObjectPath; + +const DESKTOP: &str = "org.freedesktop.portal.Desktop"; + +/// A request token: `prefix`, then 128 bits from the operating system's random device, so the +/// token is unique and can't be guessed, as the Request documentation asks. +#[cfg(target_os = "linux")] +pub(crate) fn token(prefix: &str) -> Result { + use std::io::Read as _; + + let mut bytes = [0; 16]; + std::fs::File::open("/dev/urandom") + .and_then(|mut file| file.read_exact(&mut bytes)) + .map_err(|e| format!("could not create a portal request token: {e}"))?; + let random: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect(); + Ok(format!("{prefix}_{random}")) +} + +/// Subscriptions made before a portal method call, on every request path: a portal older than +/// version 0.9 ignores `handle_token` and answers on the request path it returns, and its answer +/// can come before the call's reply. Each stream keeps every signal from the time it is made. +pub(crate) struct Responses { + replies: MessageIterator, + owners: MessageIterator, +} + +impl Responses { + pub(crate) fn new(conn: &Connection) -> Result { + let reply_rule = zbus::MatchRule::builder() + .msg_type(zbus::message::Type::Signal) + .sender(DESKTOP) + .and_then(|b| b.interface("org.freedesktop.portal.Request")) + .and_then(|b| b.member("Response")) + .map_err(|e| e.to_string())? + .build(); + let owner_rule = zbus::MatchRule::builder() + .msg_type(zbus::message::Type::Signal) + .sender("org.freedesktop.DBus") + .and_then(|b| b.path("/org/freedesktop/DBus")) + .and_then(|b| b.interface("org.freedesktop.DBus")) + .and_then(|b| b.member("NameOwnerChanged")) + .and_then(|b| b.arg(0, DESKTOP)) + .map_err(|e| e.to_string())? + .build(); + Ok(Self { + replies: MessageIterator::for_match_rule(reply_rule, conn, None).map_err(|e| e.to_string())?, + owners: MessageIterator::for_match_rule(owner_rule, conn, None).map_err(|e| e.to_string())?, + }) + } + + /// The `Response` on the request path `call` returned, from the connection that returned it. + /// An error when that connection leaves the bus first, or the bus connection closes. A + /// `Response` the portal sent before it left is still the answer. + pub(crate) fn wait(self, call: &zbus::Message) -> Result { + enum Event { + Reply(Option>), + Owner(Option>), + } + let handle: OwnedObjectPath = call.body().deserialize().map_err(|e| e.to_string())?; + let portal = call.header().sender().map(|s| s.as_str().to_string()).ok_or("the portal answered without a sender")?; + let answers = |reply: &zbus::Message| { + let header = reply.header(); + header.path().map(|p| p.as_str()) == Some(handle.as_str()) && header.sender().map(|s| s.as_str()) == Some(portal.as_str()) + }; + let mut replies = self.replies.into_inner(); + let mut owners = self.owners.into_inner(); + future::block_on(async { + loop { + let event = future::or(async { Event::Owner(owners.next().await) }, async { Event::Reply(replies.next().await) }).await; + match event { + Event::Reply(reply) => { + let reply = reply.ok_or("the portal closed without an answer")?.map_err(|e| e.to_string())?; + if answers(&reply) { + return Ok(reply); + } + } + Event::Owner(message) => { + let message = message.ok_or("the portal connection closed")?.map_err(|e| e.to_string())?; + if owner_disappeared(&message, &portal)? { + // zbus puts each message in every matching stream before it reads the + // next one, so a `Response` that came before the bus's report is + // already queued: it is still the answer. + while let Some(Some(reply)) = future::poll_once(replies.next()).await { + if let Ok(reply) = reply + && answers(&reply) + { + return Ok(reply); + } + } + return Err("the desktop portal disappeared while waiting for its answer".into()); + } + } + } + } + }) + } +} + +/// Whether `message` is the bus's `NameOwnerChanged` saying that the connection `portal` no longer +/// owns the portal's name. The bus itself must send it: another connection can't end the wait. +fn owner_disappeared(message: &zbus::Message, portal: &str) -> Result { + if message.header().sender().map(|s| s.as_str()) != Some("org.freedesktop.DBus") { + return Ok(false); + } + let (name, old, new): (String, String, String) = message.body().deserialize().map_err(|e| e.to_string())?; + Ok(name == DESKTOP && old == portal && new != portal) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_the_bus_can_report_portal_owner_loss() { + let changed = |sender, name, old, new| { + zbus::Message::signal("/org/freedesktop/DBus", "org.freedesktop.DBus", "NameOwnerChanged") + .unwrap() + .sender(sender) + .unwrap() + .build(&(name, old, new)) + .unwrap() + }; + let forged = changed(":1.42", DESKTOP, ":1.7", ""); + assert!(!owner_disappeared(&forged, ":1.7").unwrap()); + let real = changed("org.freedesktop.DBus", DESKTOP, ":1.7", ""); + assert!(owner_disappeared(&real, ":1.7").unwrap()); + let other = changed("org.freedesktop.DBus", "org.example.Other", ":1.7", ""); + assert!(!owner_disappeared(&other, ":1.7").unwrap()); + let old = changed("org.freedesktop.DBus", DESKTOP, ":1.8", ""); + assert!(!owner_disappeared(&old, ":1.7").unwrap()); + let acquired = changed("org.freedesktop.DBus", DESKTOP, "", ":1.7"); + assert!(!owner_disappeared(&acquired, ":1.7").unwrap()); + } + + /// Through a real D-Bus: when the bus has reported the portal gone, a `Response` the portal sent + /// before it left is still the answer; without one the wait ends with an error. + #[test] + fn a_queued_answer_wins_over_the_portal_leaving() { + use std::collections::HashMap; + + use zbus::blocking::connection::Builder; + use zbus::zvariant::OwnedValue; + + for answered in [true, false] { + let Some((_daemon, address)) = test_bus::private_bus() else { return }; + let address = address.as_str(); + let portal = Builder::address(address).unwrap().name(DESKTOP).unwrap().build().unwrap(); + let unique = portal.unique_name().unwrap().to_string(); + let client = Builder::address(address).unwrap().build().unwrap(); + let responses = Responses::new(&client).unwrap(); + // zbus puts each message in every matching stream before it reads the next one + // (`src/connection/socket_reader.rs`), so once this stream has the bus's report, + // `responses` holds the `Response` sent before it. + let gone_rule = zbus::MatchRule::builder() + .msg_type(zbus::message::Type::Signal) + .sender("org.freedesktop.DBus") + .unwrap() + .member("NameOwnerChanged") + .unwrap() + .arg(0, DESKTOP) + .unwrap() + .build(); + let gone = MessageIterator::for_match_rule(gone_rule, &client, None).unwrap(); + let path = "/org/freedesktop/portal/desktop/request/test/t1"; + if answered { + let results = HashMap::::new(); + portal.emit_signal(None::<&str>, path, "org.freedesktop.portal.Request", "Response", &(0_u32, results)).unwrap(); + } + portal.close().unwrap(); + // On a thread of its own, so a report that never comes fails the test instead of + // hanging it. + let (seen, report) = std::sync::mpsc::channel(); + let left = unique.clone(); + std::thread::spawn(move || { + let mut gone = gone; + let _ = seen.send(gone.any(|m| m.is_ok_and(|m| owner_disappeared(&m, &left).unwrap_or(false)))); + }); + assert_eq!(report.recv_timeout(std::time::Duration::from_secs(30)), Ok(true), "the bus did not report the portal gone"); + // The call's reply as `wait` reads it: the request path, from the portal's connection. + let call = zbus::Message::signal("/", "org.example.Test", "Reply") + .unwrap() + .sender(unique.as_str()) + .unwrap() + .build(&OwnedObjectPath::try_from(path).unwrap()) + .unwrap(); + let waited = responses.wait(&call); + assert_eq!(waited.is_ok(), answered, "{waited:?}"); + } + } +} + +/// The private session bus that the D-Bus tests of the portal requests run on. +#[cfg(test)] +pub(crate) mod test_bus { + /// A session bus of its own (`dbus-daemon`), `None` when there is none to run. + pub(crate) fn private_bus() -> Option<(Daemon, String)> { + use std::io::BufRead as _; + let spawning = crate::spawning(); + let daemon = std::process::Command::new("dbus-daemon") + .args(["--session", "--nofork", "--print-address=1"]) + .stdout(std::process::Stdio::piped()) + .spawn(); + drop(spawning); + let Ok(daemon) = daemon else { + eprintln!("no dbus-daemon: skipped"); + return None; + }; + let mut daemon = Daemon(daemon); + let mut address = String::new(); + std::io::BufReader::new(daemon.0.stdout.take().unwrap()).read_line(&mut address).unwrap(); + Some((daemon, address.trim().to_string())) + } + + /// Stops the private bus when the test ends, unwinding included. + pub(crate) struct Daemon(std::process::Child); + + impl Drop for Daemon { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } + } +} diff --git a/apps/vectorcraft/src/portal_save.rs b/apps/vectorcraft/src/portal_save.rs index 0357829aec..6d1a8734b2 100644 --- a/apps/vectorcraft/src/portal_save.rs +++ b/apps/vectorcraft/src/portal_save.rs @@ -8,6 +8,7 @@ //! ([`vectorcraft_ui_egui::picks::PickAnswer`]); the app gives the name that type's extension. //! rfd shows the dialog when the portal can't (no session bus, no file chooser), with zenity as its //! own fallback. PhotoCraft's `portal_save.rs` (storytold/photocraft#6151) makes the same call. +//! rfd also shows the dialog when the portal leaves the bus before it answers. //! //! The dialog's parent is the window: `x11:` on X11, and on Wayland (Linux) a handle //! from the compositor's xdg-foreign protocol, as rfd names it (its `window_identifier`). @@ -102,13 +103,22 @@ fn answer(code: u32, results: &HashMap) -> Result) = v.try_clone().ok()?.try_into().ok()?; - Some(label) - }); + let filter = results.get("current_filter").and_then(|v| filter_label(v)); Ok(Some(Saved { path, filter })) } +/// The label of a file type as the portal sends it, a `(sa(us))` structure; `None` for a value of +/// another shape. +fn filter_label(value: &Value<'_>) -> Option { + match value { + Value::Structure(s) => match s.fields() { + [Value::Str(label), Value::Array(globs)] if globs.element_signature() == "(us)" => Some(label.to_string()), + _ => None, + }, + _ => None, + } +} + /// `file:///home/me/A%20b.svg` → `/home/me/A b.svg` (its bytes); `None` for a file elsewhere /// (`file://host/`) or another scheme. fn file_uri_path(uri: &str) -> Option> { @@ -174,37 +184,18 @@ pub fn pick(pick: &FilePick, window: Option<&winit::window::Window>) -> Option Result, String> { use std::sync::atomic::{AtomicU32, Ordering}; - use zbus::blocking::{MessageIterator, Proxy}; - use zbus::zvariant::OwnedObjectPath; + use zbus::blocking::Proxy; const DESKTOP: &str = "org.freedesktop.portal.Desktop"; - const REQUEST: &str = "org.freedesktop.portal.Request"; static NEXT: AtomicU32 = AtomicU32::new(0); let token = format!("vectorcraft_save_{}_{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)); - // Listen before asking, on every request path: a portal older than version 0.9 ignores - // `handle_token` and answers on the request path it returns, and its answer can come before - // the call's reply. The stream keeps every `Response` from the time it is made. - let rule = zbus::MatchRule::builder() - .msg_type(zbus::message::Type::Signal) - .sender(DESKTOP) - .and_then(|b| b.interface(REQUEST)) - .and_then(|b| b.member("Response")) - .map_err(|e| e.to_string())? - .build(); - let responses = MessageIterator::for_match_rule(rule, conn, None).map_err(|e| e.to_string())?; + // Made before the call: a portal can send its answer before the call returns, and a portal + // that leaves the bus while its dialog is open ends the wait. + let responses = crate::portal_request::Responses::new(conn)?; let chooser = Proxy::new(conn, DESKTOP, "/org/freedesktop/portal/desktop", "org.freedesktop.portal.FileChooser").map_err(|e| e.to_string())?; // The title is empty, as rfd sends it for a save. let call = chooser.call_method("SaveFile", &(request.parent.as_str(), "", options(request, &token))).map_err(|e| e.to_string())?; - let handle: OwnedObjectPath = call.body().deserialize().map_err(|e| e.to_string())?; - // The answer is the `Response` on the path returned, from the connection that returned it. - let portal = call.header().sender().map(|s| s.as_str().to_string()); - let reply = responses - .filter_map(Result::ok) - .find(|m| { - let header = m.header(); - header.path().map(|p| p.as_str()) == Some(handle.as_str()) && header.sender().map(|s| s.as_str()) == portal.as_deref() - }) - .ok_or("the save dialog closed without an answer")?; + let reply = responses.wait(&call)?; let (code, results): (u32, HashMap) = reply.body().deserialize().map_err(|e| e.to_string())?; answer(code, &results) } @@ -233,6 +224,13 @@ fn parent(window: &winit::window::Window) -> (String, Option) { } } +/// [`parent`] for another dialog of the portal (the screen color sampler, `linux_screen_color`): +/// the identifier stays valid until the second value is dropped. +#[cfg(target_os = "linux")] +pub(crate) fn exported_parent(window: &winit::window::Window) -> (String, impl Send + 'static) { + parent(window) +} + /// The portal's identifier of `window`: its X11 id, else empty (no Wayland export is made off /// Linux). #[cfg(any(target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] @@ -396,6 +394,36 @@ mod tests { assert_eq!(pick_answer(saved, &request), ["/home/me/Art/poster"]); } + /// A `current_filter` of another shape than `(sa(us))` (a structure with fewer, other or more + /// fields, a string) gives the path alone; `uris` of another shape is an error. + #[test] + fn an_answer_of_another_shape_is_not_read() { + let malformed = [ + Value::from(("SVG".to_string(),)), + Value::from(("SVG".to_string(), vec![(0u32,)])), + Value::from(("SVG".to_string(), vec![("*.svg".to_string(), 0u32)])), + Value::from((1u32, vec![(0u32, "*.svg".to_string())])), + Value::from(("SVG".to_string(), vec![(0u32, "*.svg".to_string())], 1u32)), + Value::from("SVG"), + ]; + for filter in malformed { + let mut r = results("file:///tmp/card", None); + r.insert("current_filter".to_string(), OwnedValue::try_from(filter).unwrap()); + assert_eq!(answer(0, &r), Ok(Some(Saved { path: "/tmp/card".into(), filter: None }))); + } + let malformed = [ + Value::from(vec![1u32]), + Value::from(vec![("file:///tmp/card".to_string(),)]), + Value::from(Vec::::new()), + Value::from("file:///tmp/card"), + ]; + for uris in malformed { + let mut r = HashMap::new(); + r.insert("uris".to_string(), OwnedValue::try_from(uris).unwrap()); + assert!(answer(0, &r).is_err()); + } + } + /// Cancel (1) and a dialog closed another way (2) answer no file; an answer without a local file /// is an error, and rfd shows the dialog instead. #[test] @@ -449,26 +477,22 @@ mod tests { Old, /// As `Old`, with the `Response` sent before the reply that names its path. OldEarly, + /// As `Current`, but it leaves the bus 300 ms after its reply without a `Response`, as a + /// portal that exits while its dialog is open. + Exits, + /// Leaves the bus right after its reply, without a `Response`. + ExitsAtOnce, + /// Sends its `Response` right after its reply, then leaves the bus. + AnswersAndExits, } /// A session bus of its own (`dbus-daemon`) with a mock `org.freedesktop.portal.FileChooser` /// that answers `SaveFile` from `script` as `portal` says, as PhotoCraft's portal tests run it. /// `None` when there is no `dbus-daemon` to run. #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] - fn mock_portal(script: Script, portal: Portal) -> Option<(zbus::blocking::Connection, Seen, std::process::Child)> { - use std::io::BufRead as _; - + fn mock_portal(script: Script, portal: Portal) -> Option<(zbus::blocking::Connection, Seen, crate::portal_request::test_bus::Daemon)> { use zbus::zvariant::OwnedObjectPath; - let spawning = crate::spawning(); - let daemon = std::process::Command::new("dbus-daemon") - .args(["--session", "--nofork", "--print-address=1"]) - .stdout(std::process::Stdio::piped()) - .spawn(); - drop(spawning); - let mut daemon = daemon.ok()?; - let mut address = String::new(); - std::io::BufReader::new(daemon.stdout.take()?).read_line(&mut address).ok()?; - let address = address.trim().to_string(); + let (daemon, address) = crate::portal_request::test_bus::private_bus()?; let server = zbus::blocking::connection::Builder::address(address.as_str()).ok()?.name("org.freedesktop.portal.Desktop").ok()?.build().ok()?; let seen = Seen::default(); @@ -486,18 +510,15 @@ mod tests { } let Ok((_parent, _title, options)) = msg.body().deserialize::<(String, String, HashMap)>() else { break }; let text = |key: &str| options.get(key).and_then(|v| String::try_from(v.try_clone().ok()?).ok()); - let filter = options.get("current_filter").and_then(|v| { - let (label, _): (String, Vec<(u32, String)>) = v.try_clone().ok()?.try_into().ok()?; - Some(label) - }); + let filter = options.get("current_filter").and_then(|v| filter_label(v)); let calls = log.lock().map(|mut l| { l.push((text("current_name"), filter)); l.len() }); let Some(sender) = header.sender().map(|s| s.as_str().trim_start_matches(':').replace('.', "_")) else { break }; let token = match portal { - Portal::Current => text("handle_token").unwrap_or_default(), Portal::Old | Portal::OldEarly => format!("old{}", calls.unwrap_or_default()), + Portal::Current | Portal::Exits | Portal::ExitsAtOnce | Portal::AnswersAndExits => text("handle_token").unwrap_or_default(), }; let path = format!("/org/freedesktop/portal/desktop/request/{sender}/{token}"); let Ok(handle) = OwnedObjectPath::try_from(path.as_str()) else { break }; @@ -515,14 +536,22 @@ mod tests { if server.reply(&header, &handle).is_err() { break; } - if portal == Portal::Old { + if matches!(portal, Portal::Old | Portal::Exits) { // As a person answers the dialog: after the caller has the path returned. std::thread::sleep(std::time::Duration::from_millis(300)); } + if matches!(portal, Portal::Exits | Portal::ExitsAtOnce) { + break; + } if portal != Portal::OldEarly && respond().is_err() { break; } + if portal == Portal::AnswersAndExits { + break; + } } + // The portal leaves the bus: the bus sends `NameOwnerChanged` for its name. + let _ = server.close(); }); let client = zbus::blocking::connection::Builder::address(address.as_str()).ok()?.build().ok()?; Some((client, seen, daemon)) @@ -546,7 +575,7 @@ mod tests { #[test] fn the_portal_is_asked_on_the_first_file_type_and_answers_the_one_picked() { let script = vec![(0, Some(("file:///home/me/Art/poster", "PDF-compatible .ai"))), (1, None)]; - let Some((conn, seen, mut daemon)) = mock_portal(script, Portal::Current) else { + let Some((conn, seen, _daemon)) = mock_portal(script, Portal::Current) else { eprintln!("no dbus-daemon: skipped"); return; }; @@ -556,7 +585,6 @@ mod tests { assert_eq!(save_within(&conn, &request), Ok(None)); let seen = seen.lock().map(|s| s.clone()).unwrap_or_default(); assert_eq!(seen.first(), Some(&(Some("Untitled-1.vectorcraft".to_string()), Some(request.filters[0].0.clone())))); - let _ = daemon.kill(); } /// A portal older than 0.9 answers on the request path it returns, and the answer is awaited @@ -564,13 +592,12 @@ mod tests { #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] #[test] fn the_answer_is_awaited_on_the_path_the_portal_returns() { - let Some((conn, _seen, mut daemon)) = mock_portal(vec![(0, Some(("file:///tmp/card", "SVG")))], Portal::Old) else { + let Some((conn, _seen, _daemon)) = mock_portal(vec![(0, Some(("file:///tmp/card", "SVG")))], Portal::Old) else { eprintln!("no dbus-daemon: skipped"); return; }; let request = request(); assert_eq!(pick_answer(save_within(&conn, &request).unwrap(), &request), ["/tmp/card", "svg"]); - let _ = daemon.kill(); } /// A portal older than 0.9 can answer before its reply names the request path: the answer is @@ -579,14 +606,41 @@ mod tests { #[test] fn an_answer_that_comes_before_the_path_is_kept() { let script = vec![(0, Some(("file:///tmp/card", "SVG"))), (1, None)]; - let Some((conn, _seen, mut daemon)) = mock_portal(script, Portal::OldEarly) else { + let Some((conn, _seen, _daemon)) = mock_portal(script, Portal::OldEarly) else { eprintln!("no dbus-daemon: skipped"); return; }; let request = request(); assert_eq!(pick_answer(save_within(&conn, &request).unwrap(), &request), ["/tmp/card", "svg"]); assert_eq!(save_within(&conn, &request), Ok(None)); - let _ = daemon.kill(); + } + + /// A portal that leaves the bus after its reply without answering, while its dialog is open or + /// at once, ends the wait with an error, and rfd shows the dialog. + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + #[test] + fn a_portal_that_exits_during_the_dialog_ends_the_wait() { + for portal in [Portal::Exits, Portal::ExitsAtOnce] { + let Some((conn, _seen, _daemon)) = mock_portal(vec![(0, Some(("file:///tmp/card", "SVG")))], portal) else { + eprintln!("no dbus-daemon: skipped"); + return; + }; + assert_eq!(save_within(&conn, &request()), Err("the desktop portal disappeared while waiting for its answer".to_string())); + } + } + + /// A portal that answers and then leaves the bus: the save reads the answer. Whether the answer + /// or the bus's report comes first depends on timing here; `portal_request`'s + /// `a_queued_answer_wins_over_the_portal_leaving` queues both before the wait. + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + #[test] + fn an_answer_sent_just_before_the_portal_exits_is_kept() { + let Some((conn, _seen, _daemon)) = mock_portal(vec![(0, Some(("file:///tmp/card", "SVG")))], Portal::AnswersAndExits) else { + eprintln!("no dbus-daemon: skipped"); + return; + }; + let request = request(); + assert_eq!(pick_answer(save_within(&conn, &request).unwrap(), &request), ["/tmp/card", "svg"]); } /// The labels go to the dialog in the interface's language, which is how the answer is matched. diff --git a/apps/vectorcraft/src/prefs_dir.rs b/apps/vectorcraft/src/prefs_dir.rs index 96e09f5e78..11afcfe121 100644 --- a/apps/vectorcraft/src/prefs_dir.rs +++ b/apps/vectorcraft/src/prefs_dir.rs @@ -65,6 +65,14 @@ pub fn attach_scripts_dir(session: &mut vectorcraft_engine::Session) { } } +/// Have File › New start each category's documents from its profile in the `New Document +/// Profiles` folder, which `file.newProfiles.edit` makes. +pub fn attach_new_doc_profiles(session: &mut vectorcraft_engine::Session) { + if let Some(dir) = store_dir("New Document Profiles") { + session.attach_new_doc_profiles(dir); + } +} + /// Take the saved PDF presets from the `PDF Presets` folder (#2168), and keep the ones saved from /// now on there. After the preferences were restored: the folder is the one place the presets live. pub fn attach_pdf_preset_store(session: &mut vectorcraft_engine::Session) { @@ -81,6 +89,14 @@ pub fn attach_custom_dictionary(session: &mut vectorcraft_engine::Session) { } } +/// Keep the custom arrowheads (Stroke panel menu › Edit Arrowheads…) in the `Arrowheads.vectorcraft` +/// file next to the settings, and list the heads it holds. +pub fn attach_arrowheads(session: &mut vectorcraft_engine::Session) { + if let Some(path) = store_dir(vectorcraft_engine::cmd::arrowheads::FILE_NAME) { + session.attach_arrowheads_file(path.to_string_lossy().to_string()); + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/apps/vectorcraft/src/tests.rs b/apps/vectorcraft/src/tests.rs index 6e61cbe31f..6ae80944a6 100644 --- a/apps/vectorcraft/src/tests.rs +++ b/apps/vectorcraft/src/tests.rs @@ -460,3 +460,21 @@ fn the_linux_desktop_entry_opens_every_readable_format() { } } } + +/// On Linux and the BSDs, quitting hides the main window before eframe drops the app, whose +/// clipboard handles may take up to `CLIPBOARD_PROBE_STOP_WAIT` to let go. +#[cfg(not(any(target_os = "macos", windows)))] +#[test] +fn quitting_hides_the_window_before_the_clipboards_let_go() { + struct Window(std::cell::Cell); + impl QuittingWindow for Window { + fn hide(&self) { + self.0.set(self.0.get() + 1); + } + } + let window = Window(std::cell::Cell::new(0)); + hide_before_teardown(Some(&window)); + assert_eq!(window.0.get(), 1, "the window was not hidden"); + // Without a window (none was made), there is nothing to hide. + hide_before_teardown::(None); +} diff --git a/apps/vectorcraft/tests/it/automation_args.rs b/apps/vectorcraft/tests/it/automation_args.rs index 93b33fa16d..4a1e6f524c 100644 --- a/apps/vectorcraft/tests/it/automation_args.rs +++ b/apps/vectorcraft/tests/it/automation_args.rs @@ -1,8 +1,6 @@ use std::process::{Command, Stdio}; use std::time::{Duration, Instant}; -const BIN: &str = env!("CARGO_BIN_EXE_vectorcraft"); - /// Invalid roots must exit before desktop initialization on every platform, including a CI /// machine with no display. A regression must fail rather than hang with a window open. fn rejects(args: &[&str], message: &str) { @@ -10,7 +8,7 @@ fn rejects(args: &[&str], message: &str) { } fn rejects_with_env(args: &[&str], env: &[(&str, &str)], message: &str) { - let mut child = Command::new(BIN) + let mut child = Command::new(crate::bin()) .args(args) .env_remove("VECTORCRAFT_CONTROL_PORT") .env_remove("VECTORCRAFT_AUTOMATION_READ_ROOT") @@ -62,7 +60,7 @@ fn missing_empty_or_option_operands_fail_before_startup() { #[test] fn repeated_roots_are_accepted_for_both_spellings() { for flag in ["--automation-read-root", "--automation-write-root"] { - let out = Command::new(BIN).args([flag, ".", format!("{flag}=.").as_str(), flag, "./", "--version"]).output().unwrap(); + let out = Command::new(crate::bin()).args([flag, ".", format!("{flag}=.").as_str(), flag, "./", "--version"]).output().unwrap(); assert!(out.status.success(), "{flag}: {}", String::from_utf8_lossy(&out.stderr)); assert_eq!(String::from_utf8(out.stdout).unwrap(), format!("vectorcraft {}\n", env!("CARGO_PKG_VERSION"))); assert!(out.stderr.is_empty()); @@ -73,7 +71,8 @@ fn repeated_roots_are_accepted_for_both_spellings() { #[test] fn explicit_dash_folder_does_not_consume_version() { - let out = Command::new(BIN).args(["--automation-read-root=-folder", "--automation-write-root", "./-folder", "--version"]).output().unwrap(); + let out = + Command::new(crate::bin()).args(["--automation-read-root=-folder", "--automation-write-root", "./-folder", "--version"]).output().unwrap(); assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); assert_eq!(String::from_utf8(out.stdout).unwrap(), format!("vectorcraft {}\n", env!("CARGO_PKG_VERSION"))); assert!(out.stderr.is_empty()); @@ -95,7 +94,7 @@ fn control_without_a_valid_port_fails_before_startup() { #[test] fn version_wins_over_a_bad_control_port_variable() { - let out = Command::new(BIN).arg("--version").env("VECTORCRAFT_CONTROL_PORT", "abc").output().unwrap(); + let out = Command::new(crate::bin()).arg("--version").env("VECTORCRAFT_CONTROL_PORT", "abc").output().unwrap(); assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); assert_eq!(String::from_utf8(out.stdout).unwrap(), format!("vectorcraft {}\n", env!("CARGO_PKG_VERSION"))); } diff --git a/apps/vectorcraft/tests/it/help.rs b/apps/vectorcraft/tests/it/help.rs index ece66b98ab..d82475b9ff 100644 --- a/apps/vectorcraft/tests/it/help.rs +++ b/apps/vectorcraft/tests/it/help.rs @@ -6,12 +6,10 @@ use std::process::{Command, Output, Stdio}; use std::sync::mpsc; use std::time::{Duration, Instant}; -const BIN: &str = env!("CARGO_BIN_EXE_vectorcraft"); - /// Runs the desktop binary without a display and with a control port it cannot parse, so a /// regression exits with that error instead of opening a window. fn run(args: &[&str], env: &[(&str, &str)]) -> Output { - let mut child = Command::new(BIN) + let mut child = Command::new(crate::bin()) .args(args) .env_remove("DISPLAY") .env_remove("WAYLAND_DISPLAY") diff --git a/apps/vectorcraft/tests/it/main.rs b/apps/vectorcraft/tests/it/main.rs index d9dcf39cbb..658f4d49f6 100644 --- a/apps/vectorcraft/tests/it/main.rs +++ b/apps/vectorcraft/tests/it/main.rs @@ -4,3 +4,11 @@ mod automation_args; mod help; + +/// Nextest relocates archived binaries; Cargo's compile-time path still names the build runner. +fn bin() -> std::path::PathBuf { + std::env::var_os("NEXTEST_BIN_EXE_vectorcraft") + .or_else(|| std::env::var_os("CARGO_BIN_EXE_vectorcraft")) + .map(std::path::PathBuf::from) + .unwrap_or_else(|| env!("CARGO_BIN_EXE_vectorcraft").into()) +} diff --git a/assets/icons/dc-grad-diamond.svg b/assets/icons/dc-grad-diamond.svg new file mode 100644 index 0000000000..2efeca27e9 --- /dev/null +++ b/assets/icons/dc-grad-diamond.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/graduation-cap.svg b/assets/icons/graduation-cap.svg new file mode 100644 index 0000000000..fbce25edcc --- /dev/null +++ b/assets/icons/graduation-cap.svg @@ -0,0 +1,17 @@ + + + + + + diff --git a/crates/affinity/Cargo.toml b/crates/affinity/Cargo.toml index c335c7b16c..798b0734f5 100644 --- a/crates/affinity/Cargo.toml +++ b/crates/affinity/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "vectorcraft-affinity" -description = "Bounded reader for native Affinity documents: archive, object stream and document model" +description = "craft-affinity under its old name, for the corpus tests and fuzz targets" version.workspace = true edition.workspace = true license.workspace = true @@ -11,13 +11,13 @@ workspace = true [features] # Synthetic-container builders for tests and fuzz seeds; not an Affinity exporter. -synth = [] +synth = ["craft-affinity/synth"] [dependencies] -crc32fast = { workspace = true } -flate2 = { workspace = true } -image = { workspace = true } -ruzstd = "0.9.1" +craft-affinity = { workspace = true } [dev-dependencies] proptest = { workspace = true } +# The tests build containers and decode previews. +crc32fast = { workspace = true } +image = { workspace = true } diff --git a/crates/affinity/README.md b/crates/affinity/README.md index d0a641697d..38c096cbcc 100644 --- a/crates/affinity/README.md +++ b/crates/affinity/README.md @@ -1,5 +1,7 @@ # vectorcraft-affinity +The reader is [`craft-affinity`](https://github.com/storytold/craft-libs/tree/main/crates/affinity) in craft-libs; this crate re-exports it under its old name for the corpus tests and fuzz targets. The engine maps its document onto VectorCraft art (`crates/engine/src/cmd/fileio/affinity`), as described below. + An independent, bounded Rust reader for native Affinity documents: `.af` from Affinity 3 and `.afdesign`, `.afphoto` and `.afpub` from Affinity 1 and 2 (container versions 8 to 12). It reads the archive, the tagged object stream in `doc.dat` and the part of the document model listed below, diff --git a/crates/affinity/src/access.rs b/crates/affinity/src/access.rs deleted file mode 100644 index 0b60ed7dbd..0000000000 --- a/crates/affinity/src/access.rs +++ /dev/null @@ -1,105 +0,0 @@ -//! Typed reads of [`Stream`] objects. Every accessor returns `None` when a field is missing or has -//! another type, so the document mapping treats odd data as absent rather than failing. - -use crate::stream::{ObjId, Object, Stream, Tag, Value}; - -impl Stream { - pub fn object(&self, id: ObjId) -> Option<&Object> { - self.objects.get(id) - } - - pub fn field(&self, id: ObjId, tag: &[u8; 4]) -> Option<&Value> { - self.object(id)?.get(Tag::of(tag)) - } - - pub fn class(&self, id: ObjId) -> Option { - self.object(id).map(|o| o.class) - } - - pub fn is(&self, id: ObjId, class: &[u8; 4]) -> bool { - self.class(id) == Some(Tag::of(class)) - } - - /// A child object (shared, linked or inline); `None` for null or missing. - pub fn obj(&self, id: ObjId, tag: &[u8; 4]) -> Option { - match self.field(id, tag)? { - Value::Obj(o) => *o, - _ => None, - } - } - - /// An array of objects (nulls skipped). - pub fn objs(&self, id: ObjId, tag: &[u8; 4]) -> Vec { - match self.field(id, tag) { - Some(Value::Array(a)) => a.iter().filter_map(|v| if let Value::Obj(Some(o)) = v { Some(*o) } else { None }).collect(), - _ => Vec::new(), - } - } - - pub fn f64(&self, id: ObjId, tag: &[u8; 4]) -> Option { - match self.field(id, tag)? { - Value::Float(f) if f.is_finite() => Some(*f), - _ => None, - } - } - - pub fn int(&self, id: ObjId, tag: &[u8; 4]) -> Option { - match self.field(id, tag)? { - Value::Int(i) => Some(*i), - Value::UInt(u) => i64::try_from(*u).ok(), - _ => None, - } - } - - pub fn bool(&self, id: ObjId, tag: &[u8; 4]) -> Option { - match self.field(id, tag)? { - Value::Bool(b) => Some(*b), - _ => None, - } - } - - pub fn str(&self, id: ObjId, tag: &[u8; 4]) -> Option<&str> { - match self.field(id, tag)? { - Value::Str(s) => Some(s), - _ => None, - } - } - - pub fn enumeration(&self, id: ObjId, tag: &[u8; 4]) -> Option<(u16, u16)> { - match self.field(id, tag)? { - Value::Enum { id, version } => Some((*id, *version)), - _ => None, - } - } - - /// A fixed vector of `N` finite floats (points, rectangles, transforms). - pub fn floats(&self, id: ObjId, tag: &[u8; 4]) -> Option<[f64; N]> { - match self.field(id, tag)? { - Value::Floats(v) if v.len() == N && v.iter().all(|f| f.is_finite()) => { - let mut a = [0.0; N]; - a.copy_from_slice(v); - Some(a) - } - _ => None, - } - } - - pub fn bytes(&self, id: ObjId, tag: &[u8; 4]) -> Option<&[u8]> { - match self.field(id, tag)? { - Value::Bytes(b) | Value::Blob(b) => Some(b), - _ => None, - } - } - - pub fn entry(&self, id: ObjId, tag: &[u8; 4]) -> Option<&str> { - match self.field(id, tag)? { - Value::Entry(s) => Some(s), - _ => None, - } - } - - /// Untagged fields of a positional object, in order. - pub fn positional(&self, id: ObjId) -> impl Iterator { - self.object(id).into_iter().flat_map(|o| o.fields.iter().map(|(_, v)| v)) - } -} diff --git a/crates/affinity/src/container.rs b/crates/affinity/src/container.rs deleted file mode 100644 index f26948e919..0000000000 --- a/crates/affinity/src/container.rs +++ /dev/null @@ -1,425 +0,0 @@ -//! The Affinity archive: header, the chain of file allocation tables (one per save) and -//! bounded, CRC-checked extraction of named entries such as `doc.dat` and raster tiles. - -use std::collections::{HashMap, HashSet}; -use std::io::Read; - -use crate::Error; - -pub const MAGIC: &[u8; 4] = b"\x00\xffKA"; -/// Oldest and newest container versions seen in real documents (Affinity 1.x writes 8, -/// Affinity 3 writes 12). Version 7 is described by afread but no sample exists. -pub const VERSIONS: std::ops::RangeInclusive = 8..=12; -/// `Prsn` (stored byte-reversed): documents. Asset, brush and style libraries share the magic. -const DOCUMENT_KIND: &[u8; 4] = b"nsrP"; - -/// A save appends one table; real files have one to a few hundred. -const MAX_TABLES: usize = 4096; -/// Allocation records read over the whole table chain. Each save lists every entry again, so a -/// document with a few hundred saves of a few thousand entries stays far below; tables whose -/// record regions overlap (or a table chain of thousands of huge tables) can't multiply the work. -const MAX_INDEX_RECORDS: usize = 1 << 22; -/// Bytes of entry names kept by the index (after lossy UTF-8 decoding, which can triple a name). -/// Real names (`doc.dat`, `d/12`) are a few bytes each. -const MAX_INDEX_NAME_BYTES: usize = 16 << 20; -/// zstd window ceiling: real documents use a few MiB; this stops a header from reserving gigabytes. -const MAX_ZSTD_WINDOW: u64 = 64 << 20; - -/// Decompression budget for one import. Every entry declares its size, which is checked against -/// these limits before anything is allocated, and the decoded length must match it exactly. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Limits { - /// Largest single entry (`doc.dat` or one tile). - pub max_entry: usize, - /// Total bytes extracted over the whole import. - pub max_total: usize, -} - -impl Default for Limits { - fn default() -> Self { - Self { max_entry: 256 << 20, max_total: 1 << 30 } - } -} - -/// The container header, all integers little-endian. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Header { - pub version: u16, - /// Seen as 0, 4 or 8 in real files; bits 0 and 1 mark container variants that are rejected. - pub flags: u16, - pub(crate) fat_offset: u64, - pub(crate) thumbnail_offset: u64, - /// Save time in Unix seconds, as written by the application. - pub saved: u32, -} - -/// One FAT record, as of the newest table that mentions its id. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Entry { - pub id: u32, - pub name: String, - offset: u64, - size: u64, - compressed: u64, - crc: u32, - compression: u8, -} - -impl Entry { - /// Decompressed size declared by the table. - pub fn size(&self) -> u64 { - self.size - } -} - -#[derive(Debug)] -pub struct Archive<'a> { - bytes: &'a [u8], - pub header: Header, - /// Head revision of every named, non-deleted entry. - entries: HashMap, - /// Number of tables (saves) in the chain. - pub revisions: usize, - extracted: usize, - limits: Limits, - /// Entries whose extraction failed after their size was charged: asked again, they fail - /// again without being decompressed again. - failed: HashMap, -} - -pub(crate) struct Cursor<'a> { - bytes: &'a [u8], - pub(crate) pos: usize, -} - -impl<'a> Cursor<'a> { - pub(crate) fn new(bytes: &'a [u8], pos: usize) -> Self { - Self { bytes, pos } - } - pub(crate) fn remaining(&self) -> usize { - self.bytes.len().saturating_sub(self.pos) - } - pub(crate) fn take(&mut self, n: usize) -> Result<&'a [u8], Error> { - let end = self.pos.checked_add(n).ok_or(Error::Malformed("length overflow"))?; - let s = self.bytes.get(self.pos..end).ok_or(Error::Malformed("truncated data"))?; - self.pos = end; - Ok(s) - } - pub(crate) fn array(&mut self) -> Result<[u8; N], Error> { - let s = self.take(N)?; - let mut a = [0u8; N]; - a.copy_from_slice(s); - Ok(a) - } - pub(crate) fn u8(&mut self) -> Result { - Ok(self.array::<1>()?[0]) - } - pub(crate) fn u16(&mut self) -> Result { - Ok(u16::from_le_bytes(self.array()?)) - } - pub(crate) fn u32(&mut self) -> Result { - Ok(u32::from_le_bytes(self.array()?)) - } - pub(crate) fn u64(&mut self) -> Result { - Ok(u64::from_le_bytes(self.array()?)) - } -} - -fn offset(v: u64) -> Result { - usize::try_from(v).map_err(|_| Error::Malformed("offset beyond addressable memory")) -} - -/// True when `bytes` start with the Affinity container signature (documents and libraries). -pub fn is_affinity(bytes: &[u8]) -> bool { - bytes.starts_with(MAGIC) -} - -/// Check the signature, version and document kind. -pub fn header(bytes: &[u8]) -> Result { - if !is_affinity(bytes) { - return Err(Error::Malformed("missing container signature")); - } - let mut c = Cursor::new(bytes, 4); - let version = c.u16()?; - let flags = c.u16()?; - if !VERSIONS.contains(&version) { - return Err(Error::Unsupported("unknown container version")); - } - if flags & 3 != 0 { - return Err(Error::Unsupported("container variant")); - } - if c.take(4)? != DOCUMENT_KIND { - return Err(Error::Unsupported("this Affinity file is a library (assets, brushes or styles), not a document")); - } - if c.take(4)? != b"#Inf" { - return Err(Error::Malformed("missing information header")); - } - let fat_offset = c.u64()?; - let thumbnail_offset = c.u64()?; - c.take(16)?; - let saved = u32::try_from(c.u64()?).unwrap_or(0); - c.take(8)?; - if c.take(4)? != b"Prot" { - return Err(Error::Malformed("missing protocol header")); - } - Ok(Header { version, flags, fat_offset, thumbnail_offset, saved }) -} - -impl<'a> Archive<'a> { - pub fn open(bytes: &'a [u8], limits: Limits) -> Result { - Self::open_within(bytes, limits, MAX_INDEX_RECORDS, MAX_INDEX_NAME_BYTES) - } - - /// [`Archive::open`] reading at most `max_records` allocation records and keeping at most - /// `max_name_bytes` bytes of entry names, both over the whole table chain. - pub(crate) fn open_within(bytes: &'a [u8], limits: Limits, max_records: usize, max_name_bytes: usize) -> Result { - let header = header(bytes)?; - let mut records_left = max_records; - let mut name_bytes_left = max_name_bytes; - // Newest record per id: (table date, table index, record). - let mut latest: HashMap)> = HashMap::new(); - let mut names: HashMap = HashMap::new(); - let mut seen = HashSet::new(); - let mut next = header.fat_offset; - let mut tables = 0usize; - while next != 0 { - if !seen.insert(next) { - return Err(Error::Malformed("allocation tables form a cycle")); - } - tables += 1; - if tables > MAX_TABLES { - return Err(Error::Limit("too many saved revisions")); - } - let mut c = Cursor::new(bytes, offset(next)?); - let tag = c.array::<4>()?; - let level = match &tag { - b"#FAT" => 1, - b"#FT2" => 2, - b"#FT3" => 3, - b"#FT4" => 4, - _ => return Err(Error::Malformed("missing allocation table")), - }; - next = c.u64()?; - let date = c.u64()?; - c.take(24)?; - let files = c.u32()?; - c.take(8)?; - let dirs = c.u16()?; - c.take(1)?; - for _ in 0..files { - records_left = records_left.checked_sub(1).ok_or(Error::Limit("too many archive entries"))?; - let id = c.u32()?; - let flag = c.u8()?; - let mut record = None; - match flag { - 0 | 1 => { - let offset = c.u64()?; - let size = c.u64()?; - let compressed = c.u64()?; - let crc = c.u32()?; - let stored = c.u8()?; - if level >= 2 { - c.take(4)?; - } - if level >= 4 { - c.take(4)?; - } - // Old tables number the methods; newer ones store the method byte itself. - let compression = if level <= 2 { - match stored { - 1 => 0x01, - 2 => 0x41, - 3 => 0x81, - 4 => 0xC1, - _ => 0, - } - } else { - stored - }; - record = Some(Entry { id, name: String::new(), offset, size, compressed, crc, compression }); - } - 2 => {} - _ => return Err(Error::Malformed("unknown allocation record")), - } - if flag == 0 { - let len = usize::from(c.u16()?); - let raw = c.take(len)?; - // Only the first name of an id is kept: later ones are not even decoded. - if let std::collections::hash_map::Entry::Vacant(slot) = names.entry(id) { - let name = String::from_utf8_lossy(raw); - name_bytes_left = name_bytes_left.checked_sub(name.len()).ok_or(Error::Limit("archive entry names too long"))?; - slot.insert(name.into_owned()); - } - } - // Equal dates: the first table in the chain (the newest) wins, as in afread. - let replace = latest.get(&id).is_none_or(|(d, _, _)| date > *d); - if replace { - latest.insert(id, (date, tables, record)); - } - } - for _ in 0..dirs { - records_left = records_left.checked_sub(1).ok_or(Error::Limit("too many archive entries"))?; - let len = usize::from(c.u16()?); - c.take(10)?; - c.take(len)?; - } - } - let mut entries = HashMap::new(); - for (id, (_, _, record)) in latest { - if let (Some(mut e), Some(name)) = (record, names.remove(&id)) { - e.name = name; - entries.insert(e.name.clone(), e); - } - } - Ok(Self { bytes, header, entries, revisions: tables, extracted: 0, limits, failed: HashMap::new() }) - } - - pub fn entry(&self, name: &str) -> Option<&Entry> { - self.entries.get(name) - } - - pub fn entry_names(&self) -> impl Iterator { - self.entries.keys().map(String::as_str) - } - - /// Bytes extracted so far, counted against [`Limits::max_total`]. - pub fn extracted(&self) -> usize { - self.extracted - } - - /// Extract an entry by name: decompress, undo the byte predictor and verify the CRC. - /// What is left of the limits for documents embedded in this one. - pub(crate) fn remaining(&self) -> Limits { - Limits { max_entry: self.limits.max_entry, max_total: self.limits.max_total.saturating_sub(self.extracted) } - } - - /// Count `n` bytes extracted elsewhere (from embedded documents) against this import. - pub(crate) fn charge(&mut self, n: usize) -> Result<(), Error> { - let total = self.extracted.checked_add(n).ok_or(Error::Limit("document too large"))?; - if total > self.limits.max_total { - return Err(Error::Limit("document too large")); - } - self.extracted = total; - Ok(()) - } - - pub fn read(&mut self, name: &str) -> Result, Error> { - if let Some(e) = self.failed.get(name) { - return Err(*e); - } - let e = self.entries.get(name).ok_or(Error::Malformed("missing archive entry"))?; - let size = usize::try_from(e.size).map_err(|_| Error::Limit("archive entry too large"))?; - if size > self.limits.max_entry { - return Err(Error::Limit("archive entry too large")); - } - let total = self.extracted.checked_add(size).ok_or(Error::Limit("document too large"))?; - if total > self.limits.max_total { - return Err(Error::Limit("document too large")); - } - // Charged before the work, and kept when it fails: an entry that fails its checksum - // can't be decompressed over and over for free. - self.extracted = total; - let result = extract(self.bytes, e, size); - if let Err(err) = result { - self.failed.insert(name.to_owned(), err); - } - result - } -} - -/// Decompress entry `e` of `bytes` (declared `size` bytes), undo its predictor and check its CRC. -fn extract(bytes: &[u8], e: &Entry, size: usize) -> Result, Error> { - let mut c = Cursor::new(bytes, offset(e.offset)?); - if c.take(4)? != b"#Fil" { - return Err(Error::Malformed("archive entry has no data block")); - } - let method = e.compression & 3; - let stored_len = if matches!(method, 1 | 2) { e.compressed } else { e.size }; - let data = c.take(offset(stored_len)?)?; - let mut out = match method { - 1 => inflate(data, size)?, - 2 => unzstd(data, size)?, - _ => data.to_vec(), - }; - if out.len() != size { - return Err(Error::Malformed("archive entry size mismatch")); - } - unpredict(&mut out, e.compression)?; - if crc32fast::hash(&out) != e.crc { - return Err(Error::Malformed("archive entry checksum mismatch")); - } - Ok(out) -} - -/// Read at most `size + 1` bytes so a stream that decodes past its declared size is caught -/// without unbounded allocation. -fn read_bounded(mut r: impl Read, size: usize) -> Result, Error> { - let mut out = Vec::with_capacity(size.min(64 << 20)); - let cap = u64::try_from(size).unwrap_or(u64::MAX).saturating_add(1); - r.by_ref().take(cap).read_to_end(&mut out).map_err(|_| Error::Malformed("corrupt compressed entry"))?; - Ok(out) -} - -fn inflate(data: &[u8], size: usize) -> Result, Error> { - read_bounded(flate2::read::ZlibDecoder::new(data), size) -} - -fn unzstd(data: &[u8], size: usize) -> Result, Error> { - let mut src = data; - let mut out = Vec::new(); - // Entries may hold several concatenated frames. - while !src.is_empty() { - let left = size.checked_sub(out.len()).ok_or(Error::Malformed("archive entry size mismatch"))?; - let decoder = ruzstd::decoding::StreamingDecoder::new_with_max_window_size(&mut src, MAX_ZSTD_WINDOW) - .map_err(|_| Error::Malformed("corrupt compressed entry"))?; - let frame = read_bounded(decoder, left)?; - if frame.is_empty() { - return Err(Error::Malformed("corrupt compressed entry")); - } - out.extend_from_slice(&frame); - if out.len() > size { - return Err(Error::Malformed("archive entry size mismatch")); - } - } - Ok(out) -} - -/// Undo the byte predictor selected by the high bits of the compression byte. -fn unpredict(b: &mut [u8], compression: u8) -> Result<(), Error> { - match (compression & 0xC0, compression & 0x20 != 0) { - (0x00, _) => {} - (0x40, _) => byte_delta(b), - (0x80, false) => { - let mut prev = 0u16; - for pair in b.as_chunks_mut::<2>().0.iter_mut() { - let v = u16::from_le_bytes([pair[0], pair[1]]).wrapping_add(prev); - pair.copy_from_slice(&v.to_le_bytes()); - prev = v; - } - } - (0x80, true) => { - byte_delta(b); - // A 64 KiB tile of 16-bit samples is stored as all high bytes, then all low bytes. - if b.len() == 0x10000 { - let planes = b.to_vec(); - let (hi, lo) = planes.split_at(0x8000); - for (i, out) in b.as_chunks_mut::<4>().0.iter_mut().enumerate() { - let (Some(h), Some(l)) = (hi.get(2 * i..2 * i + 2), lo.get(2 * i..2 * i + 2)) else { - return Err(Error::Malformed("tile size")); - }; - out.copy_from_slice(&[l[0], h[0], l[1], h[1]]); - } - } - } - _ => return Err(Error::Unsupported("archive entry predictor")), - } - Ok(()) -} - -fn byte_delta(b: &mut [u8]) { - let mut prev = 0u8; - for v in b { - *v = v.wrapping_add(prev); - prev = *v; - } -} diff --git a/crates/affinity/src/geometry.rs b/crates/affinity/src/geometry.rs deleted file mode 100644 index bb1c45746b..0000000000 --- a/crates/affinity/src/geometry.rs +++ /dev/null @@ -1,360 +0,0 @@ -//! Outlines of curves (`PCvD` node lists), parametric shapes (`Shpe` objects) and compounds, in -//! node space. - -use crate::model::{Affine, Path, Point, Reader, SubPath}; -use crate::stream::{ObjId, Tag, Value}; - -/// Nodes per curve object. -const MAX_NODES: usize = 4_000_000; -/// A shared-object stream is bounded, but a compound graph can expand exponentially. Count -/// each visit and each curve record / generated contour / transformed segment across the whole -/// outline, including repeated references. Match the document reader's nesting limit. -const MAX_OUTLINE_DEPTH: usize = 128; -const MAX_OUTLINE_VISITS: usize = 100_000; - -struct OutlineBudget { - active: Vec, - visits: usize, - work: usize, - failed: bool, -} - -impl OutlineBudget { - fn fail(&mut self, r: &mut Reader, warning: &'static str) -> Option<()> { - if !self.failed { - r.warn(warning); - } - self.failed = true; - None - } - - fn spend(&mut self, r: &mut Reader, work: usize) -> Option<()> { - if work > self.work { - return self.fail(r, "compound outlines exceeding the geometry work limit"); - } - self.work -= work; - Some(()) - } - - fn path(&mut self, r: &mut Reader, path: &Path) -> Option<()> { - for subpath in &path.subpaths { - self.spend(r, 1)?; - self.spend(r, subpath.segments.len())?; - } - Some(()) - } -} - -/// The node-space outline of a curve, shape or compound node, and whether it fills even-odd. -/// Instances (master-page or symbol copies) take the geometry of their master. -pub(crate) fn outline(r: &mut Reader, id: ObjId, class: Tag, world: Affine) -> Option<(Path, bool)> { - let mut budget = OutlineBudget { active: Vec::new(), visits: MAX_OUTLINE_VISITS, work: MAX_NODES, failed: false }; - bounded_outline(r, id, class, world, &mut budget) -} - -fn bounded_outline(r: &mut Reader, id: ObjId, class: Tag, world: Affine, budget: &mut OutlineBudget) -> Option<(Path, bool)> { - if budget.active.contains(&id) { - budget.fail(r, "a compound outline that contains itself")?; - } - if budget.active.len() >= MAX_OUTLINE_DEPTH { - budget.fail(r, "compound outlines nested deeper than 128 levels")?; - } - if budget.visits == 0 { - budget.fail(r, "compound outlines exceeding the operand visit limit")?; - } - budget.visits -= 1; - budget.active.push(id); - let result = outline_inner(r, id, class, world, budget); - // The popped value is our own stack marker, and is no longer needed. - let _ = budget.active.pop(); - result -} - -fn outline_inner(r: &mut Reader, id: ObjId, class: Tag, world: Affine, budget: &mut OutlineBudget) -> Option<(Path, bool)> { - let s = r.s; - match &class.0.to_be_bytes() { - b"PCrv" | b"TxtC" => { - let crvs = s.obj(id, b"Crvs").or_else(|| s.obj(id, b"MCrM").and_then(|m| s.obj(m, b"Crvs")))?; - let path = curves(r, crvs, budget)?; - budget.path(r, &path)?; - let multi = path.subpaths.len() > 1; - Some((path, multi)) - } - b"Comp" => { - // One path of all the operands' contours in the compound's space, filled even-odd: this - // matches add and subtract operands in every public sample; a true union of overlapping - // added operands would differ. - let mut path = Path::default(); - for c in s.objs(id, b"Chld") { - let local = s.floats::<6>(c, b"Xfrm").map(Affine::from_xfrm).unwrap_or(Affine::IDENTITY); - let class = s.class(c)?; - if s.enumeration(c, b"ComO").is_some_and(|(op, _)| op != 0 && op != 2) { - r.warn("compound shapes that intersect or exclude (imported as add)"); - } - let child_world = local.then(world); - if !child_world.is_finite() { - budget.fail(r, "a compound operand with an invalid transform")?; - } - if let Some((mut p, _)) = bounded_outline(r, c, class, child_world, budget) { - // Charge before transforming or extending. Transform the owned path in place - // so nested compounds do not make an additional copy of every contour. - budget.path(r, &p)?; - for subpath in &mut p.subpaths { - subpath.start = local.apply(subpath.start); - for segment in &mut subpath.segments { - *segment = segment.map(|point| local.apply(point)); - } - } - path.subpaths.extend(p.subpaths); - } else if budget.failed { - // Never present a partial compound as complete after a cycle or budget limit. - return None; - } - } - Some((path, true)) - } - _ => { - let (shape, box_owner) = match s.obj(id, b"Shpe") { - Some(sh) => (sh, id), - None => { - let master = s.obj(id, b"ShpM")?; - (s.obj(master, b"Shpe")?, master) - } - }; - let b = s.floats::<4>(box_owner, b"ShpB")?; - let path = crate::shapes::shape(r, shape, b, world)?; - budget.path(r, &path)?; - Some((path, false)) - } - } -} - -/// `PCvD.Data`: positional `[u8, u32 count, then per subpath: bool closed, 18-byte records]`. -/// A record is (f64 x, f64 y, u8 kind, u8 role): role 0 is an anchor, 1 the out-handle of the -/// anchor before it, 2 the in-handle of the anchor after it. A closed subpath repeats its first -/// anchor at the end. `CnrD` live corners are rounded on the stored polyline. -fn curves(r: &mut Reader, crvs: ObjId, budget: &mut OutlineBudget) -> Option { - let s = r.s; - let data = s.obj(crvs, b"Data")?; - let mut fields = s.positional(data); - fields.next()?; - let count = match fields.next()? { - Value::UInt(n) => usize::try_from(*n).ok()?, - _ => return None, - }; - budget.spend(r, count)?; - let corners = s.obj(crvs, b"CnrD").and_then(|c| corner_radii(s.positional(c).collect())); - let mut path = Path::default(); - let mut seen = 0usize; - for index in 0..count { - let closed = match fields.next()? { - Value::Bool(b) => *b, - _ => return None, - }; - let Value::Array(records) = fields.next()? else { return None }; - seen = seen.checked_add(records.len())?; - if seen > MAX_NODES { - budget.fail(r, "curves with more than four million nodes")?; - } - budget.spend(r, records.len())?; - let anchors = anchors(records)?; - let radii = if index == 0 { corners.as_ref() } else { None }; - if let Some(sp) = subpath(&anchors, closed, radii) { - path.subpaths.push(sp); - } - } - if corners.is_some() && count > 1 { - r.warn("rounded corners on curves with several subpaths (only the first is rounded)"); - } - Some(path) -} - -/// Most segments a stroke's pressure curve may have; the curves in real documents have a handful. -const MAX_PRESSURE_SEGMENTS: usize = 256; - -/// Most regular samples of a pressure curve: each segment gets an equal share, at least 2 (its -/// middle and its end) and 8 at most. The points where a segment's width stops rising or falling -/// come on top (at most two per segment), so a curve has at most 1 + 4 × [`MAX_PRESSURE_SEGMENTS`] -/// points; the document's limit counts all of them. -const PRESSURE_POINTS: usize = 512; - -/// Most points one pressure curve can have (see [`PRESSURE_POINTS`]). A curve that can't be read -/// counts this many against the document's limit. -pub(crate) const MAX_PRESSURE_CURVE_POINTS: usize = 1 + 4 * MAX_PRESSURE_SEGMENTS; - -/// A stroke's pressure curve (`LDsc.LDeP`, a `CrvD` whose positional `Data` holds an array of -/// 18-byte records as in [`curves`]): x is the position along the path (0 to 1) and y the width as -/// a fraction of the stroke's weight. Each segment is sampled at 2 to 8 points, at most -/// [`PRESSURE_POINTS`] in all, and also where its width stops rising or falling (at most two more -/// points), so a dip between samples is kept → (position, width) in order along the path, -/// positions clamped into 0..1 and never going back, widths clamped into 0..1. `None` when the -/// curve can't be read or has more than [`MAX_PRESSURE_SEGMENTS`] segments. -pub(crate) fn pressure(r: &Reader, crvd: ObjId) -> Option> { - let s = r.s; - let data = s.obj(crvd, b"Data")?; - let records = s.positional(data).find_map(|v| if let Value::Array(a) = v { Some(a) } else { None })?; - // Every segment takes at least an anchor record. - if records.len() > MAX_PRESSURE_SEGMENTS * 3 + 1 { - return None; - } - let curve = subpath(&anchors(records)?, false, None)?; - if curve.segments.len() > MAX_PRESSURE_SEGMENTS { - return None; - } - let steps = u32::try_from((PRESSURE_POINTS / curve.segments.len().max(1)).clamp(2, 8)).unwrap_or(2); - let mut samples = vec![(curve.start.x, curve.start.y)]; - let mut from = curve.start; - for [c1, c2, to] in &curve.segments { - let mut ts: Vec = (1..=steps).map(|i| f64::from(i) / f64::from(steps)).collect(); - ts.extend(turning_points(from.y, c1.y, c2.y, to.y).into_iter().flatten()); - ts.sort_by(f64::total_cmp); - ts.dedup_by(|a, b| (*a - *b).abs() < 1e-9); - for t in ts { - let u = 1.0 - t; - let at = |a: f64, b: f64, c: f64, d: f64| u * u * u * a + 3.0 * u * u * t * b + 3.0 * u * t * t * c + t * t * t * d; - samples.push((at(from.x, c1.x, c2.x, to.x), at(from.y, c1.y, c2.y, to.y))); - } - from = *to; - } - let mut last = 0.0f64; - Some( - samples - .into_iter() - .map(|(x, y)| { - last = x.clamp(last, 1.0); - (last, y.clamp(0.0, 1.0)) - }) - .collect(), - ) -} - -/// The parameters strictly between 0 and 1 where the cubic Bézier with control values `a`, `b`, -/// `c` and `d` stops rising or falling (where its derivative is 0). The values are scaled into -/// -1..1 first, so huge ones can't overflow the discriminant. -fn turning_points(a: f64, b: f64, c: f64, d: f64) -> [Option; 2] { - let scale = a.abs().max(b.abs()).max(c.abs()).max(d.abs()); - if !(scale.is_finite() && scale > 0.0) { - return [None, None]; - } - let (a, b, c, d) = (a / scale, b / scale, c / scale, d / scale); - let (d0, d1, d2) = (b - a, c - b, d - c); - let (qa, qb, qc) = (d0 - 2.0 * d1 + d2, 2.0 * (d1 - d0), d0); - let inside = |t: f64| (t.is_finite() && t > 0.0 && t < 1.0).then_some(t); - if qa.abs() < 1e-12 { - return [if qb.abs() < 1e-12 { None } else { inside(-qc / qb) }, None]; - } - let disc = qb * qb - 4.0 * qa * qc; - if disc < 0.0 { - return [None, None]; - } - let root = disc.sqrt(); - [inside((-qb - root) / (2.0 * qa)), inside((-qb + root) / (2.0 * qa))] -} - -struct Anchor { - p: Point, - inh: Option, - out: Option, - /// Index of the anchor's record (live corners refer to records). - record: usize, -} - -fn record(v: &Value) -> Option<(Point, u8)> { - let Value::Bytes(b) = v else { return None }; - if b.len() != 18 { - return None; - } - let x = f64::from_le_bytes(b.get(0..8)?.try_into().ok()?); - let y = f64::from_le_bytes(b.get(8..16)?.try_into().ok()?); - if !x.is_finite() || !y.is_finite() { - return None; - } - Some((Point { x, y }, *b.get(17)?)) -} - -fn anchors(records: &[Value]) -> Option> { - let mut out: Vec = Vec::with_capacity(records.len() / 3 + 1); - let mut pending_in = None; - for (i, v) in records.iter().enumerate() { - let (p, role) = record(v)?; - match role { - 0 => { - out.push(Anchor { p, inh: pending_in.take(), out: None, record: i }); - } - 1 => { - // A leading out-handle without an anchor is edit state only. - if let Some(a) = out.last_mut() { - a.out = Some(p); - } - } - 2 => pending_in = Some(p), - _ => return None, - } - } - Some(out) -} - -fn subpath(anchors: &[Anchor], closed: bool, radii: Option<&Vec<(usize, f64)>>) -> Option { - let first = anchors.first()?; - if let Some(radii) = radii.filter(|r| !r.is_empty()) { - // The largest radius of each record, once (not a scan of all of them for each anchor). - let mut largest: std::collections::HashMap = std::collections::HashMap::new(); - for (rec, r) in radii { - let e = largest.entry(*rec).or_insert(0.0); - *e = e.max(*r); - } - let corner = |a: &Anchor| largest.get(&a.record).copied().unwrap_or(0.0); - let polyline = anchors.iter().all(|a| a.inh.is_none_or(|h| h == a.p) && a.out.is_none_or(|h| h == a.p)); - if polyline { - let mut pts: Vec<(Point, f64)> = anchors.iter().map(|a| (a.p, corner(a))).collect(); - // A closed subpath repeats its first anchor; its radius may be on either copy. - if closed - && pts.len() > 1 - && pts.first().map(|p| p.0) == pts.last().map(|p| p.0) - && let Some((_, r)) = pts.pop() - && let Some(f) = pts.first_mut() - { - f.1 = f.1.max(r); - } - return Some(crate::shapes::fillet(&pts, closed)); - } - } - let segments = anchors - .windows(2) - .filter_map(|w| { - let [a, b] = w else { return None }; - Some([a.out.unwrap_or(a.p), b.inh.unwrap_or(b.p), b.p]) - }) - .collect(); - Some(SubPath { start: first.p, segments, closed }) -} - -/// `CnrD`: positional `[u8, i32[] record indices, f64[] radii, u8[] types]`. -fn corner_radii(fields: Vec<&Value>) -> Option> { - let (Some(Value::Array(idx)), Some(Value::Array(rad))) = (fields.get(1), fields.get(2)) else { return None }; - Some( - idx.iter() - .zip(rad) - .filter_map(|(i, r)| match (i, r) { - (Value::Int(i), Value::Float(r)) if r.is_finite() && *r > 0.0 => Some((usize::try_from(*i).ok()?, *r)), - _ => None, - }) - .collect(), - ) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn turning_points_of_huge_control_values_are_found() { - let small = turning_points(1.0, -3.0, 3.0, 1.0); - let huge = turning_points(1e200, -3e200, 3e200, 1e200); - assert!(small.iter().all(Option::is_some), "{small:?}"); - for (s, h) in small.iter().zip(&huge) { - let (Some(s), Some(h)) = (s, h) else { panic!("{huge:?}") }; - assert!((s - h).abs() < 1e-12, "{small:?} {huge:?}"); - } - } -} diff --git a/crates/affinity/src/lib.rs b/crates/affinity/src/lib.rs index 38d86a8990..e14c1439a7 100644 --- a/crates/affinity/src/lib.rs +++ b/crates/affinity/src/lib.rs @@ -1,52 +1,6 @@ -//! Reader for native Affinity documents (`.af`, and `.afdesign`/`.afphoto`/`.afpub` from -//! Affinity 1 and 2): the archive container, the tagged object stream in `doc.dat`, and the -//! subset of the document model VectorCraft imports. -//! -//! Layouts follow the MIT-licensed afread reference and were checked against public documents -//! saved by Affinity 1.x to 3.x (container versions 8 to 12); see the crate README for provenance -//! and the exact supported subset. Nothing here writes Affinity files. +//! The Affinity reader is `craft-affinity` (storytold/craft-libs). This crate keeps its name so +//! the corpus tests and fuzz targets under it, and the CI job that runs them, still build. #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] -use std::fmt; - -mod access; -pub mod container; -mod geometry; -pub mod model; -pub mod overlay; -pub mod paint; -pub mod preview; -mod raster; -mod shapes; -pub mod stream; -#[cfg(any(test, feature = "synth"))] -pub mod synth; -mod text; - -pub use container::{Archive, Limits, MAGIC, is_affinity}; -pub use model::{Document, read}; -pub use preview::{MAX_PREVIEW_BYTES, MAX_PREVIEW_DIMENSION, Preview, preview}; - -/// Why a file could not be read. Messages are short reasons; callers add advice. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Error { - Malformed(&'static str), - Unsupported(&'static str), - Limit(&'static str), -} - -impl fmt::Display for Error { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Malformed(s) => write!(f, "damaged Affinity file: {s}"), - Self::Unsupported(s) => write!(f, "unsupported Affinity file: {s}"), - Self::Limit(s) => write!(f, "Affinity file exceeds a safety limit: {s}"), - } - } -} - -impl std::error::Error for Error {} - -#[cfg(test)] -mod tests; +pub use craft_affinity::*; diff --git a/crates/affinity/src/model.rs b/crates/affinity/src/model.rs deleted file mode 100644 index a6d18f339e..0000000000 --- a/crates/affinity/src/model.rs +++ /dev/null @@ -1,471 +0,0 @@ -//! The document model the Craft apps import: spreads, artboards, layers, groups, curves, shapes, -//! text and images, with transforms composed into document space. Anything else is reported -//! by [`Document::warnings`] instead of being dropped silently. - -use std::collections::{BTreeMap, HashSet}; - -use crate::paint::{self, Paint, Stroke}; -use crate::stream::{ObjId, Stream, Tag}; -use crate::{Archive, Error, Limits, stream}; - -mod bounds; -mod read; - -pub(crate) use bounds::rect; -pub use bounds::{kind_bounds, nodes_bounds}; -pub(crate) use read::Reader; -pub use read::read; -#[cfg(test)] -pub(crate) use read::read_within; - -/// Affine map `x' = a·x + c·y + e`, `y' = b·x + d·y + f` (kurbo's coefficient order). -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct Affine(pub [f64; 6]); - -impl Affine { - pub const IDENTITY: Self = Self([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]); - - /// Affinity's `Xfrm`, stored row by row: (a, c, e, b, d, f). - pub(crate) fn from_xfrm(m: [f64; 6]) -> Self { - Self([m[0], m[3], m[1], m[4], m[2], m[5]]) - } - - pub fn then(self, outer: Self) -> Self { - let [a, b, c, d, e, f] = self.0; - let [oa, ob, oc, od, oe, of] = outer.0; - Self([oa * a + oc * b, ob * a + od * b, oa * c + oc * d, ob * c + od * d, oa * e + oc * f + oe, ob * e + od * f + of]) - } - - pub fn apply(&self, p: Point) -> Point { - let [a, b, c, d, e, f] = self.0; - Point { x: a * p.x + c * p.y + e, y: b * p.x + d * p.y + f } - } - - /// Geometric mean of the axis scales: how much a stroke width or font size grows. - pub fn scale(&self) -> f64 { - let [a, b, c, d, ..] = self.0; - (a * d - b * c).abs().sqrt() - } - - pub fn is_finite(&self) -> bool { - self.0.iter().all(|v| v.is_finite()) - } -} - -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct Point { - pub x: f64, - pub y: f64, -} - -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct Rect { - pub x0: f64, - pub y0: f64, - pub x1: f64, - pub y1: f64, -} - -/// One cubic Bézier subpath, in document pixels. -#[derive(Debug, Clone, PartialEq)] -pub struct SubPath { - pub start: Point, - /// (control 1, control 2, end) per segment. - pub segments: Vec<[Point; 3]>, - pub closed: bool, -} - -/// An outline in document pixels. -#[derive(Debug, Clone, Default, PartialEq)] -pub struct Path { - pub subpaths: Vec, -} - -impl Path { - pub fn transformed(&self, m: Affine) -> Self { - Self { - subpaths: self - .subpaths - .iter() - .map(|s| SubPath { - start: m.apply(s.start), - segments: s.segments.iter().map(|seg| seg.map(|p| m.apply(p))).collect(), - closed: s.closed, - }) - .collect(), - } - } -} - -/// Affinity's blend modes, numbered by the `Blnd` enum. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -pub enum Blend { - #[default] - Normal, - PassThrough, - Darken, - DarkerColor, - Multiply, - ColorBurn, - Lighten, - LighterColor, - Screen, - ColorDodge, - Add, - Overlay, - SoftLight, - HardLight, - VividLight, - PinLight, - LinearLight, - HardMix, - Difference, - Exclusion, - Subtract, - Hue, - Saturation, - Luminosity, - Color, - Average, - Negation, - Reflect, - Glow, - Erase, -} - -impl Blend { - /// The enum (id, version) pairs observed in a document whose layers are named after their mode. - fn from_enum(id: u16, version: u16) -> Option { - use Blend::*; - Some(match (id, version) { - (0, _) => Normal, - (1, 0) => Darken, - (2, 1) => DarkerColor, - (2, 0) => Multiply, - (3, 0) => ColorBurn, - (4, 0) => Lighten, - (6, 1) => LighterColor, - (5, 0) => Screen, - (6, 0) => ColorDodge, - (7, 0) => Add, - (8, 0) => Overlay, - (9, 0) => SoftLight, - (10, 0) => HardLight, - (11, 0) => VividLight, - (12, 0) => PinLight, - (15, 1) => LinearLight, - (13, 0) => HardMix, - (14, 0) => Difference, - (15, 0) => Exclusion, - (16, 0) => Subtract, - (17, 0) => Hue, - (18, 0) => Saturation, - (19, 0) => Luminosity, - (20, 0) => Color, - (21, 0) => Average, - (22, 0) => Negation, - (23, 0) => Reflect, - (24, 0) => Glow, - (25, 0) => Erase, - _ => return None, - }) - } -} - -/// A run of text with one set of character attributes. -#[derive(Debug, Clone, PartialEq)] -pub struct TextRun { - pub text: String, - /// PostScript name and family of the chosen font. - pub postscript: String, - pub family: String, - /// CSS weight (400 regular, 700 bold). - pub weight: i64, - pub italic: bool, - /// Boolean OpenType feature overrides, as tags or `-tag` for disabled features. - pub features: Vec, - pub all_caps: bool, - /// Underlined characters (`Ints` slot 0 is 1; identified on underlined words in a document its - /// owner made, all other characters there and in the public corpus have 0). - pub underline: bool, - /// Struck-through characters (`Ints` slot 1 is 1; identified the same way, on prices struck - /// through in another document its owner made). - pub strikethrough: bool, - /// Font size in document pixels, before the node's transform. - pub size: f64, - /// Tracking in em. - pub tracking: f64, - /// Horizontal scale of the glyphs (1 = as designed). - pub h_scale: f64, - /// Fixed line pitch in document pixels, when the run overrides automatic leading. - pub leading: Option, - pub fill: Paint, - /// Outlined characters: the outline's paint and width (node space). - pub stroke: Option, - /// The run's paragraph: alignment, indents and spacing. - pub paragraph: Paragraph, -} - -/// Paragraph alignment, indents, spacing and leading, in node space (document pixels before the -/// node's text scale). -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct Paragraph { - pub align: Align, - /// Indent of every line but the first, from the left. - pub left: f64, - pub right: f64, - /// Indent of the first line, from the left. - pub first: f64, - pub space_before: f64, - pub space_after: f64, - /// Fixed distance between baselines, when the paragraph sets one. - pub leading: Option, - /// Automatic leading as a multiple of the font's own line height (ascent plus descent). - pub auto_leading: f64, -} - -impl Default for Paragraph { - fn default() -> Self { - Self { align: Align::Left, left: 0.0, right: 0.0, first: 0.0, space_before: 0.0, space_after: 0.0, leading: None, auto_leading: 1.0 } - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -pub enum Align { - #[default] - Left, - Center, - Right, - Justify, -} - -#[derive(Debug, Clone, PartialEq)] -pub struct Text { - pub runs: Vec, - pub align: Align, - /// Artistic text: the first baseline's anchor point in node space (start, centre or end of the - /// line according to `align`). Frame text: the frame box in node space. - pub anchor: Point, - pub frame: Option, - /// Node space to document pixels. - pub transform: Affine, - /// Node space to document pixels for the type (its linear part matters): artistic text scales - /// with its node, frame text only with its frame's text scale. - pub text_transform: Affine, -} - -/// Vertical alignment of a table cell's text. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum VAlign { - Top, - Center, - Bottom, -} - -#[derive(Debug, Clone, PartialEq)] -pub struct TableCell { - pub runs: Vec, - /// Space between the cell edges and its text, in node space: left, top, right, bottom. - pub inset: [f64; 4], - pub valign: VAlign, - /// Part of the cell to its left (merged): it has no text of its own. - pub merged_left: bool, -} - -/// A table: a grid of cells with text, and a line on every cell edge. -#[derive(Debug, Clone, PartialEq)] -pub struct Table { - /// Column boundaries (one more than the columns), increasing, in node space. - pub columns: Vec, - /// Row boundaries (one more than the rows), increasing, in node space. - pub rows: Vec, - /// Row by row. - pub cells: Vec, - /// Vertical edges row by row, one more per row than the columns; `None` draws no line, and - /// the list is empty when the file's didn't match the grid. - pub vertical: Vec>, - /// Horizontal edges boundary by boundary (one more than the rows), one per column (empty - /// as `vertical` can be). - pub horizontal: Vec>, - /// Node space to document pixels. - pub transform: Affine, - /// Node space to document pixels for the cells' type: resizing a table moves its grid, not - /// its type. - pub text_transform: Affine, -} - -impl Table { - pub fn ncols(&self) -> usize { - self.columns.len().saturating_sub(1) - } - pub fn nrows(&self) -> usize { - self.rows.len().saturating_sub(1) - } -} - -#[derive(Debug, Clone, PartialEq)] -pub enum Pixels { - /// Straight-alpha RGBA, 8 bits per channel, row by row. - Rgba8(Vec), - /// A CMYK pixel layer: cyan, magenta, yellow and black ink amounts (0 none, 255 full) and - /// straight alpha, 8 bits each, row by row. Left in CMYK for the importer to show through a - /// colour profile: the profile-free formula turns the extra cyan of a separation's neutrals - /// into a blue cast. - Cmyka8(Vec), - /// The original file a placed image was made from (PNG, JPEG…), as embedded. - Encoded(Vec), -} - -#[derive(Debug, Clone, PartialEq)] -pub struct Image { - pub width: u32, - pub height: u32, - pub pixels: Pixels, - /// Pixel space (0..w, 0..h) to document pixels. - pub transform: Affine, -} - -#[derive(Debug, Clone, PartialEq)] -pub enum Kind { - /// Layer container (`Scop`). - Layer, - Group, - /// Artboard: an export rectangle and vector outline that clips its children. - /// `background` paints behind them, and `strokes` over them. - Artboard { - rect: Rect, - /// Actual clipping outline in document pixels. The artboard's export rectangle is its - /// bounding box, but a rotated or non-rectangular board still clips to this outline. - path: Path, - even_odd: bool, - background: Vec, - strokes: Vec, - }, - /// Curve, parametric shape or compound shape: an outline with its fills and strokes. - /// Children of a shape are clipped by its outline (painted over its fills, under its strokes). - Shape { - path: Path, - fills: Vec, - strokes: Vec, - even_odd: bool, - }, - Text(Text), - Table(Table), - Image(Image), - /// A master page shown on this spread's pages: pages `page..page + count` show the master - /// spread [`Document::masters`]`[master]`'s pages from `master_page` on. - MasterInstance { - master: usize, - page: usize, - master_page: usize, - count: usize, - }, - /// Something this reader does not import; its children are still imported. - Unsupported, -} - -/// A layer effect. Lengths are document pixels; `angle` is the direction the shadow is offset in -/// (radians, clockwise from +x as y points down: π/2 puts it below). -#[derive(Debug, Clone, PartialEq)] -pub enum Effect { - DropShadow { - color: crate::paint::Color, - opacity: f64, - radius: f64, - distance: f64, - angle: f64, - }, - InnerShadow { - color: crate::paint::Color, - opacity: f64, - radius: f64, - distance: f64, - angle: f64, - }, - OuterGlow { - color: crate::paint::Color, - opacity: f64, - radius: f64, - }, - /// An outline of `width` around the node's shape: `align` 0 outside, 1 inside, 2 centred. - Outline { - color: crate::paint::Color, - opacity: f64, - width: f64, - align: u16, - }, - /// Bevel and emboss: lit and shaded edges `size` wide. `angle` is the light's azimuth - /// (radians, counter-clockwise from +x with y up), `depth` Affinity's depth (5 by default); - /// `inner` is false for the outer, emboss and pillow kinds. - Bevel { - size: f64, - depth: f64, - angle: f64, - highlight: crate::paint::Color, - highlight_opacity: f64, - shadow: crate::paint::Color, - shadow_opacity: f64, - inner: bool, - }, - /// Colour overlay: everything the node paints takes `color`, laid over it in `blend` mode at - /// `opacity` (the node's own alpha is kept). - ColorOverlay { - color: crate::paint::Color, - opacity: f64, - blend: Blend, - }, - /// Gradient overlay: a colour overlay whose colour comes from `gradient` (document pixels). - GradientOverlay { - gradient: crate::paint::Gradient, - opacity: f64, - blend: Blend, - }, -} - -#[derive(Debug, Clone, PartialEq)] -pub struct Node { - pub class: Tag, - pub name: String, - pub visible: bool, - pub locked: bool, - pub opacity: f64, - pub blend: Blend, - pub kind: Kind, - /// Vector mask in document pixels: the node shows only inside it (nonzero fill). - pub mask: Option, - /// Pixel mask: grey levels (white shows the node, black hides it); outside it the node is hidden. - pub pixel_mask: Option, - /// Layer effects the importer can show or bake in (others are reported). - pub effects: Vec, - /// Bottom to top. - pub children: Vec, -} - -#[derive(Debug, Clone, PartialEq)] -pub struct Spread { - /// Spread bounds in document pixels (the canvas, or the union of the artboards). - pub bounds: Rect, - /// Pages of a Publisher-style spread (one, or two facing pages), in document pixels. - pub pages: Vec, - /// Transparent background; otherwise the page is white. - pub transparent: bool, - /// Bottom to top. - pub nodes: Vec, -} - -#[derive(Debug, Clone, PartialEq)] -pub struct Document { - /// Pixels per inch: all geometry is in document pixels at this resolution. - pub dpi: f64, - pub spreads: Vec, - /// Master spreads, which [`Kind::MasterInstance`] nodes show on pages. - pub masters: Vec, - /// Application that last saved the file, as stored (`Affinity 3.0.2`), when present. - pub saved_by: Option, - /// Content that was not imported or was approximated, one line per kind, deduplicated. - pub warnings: Vec, - /// The document's CMYK colour profile (an ICC file), when it embeds one: the root's `CMYP`, - /// which each CMYK pixel layer's colour settings (`Prof`) also name, with relative - /// colorimetric intent and black-point compensation in every document checked. - pub cmyk_profile: Option>, -} diff --git a/crates/affinity/src/model/bounds.rs b/crates/affinity/src/model/bounds.rs deleted file mode 100644 index 7ef9fff0b2..0000000000 --- a/crates/affinity/src/model/bounds.rs +++ /dev/null @@ -1,142 +0,0 @@ -use super::read::MAX_TREE_DEPTH; -use super::{Affine, Kind, Node, ObjId, Point, Rect, Stream, Tag}; - -/// The bounds of what visible `nodes` draw (control points of outlines, corners of images, frames -/// and tables), in document pixels. -pub fn nodes_bounds(nodes: &[Node]) -> Option { - let mut out = None; - walk_bounds(nodes, true, 0, &mut out); - out -} - -/// The bounds of `node` and everything in it, hidden or not. -pub(super) fn tree_bounds(node: &Node) -> Option { - let mut out = None; - walk_bounds(std::slice::from_ref(node), false, 0, &mut out); - out -} - -fn walk_bounds(nodes: &[Node], visible_only: bool, depth: usize, out: &mut Option) { - if depth > MAX_TREE_DEPTH { - return; - } - for n in nodes.iter().filter(|n| n.visible || !visible_only) { - kind_points(&n.kind, &mut |p| add_point(out, p)); - walk_bounds(&n.children, visible_only, depth + 1, out); - } -} - -/// What a pixel mask over a node of `kind` with `children` is read over: the bounds of what they -/// draw, strokes included, or `None` (all of the mask) when some of it has no bounds known here: -/// artistic text, whose glyphs only the layout places. -pub(super) fn mask_extent(kind: &Kind, children: &[Node]) -> Option { - fn visit(kind: &Kind, children: &[Node], depth: usize, out: &mut Option) -> bool { - if depth > MAX_TREE_DEPTH || matches!(kind, Kind::Text(t) if t.frame.is_none()) { - return false; - } - let mut own = kind_bounds(kind); - if let (Some(r), Kind::Shape { strokes, .. } | Kind::Artboard { strokes, .. }) = (own, kind) { - // As far as a stroke can reach out of its path, miter joins included. - let reach = strokes.iter().map(|s| s.width * s.miter_limit.clamp(1.0, 10.0)).filter(|w| w.is_finite()).fold(0.0, f64::max); - own = Some(Rect { x0: r.x0 - reach, y0: r.y0 - reach, x1: r.x1 + reach, y1: r.y1 + reach }); - } - if let Some(r) = own { - *out = Some(out.map_or(r, |o| union(o, r))); - } - children.iter().filter(|n| n.visible).all(|n| visit(&n.kind, &n.children, depth + 1, out)) - } - let mut out = None; - if visit(kind, children, 0, &mut out) { out } else { None } -} - -/// The bounds of what one node's own kind draws (not its children): its outline's points, its -/// image's or frame's corners, or artistic text's anchor. -pub fn kind_bounds(kind: &Kind) -> Option { - let mut out = None; - kind_points(kind, &mut |p| add_point(&mut out, p)); - out -} - -fn add_point(out: &mut Option, p: Point) { - if p.x.is_finite() && p.y.is_finite() { - let r = Rect { x0: p.x, y0: p.y, x1: p.x, y1: p.y }; - *out = Some(out.map_or(r, |o| union(o, r))); - } -} - -fn kind_points(kind: &Kind, add: &mut dyn FnMut(Point)) { - let corners = |r: Rect, m: Affine| [(r.x0, r.y0), (r.x1, r.y0), (r.x1, r.y1), (r.x0, r.y1)].map(|(x, y)| m.apply(Point { x, y })); - match kind { - Kind::Shape { path, .. } | Kind::Artboard { path, .. } => { - for sp in &path.subpaths { - add(sp.start); - for seg in &sp.segments { - seg.iter().for_each(|p| add(*p)); - } - } - } - Kind::Image(img) => { - corners(Rect { x0: 0.0, y0: 0.0, x1: f64::from(img.width), y1: f64::from(img.height) }, img.transform).into_iter().for_each(add) - } - Kind::Text(t) => match t.frame { - Some(f) => corners(f, t.transform).into_iter().for_each(add), - None => add(t.transform.apply(t.anchor)), - }, - Kind::Table(t) => { - if let (Some(&x0), Some(&x1), Some(&y0), Some(&y1)) = (t.columns.first(), t.columns.last(), t.rows.first(), t.rows.last()) { - corners(Rect { x0, y0, x1, y1 }, t.transform).into_iter().for_each(add); - } - } - Kind::Layer | Kind::Group | Kind::Unsupported | Kind::MasterInstance { .. } => {} - } -} - -/// Page rectangles: `SpMd.PagR[].rctp` (Publisher 2, Affinity 3) or `SprB` split into `PagC` -/// equal pages (Publisher 1 facing spreads). -pub(super) fn pages(s: &Stream, spread: ObjId) -> Vec { - if let Some(md) = s.obj(spread, b"SpMd") { - let v: Vec = - s.objs(md, b"PagR").into_iter().filter_map(|p| s.floats::<4>(p, b"rctp").map(rect)).filter(|r| r.x1 > r.x0 && r.y1 > r.y0).collect(); - if !v.is_empty() { - return v; - } - } - match (s.floats::<4>(spread, b"SprB").map(rect), s.int(spread, b"PagC")) { - (Some(b), Some(n @ 2..=16)) => { - let w = (b.x1 - b.x0) / n as f64; - (0..n).map(|i| Rect { x0: b.x0 + w * i as f64, x1: b.x0 + w * (i + 1) as f64, ..b }).collect() - } - _ => Vec::new(), - } -} - -pub(crate) fn union(a: Rect, b: Rect) -> Rect { - Rect { x0: a.x0.min(b.x0), y0: a.y0.min(b.y0), x1: a.x1.max(b.x1), y1: a.y1.max(b.y1) } -} - -pub(super) fn is_container(class: Tag) -> bool { - class == Tag::of(b"Scop") || class == Tag::of(b"Grup") -} - -pub(crate) fn rect(v: [f64; 4]) -> Rect { - Rect { x0: v[0], y0: v[1], x1: v[2], y1: v[3] } -} - -/// A readable name for a layer class in warnings. -pub(crate) fn describe(class: Tag) -> &'static str { - match &class.0.to_be_bytes() { - b"PCrv" => "curve", - b"ShpN" | b"SNEN" | b"SNRR" | b"ShRN" => "shape", - b"Comp" => "compound", - b"Rstr" => "pixel", - b"ImgN" => "image", - b"EmbN" => "embedded document", - b"MPIN" => "master page instance", - b"FRst" => "fill", - b"MRst" => "mask", - b"Slic" | b"SlcP" => "slice", - b"3DLA" => "3D", - [_, _, b'R', b'A'] => "adjustment", - _ => "unknown", - } -} diff --git a/crates/affinity/src/model/read.rs b/crates/affinity/src/model/read.rs deleted file mode 100644 index 80f4e0993b..0000000000 --- a/crates/affinity/src/model/read.rs +++ /dev/null @@ -1,685 +0,0 @@ -use super::bounds::{describe, is_container, mask_extent, nodes_bounds, pages, rect, tree_bounds, union}; -use super::{ - Affine, Archive, BTreeMap, Blend, Document, Effect, Error, HashSet, Image, Kind, Limits, Node, ObjId, Paint, Path, Point, Rect, Spread, Stream, - Tag, paint, stream, -}; - -/// Largest embedded colour profile kept (real CMYK profiles are a few megabytes). -const MAX_PROFILE_BYTES: usize = 32 << 20; - -/// Deepest layer nesting followed; deeper content is reported, not imported. -pub(super) const MAX_TREE_DEPTH: usize = 128; - -/// Total layer nodes imported. -const MAX_NODES: usize = 500_000; - -/// Pixels decoded from pixel layers over a whole document (2 GB as RGBA). The archive's limits -/// count the bytes extracted from it, and a layer of one flat colour needs none (#1704). -const MAX_LAYER_PIXELS: u64 = 512 << 20; - -/// Embedded documents inside embedded documents are followed this deep. -const MAX_EMBED_DEPTH: usize = 4; - -/// Characters of all stories together (a story may be shared by many text layers). -const MAX_DOCUMENT_CHARS: usize = 16 << 20; - -/// Table cells of all tables together (each becomes a text object with its edge lines). -const MAX_DOCUMENT_CELLS: usize = 1 << 18; - -/// Points of all strokes' pressure curves together (a stroke style may be shared by many layers). -const MAX_DOCUMENT_PRESSURE_POINTS: usize = 1 << 20; - -/// 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. -#[derive(Clone, Copy, Debug)] -pub(crate) struct Budget { - /// Layer nodes ([`MAX_NODES`] in all). - pub(crate) nodes: usize, - /// Pixels the pixel layers may decode ([`MAX_LAYER_PIXELS`] in all). - pub(crate) pixels: u64, - /// Characters of stories ([`MAX_DOCUMENT_CHARS`] in all). - pub(crate) chars: usize, - /// Table cells ([`MAX_DOCUMENT_CELLS`] in all). - pub(crate) cells: usize, - /// Points of pressure curves ([`MAX_DOCUMENT_PRESSURE_POINTS`] in all). - pub(crate) pressure: usize, - /// 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 { - pub(crate) const FULL: Budget = Budget { - nodes: MAX_NODES, - pixels: MAX_LAYER_PIXELS, - chars: MAX_DOCUMENT_CHARS, - cells: MAX_DOCUMENT_CELLS, - pressure: MAX_DOCUMENT_PRESSURE_POINTS, - 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. -pub fn read(bytes: &[u8], limits: Limits) -> Result { - read_within(bytes, limits, MAX_LAYER_PIXELS) -} - -/// [`read`], its pixel layers holding at most `pixels` pixels together. -pub(crate) fn read_within(bytes: &[u8], limits: Limits, pixels: u64) -> Result { - read_at(bytes, limits, &mut Budget { pixels, ..Budget::FULL }, Affine::IDENTITY, 0).document -} - -/// A document read by [`read_at`] (or why it couldn't be), with the bytes its archive extracted -/// either way. -struct ReadAt { - document: Result, - extracted: usize, -} - -/// Read a document whose spreads are placed by `base` (for embedded documents, nested `depth` -/// deep). What it uses is taken from `budget`, also when it fails part of the way. -/// The most characters of a layer's name kept. -const MAX_NAME_CHARS: usize = 1024; - -fn read_at(bytes: &[u8], limits: Limits, budget: &mut Budget, base: Affine, depth: usize) -> ReadAt { - let mut archive = match Archive::open(bytes, limits) { - Ok(a) => a, - Err(e) => return ReadAt { document: Err(e), extracted: 0 }, - }; - let document = read_archive(&mut archive, budget, base, depth); - ReadAt { document, extracted: archive.extracted() } -} - -fn read_archive(archive: &mut Archive, budget: &mut Budget, base: Affine, depth: usize) -> Result { - let doc = archive.read("doc.dat")?; - let s = stream::parse(&doc)?; - let mut reader = Reader::new(&s, archive, base, depth); - reader.budget = *budget; - let document = reader.document(); - *budget = reader.budget; - document -} - -pub(crate) struct Reader<'s, 'a, 'b> { - pub(crate) s: &'s Stream, - pub(crate) archive: &'b mut Archive<'a>, - pub(crate) dpi: f64, - pub(crate) warnings: BTreeMap, - active: HashSet, - /// Where the spreads go: the identity, or an embedding document's placement. - base: Affine, - /// The linear part of `base`, which also scales frame text. - pub(crate) type_base: Affine, - /// How deep inside embedded documents this one is. - depth: usize, - /// An embedded document's content, waiting to become its node's children. - pending: Option>, - /// The master spreads, in the order of [`Document::masters`]. - master_ids: Vec, - /// What the rest of the read may use. - pub(crate) budget: Budget, -} - -impl<'s, 'a, 'b> Reader<'s, 'a, 'b> { - pub(crate) fn new(s: &'s Stream, archive: &'b mut Archive<'a>, base: Affine, depth: usize) -> Self { - let [a, b, c, d, ..] = base.0; - Self { - s, - archive, - dpi: 72.0, - warnings: BTreeMap::new(), - active: HashSet::new(), - base, - type_base: Affine([a, b, c, d, 0.0, 0.0]), - depth, - pending: None, - master_ids: Vec::new(), - budget: Budget::FULL, - } - } - - pub(crate) fn warn(&mut self, what: impl Into) { - *self.warnings.entry(what.into()).or_default() += 1; - } - - /// The document. - fn document(&mut self) -> Result { - let s = self.s; - let root = s.root; - self.dpi = s.obj(root, b"UVCn").and_then(|u| s.f64(u, b"UPPI")).filter(|d| *d > 0.0 && *d < 100_000.0).unwrap_or(72.0); - let saved_by = s.obj(root, b"NVer").map(|v| { - let product = s.str(v, b"Prod").unwrap_or("Affinity"); - match (s.int(v, b"Majr"), s.int(v, b"Minr"), s.int(v, b"Bild")) { - (Some(a), Some(b), Some(c)) => format!("{product} {a}.{b}.{c}"), - _ => product.to_string(), - } - }); - let doc = s.obj(root, b"DocR").ok_or(Error::Malformed("document has no root node"))?; - self.master_ids = s.objs(doc, b"MpCh").into_iter().filter(|m| s.is(*m, b"Sprd")).collect(); - let mut spreads = Vec::new(); - for spread in s.objs(doc, b"Chld") { - if let Some(sp) = self.spread(doc, spread)? { - spreads.push(sp); - } - } - if spreads.is_empty() { - return Err(Error::Malformed("document has no pages")); - } - let mut masters = Vec::new(); - for master in self.master_ids.clone() { - match self.spread(doc, master)? { - Some(sp) => masters.push(sp), - // Keep the indices of `MasterInstance::master` valid. - None => masters.push(Spread { - bounds: Rect { x0: 0.0, y0: 0.0, x1: 0.0, y1: 0.0 }, - pages: Vec::new(), - transparent: true, - nodes: Vec::new(), - }), - } - } - let cmyk_profile = s - .obj(root, b"CMYP") - .and_then(|p| s.bytes(p, b"Data")) - .filter(|b| b.len() <= MAX_PROFILE_BYTES && b.get(16..20) == Some(b"CMYK".as_slice())) - .map(<[u8]>::to_vec); - let warnings = std::mem::take(&mut self.warnings).into_iter().map(|(w, n)| if n > 1 { format!("{w} ({n}×)") } else { w }).collect(); - Ok(Document { dpi: self.dpi, spreads, masters, saved_by, warnings, cmyk_profile }) - } - - /// A spread (`Sprd`) of the document `doc`, or of its master spreads. - fn spread(&mut self, doc: ObjId, spread: ObjId) -> Result, Error> { - let s = self.s; - if !s.is(spread, b"Sprd") { - self.warn("an unknown kind of page"); - 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, - y0: 0.0, - x1: 0.0, - y1: 0.0, - }); - let transparent = s.bool(spread, b"SprT").unwrap_or(false); - let (nodes, mask) = self.children(spread, self.base, 0)?; - if mask.is_some() { - self.warn("mask layers directly on a page (imported without them)"); - } - Ok(Some(Spread { bounds, pages, transparent, nodes })) - } - - /// The children of `parent`, and the mask layer among them that masks the parent (with its - /// placement), read later over just what it masks. - #[allow(clippy::type_complexity)] - fn children(&mut self, parent: ObjId, world: Affine, depth: usize) -> Result<(Vec, Option<(ObjId, Affine)>), Error> { - let s = self.s; - let mut out = Vec::new(); - let mut mask = None; - 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) { - continue; - } - let local = s.floats::<6>(c, b"Xfrm").map(Affine::from_xfrm).unwrap_or(Affine::IDENTITY); - if mask.is_none() { - mask = Some((c, local.then(world))); - } else { - self.warn("several pixel masks on one layer (only the first is used)"); - } - continue; - } - if let Some(n) = self.node(c, world, depth + 1)? { - out.push(n); - } - } - Ok((out, mask)) - } - - fn node(&mut self, id: ObjId, parent: Affine, depth: usize) -> Result, Error> { - let s = self.s; - if depth > MAX_TREE_DEPTH { - self.warn("layers nested deeper than 128 levels"); - return Ok(None); - } - let Some(left) = self.budget.nodes.checked_sub(1) else { - return Err(Error::Limit("too many layers")); - }; - self.budget.nodes = left; - // A node that contains itself (a shared object linked back into its own subtree). - if !self.active.insert(id) { - self.warn("a layer that contains itself"); - return Ok(None); - } - let local = s.floats::<6>(id, b"Xfrm").map(Affine::from_xfrm).unwrap_or(Affine::IDENTITY); - 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.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)); - let blend = match s.enumeration(id, b"Blnd") { - None if s.bool(id, b"PasT") != Some(false) && is_container(class) => Blend::PassThrough, - None => Blend::Normal, - Some((i, v)) => Blend::from_enum(i, v).unwrap_or_else(|| { - self.warn("an unknown blend mode (imported as Normal)"); - Blend::Normal - }), - }; - let kind = if !world.is_finite() { - self.warn("a layer with an invalid transform"); - Kind::Unsupported - } else { - self.kind(id, class, world, parent)? - }; - // This node's embedded content, before its children's `node` calls can take it. - let embedded = self.pending.take(); - // A compound's children are its operands, already merged into its outline. - let (mut children, child_mask) = if class == Tag::of(b"Comp") { (Vec::new(), None) } else { self.children(id, world, depth)? }; - if let Some(embedded) = embedded { - children.extend(embedded); - } - // Pixel masks are read only over what they mask (they can span a whole spread at print - // resolution, a gigapixel). - let over = mask_extent(&kind, &children); - let child_mask = match child_mask { - Some((c, at)) => crate::raster::mask(self, c, at, over)?, - None => None, - }; - let (mask, attached_mask) = self.attached_masks(id, world, over)?; - let pixel_mask = attached_mask.or(child_mask); - self.active.remove(&id); - let mut node = Node { class, name, visible, locked, opacity, blend, kind, mask, pixel_mask, effects: Vec::new(), children }; - // Gradient overlays are laid out over the node's bounds, also while it is hidden. - let bounds = tree_bounds(&node); - node.effects = self.effects(id, world, bounds); - Ok(Some(node)) - } - - fn kind(&mut self, id: ObjId, class: Tag, world: Affine, parent: Affine) -> Result { - let s = self.s; - Ok(match &class.0.to_be_bytes() { - b"Scop" => Kind::Layer, - b"Grup" => Kind::Group, - b"PCrv" | b"ShpN" | b"Comp" | b"SNEN" | b"SNRR" | b"ShRN" => { - // Affinity 3.2.3's two-board public fixture marks board shapes with an `aprp` - // property object in `phrp`, while older documents use `ABEn`. Ordinary shapes - // in that fixture have neither. See the pinned corpus and validation audit. - if s.bool(id, b"ABEn") == Some(true) || s.obj(id, b"phrp").is_some_and(|p| s.is(p, b"aprp")) { - return Ok(self.artboard(id, world)); - } - let Some((local, even_odd)) = crate::geometry::outline(self, id, class, world) else { - 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 } - } - b"TxtT" => match crate::text::table(self, id, world) { - Some(t) => Kind::Table(t), - None => { - self.warn("tables that could not be read"); - Kind::Unsupported - } - }, - b"TxtA" | b"TxtF" | b"TxtC" => match crate::text::read(self, id, world) { - Some(t) => Kind::Text(t), - None => { - self.warn("text whose story could not be read (master-page text, or an unknown layout)"); - Kind::Unsupported - } - }, - b"ImgN" | b"Rstr" => match crate::raster::node_image(self, id, world)? { - Some(img) => Kind::Image(img), - None => Kind::Unsupported, - }, - b"MPIN" => { - // `SLnk` links the instance with the master spread it shows. - let linked = s.obj(id, b"SLnk").map(|l| s.objs(l, b"ILOb")).unwrap_or_default(); - let master = linked.iter().find_map(|o| self.master_ids.iter().position(|m| m == o)); - let at = |t: &[u8; 4], default: usize| s.int(id, t).and_then(|v| usize::try_from(v).ok()).unwrap_or(default).min(4096); - match master { - Some(master) => Kind::MasterInstance { master, page: at(b"PgOf", 0), master_page: at(b"MPOf", 0), count: at(b"PgCt", 1) }, - None => { - self.warn("master page instances without their master"); - Kind::Unsupported - } - } - } - b"EmbN" => match self.embedded_document(id, world) { - // The embedded document itself, as editable content. - Some(nodes) => { - self.pending = Some(nodes); - Kind::Group - } - None => match crate::raster::embedded(self, id, world)? { - Some(img) => { - self.warn("embedded documents and symbols (imported as pictures of them)"); - Kind::Image(img) - } - None => { - self.warn("embedded documents and symbols without a cached picture"); - Kind::Unsupported - } - }, - }, - b"FRst" => { - // A fill layer paints its whole bitmap area; its gradient lives in page space. - let b = s.obj(id, b"Bitm"); - let size = |t: &[u8; 4]| b.and_then(|b| s.int(b, t)).map(|v| v as f64).filter(|v| *v > 0.0); - match (size(b"BmpW"), size(b"BmpH")) { - (Some(w), Some(h)) => { - let local = Path { subpaths: vec![crate::shapes::rectangle(0.0, 0.0, w, h)] }; - let fills = paint::fills(self, id, parent, b"BFFl"); - Kind::Shape { path: local.transformed(world), fills, strokes: Vec::new(), even_odd: false } - } - _ => { - self.warn("fill layers without an area"); - Kind::Unsupported - } - } - } - _ => { - self.warn(format!("{} layers", describe(class))); - Kind::Unsupported - } - }) - } - - /// The enabled layer effects (`FiEf`) of node `id`. The angle convention was measured on the - /// public MIT fx fixture (Patchy): an angle of π/2 with offset 10 shadows 10 below. - fn effects(&mut self, id: ObjId, world: Affine, bounds: Option) -> Vec { - let s = self.s; - let mut out = Vec::new(); - for e in s.objs(id, b"FiEf").into_iter().take(64) { - if s.bool(e, b"Enab") == Some(false) { - continue; - } - // "Scale with object": lengths follow the node's transform; otherwise they are absolute. - let k = if s.bool(e, b"SclO") == Some(true) { world.scale() } else { 1.0 }; - let len = |t: &[u8; 4]| s.f64(e, t).filter(|v| v.is_finite() && *v >= 0.0 && *v < 1e6).unwrap_or(0.0) * k; - let opacity = s.f64(e, b"Opac").filter(|v| v.is_finite()).unwrap_or(1.0).clamp(0.0, 1.0); - let angle = s.f64(e, b"Angl").filter(|v| v.is_finite()).unwrap_or(0.0); - let color = s.obj(e, b"Colr").and_then(|c| crate::paint::color(self, c)); - let class = s.class(e).map(|c| c.0.to_be_bytes()); - match (class.as_ref(), color) { - (Some(b"Shad"), Some(color)) => out.push(Effect::DropShadow { color, opacity, radius: len(b"Radi"), distance: len(b"Offs"), angle }), - (Some(b"InnS"), Some(color)) => out.push(Effect::InnerShadow { color, opacity, radius: len(b"Radi"), distance: len(b"Offs"), angle }), - (Some(b"OutG"), Some(color)) => out.push(Effect::OuterGlow { color, opacity, radius: len(b"Radi") }), - (Some(b"Strk"), Some(color)) if s.enumeration(e, b"Ftyp").is_none_or(|(t, _)| t == 0) => { - let align = s.enumeration(e, b"Alig").map_or(0, |(a, _)| a); - out.push(Effect::Outline { color, opacity, width: len(b"Radi"), align }); - } - (Some(b"Strk"), _) => self.warn("gradient outline effects (left out)"), - (Some(b"BevE" | b"EmbE"), _) => { - // No radius, no bevel (as Affinity draws it). - let size = len(b"Radi"); - if size > 0.0 { - let white = crate::paint::Color::Rgb { r: 1.0, g: 1.0, b: 1.0, a: 1.0 }; - let black = crate::paint::Color::Rgb { r: 0.0, g: 0.0, b: 0.0, a: 1.0 }; - let highlight = s.obj(e, b"HiCl").and_then(|c| crate::paint::color(self, c)).unwrap_or(white); - let shadow = s.obj(e, b"ShCl").and_then(|c| crate::paint::color(self, c)).unwrap_or(black); - let shadow_opacity = s.f64(e, b"ShOp").filter(|v| v.is_finite()).unwrap_or(0.75).clamp(0.0, 1.0); - let depth = s.f64(e, b"Dept").filter(|v| v.is_finite()).unwrap_or(5.0); - let azimuth = s.f64(e, b"Azim").filter(|v| v.is_finite()).unwrap_or(std::f64::consts::FRAC_PI_4 * 3.0); - let inner = s.enumeration(e, b"Beve").is_none_or(|(k, _)| k == 0); - out.push(Effect::Bevel { size, depth, angle: azimuth, highlight, highlight_opacity: opacity, shadow, shadow_opacity, inner }); - } - } - (Some(b"ColO"), Some(color)) => { - let blend = self.effect_blend(e); - out.push(Effect::ColorOverlay { color, opacity, blend }); - } - (Some(b"GrdO"), _) => { - let blend = self.effect_blend(e); - // The gradient's unit space spans the node's bounding box from -1 to 1, centred - // on it (y down): checked against the stored previews of real documents. - let space = - bounds.map(|b| Affine([(b.x1 - b.x0) / 2.0, 0.0, 0.0, (b.y1 - b.y0) / 2.0, (b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0])); - match (s.obj(e, b"GrFl"), space) { - (Some(fill), Some(space)) => match paint::descriptor(self, fill, space) { - Some(Paint::Gradient(gradient)) => out.push(Effect::GradientOverlay { gradient, opacity, blend }), - Some(Paint::Solid(color)) => out.push(Effect::ColorOverlay { color, opacity, blend }), - _ => {} - }, - // Nothing visible to lay it over. - (Some(_), None) => {} - (None, _) => self.warn("gradient overlay effects that could not be read (left out)"), - } - } - (Some(b"ColO"), None) => self.warn("colour overlay effects that could not be read (left out)"), - (Some(b"Gaus"), _) => self.warn("blur effects (left out)"), - _ => self.warn("layer effects of other kinds (left out)"), - } - } - for a in s.objs(id, b"AdCh") { - if let Some(effect) = self.attached_recolor(a) { - out.push(effect); - } - } - out - } - fn attached_recolor(&mut self, a: ObjId) -> Option { - let s = self.s; - if !s.is(a, b"RcRA") { - return None; - } - if s.bool(a, b"Visi") == Some(false) { - return None; - } - let adjp = s.obj(a, b"AdjP")?; - if !s.is(adjp, b"RecP") { - return None; - } - let h = s.f64(adjp, b"RecH").unwrap_or(0.0); - let sat = s.f64(adjp, b"RecS").unwrap_or(1.0); - let l = s.f64(adjp, b"RecL").unwrap_or(0.5); - let (r, g, b) = crate::paint::hsl(h, sat, l); - let color = crate::paint::Color::Rgb { r, g, b, a: 1.0 }; - let opacity = s.f64(a, b"Opac").filter(|v| v.is_finite()).unwrap_or(1.0).clamp(0.0, 1.0); - let blend = self.effect_blend(a); - Some(Effect::ColorOverlay { color, opacity, blend }) - } - - /// A layer effect's blend mode (`BlnM`); unknown modes are Normal (warned). - fn effect_blend(&mut self, e: ObjId) -> Blend { - match self.s.enumeration(e, b"BlnM") { - None => Blend::Normal, - Some((i, v)) => Blend::from_enum(i, v).unwrap_or_else(|| { - self.warn("an unknown blend mode (imported as Normal)"); - Blend::Normal - }), - } - } - - /// Vector shapes attached to a node (`AdCh`) mask it: it shows only inside their outlines; - /// an attached mask layer is a pixel mask. Adjustments attached the same way are reported. - fn attached_masks(&mut self, id: ObjId, world: Affine, over: Option) -> Result<(Option, Option), Error> { - let s = self.s; - let attached = s.objs(id, b"AdCh"); - let mut mask: Option = None; - let mut pixels: Option = None; - for a in attached { - let class = s.class(a).unwrap_or(Tag(0)); - if s.bool(a, b"Visi") == Some(false) { - continue; - } - if class == Tag::of(b"PCrv") || class == Tag::of(b"ShpN") || class == Tag::of(b"Comp") { - let local = s.floats::<6>(a, b"Xfrm").map(Affine::from_xfrm).unwrap_or(Affine::IDENTITY).then(world); - if let Some((p, _)) = crate::geometry::outline(self, a, class, local) { - mask.get_or_insert_with(Path::default).subpaths.extend(p.transformed(local).subpaths); - } - } else if class == Tag::of(b"MRst") { - let local = s.floats::<6>(a, b"Xfrm").map(Affine::from_xfrm).unwrap_or(Affine::IDENTITY).then(world); - match crate::raster::mask(self, a, local, over)? { - Some(m) if pixels.is_none() => pixels = Some(m), - Some(_) => self.warn("several pixel masks on one layer (only the first is used)"), - None => {} - } - } else if class == Tag::of(b"RcRA") { - // Handled in `effects` as a colour overlay. - } else { - self.warn(format!("{} layers attached to other layers (imported without them)", describe(class))); - } - } - Ok((mask, pixels)) - } - - /// The content of an Affinity document embedded in this one (`EmbN` whose `EmbC` entry holds - /// `EmDc`, four more bytes and a complete Affinity document): its first spread's nodes, - /// placed so the centre of its page, first artboard or content is the node's origin. - fn embedded_document(&mut self, id: ObjId, world: Affine) -> Option> { - let s = self.s; - let entry = s.obj(id, b"Bitm").and_then(|b| s.obj(b, b"EmCn")).and_then(|c| s.entry(c, b"EmbC"))?.to_string(); - if entry.is_empty() { - return None; - } - if self.depth >= MAX_EMBED_DEPTH { - self.warn("embedded documents nested more than four deep"); - return None; - } - let data = self.archive.read(&entry).ok()?; - let inner = data.strip_prefix(b"EmDc").and_then(|d| d.get(4..))?; - if !crate::is_affinity(inner) { - return None; - } - // A first reading finds its page and resolution, the second places it. - // Both readings are charged to the budget and the archive's limits, also when they fail: - // each does the work. - let mut budget = self.budget; - let probe = read_at(inner, self.archive.remaining(), &mut budget, Affine::IDENTITY, self.depth + 1); - self.budget = budget; - if self.archive.charge(probe.extracted).is_err() { - self.warn("embedded documents beyond the size limit (left out)"); - return None; - } - let probe = match probe.document { - Ok(d) => d, - Err(e) => { - self.warn(format!("embedded documents that could not be read ({e})")); - return None; - } - }; - let spread = probe.spreads.first()?; - // `PBBx` 2 places the content's own bounds (as with a cached picture); otherwise its page. - let content = s.obj(id, b"Bitm").and_then(|b| s.enumeration(b, b"PBBx")).is_some_and(|(k, _)| k == 2); - let first_board = spread.nodes.iter().find_map(|n| if let Kind::Artboard { rect, .. } = &n.kind { Some(*rect) } else { None }); - let page = if content { None } else { spread.pages.first().copied().or(first_board) }; - let page = page.or_else(|| nodes_bounds(&spread.nodes)).unwrap_or(spread.bounds); - // Its pixels aren't needed any more: never hold both readings' at once. - drop(probe); - // Its document pixels are the node's units, whatever either document's resolution. - let k = 1.0; - let (cx, cy) = ((page.x0 + page.x1) / 2.0, (page.y0 + page.y1) / 2.0); - let base = Affine([k, 0.0, 0.0, k, -cx * k, -cy * k]).then(world); - if !base.is_finite() { - self.warn("embedded documents with an invalid placement"); - return None; - } - let mut budget = self.budget; - let placed = read_at(inner, self.archive.remaining(), &mut budget, base, self.depth + 1); - self.budget = budget; - if self.archive.charge(placed.extracted).is_err() { - self.warn("embedded documents beyond the size limit (left out)"); - return None; - } - let doc = placed.document.ok()?; - for w in doc.warnings { - self.warn(format!("{w} [in embedded documents]")); - } - if doc.spreads.len() > 1 { - self.warn("embedded documents with several pages (the first is used)"); - } - let mut nodes = doc.spreads.into_iter().next()?.nodes; - // Its master page instances count its own masters, which aren't kept: in this document - // they would show other masters. - fn strip_masters(nodes: &mut [Node], depth: usize) -> bool { - let mut found = false; - for n in nodes { - if matches!(n.kind, Kind::MasterInstance { .. }) { - n.kind = Kind::Unsupported; - found = true; - } - if depth < MAX_TREE_DEPTH { - found |= strip_masters(&mut n.children, depth + 1); - } - } - found - } - if strip_masters(&mut nodes, 0) { - self.warn("master pages of embedded documents (left out)"); - } - Some(nodes) - } - - fn artboard(&mut self, id: ObjId, world: Affine) -> Kind { - let s = self.s; - let Some(b) = s.floats::<4>(id, b"ShpB").map(rect).filter(|b| b.x1 > b.x0 && b.y1 > b.y0) else { - self.warn("an artboard without valid bounds (its children are kept without clipping)"); - return Kind::Unsupported; - }; - let corners = - [Point { x: b.x0, y: b.y0 }, Point { x: b.x1, y: b.y0 }, Point { x: b.x1, y: b.y1 }, Point { x: b.x0, y: b.y1 }].map(|p| world.apply(p)); - let [a, b2, c, d, ..] = world.0; - if b2.abs() > 1e-9 || c.abs() > 1e-9 || a <= 0.0 || d <= 0.0 { - self.warn("a rotated or flipped artboard (export bounds are its bounding box; artwork keeps its outline)"); - } - let xs = corners.map(|p| p.x); - let ys = corners.map(|p| p.y); - let rect = Rect { - x0: xs.iter().copied().fold(f64::INFINITY, f64::min), - y0: ys.iter().copied().fold(f64::INFINITY, f64::min), - x1: xs.iter().copied().fold(f64::NEG_INFINITY, f64::max), - y1: ys.iter().copied().fold(f64::NEG_INFINITY, f64::max), - }; - if ![rect.x0, rect.y0, rect.x1, rect.y1].iter().all(|v| v.is_finite()) || rect.x1 <= rect.x0 || rect.y1 <= rect.y0 { - self.warn("an artboard with an invalid transformed size (its children are kept without clipping)"); - return Kind::Unsupported; - } - let class = s.class(id).unwrap_or(Tag::of(b"ShpN")); - let (path, even_odd) = crate::geometry::outline(self, id, class, world).unwrap_or_else(|| { - self.warn("an artboard whose outline could not be read (clipped to its rectangle)"); - (Path { subpaths: vec![crate::shapes::rectangle(b.x0, b.y0, b.x1, b.y1)] }, false) - }); - let (background, strokes) = paint::node_paint(self, id, world); - 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"))); - } -} diff --git a/crates/affinity/src/overlay.rs b/crates/affinity/src/overlay.rs deleted file mode 100644 index 80f54f68e9..0000000000 --- a/crates/affinity/src/overlay.rs +++ /dev/null @@ -1,675 +0,0 @@ -//! Colour and gradient overlays. VectorCraft has no such effect, so an overlay is baked into what -//! its node paints: fill, stroke and text colours, and pixels. The overlay lies over the node's -//! own paint in its blend mode at its opacity, inside the node's alpha (which it keeps). -//! -//! Blend modes follow the W3C Compositing and Blending formulas; the modes PDF lacks (Vivid -//! Light, Linear Light, Pin Light, Hard Mix, Add, Subtract, Average, Negation, Reflect, Glow, -//! Darker/Lighter Color) use their usual definitions. - -use std::borrow::Cow; - -use crate::model::{Affine, Blend, Effect, Image, Kind, Node, Pixels, Point}; -use crate::paint::{Color, Gradient, GradientKind, Paint, Stop, Stroke}; - -/// Deepest subtree an overlay is baked into (the reader bounds trees well below this). -const MAX_DEPTH: usize = 256; - -/// Most pixels an overlay is baked into per image. -const MAX_PIXELS: usize = 64 << 20; - -/// Work the overlays of one import may take together: each overlay counts the nodes and pixels -/// of the subtree it is baked into (which is copied once more for them all). Nested overlays -/// and shared content would otherwise multiply it; past it, overlays are left out and said. -pub const MAX_WORK: u64 = 1 << 29; - -#[derive(Clone, Copy)] -enum Source<'a> { - Solid(Color), - Gradient(&'a Gradient), -} - -#[derive(Clone, Copy)] -struct Overlay<'a> { - source: Source<'a>, - opacity: f64, - blend: Blend, -} - -/// `node` with its colour and gradient overlays baked in, and those of everything in it -/// (borrowed unchanged when `node` has none, or when what is left of `work`, see [`MAX_WORK`], -/// can't pay for copying it). `warn` hears what could only be approximated or was left out. -pub fn apply<'a>(node: &'a Node, work: &mut u64, warn: &mut dyn FnMut(&str)) -> Cow<'a, Node> { - if overlays(&node.effects).is_empty() { - return Cow::Borrowed(node); - } - let Some(left) = work.checked_sub(subtree_cost(node, *work, 0)) else { - warn("overlay effects beyond the work one import may take (left out)"); - return Cow::Borrowed(node); - }; - *work = left; - let mut out = node.clone(); - bake_tree(&mut out, work, 0, warn); - Cow::Owned(out) -} - -/// The visible colour and gradient overlays among `effects`. -fn overlays(effects: &[Effect]) -> Vec> { - effects - .iter() - .filter_map(|e| match e { - Effect::ColorOverlay { color, opacity, blend } => Some(Overlay { source: Source::Solid(*color), opacity: *opacity, blend: *blend }), - Effect::GradientOverlay { gradient, opacity, blend } => { - Some(Overlay { source: Source::Gradient(gradient), opacity: *opacity, blend: *blend }) - } - _ => None, - }) - .filter(|o| o.opacity > 0.0) - .collect() -} - -fn is_overlay(e: &Effect) -> bool { - matches!(e, Effect::ColorOverlay { .. } | Effect::GradientOverlay { .. }) -} - -/// Bakes the overlays of `node` and its subtree into their paint, innermost first: an overlay -/// lies over what its node shows, its children's overlays included. Each overlay pays for the -/// subtree it is baked into out of `work`; past it, it is left out (and said). -fn bake_tree(node: &mut Node, work: &mut u64, depth: usize, warn: &mut dyn FnMut(&str)) { - if depth > MAX_DEPTH { - return; - } - for c in &mut node.children { - bake_tree(c, work, depth + 1, warn); - } - if !node.effects.iter().any(is_overlay) { - return; - } - let (effects, rest): (Vec, Vec) = std::mem::take(&mut node.effects).into_iter().partition(is_overlay); - node.effects = rest; - let overlays = overlays(&effects); - if overlays.is_empty() { - return; - } - let count = u64::try_from(overlays.len()).unwrap_or(u64::MAX); - let cost = subtree_cost(node, *work / count, 0).saturating_mul(count); - let Some(left) = work.checked_sub(cost) else { - warn("overlay effects beyond the work one import may take (left out)"); - return; - }; - *work = left; - for o in &overlays { - if matches!(o.blend, Blend::Erase | Blend::PassThrough) { - warn("overlay effects in a blend mode VectorCraft doesn't have (imported as Normal)"); - } - bake_node(node, o, 0, warn); - } -} - -/// Nodes and pixels in `node`'s subtree, counted only until they pass `limit`. -fn subtree_cost(node: &Node, limit: u64, depth: usize) -> u64 { - if depth > MAX_DEPTH { - return 0; - } - let mut cost: u64 = match &node.kind { - Kind::Image(img) => (u64::from(img.width) * u64::from(img.height)).saturating_add(1), - Kind::Text(t) => u64::try_from(t.runs.len()).unwrap_or(u64::MAX).saturating_add(1), - Kind::Table(t) => u64::try_from(t.cells.len()).unwrap_or(u64::MAX).saturating_add(1), - _ => 1, - }; - for c in &node.children { - if cost > limit { - break; - } - cost = cost.saturating_add(subtree_cost(c, limit - cost, depth + 1)); - } - cost -} - -fn bake_node(node: &mut Node, o: &Overlay, depth: usize, warn: &mut dyn FnMut(&str)) { - if depth > MAX_DEPTH { - return; - } - match &mut node.kind { - Kind::Shape { fills, strokes, .. } => { - for f in fills.iter_mut() { - *f = paint(f, o, warn); - } - strokes.iter_mut().for_each(|s| stroke(s, o, warn)); - } - Kind::Artboard { background, strokes, .. } => { - for f in background.iter_mut() { - *f = paint(f, o, warn); - } - strokes.iter_mut().for_each(|s| stroke(s, o, warn)); - } - Kind::Text(t) => { - for r in &mut t.runs { - r.fill = paint(&r.fill, o, warn); - if let Some(s) = &mut r.stroke { - stroke(s, o, warn); - } - } - } - Kind::Table(t) => { - for c in &mut t.cells { - for r in &mut c.runs { - r.fill = paint(&r.fill, o, warn); - if let Some(s) = &mut r.stroke { - stroke(s, o, warn); - } - } - } - for s in t.vertical.iter_mut().chain(t.horizontal.iter_mut()).flatten() { - stroke(s, o, warn); - } - } - Kind::Image(img) => { - if !pixels(img, o) { - warn("overlay effects on images too large to recolour (left out)"); - } - } - Kind::Layer | Kind::Group | Kind::Unsupported | Kind::MasterInstance { .. } => {} - } - for e in &mut node.effects { - match e { - Effect::Outline { color, .. } => *color = over(*color, o.source.at_solid(), o), - Effect::DropShadow { .. } | Effect::InnerShadow { .. } | Effect::OuterGlow { .. } | Effect::Bevel { .. } => {} - Effect::ColorOverlay { .. } | Effect::GradientOverlay { .. } => {} - } - } - for c in &mut node.children { - bake_node(c, o, depth + 1, warn); - } -} - -fn stroke(s: &mut Stroke, o: &Overlay, warn: &mut dyn FnMut(&str)) { - s.paint = paint(&s.paint, o, warn); -} - -/// A paint with the overlay over it. -fn paint(p: &Paint, o: &Overlay, warn: &mut dyn FnMut(&str)) -> Paint { - match (p, o.source) { - (Paint::None, _) => Paint::None, - (Paint::Solid(c), Source::Solid(s)) => Paint::Solid(over(*c, s, o)), - (Paint::Gradient(g), Source::Solid(s)) => { - Paint::Gradient(Gradient { stops: g.stops.iter().map(|st| Stop { color: over(st.color, s, o), ..*st }).collect(), ..g.clone() }) - } - // Over one colour, the result is the overlay's gradient with each stop laid over it. - (Paint::Solid(c), Source::Gradient(g)) => { - Paint::Gradient(Gradient { stops: g.stops.iter().map(|st| Stop { color: over(*c, st.color, o), ..*st }).collect(), ..g.clone() }) - } - (Paint::Gradient(base), Source::Gradient(g)) => { - if !(o.blend == Blend::Normal && o.opacity >= 1.0) { - warn("gradient overlays on gradients (approximated)"); - } - // Exact when the overlay covers it; otherwise over the base gradient's average colour. - let avg = average(base); - Paint::Gradient(Gradient { stops: g.stops.iter().map(|st| Stop { color: over(avg, st.color, o), ..*st }).collect(), ..g.clone() }) - } - } -} - -impl Source<'_> { - /// One colour for the source (a gradient's average) where only one fits. - fn at_solid(&self) -> Color { - match self { - Source::Solid(c) => *c, - Source::Gradient(g) => average(g), - } - } -} - -fn average(g: &Gradient) -> Color { - let n = g.stops.len().max(1) as f64; - let (mut r, mut gr, mut b, mut a) = (0.0, 0.0, 0.0, 0.0); - for s in &g.stops { - let [sr, sg, sb] = rgb(s.color); - r += sr; - gr += sg; - b += sb; - a += s.color.alpha(); - } - Color::Rgb { r: r / n, g: gr / n, b: b / n, a: a / n } -} - -/// `source` laid over `base` in the overlay's mode and opacity; `base`'s alpha is kept. -fn over(base: Color, source: Color, o: &Overlay) -> Color { - let k = (o.opacity * source.alpha()).clamp(0.0, 1.0); - let alpha = base.alpha(); - // Normal mixes within the colour model when both share it, so CMYK stays CMYK. - if matches!(o.blend, Blend::Normal | Blend::PassThrough | Blend::Erase) { - let mix = |a: f64, b: f64| a + (b - a) * k; - match (base, source) { - (Color::Cmyk { c, m, y, k: kk, .. }, Color::Cmyk { c: c2, m: m2, y: y2, k: k2, .. }) => { - return Color::Cmyk { c: mix(c, c2), m: mix(m, m2), y: mix(y, y2), k: mix(kk, k2), a: alpha }; - } - (Color::Gray { v, .. }, Color::Gray { v: v2, .. }) => return Color::Gray { v: mix(v, v2), a: alpha }, - (_, s) if k >= 1.0 => return with_alpha(s, alpha), - _ => {} - } - } - let b = rgb(base); - let s = rgb(source); - let blended = blend(o.blend, b, s); - let [r, g, bl] = [0, 1, 2].map(|i| b[i] + (blended[i] - b[i]) * k); - Color::Rgb { r, g, b: bl, a: alpha } -} - -fn with_alpha(c: Color, a: f64) -> Color { - match c { - Color::Rgb { r, g, b, .. } => Color::Rgb { r, g, b, a }, - Color::Cmyk { c, m, y, k, .. } => Color::Cmyk { c, m, y, k, a }, - Color::Gray { v, .. } => Color::Gray { v, a }, - Color::Lab { l, a: la, b, .. } => Color::Lab { l, a: la, b, alpha: a }, - } -} - -/// sRGB components (0..1) of a colour. CMYK uses the profile-free formula (the engine shows the -/// node's other CMYK colours through the document's profile), Lab its D50 sRGB colour. -fn rgb(c: Color) -> [f64; 3] { - let f = |v: f64| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }; - match c { - Color::Rgb { r, g, b, .. } => [f(r), f(g), f(b)], - Color::Gray { v, .. } => [f(v); 3], - Color::Cmyk { c, m, y, k, .. } => { - let w = 1.0 - f(k); - [(1.0 - f(c)) * w, (1.0 - f(m)) * w, (1.0 - f(y)) * w] - } - Color::Lab { l, a, b, .. } => lab_to_srgb(l, a, b).map(f), - } -} - -/// CIE L*a*b* (D50) to sRGB, through XYZ and the Bradford adaptation to D65. -fn lab_to_srgb(l: f64, a: f64, b: f64) -> [f64; 3] { - let finite = |v: f64| if v.is_finite() { v } else { 0.0 }; - let (l, a, b) = (finite(l), finite(a), finite(b)); - let fy = (l + 16.0) / 116.0; - let (fx, fz) = (fy + a / 500.0, fy - b / 200.0); - let inv = |t: f64| if t > 6.0 / 29.0 { t * t * t } else { 3.0 * (6.0f64 / 29.0).powi(2) * (t - 4.0 / 29.0) }; - // D50 white. - let (x, y, z) = (0.964_22 * inv(fx), inv(fy), 0.825_21 * inv(fz)); - // XYZ (D50) to linear sRGB, Bradford-adapted. - let r = 3.133_856 * x - 1.616_867 * y - 0.490_615 * z; - let g = -0.978_768 * x + 1.916_142 * y + 0.033_454 * z; - let bl = 0.071_945 * x - 0.228_991 * y + 1.405_243 * z; - let gamma = |v: f64| if v <= 0.003_130_8 { 12.92 * v } else { 1.055 * v.max(0.0).powf(1.0 / 2.4) - 0.055 }; - [gamma(r), gamma(g), gamma(bl)] -} - -/// Bake the overlay into an image's pixels. False if they couldn't be read or are too many. -fn pixels(img: &mut Image, o: &Overlay) -> bool { - let Some(n) = (img.width as usize).checked_mul(img.height as usize).filter(|n| *n <= MAX_PIXELS) else { return false }; - let Some(len) = n.checked_mul(4) else { return false }; - let mut px = match &img.pixels { - Pixels::Rgba8(p) => match p.get(..len) { - Some(p) => p.to_vec(), - None => return false, - }, - Pixels::Encoded(bytes) => match decode(bytes, img.width, img.height) { - Some(p) => p, - None => return false, - }, - // An overlay is blended in RGB: CMYK pixels take the profile-free formula here. - Pixels::Cmyka8(p) => match p.get(..n.saturating_mul(5)) { - Some(p) if p.len() == n * 5 => p - .as_chunks::<5>() - .0 - .iter() - .flat_map(|[c, m, y, k, a]| { - let w = 255 - u16::from(*k); - let ch = |v: u8| ((u16::from(255 - v) * w + 127) / 255) as u8; - [ch(*c), ch(*m), ch(*y), *a] - }) - .collect(), - _ => return false, - }, - }; - let width = img.width.max(1) as usize; - // A solid source is converted once; a gradient is sampled at each pixel's centre. - let solid = match o.source { - Source::Solid(c) => Some((rgb(c), c.alpha())), - Source::Gradient(_) => None, - }; - let to_unit = match o.source { - Source::Gradient(g) => match invert(g.transform) { - Some(m) => Some((img.transform.then(m), g, stop_reach(g))), - None => return false, - }, - Source::Solid(_) => None, - }; - for (i, p) in px.as_chunks_mut::<4>().0.iter_mut().enumerate() { - if p[3] == 0 { - continue; - } - let (s, sa) = match (solid, &to_unit) { - (Some(s), _) => s, - (None, Some((m, g, reach))) => { - let q = m.apply(Point { x: (i % width) as f64 + 0.5, y: (i / width) as f64 + 0.5 }); - let c = sample(g, reach, q); - (rgb(c), c.alpha()) - } - (None, None) => continue, - }; - let k = (o.opacity * sa).clamp(0.0, 1.0); - let b = [p[0], p[1], p[2]].map(|v| f64::from(v) / 255.0); - let m = blend(o.blend, b, s); - for c in 0..3 { - p[c] = ((b[c] + (m[c] - b[c]) * k).clamp(0.0, 1.0) * 255.0).round() as u8; - } - } - img.pixels = Pixels::Rgba8(px); - true -} - -/// An encoded original's RGBA pixels, decoded only if it is `width` × `height` as its layer says. -fn decode(bytes: &[u8], width: u32, height: u32) -> Option> { - let probe = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok()?; - if probe.into_dimensions().ok()? != (width, height) { - return None; - } - let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok()?; - let mut limits = image::Limits::default(); - limits.max_image_width = Some(width); - limits.max_image_height = Some(height); - limits.max_alloc = u64::try_from(MAX_PIXELS).ok().map(|n| n * 8); - reader.limits(limits); - Some(reader.decode().ok()?.into_rgba8().into_raw()) -} - -/// For each pair of neighbouring stops (`k`, `k + 1`), the largest offset of stops `1..=k + 1`: -/// the first pair whose end offset a `t` doesn't pass is the first whose reach it doesn't pass, and -/// reaches never decrease, so [`sample`] finds it by binary search, sorted stops or not. -fn stop_reach(g: &Gradient) -> Vec { - g.stops - .iter() - .skip(1) - .scan(f64::NEG_INFINITY, |m, s| { - *m = m.max(s.offset); - Some(*m) - }) - .collect() -} - -/// The gradient's colour at unit-space point `q` (`reach`: [`stop_reach`] of `g`). -fn sample(g: &Gradient, reach: &[f64], q: Point) -> Color { - let t = match g.kind { - GradientKind::Linear => q.x, - GradientKind::Radial => q.x.hypot(q.y), - GradientKind::Conical => q.y.atan2(q.x).rem_euclid(std::f64::consts::TAU) / std::f64::consts::TAU, - }; - let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 }; - let (Some(first), Some(last)) = (g.stops.first(), g.stops.last()) else { return Color::Rgb { r: 0.0, g: 0.0, b: 0.0, a: 0.0 } }; - if t <= first.offset { - return first.color; - } - let k = reach.partition_point(|r| *r < t); - if let (Some(a), Some(b)) = (g.stops.get(k), g.stops.get(k + 1)) { - let span = b.offset - a.offset; - let u = if span > 1e-9 { (t - a.offset) / span } else { 1.0 }; - // Affinity's midpoint bias (see `Stop::half_point`). - let k = 1.0 + 8.0 * (a.bias - 0.5).abs(); - let u = if a.bias >= 0.5 { u.powf(k) } else { 1.0 - (1.0 - u).powf(k) }; - let (x, y) = (rgb(a.color), rgb(b.color)); - let [r, g, bl] = [0, 1, 2].map(|i| x[i] + (y[i] - x[i]) * u); - return Color::Rgb { r, g, b: bl, a: a.color.alpha() + (b.color.alpha() - a.color.alpha()) * u }; - } - last.color -} - -fn invert(m: Affine) -> Option { - let [a, b, c, d, e, f] = m.0; - let det = a * d - b * c; - if !(det.is_finite() && det.abs() > 1e-12) { - return None; - } - let (ia, ib, ic, id) = (d / det, -b / det, -c / det, a / det); - Some(Affine([ia, ib, ic, id, -(ia * e + ic * f), -(ib * e + id * f)])) -} - -/// The blend of backdrop `b` and source `s` (sRGB, 0..1). -fn blend(mode: Blend, b: [f64; 3], s: [f64; 3]) -> [f64; 3] { - use Blend::*; - let sep = |f: fn(f64, f64) -> f64| [0, 1, 2].map(|i| f(b[i], s[i]).clamp(0.0, 1.0)); - match mode { - Normal | PassThrough | Erase => s, - Darken => sep(f64::min), - Lighten => sep(f64::max), - Multiply => sep(|b, s| b * s), - Screen => sep(screen), - ColorBurn => sep(burn), - ColorDodge => sep(dodge), - Blend::Overlay => sep(|b, s| hard_light(s, b)), - HardLight => sep(hard_light), - SoftLight => sep(soft_light), - Difference => sep(|b, s| (b - s).abs()), - Exclusion => sep(|b, s| b + s - 2.0 * b * s), - Add => sep(|b, s| b + s), - Subtract => sep(|b, s| b - s), - VividLight => sep(|b, s| if s <= 0.5 { burn(b, 2.0 * s) } else { dodge(b, 2.0 * s - 1.0) }), - LinearLight => sep(|b, s| b + 2.0 * s - 1.0), - PinLight => sep(|b, s| if s <= 0.5 { b.min(2.0 * s) } else { b.max(2.0 * s - 1.0) }), - HardMix => sep(|b, s| if b + s >= 1.0 { 1.0 } else { 0.0 }), - Average => sep(|b, s| (b + s) / 2.0), - Negation => sep(|b, s| 1.0 - (1.0 - b - s).abs()), - Reflect => sep(reflect), - Glow => sep(|b, s| reflect(s, b)), - DarkerColor => { - if lum(s) < lum(b) { - s - } else { - b - } - } - LighterColor => { - if lum(s) > lum(b) { - s - } else { - b - } - } - Hue => set_lum(set_sat(s, sat(b)), lum(b)), - Saturation => set_lum(set_sat(b, sat(s)), lum(b)), - Blend::Color => set_lum(s, lum(b)), - Luminosity => set_lum(b, lum(s)), - } -} - -fn screen(b: f64, s: f64) -> f64 { - b + s - b * s -} - -fn burn(b: f64, s: f64) -> f64 { - if b >= 1.0 { - 1.0 - } else if s <= 0.0 { - 0.0 - } else { - 1.0 - ((1.0 - b) / s).min(1.0) - } -} - -fn dodge(b: f64, s: f64) -> f64 { - if b <= 0.0 { - 0.0 - } else if s >= 1.0 { - 1.0 - } else { - (b / (1.0 - s)).min(1.0) - } -} - -fn hard_light(b: f64, s: f64) -> f64 { - if s <= 0.5 { b * 2.0 * s } else { screen(b, 2.0 * s - 1.0) } -} - -fn soft_light(b: f64, s: f64) -> f64 { - if s <= 0.5 { - b - (1.0 - 2.0 * s) * b * (1.0 - b) - } else { - let d = if b <= 0.25 { ((16.0 * b - 12.0) * b + 4.0) * b } else { b.sqrt() }; - b + (2.0 * s - 1.0) * (d - b) - } -} - -fn reflect(b: f64, s: f64) -> f64 { - if s >= 1.0 { 1.0 } else { (b * b / (1.0 - s)).min(1.0) } -} - -fn lum(c: [f64; 3]) -> f64 { - 0.3 * c[0] + 0.59 * c[1] + 0.11 * c[2] -} - -fn clip_color(c: [f64; 3]) -> [f64; 3] { - let l = lum(c); - let n = c[0].min(c[1]).min(c[2]); - let x = c[0].max(c[1]).max(c[2]); - c.map(|v| { - let mut v = v; - if n < 0.0 && l - n > 1e-12 { - v = l + (v - l) * l / (l - n); - } - if x > 1.0 && x - l > 1e-12 { - v = l + (v - l) * (1.0 - l) / (x - l); - } - v.clamp(0.0, 1.0) - }) -} - -fn set_lum(c: [f64; 3], l: f64) -> [f64; 3] { - let d = l - lum(c); - clip_color(c.map(|v| v + d)) -} - -fn sat(c: [f64; 3]) -> f64 { - c[0].max(c[1]).max(c[2]) - c[0].min(c[1]).min(c[2]) -} - -fn set_sat(c: [f64; 3], s: f64) -> [f64; 3] { - let max = c[0].max(c[1]).max(c[2]); - let min = c[0].min(c[1]).min(c[2]); - if max - min <= 1e-12 { - return [0.0; 3]; - } - c.map(|v| (v - min) * s / (max - min)) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn solid(c: Color, opacity: f64, blend: Blend) -> Node { - Node { - class: crate::stream::Tag::of(b"ShpN"), - name: String::new(), - visible: true, - locked: false, - opacity: 1.0, - blend: Blend::Normal, - kind: Kind::Shape { - path: Default::default(), - fills: vec![Paint::Solid(Color::Rgb { r: 1.0, g: 0.5, b: 0.0, a: 1.0 })], - strokes: vec![], - even_odd: false, - }, - mask: None, - pixel_mask: None, - effects: vec![Effect::ColorOverlay { color: c, opacity, blend }], - children: vec![], - } - } - - fn fill(n: &Node) -> Color { - match &n.kind { - Kind::Shape { fills, .. } => match fills.first() { - Some(Paint::Solid(c)) => *c, - other => panic!("{other:?}"), - }, - other => panic!("{other:?}"), - } - } - - #[test] - fn a_full_colour_overlay_replaces_the_fill_and_keeps_its_alpha() { - let white = Color::Rgb { r: 1.0, g: 1.0, b: 1.0, a: 1.0 }; - let n = apply(&solid(white, 1.0, Blend::Normal), &mut { MAX_WORK }, &mut |_| {}).into_owned(); - assert_eq!(fill(&n), white); - assert!(n.effects.is_empty(), "the overlay is baked, not kept"); - // Half way, mixed in RGB. - let n = apply(&solid(white, 0.5, Blend::Normal), &mut { MAX_WORK }, &mut |_| {}).into_owned(); - assert_eq!(fill(&n), Color::Rgb { r: 1.0, g: 0.75, b: 0.5, a: 1.0 }); - } - - #[test] - fn blend_modes_follow_their_formulas() { - let b = [0.25, 0.5, 1.0]; - assert_eq!(blend(Blend::Multiply, b, [0.5; 3]), [0.125, 0.25, 0.5]); - assert_eq!(blend(Blend::Screen, b, [0.5; 3]), [0.625, 0.75, 1.0]); - assert_eq!(blend(Blend::VividLight, [0.5; 3], [0.75; 3]), [1.0; 3]); - assert_eq!(blend(Blend::HardMix, [0.5; 3], [0.6; 3]), [1.0; 3]); - // Color keeps the backdrop's luminosity with the source's hue and saturation. - let c = blend(Blend::Color, [0.5; 3], [1.0, 0.0, 0.0]); - assert!((lum(c) - 0.5).abs() < 1e-9 && c[0] > c[1] && (c[1] - c[2]).abs() < 1e-9, "{c:?}"); - } - - #[test] - fn overlays_recolour_pixels_inside_their_alpha() { - let mut n = solid(Color::Rgb { r: 0.0, g: 0.0, b: 1.0, a: 1.0 }, 1.0, Blend::Normal); - n.kind = Kind::Image(Image { width: 2, height: 1, pixels: Pixels::Rgba8(vec![255, 0, 0, 255, 255, 0, 0, 0]), transform: Affine::IDENTITY }); - let out = apply(&n, &mut { MAX_WORK }, &mut |_| {}).into_owned(); - let Kind::Image(img) = &out.kind else { panic!() }; - assert_eq!(img.pixels, Pixels::Rgba8(vec![0, 0, 255, 255, 255, 0, 0, 0])); - } - - #[test] - fn a_gradient_overlay_over_one_colour_becomes_that_gradient() { - let g = Gradient { - kind: GradientKind::Linear, - stops: vec![ - Stop { offset: 0.0, color: Color::Rgb { r: 0.0, g: 0.0, b: 0.0, a: 1.0 }, bias: 0.5 }, - Stop { offset: 1.0, color: Color::Rgb { r: 1.0, g: 1.0, b: 1.0, a: 1.0 }, bias: 0.5 }, - ], - transform: Affine([10.0, 0.0, 0.0, 10.0, 0.0, 0.0]), - }; - let mut n = solid(Color::Rgb { r: 0.0, g: 0.0, b: 0.0, a: 1.0 }, 1.0, Blend::Normal); - n.effects = vec![Effect::GradientOverlay { gradient: g.clone(), opacity: 1.0, blend: Blend::Normal }]; - let out = apply(&n, &mut { MAX_WORK }, &mut |_| {}).into_owned(); - let Kind::Shape { fills, .. } = &out.kind else { panic!() }; - assert_eq!(fills.first(), Some(&Paint::Gradient(g))); - } - - #[test] - fn a_group_overlay_lies_over_its_childrens_overlays() { - let red = Color::Rgb { r: 1.0, g: 0.0, b: 0.0, a: 1.0 }; - let blue = Color::Rgb { r: 0.0, g: 0.0, b: 1.0, a: 1.0 }; - let mut group = solid(red, 0.5, Blend::Normal); - group.kind = Kind::Group; - group.children = vec![solid(blue, 1.0, Blend::Normal)]; - // The copy (2 nodes), the child's overlay (1) and the group's (2). - let mut work = 5; - let out = apply(&group, &mut work, &mut |_| {}).into_owned(); - assert_eq!(work, 0); - let child = out.children.first().unwrap(); - // Blue first, then half of the group's red over it. - assert_eq!(fill(child), Color::Rgb { r: 0.5, g: 0.0, b: 0.5, a: 1.0 }); - assert!(out.effects.is_empty() && child.effects.is_empty(), "both overlays are baked"); - // With no work left for the group's overlay, the child's still applies. - let mut warnings = Vec::new(); - let out = apply(&group, &mut { 4 }, &mut |w| warnings.push(w.to_string())).into_owned(); - assert_eq!(fill(out.children.first().unwrap()), blue); - assert!(warnings.iter().any(|w| w.contains("beyond the work")), "{warnings:?}"); - } - - #[test] - fn overlays_stop_at_the_work_one_import_may_take() { - let mut n = solid(Color::Rgb { r: 0.0, g: 0.0, b: 1.0, a: 1.0 }, 1.0, Blend::Normal); - n.kind = Kind::Image(Image { width: 4, height: 4, pixels: Pixels::Rgba8(vec![255; 64]), transform: Affine::IDENTITY }); - // 16 pixels and the node, for the copy and for the overlay: 34. - let mut work = 40; - let mut warnings = Vec::new(); - assert!(matches!(apply(&n, &mut work, &mut |w| warnings.push(w.to_string())), Cow::Owned(_))); - assert_eq!((work, warnings.len()), (6, 0)); - assert!(matches!(apply(&n, &mut work, &mut |w| warnings.push(w.to_string())), Cow::Borrowed(_))); - assert_eq!(work, 6); - assert!(warnings.iter().any(|w| w.contains("beyond the work")), "{warnings:?}"); - } -} diff --git a/crates/affinity/src/paint.rs b/crates/affinity/src/paint.rs deleted file mode 100644 index c7b2acbbd3..0000000000 --- a/crates/affinity/src/paint.rs +++ /dev/null @@ -1,403 +0,0 @@ -//! Fills, strokes and colours. Two schemas exist: Affinity 1 (`BFil` fill, `PFil` stroke paint, -//! `LSty` stroke style) and Affinity 2/3 (`BFFl`, `LIFl` and `LILn` lists with a current index). - -use crate::model::{Affine, Reader}; -use crate::stream::{ObjId, Value}; - -/// A colour as stored: RGB and grey values are encoded in the document's RGB space (sRGB unless -/// the document embeds another profile), CMYK values go through its CMYK profile. Alpha is straight. -#[derive(Debug, Clone, Copy, PartialEq)] -pub enum Color { - Rgb { - r: f64, - g: f64, - b: f64, - a: f64, - }, - Cmyk { - c: f64, - m: f64, - y: f64, - k: f64, - a: f64, - }, - Gray { - v: f64, - a: f64, - }, - /// CIE L*a*b* (D50). - Lab { - l: f64, - a: f64, - b: f64, - alpha: f64, - }, -} - -impl Color { - pub fn alpha(&self) -> f64 { - match self { - Color::Rgb { a, .. } | Color::Cmyk { a, .. } | Color::Gray { a, .. } => *a, - Color::Lab { alpha, .. } => *alpha, - } - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum GradientKind { - Linear, - /// Elliptical and radial: distance from the centre in unit space. - Radial, - /// Angle around the centre. - Conical, -} - -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct Stop { - pub offset: f64, - pub color: Color, - /// Affinity's midpoint bias for the segment from this stop to the next (0.5 = even blend). - pub bias: f64, -} - -impl Stop { - /// Where, between this stop (0) and the next (1), the blend reaches half way: the bias curve - /// fitted to Affinity's renders is `t^k` (bias ≥ 0.5) or `1-(1-t)^k`, with `k = 1 + 8·|bias-0.5|`. - pub fn half_point(&self) -> f64 { - let k = 1.0 + 8.0 * (self.bias - 0.5).abs(); - let h = 0.5f64.powf(1.0 / k); - if self.bias >= 0.5 { h } else { 1.0 - h } - } -} - -#[derive(Debug, Clone, PartialEq)] -pub struct Gradient { - pub kind: GradientKind, - pub stops: Vec, - /// Unit space to document pixels: linear runs from unit (0,0) to (1,0); radial is the unit - /// circle; conical starts along unit +x and turns towards unit +y. - pub transform: Affine, -} - -#[derive(Debug, Clone, PartialEq, Default)] -pub enum Paint { - #[default] - None, - Solid(Color), - Gradient(Gradient), -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Cap { - Butt, - Round, - Square, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Join { - Miter, - Round, - Bevel, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Align { - Center, - Inside, - Outside, -} - -#[derive(Debug, Clone, PartialEq)] -pub struct Stroke { - pub paint: Paint, - /// Width in document pixels. - pub width: f64, - pub cap: Cap, - pub join: Join, - pub miter_limit: f64, - pub align: Align, - /// Dash and gap lengths in document pixels, and the phase. - pub dash: Option<(Vec, f64)>, - /// Painted below the fill instead of above it. - pub behind: bool, - /// The pressure curve: (position 0..1 along the path, width as a fraction of `width`) in - /// order along the path, `None` for a stroke of the same width all along. - pub profile: Option>, -} - -/// Gradient stops per gradient. -const MAX_STOPS: usize = 1024; - -/// Dash and gap lengths per dash pattern (a pattern has a few; strokes and text runs copy theirs). -const MAX_DASHES: usize = 64; - -fn floats(v: &Value) -> Option> { - match v { - Value::Floats(f) => Some(f.clone()), - Value::Bytes(b) if b.len() % 4 == 0 => Some(b.as_chunks::<4>().0.iter().map(|c| f64::from(f32::from_le_bytes(*c))).collect()), - _ => None, - } -} - -/// A colour object (`RGBA`, `HSLA`, `CMYK`, `GRAY`, `LABA`, `Pant`). -pub(crate) fn color(r: &mut Reader, id: ObjId) -> Option { - color_within(r, id, 0) -} - -/// The most spot colours that stand for one another followed. -const MAX_SPOT_CHAIN: u32 = 8; - -/// [`color`], `depth` spot colours deep: one that stands for itself (or a ring of them) ends here. -fn color_within(r: &mut Reader, id: ObjId, depth: u32) -> Option { - let s = r.s; - let class = s.class(id)?; - let col = || -> Option> { - let v = floats(s.field(id, b"_col")?)?; - v.iter().all(|f| f.is_finite()).then_some(v) - }; - Some(match &class.0.to_be_bytes() { - b"RGBA" => { - let v = col()?; - Color::Rgb { r: *v.first()?, g: *v.get(1)?, b: *v.get(2)?, a: v.get(3)?.clamp(0.0, 1.0) } - } - b"HSLA" => { - let v = col()?; - let (r2, g, b) = hsl(*v.first()?, *v.get(1)?, *v.get(2)?); - Color::Rgb { r: r2, g, b, a: v.get(3)?.clamp(0.0, 1.0) } - } - b"CMYK" => { - let v = col()?; - Color::Cmyk { c: *v.first()?, m: *v.get(1)?, y: *v.get(2)?, k: *v.get(3)?, a: v.get(4)?.clamp(0.0, 1.0) } - } - b"GRAY" => { - let v = col()?; - Color::Gray { v: *v.first()?, a: v.get(1)?.clamp(0.0, 1.0) } - } - b"LABA" => { - let b = s.bytes(id, b"_col")?; - let u = |i: usize| -> Option { Some(f64::from(u16::from_le_bytes([*b.get(2 * i)?, *b.get(2 * i + 1)?])) / 65535.0) }; - Color::Lab { l: 100.0 * u(0)?, a: 255.0 * u(1)? - 128.0, b: 255.0 * u(2)? - 128.0, alpha: u(3)? } - } - b"Pant" => { - r.warn("spot colours (imported as their RGB equivalent)"); - if depth >= MAX_SPOT_CHAIN { - return None; - } - return s - .obj(id, b"srgb") - .and_then(|c| color_within(r, c, depth + 1)) - .or_else(|| s.obj(id, b"base").and_then(|c| color_within(r, c, depth + 1))); - } - b"RegC" => Color::Cmyk { c: 1.0, m: 1.0, y: 1.0, k: 1.0, a: 1.0 }, - _ => { - r.warn("colours in an unknown model"); - return None; - } - }) -} - -pub(crate) fn hsl(h: f64, s: f64, l: f64) -> (f64, f64, f64) { - let c = (1.0 - (2.0 * l - 1.0).abs()) * s; - let hp = (h.rem_euclid(1.0)) * 6.0; - let x = c * (1.0 - (hp % 2.0 - 1.0).abs()); - let (r, g, b) = match hp as u32 { - 0 => (c, x, 0.0), - 1 => (x, c, 0.0), - 2 => (0.0, c, x), - 3 => (0.0, x, c), - 4 => (x, 0.0, c), - _ => (c, 0.0, x), - }; - let m = l - c / 2.0; - (r + m, g + m, b + m) -} - -/// A fill descriptor (`FDsc`) or, in Affinity 1 files, a bare `FilS`; `local` maps the node's -/// space to document pixels. -pub(crate) fn descriptor(r: &mut Reader, id: ObjId, local: Affine) -> Option { - let s = r.s; - let (fill, unit) = if s.is(id, b"FDsc") { - let unit = s.floats::<6>(id, b"FDeX").map(Affine::from_xfrm).unwrap_or(Affine::IDENTITY); - (s.obj(id, b"FDeF")?, unit) - } else { - (id, Affine::IDENTITY) - }; - match &s.class(fill)?.0.to_be_bytes() { - b"FilN" => Some(Paint::None), - b"FilS" => Some(Paint::Solid(color(r, s.obj(fill, b"Colr")?)?)), - b"FilG" => { - let kind = match s.enumeration(fill, b"Type").map(|(i, _)| i) { - Some(0) | None => GradientKind::Linear, - Some(1 | 2) => GradientKind::Radial, - Some(3) => GradientKind::Conical, - Some(_) => { - r.warn("gradients of an unknown kind (imported as linear)"); - GradientKind::Linear - } - }; - let grad = s.obj(fill, b"Grad")?; - let cols = s.objs(grad, b"Cols"); - // 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.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); - stops.push(Stop { offset, color, bias }); - } - if stops.is_empty() { - return Some(Paint::None); - } - Some(Paint::Gradient(Gradient { kind, stops, transform: unit.then(local) })) - } - b"FilB" => { - r.warn("bitmap and pattern fills (left empty)"); - Some(Paint::None) - } - _ => { - r.warn("fills of an unknown kind (left empty)"); - Some(Paint::None) - } - } -} - -fn current(r: &Reader, id: ObjId, list: &[u8; 4], index: &[u8; 4]) -> Option { - let items = r.s.objs(id, list); - let i = r.s.int(id, index).and_then(|i| usize::try_from(i).ok()).unwrap_or(0); - items.get(i).or_else(|| items.first()).copied() -} - -/// The fills of `list` (artboard backgrounds use `BFFl`). -pub(crate) fn fills(r: &mut Reader, id: ObjId, local: Affine, list: &[u8; 4]) -> Vec { - let d = current(r, id, list, b"BFCr").or_else(|| r.s.obj(id, b"BFil")); - d.and_then(|d| descriptor(r, d, local)).filter(|p| *p != Paint::None).into_iter().collect() -} - -/// A node's fill and stroke. `local` maps the node's space to document pixels. -pub(crate) fn node_paint(r: &mut Reader, id: ObjId, local: Affine) -> (Vec, Vec) { - let s = r.s; - let fills = fills(r, id, local, b"BFFl"); - if r.s.objs(id, b"BFFl").len() > 1 || r.s.objs(id, b"LIFl").len() > 1 { - r.warn("several fills or strokes on one object (only the active one is imported)"); - } - if s.f64(id, b"FOpc").is_some_and(|o| o < 0.999) { - r.warn("fill opacity (imported at full fill opacity)"); - } - if s.obj(id, b"Trns").is_some() { - r.warn("transparency gradients (imported without them)"); - } - let (pen, style) = if s.field(id, b"LIFl").is_some() { - (current(r, id, b"LIFl", b"LICr"), current(r, id, b"LILn", b"LICr")) - } else { - (s.obj(id, b"PFil"), s.obj(id, b"LSty")) - }; - let behind = matches!(s.field(id, b"DrwO"), Some(Value::Array(a)) if a.first() == Some(&Value::Enum { id: 1, version: 0 })); - let stroke = match (pen, style) { - (Some(pen), Some(style)) => stroke(r, pen, style, local, behind), - _ => None, - }; - (fills, stroke.into_iter().collect()) -} - -pub(crate) fn stroke(r: &mut Reader, pen: ObjId, ldsc: ObjId, local: Affine, behind: bool) -> Option { - let s = r.s; - let paint = descriptor(r, pen, local)?; - if paint == Paint::None { - return None; - } - let lsty = if s.is(ldsc, b"LDsc") { s.obj(ldsc, b"LDeL")? } else { ldsc }; - let weight = s.f64(lsty, b"Wght").filter(|w| *w > 0.0 && *w < 1e7)?; - // "Scale with object": the weight follows the object's transform; otherwise it is absolute. - let scales = s.bool(ldsc, b"LDSc").unwrap_or(true); - let width = if scales { weight * local.scale() } else { weight }; - let data = s.bytes(lsty, b"Data").unwrap_or_default(); - // Byte 10 is the stroke's style: 0 none, 1 solid, 2 dashed, 3 a brush. A shape without a - // stroke still stores one (black, 1 px wide), with style 0. Identified on two documents their - // owner made, where every such stroke is invisible in Affinity's own PDF export, and checked - // against the public corpus's thumbnails. - if data.get(10) == Some(&0) { - return None; - } - let miter_limit = data.get(0..8).and_then(|b| b.try_into().ok()).map(f64::from_le_bytes).filter(|m| m.is_finite() && *m >= 1.0).unwrap_or(4.0); - // Cap and join bytes are only partly understood: (0, 0) is butt/miter in every clean sample; - // (2, 2) ends plain lines square and brush lines round; joins import round, which never - // looks wrong. - let (cap, join) = match (data.get(8).copied(), data.get(9).copied(), data.get(10).copied()) { - (Some(0), Some(0), _) => (Cap::Butt, Join::Miter), - (Some(0), Some(_), _) => (Cap::Butt, Join::Round), - (Some(2), Some(2), Some(3)) => (Cap::Round, Join::Round), - (Some(2), Some(2), _) => (Cap::Square, Join::Round), - _ => (Cap::Round, Join::Round), - }; - let align = match s.int(ldsc, b"LDSa") { - Some(1) => Align::Inside, - Some(2) => Align::Outside, - _ => Align::Center, - }; - let dash = match s.field(lsty, b"Patn") { - Some(Value::Array(a)) if a.len() > MAX_DASHES => { - r.warn("dash patterns of more than 64 lengths (imported as solid lines)"); - None - } - Some(Value::Array(a)) if data.get(10) == Some(&2) || !a.is_empty() => { - let mut v: Vec = a.iter().filter_map(|x| if let Value::Float(f) = x { Some(*f) } else { None }).collect(); - while v.len() >= 2 && v.iter().rev().take(2).all(|x| *x == 0.0) { - v.truncate(v.len() - 2); - } - let valid = !v.is_empty() && v.iter().all(|x| x.is_finite() && *x >= 0.0) && v.iter().any(|x| *x > 0.0); - valid.then(|| (v.iter().map(|x| x * width).collect(), s.f64(lsty, b"Phse").unwrap_or(0.0) * width)) - } - _ => None, - }; - if s.obj(lsty, b"Brus").is_some() { - r.warn("brush strokes (imported as plain strokes)"); - } - // The pressure curve sets the width along the path; one at full width all along is a plain - // stroke. Every curve read counts against the document's points: one at full width counts its - // points, and one that can't be read counts the most a curve may have. Once the points are - // used up the rest are not read. - const BEYOND: &str = "pressure strokes beyond the pressure points one document may hold (imported as plain strokes)"; - let ldep = s.obj(ldsc, b"LDeP"); - if ldep.is_some() && r.budget.pressure == 0 { - r.warn(BEYOND); - } - let profile = match ldep.filter(|_| r.budget.pressure > 0).map(|p| crate::geometry::pressure(r, p)) { - Some(Some(points)) => match r.budget.pressure.checked_sub(points.len()) { - Some(left) => { - r.budget.pressure = left; - (!points.iter().all(|(_, w)| (w - 1.0).abs() < 1e-9)).then_some(points) - } - None => { - r.budget.pressure = 0; - r.warn(BEYOND); - None - } - }, - Some(None) => { - r.budget.pressure = r.budget.pressure.saturating_sub(crate::geometry::MAX_PRESSURE_CURVE_POINTS); - r.warn("pressure strokes whose pressure curve can't be read (imported as plain strokes)"); - None - } - None => None, - }; - Some(Stroke { paint, width, cap, join, miter_limit, align, dash, behind, profile }) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn hsl_lightness_1_is_white_and_0_is_black() { - assert_eq!(hsl(0.0, 1.0, 1.0), (1.0, 1.0, 1.0)); - assert_eq!(hsl(0.5, 1.0, 1.0), (1.0, 1.0, 1.0)); - assert_eq!(hsl(0.0, 1.0, 0.0), (0.0, 0.0, 0.0)); - let (r, g, b) = hsl(0.0, 1.0, 0.5); - assert!((r - 1.0).abs() < 1e-6 && g.abs() < 1e-6 && b.abs() < 1e-6); - } -} diff --git a/crates/affinity/src/preview.rs b/crates/affinity/src/preview.rs deleted file mode 100644 index d3341eeb1c..0000000000 --- a/crates/affinity/src/preview.rs +++ /dev/null @@ -1,124 +0,0 @@ -//! The indexed PNG thumbnail Affinity stores next to the archive: Affinity's own render of the -//! document, at most 512 pixels on the long side in real files, never the document itself. - -use crate::Error; -use crate::container::header; - -pub const MAX_PREVIEW_BYTES: usize = 16 << 20; -pub const MAX_PREVIEW_DIMENSION: u32 = 4096; - -/// Borrowed embedded thumbnail, at its own dimensions, never the native document dimensions. -#[derive(Debug)] -pub struct Preview<'a> { - pub png: &'a [u8], - pub width: u32, - pub height: u32, -} - -fn bytes_at(bytes: &[u8], offset: usize, length: usize) -> Result<&[u8], Error> { - let end = offset.checked_add(length).ok_or(Error::Malformed("offset overflow"))?; - bytes.get(offset..end).ok_or(Error::Malformed("truncated record")) -} - -fn le32(bytes: &[u8], offset: usize) -> Result { - let b = bytes_at(bytes, offset, 4)?; - Ok(u32::from_le_bytes(b.try_into().map_err(|_| Error::Malformed("integer"))?)) -} - -fn be32(bytes: &[u8], offset: usize) -> Result { - let b = bytes_at(bytes, offset, 4)?; - Ok(u32::from_be_bytes(b.try_into().map_err(|_| Error::Malformed("PNG integer"))?)) -} - -/// Read only the indexed `Thmb` record (identical in container versions 8 to 12), checking every PNG chunk CRC. Compressed -/// pixels must still be validated by the consuming image decoder, with allocation limits. -pub fn preview(bytes: &[u8]) -> Result, Error> { - let h = header(bytes)?; - if h.thumbnail_offset == 0 { - return Err(Error::Unsupported("no embedded preview")); - } - let offset = usize::try_from(h.thumbnail_offset).map_err(|_| Error::Malformed("thumbnail offset overflow"))?; - if offset < 72 { - return Err(Error::Malformed("thumbnail overlaps the file header")); - } - let record = bytes.get(offset..).ok_or(Error::Malformed("thumbnail offset outside file"))?; - if bytes_at(record, 0, 8)? != b"\xff\xff\xff\xffThmb" { - return Err(Error::Malformed("missing indexed thumbnail")); - } - if le32(record, 8)? != 1 || bytes_at(record, 28, 1)? != [1] { - return Err(Error::Unsupported("thumbnail record version or encoding")); - } - let size = usize::try_from(le32(record, 24)?).map_err(|_| Error::Limit("encoded size"))?; - if size > MAX_PREVIEW_BYTES { - return Err(Error::Limit("encoded preview exceeds 16 MiB")); - } - if le32(record, 16)? != 29 || le32(record, 20)? != 0 || u64::from(le32(record, 12)?) != size as u64 + 13 { - return Err(Error::Malformed("inconsistent thumbnail record lengths")); - } - let png = bytes_at(record, 29, size)?; - if bytes_at(png, 0, 8)? != b"\x89PNG\r\n\x1a\n" || be32(png, 8)? != 13 || bytes_at(png, 12, 4)? != b"IHDR" { - return Err(Error::Malformed("thumbnail is not a PNG")); - } - let width = be32(png, 16)?; - let height = be32(png, 20)?; - if width == 0 || height == 0 || width > MAX_PREVIEW_DIMENSION || height > MAX_PREVIEW_DIMENSION { - return Err(Error::Limit("preview dimensions must be 1..4096")); - } - // Bound work by bytes, not a file-supplied chunk count, and require exactly one complete PNG. - let mut pos = 8usize; - let (mut palette, mut image_data, mut image_data_ended) = (false, false, false); - loop { - let length = usize::try_from(be32(png, pos)?).map_err(|_| Error::Limit("PNG chunk length"))?; - let chunk_size = length.checked_add(12).ok_or(Error::Malformed("PNG chunk overflow"))?; - let chunk = bytes_at(png, pos, chunk_size)?; - let checksum_input = bytes_at(chunk, 4, chunk_size - 8)?; - if crc32fast::hash(checksum_input) != be32(chunk, chunk_size - 4)? { - return Err(Error::Malformed("PNG chunk checksum")); - } - let kind = bytes_at(chunk, 4, 4)?; - if !kind.iter().all(u8::is_ascii_alphabetic) { - return Err(Error::Malformed("PNG chunk type")); - } - match kind { - b"IHDR" if pos == 8 => {} - b"IHDR" => return Err(Error::Malformed("duplicate PNG header")), - b"PLTE" => { - if palette || image_data { - return Err(Error::Malformed("PNG palette order")); - } - palette = true; - } - b"IDAT" => { - if image_data_ended { - return Err(Error::Malformed("non-contiguous PNG image data")); - } - image_data = true; - } - b"IEND" if !image_data => return Err(Error::Malformed("PNG has no image data")), - b"IEND" => {} - _ if kind.first().is_some_and(u8::is_ascii_uppercase) => { - return Err(Error::Unsupported("unknown critical PNG chunk")); - } - _ => {} - } - if image_data && kind != b"IDAT" { - image_data_ended = true; - } - // Native sample previews are plain, single-frame PNGs. Pixel allocation limits do not - // necessarily bound aggregate compressed metadata; leave these layouts unsupported. - if matches!(kind, b"zTXt" | b"iTXt" | b"iCCP") { - return Err(Error::Unsupported("compressed PNG metadata in the preview")); - } - if matches!(kind, b"acTL" | b"fcTL" | b"fdAT") { - return Err(Error::Unsupported("animated PNG preview")); - } - pos = pos.checked_add(chunk_size).ok_or(Error::Malformed("PNG offset overflow"))?; - if kind == b"IEND" { - if length != 0 || pos != png.len() { - return Err(Error::Malformed("PNG end or trailing data")); - } - break; - } - } - Ok(Preview { png, width, height }) -} diff --git a/crates/affinity/src/raster.rs b/crates/affinity/src/raster.rs deleted file mode 100644 index bb8c1c88b8..0000000000 --- a/crates/affinity/src/raster.rs +++ /dev/null @@ -1,650 +0,0 @@ -//! Pixel layers (`Rstr`) and placed images (`ImgN`). A placed image keeps its original file -//! (`DyBm.Bckg` → archive entry `c/N`), which is imported as is; other pixels are planar tiles of -//! 256 bytes × 256 rows per channel, each its own archive entry. - -use std::collections::HashMap; - -use crate::Error; -use crate::model::{Affine, Image, Pixels, Reader}; -use crate::stream::{self, ObjId, Tag, Value}; - -/// Pixels decoded per layer (the content's bounding box, not the canvas). -const MAX_PIXELS: u64 = 64 << 20; -const TILE: usize = 256; -const TILE_BYTES: usize = TILE * TILE; - -struct CachedPixels { - tiles: HashMap>, - source: Option<(usize, Vec)>, -} - -pub(crate) fn node_image(r: &mut Reader, id: ObjId, world: Affine) -> Result, Error> { - let s = r.s; - let Some(bitmap) = s.obj(id, b"Bitm") else { - r.warn("pixel layers without pixels"); - return Ok(None); - }; - if !s.is(bitmap, b"DyBm") { - r.warn("pixel layers stored in an unknown way"); - return Ok(None); - } - 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); - if width == 0 || height == 0 { - return Ok(None); - } - // A placed image: the original file, byte for byte. - let has_tiles = s.field(bitmap, b"Sta1").is_some(); - if let Some(name) = s.entry(bitmap, b"Bckg").filter(|n| !n.is_empty()) - && (s.is(id, b"ImgN") || !has_tiles) - { - match original(r, name) { - // HEIF/HEIC (phone photos) and AVIF originals can't be decoded here: the same pixels - // stored as tiles are used instead (see `decode` when the tiles point back at the original). - Ok(bytes) if is_heif(&bytes) && has_tiles => {} - Ok(bytes) => return Ok(Some(Image { width, height, pixels: Pixels::Encoded(bytes), transform: world })), - Err(Error::Limit(e)) => return Err(Error::Limit(e)), - Err(_) => r.warn("an embedded image file that could not be read (its cached pixels were used)"), - } - } - // The content's bounding box, so a mostly empty canvas-sized layer stays small. - let crop = s - .field(id, b"BitR") - .and_then(|v| if let Value::Ints(i) = v { Some(i.clone()) } else { None }) - .filter(|v| v.len() == 4 && v[0] > i64::from(i32::MIN) + 1) - .map(|v| { - ( - v[0].clamp(0, i64::from(width)) as u32, - v[1].clamp(0, i64::from(height)) as u32, - v[2].clamp(0, i64::from(width)) as u32, - v[3].clamp(0, i64::from(height)) as u32, - ) - }) - .unwrap_or((0, 0, width, height)); - let source_tiles_only = - (1..=4).all(|c| matches!(s.field(bitmap, &tag(b"Sta", c)), Some(Value::Array(a)) if !a.is_empty() && a.iter().all(|v| *v == Value::UInt(5)))); - if s.field(bitmap, b"Bckg").is_some() && has_tiles && !source_tiles_only && !s.is(id, b"ImgN") { - r.warn("edited placed images use their stored pixels"); - } - decode(r, bitmap, crop, world) -} - -/// An ISO base media file holding a HEIF image (HEIC, AVIF): `ftyp` with an image brand. -fn is_heif(bytes: &[u8]) -> bool { - bytes.get(4..8) == Some(b"ftyp".as_slice()) - && bytes.get(8..12).is_some_and(|brand| { - [b"heic", b"heix", b"hevc", b"hevx", b"heim", b"heis", b"mif1", b"msf1", b"avif", b"avis"].iter().any(|b| brand == b.as_slice()) - }) -} - -/// A mask layer (`MRst`): one channel of coverage as grey pixels (white shows, black hides), read -/// over `over` (document pixels) when given; outside its pixels a mask hides everything. -pub(crate) fn mask(r: &mut Reader, id: ObjId, world: Affine, over: Option) -> Result, Error> { - let s = r.s; - let Some(bitmap) = s.obj(id, b"Bitm") else { return Ok(None) }; - 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); - if width == 0 || height == 0 || !matches!(s.enumeration(bitmap, b"Frmt"), Some((6 | 7, _))) { - r.warn("pixel masks in an unknown format (imported without them)"); - return Ok(None); - } - let crop = match over.map(|o| crop_to(o, world, width, height)) { - Some(Some(c)) => c, - // What it masks lies outside it: all hidden, which one black pixel says as well. - Some(None) => return Ok(Some(Image { width: 1, height: 1, pixels: Pixels::Rgba8(vec![0, 0, 0, 255]), transform: world })), - None => (0, 0, width, height), - }; - decode(r, bitmap, crop, world) -} - -/// The bitmap pixels (x0, y0, x1, y1) of a `width` × `height` bitmap placed by `world` that cover -/// document rectangle `over`, one pixel wider all round; `None` if they don't overlap. -fn crop_to(over: crate::model::Rect, world: Affine, width: u32, height: u32) -> Option<(u32, u32, u32, u32)> { - let inv = invert(world)?; - let pts = [(over.x0, over.y0), (over.x1, over.y0), (over.x1, over.y1), (over.x0, over.y1)].map(|(x, y)| inv.apply(crate::model::Point { x, y })); - let (mut x0, mut y0, mut x1, mut y1) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY); - for p in pts { - if !(p.x.is_finite() && p.y.is_finite()) { - return Some((0, 0, width, height)); - } - (x0, y0, x1, y1) = (x0.min(p.x), y0.min(p.y), x1.max(p.x), y1.max(p.y)); - } - let clamp = |v: f64, max: u32| v.clamp(0.0, f64::from(max)) as u32; - let (cx0, cy0, cx1, cy1) = - (clamp(x0.floor() - 1.0, width), clamp(y0.floor() - 1.0, height), clamp(x1.ceil() + 1.0, width), clamp(y1.ceil() + 1.0, height)); - (cx1 > cx0 && cy1 > cy0).then_some((cx0, cy0, cx1, cy1)) -} - -fn invert(m: Affine) -> Option { - let [a, b, c, d, e, f] = m.0; - let det = a * d - b * c; - if !(det.is_finite() && det.abs() > 1e-12) { - return None; - } - let (ia, ib, ic, id) = (d / det, -b / det, -c / det, a / det); - Some(Affine([ia, ib, ic, id, -(ia * e + ic * f), -(ib * e + id * f)])) -} - -/// An embedded document or symbol instance (`EmbN`), as the picture of it Affinity caches. -pub(crate) fn embedded(r: &mut Reader, id: ObjId, world: Affine) -> Result, Error> { - let s = r.s; - let Some(cache) = s.obj(id, b"Bitm").and_then(|e| s.obj(e, b"Cach")) else { return Ok(None) }; - let Some(bbox) = s.obj(id, b"Bitm").and_then(|e| s.floats::<4>(e, b"ChBB")) else { return Ok(None) }; - let width = s.int(cache, b"BmpW").and_then(|v| u32::try_from(v).ok()).unwrap_or(0); - let height = s.int(cache, b"BmpH").and_then(|v| u32::try_from(v).ok()).unwrap_or(0); - if width == 0 || height == 0 { - return Ok(None); - } - let [x0, y0, x1, y1] = bbox; - // The instance's origin is the centre of the embedded content (checked against the - // thumbnails of documents with embedded documents and SVG files). - let (cx, cy) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0); - let place = Affine([(x1 - x0) / f64::from(width), 0.0, 0.0, (y1 - y0) / f64::from(height), x0 - cx, y0 - cy]).then(world); - decode(r, cache, (0, 0, width, height), place) -} - -/// Decode the tiles of a bitmap inside `crop` (pixels), placed by `world` (bitmap pixels to document). -fn decode(r: &mut Reader, bitmap: ObjId, crop: (u32, u32, u32, u32), world: Affine) -> Result, Error> { - decode_within(r, bitmap, crop, world, MAX_PIXELS) -} - -/// [`decode`] with at most `max_pixels` decoded pixels. -fn decode_within(r: &mut Reader, bitmap: ObjId, crop: (u32, u32, u32, u32), world: Affine, max_pixels: u64) -> Result, Error> { - let s = r.s; - let (x0, y0, x1, y1) = crop; - if x1 <= x0 || y1 <= y0 { - return Ok(None); - } - let (w, h) = (x1 - x0, y1 - y0); - // Larger layers (mostly masks of whole spreads) are read at a half, a quarter… of their - // resolution: every `step`th pixel of every `step`th row. - let mut step = 1u32; - while u64::from(w.div_ceil(step)) * u64::from(h.div_ceil(step)) > max_pixels { - step *= 2; - if step > 1 << 12 { - r.warn("pixel layers too large to read (left out)"); - return Ok(None); - } - } - // Before anything is allocated: a layer's tiles can be flat colour, with nothing to extract. - let pixels = u64::from(w.div_ceil(step)) * u64::from(h.div_ceil(step)); - let Some(left) = r.budget.pixels.checked_sub(pixels) else { - r.warn("pixel layers beyond the pixels one document may hold"); - return Ok(None); - }; - r.budget.pixels = left; - let format = s.enumeration(bitmap, b"Frmt").map(|(f, _)| f); - let (channels, bps) = match format { - Some(0) => (4, 1), - Some(1) => (4, 2), - Some(6) => (1, 1), - Some(7) => (1, 2), - Some(4) => (5, 1), - _ => { - r.warn("pixel layers in grey, Lab or 32-bit formats"); - return Ok(None); - } - }; - let mut planes = Vec::with_capacity(channels); - // Current .af documents can keep level-zero tiles in their embedded JPEG/PNG instead of - // duplicating the pixels. State 5 is checked in the public Patchy embedded-jpeg fixture. - // Support only the observed, same-size RGBA8 image with a zero bitmap origin; other - // representations still receive the existing loss warning rather than guessing a mapping. - let needs_source = (1..=channels).any(|c| matches!(s.field(bitmap, &tag(b"Sta", c)), Some(Value::Array(a)) if a.contains(&Value::UInt(5)))); - let source = if needs_source && format == Some(0) && s.int(bitmap, b"LInf") == Some(0) && s.int(bitmap, b"TInf") == Some(0) { - 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)), - Err(_) => None, - } - } else { - None - } - } else { - None - }; - // Tiles kept only in an original that can't be decoded here are left empty (transparent). Where - // a tile's colour is in the original but its alpha is stored, as in CMYK layers, it would come - // out opaque white instead: such a layer (a HEIC photo in a CMYK document) is left out, and said. - if needs_source && source.is_none() && channels > 1 { - let states = |c: usize| match s.field(bitmap, &tag(b"Sta", c)) { - Some(Value::Array(a)) => a.clone(), - _ => Vec::new(), - }; - let alpha = states(channels); - let blank = (1..channels).any(|c| states(c).iter().enumerate().any(|(i, v)| *v == Value::UInt(5) && alpha.get(i) != Some(&Value::UInt(5)))); - if blank { - r.warn("placed images whose pixels are only in an original the reader can't decode, such as HEIC photos (left out)"); - return Ok(None); - } - } - if step > 1 { - // Its stored tiles must fit what is left of the import's extraction budget. - let stored: usize = (1..=channels).map(|c| tiles_in(s, bitmap, c, bps, (x0, y0, w, h)).len()).sum(); - if stored.saturating_mul(TILE_BYTES) > r.archive.remaining().max_total { - r.warn("pixel layers too large to read (left out)"); - return Ok(None); - } - r.warn("pixel layers larger than 64 megapixels (read at a lower resolution)"); - } - let mut cache = CachedPixels { tiles: HashMap::new(), source }; - for c in 1..=channels { - planes.push(plane(r, bitmap, c, bps, (x0, y0, w, h), step, &mut cache)?); - } - let (w, h) = (w.div_ceil(step), h.div_ceil(step)); - let n = (w as usize) * (h as usize); - let k = f64::from(step); - let transform = Affine([k, 0.0, 0.0, k, f64::from(x0), f64::from(y0)]).then(world); - if channels == 5 { - // Ink amounts and alpha as stored (8 bits), interleaved. - let mut cmyka = vec![0u8; n * 5]; - for (i, px) in cmyka.as_chunks_mut::<5>().0.iter_mut().enumerate() { - for (c, v) in px.iter_mut().enumerate() { - *v = planes.get(c).and_then(|p| p.get(i)).copied().unwrap_or(0); - } - } - return Ok(Some(Image { width: w, height: h, pixels: Pixels::Cmyka8(cmyka), transform })); - } - let mut rgba = vec![0u8; n * 4]; - let sample = |p: &Vec, i: usize| -> f64 { - if bps == 2 { - f64::from(u16::from_le_bytes([p.get(2 * i).copied().unwrap_or(0), p.get(2 * i + 1).copied().unwrap_or(0)])) / 65535.0 - } else { - f64::from(p.get(i).copied().unwrap_or(0)) / 255.0 - } - }; - for (i, px) in rgba.as_chunks_mut::<4>().0.iter_mut().enumerate() { - let v: Vec = planes.iter().map(|p| sample(p, i)).collect(); - let (r2, g, b, a) = if channels == 1 { (v[0], v[0], v[0], 1.0) } else { (v[0], v[1], v[2], v[3]) }; - px.copy_from_slice(&[r2, g, b, a].map(|c| (c.clamp(0.0, 1.0) * 255.0).round() as u8)); - } - Ok(Some(Image { width: w, height: h, pixels: Pixels::Rgba8(rgba), transform })) -} - -/// The original image file: entry `c/N` is a stream whose root (`Blck`) holds it as `Data`. -fn original(r: &mut Reader, name: &str) -> Result, Error> { - let bytes = r.archive.read(name)?; - let s = stream::parse(&bytes)?; - let root = s.object(s.root).ok_or(Error::Malformed("embedded image"))?; - match root.get(Tag::of(b"Data")) { - Some(Value::Blob(b)) if !b.is_empty() => Ok(b.clone()), - _ => Err(Error::Malformed("embedded image without data")), - } -} - -/// Decode the source under the same pixel budget as tiled layers, checking its actual -/// dimensions before allocating decoded pixels. Only JPEG and PNG sources are supported. -fn source_pixels(bytes: &[u8], width: u32, height: u32) -> Result, Error> { - use image::{ImageFormat, ImageReader}; - use std::io::Cursor; - - if u64::from(width) * u64::from(height) > MAX_PIXELS { - return Err(Error::Limit("embedded image pixels")); - } - let mut reader = ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(|_| Error::Malformed("embedded image format"))?; - if !matches!(reader.format(), Some(ImageFormat::Jpeg | ImageFormat::Png)) { - return Err(Error::Unsupported("embedded source pixel format")); - } - let dimensions = ImageReader::new(Cursor::new(bytes)) - .with_guessed_format() - .map_err(|_| Error::Malformed("embedded image format"))? - .into_dimensions() - .map_err(|_| Error::Malformed("embedded image dimensions"))?; - if dimensions != (width, height) || width == 0 || height == 0 { - return Err(Error::Malformed("embedded source and bitmap dimensions differ")); - } - let mut limits = image::Limits::default(); - limits.max_image_width = Some(width); - limits.max_image_height = Some(height); - limits.max_alloc = Some(MAX_PIXELS * 8); - reader.limits(limits); - let decoded = reader.decode().map_err(|e| match e { - image::ImageError::Limits(_) => Error::Limit("embedded image decoding"), - _ => Error::Malformed("embedded image decoding"), - })?; - Ok(decoded.into_rgba8().into_raw()) -} - -fn tag(prefix: &[u8; 3], c: usize) -> [u8; 4] { - [prefix[0], prefix[1], prefix[2], b'0' + c as u8] -} - -/// Channel `c`'s tile grid: (tiles across, tiles down, each tile's state). -fn grid(s: &stream::Stream, bitmap: ObjId, c: usize, bps: usize) -> (usize, usize, Vec) { - let width = s.int(bitmap, b"BmpW").and_then(|v| usize::try_from(v).ok()).unwrap_or(0); - 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 = match s.field(bitmap, &tag(b"Sta", c)) { - 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) -} - -/// The stored tiles (state 4) of channel `c` that overlap the crop, by their index in `Idx`. -fn tiles_in(s: &stream::Stream, bitmap: ObjId, c: usize, bps: usize, (x0, y0, w, h): (u32, u32, u32, u32)) -> Vec { - let (tw, th, states) = grid(s, bitmap, c, bps); - let (bx0, bx1) = (x0 as usize * bps, (x0 + w) as usize * bps); - let (py0, py1) = (y0 as usize, (y0 + h) as usize); - let mut out = Vec::new(); - let mut next = 0usize; - for (t, state) in states.iter().enumerate().take(tw.saturating_mul(th)) { - if *state != 4 { - continue; - } - let (ox, oy) = ((t % tw.max(1)) * TILE, (t / tw.max(1)) * TILE); - if !(ox >= bx1 || ox + TILE <= bx0 || oy >= py1 || oy + TILE <= py0) { - out.push(next); - } - next += 1; - } - out -} - -/// One channel of level 0, cropped to (x0, y0, w, h) pixels and taking every `step`th pixel of -/// every `step`th row; `bps` bytes per sample. -fn plane( - r: &mut Reader, - bitmap: ObjId, - c: usize, - bps: usize, - (x0, y0, w, h): (u32, u32, u32, u32), - step: u32, - cache: &mut CachedPixels, -) -> Result, Error> { - let CachedPixels { tiles: cache, source } = cache; - let s = r.s; - let (tw, th, states) = grid(s, bitmap, c, bps); - let tiles = s.objs(bitmap, &tag(b"Idx", c)); - let at = Crop { bps, x0: x0 as usize, y0: y0 as usize, w: w as usize, h: h as usize, step: step.max(1) as usize }; - let row = at.w.div_ceil(at.step) * bps; - let mut out = vec![0u8; row * at.h.div_ceil(at.step)]; - let (bx0, bx1) = (x0 as usize * bps, (x0 + w) as usize * bps); - let (py0, py1) = (y0 as usize, (y0 + h) as usize); - let mut next = 0usize; - for (t, state) in states.iter().enumerate().take(tw.saturating_mul(th)) { - let (ty, tx) = (t / tw.max(1), t % tw.max(1)); - let fill = match state { - 0 | 1 => None, - 2 => Some(0xFF), - 4 => { - let Some(blck) = tiles.get(next).copied() else { return Err(Error::Malformed("missing pixel tile")) }; - next += 1; - let (ox, oy) = (tx * TILE, ty * TILE); - if ox >= bx1 || ox + TILE <= bx0 || oy >= py1 || oy + TILE <= py0 { - continue; - } - let name = s.entry(blck, b"Data").ok_or(Error::Malformed("pixel tile without data"))?.to_string(); - let read = |r: &mut Reader| -> Result, Error> { - let mut data = r.archive.read(&name)?; - // Older files wrap a tile in a one-field stream: header, then a 64 KiB blob. - if data.len() == TILE_BYTES + 22 && data.starts_with(b"\x00\xffKS") { - data = data.get(21..21 + TILE_BYTES).ok_or(Error::Malformed("pixel tile"))?.to_vec(); - } - if data.len() != TILE_BYTES { - return Err(Error::Malformed("pixel tile size")); - } - Ok(data) - }; - // A layer read at a lower resolution is too large to keep its tiles around. - if at.step > 1 { - let tile = read(r)?; - copy(&mut out, &at, (ox, oy), |x, y| tile.get(y * TILE + x).copied().unwrap_or(0)); - continue; - } - if !cache.contains_key(&name) { - let data = read(r)?; - cache.insert(name.clone(), data); - } - let tile = cache.get(&name).ok_or(Error::Malformed("pixel tile"))?; - copy(&mut out, &at, (ox, oy), |x, y| tile.get(y * TILE + x).copied().unwrap_or(0)); - continue; - } - 3 => { - r.warn("32-bit pixel layers"); - None - } - 5 => { - if let Some((source_width, pixels)) = source.as_ref() { - let (ox, oy) = (tx * TILE, ty * TILE); - copy(&mut out, &at, (ox, oy), |x, y| pixels.get(((oy + y) * source_width + ox + x) * 4 + c - 1).copied().unwrap_or(0)); - continue; - } - r.warn("pixel layers drawn from an embedded image (left empty)"); - None - } - _ => return Err(Error::Malformed("unknown pixel tile state")), - }; - if let Some(v) = fill { - copy(&mut out, &at, (tx * TILE, ty * TILE), |_, _| v); - } - } - Ok(out) -} - -/// Where a plane's pixels come from: the crop (pixels) and the sampling step. -struct Crop { - bps: usize, - x0: usize, - y0: usize, - w: usize, - h: usize, - step: usize, -} - -/// Copy the overlap of a tile at byte column `ox`, row `oy` into the cropped plane, keeping every -/// `step`th pixel of every `step`th row. -fn copy(out: &mut [u8], c: &Crop, (ox, oy): (usize, usize), at: impl Fn(usize, usize) -> u8) { - let row = c.w.div_ceil(c.step) * c.bps; - let (bx0, bx1) = (c.x0 * c.bps, (c.x0 + c.w) * c.bps); - for y in oy.max(c.y0)..(oy + TILE).min(c.y0 + c.h) { - if !(y - c.y0).is_multiple_of(c.step) { - continue; - } - let out_row = (y - c.y0) / c.step * row; - for x in ox.max(bx0)..(ox + TILE).min(bx1) { - let px = x / c.bps - c.x0; - if !px.is_multiple_of(c.step) { - continue; - } - if let Some(b) = out.get_mut(out_row + px / c.step * c.bps + x % c.bps) { - *b = at(x - ox, y - oy); - } - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::model::Kind; - use crate::synth::{self, F, Method, tag}; - - #[test] - fn heif_originals_are_recognised_by_their_brand() { - assert!(is_heif(b"\0\0\0\x18ftypheic\0\0\0\0")); - assert!(is_heif(b"\0\0\0\x1cftypavif")); - assert!(!is_heif(b"\0\0\0\x18ftypisom"), "a video is not a photo"); - assert!(!is_heif(&png())); - assert!(!is_heif(b"ftyp")); - } - - fn png() -> Vec { - let pixels = image::RgbaImage::from_fn(300, 2, |x, y| image::Rgba([(x % 251) as u8, (y * 31) as u8, 77, 255])); - let mut bytes = std::io::Cursor::new(Vec::new()); - pixels.write_to(&mut bytes, image::ImageFormat::Png).unwrap(); - bytes.into_inner() - } - - /// An original synthetic mixed source/cache bitmap. It exercises reader recovery, - /// not a claim that Affinity itself accepts the synthetic container. - fn fixture(source: &[u8], origin: i32) -> Vec { - fixture_in(source, origin, false) - } - - /// `cmyk`: a CMYK bitmap whose colour tiles are all in the source and whose alpha is stored. - fn fixture_in(source: &[u8], origin: i32, cmyk: bool) -> Vec { - let channels = if cmyk { 5 } else { 4 }; - let mut bitmap = vec![ - (tag(b"Frmt"), F::Enum(if cmyk { 4 } else { 0 }, 0)), - (tag(b"BmpW"), F::I32(300)), - (tag(b"BmpH"), F::I32(2)), - (tag(b"LInf"), F::I32(origin)), - (tag(b"TInf"), F::I32(0)), - (tag(b"Bckg"), F::Entry("c/1".into())), - ]; - for c in 1..=channels { - let states = match (cmyk, c) { - (false, _) => vec![5, 4], - (true, 5) => vec![4, 4], - (true, _) => vec![5, 5], - }; - bitmap.push((tag(&super::tag(b"TWi", c)), F::I32(2))); - bitmap.push((tag(&super::tag(b"THi", c)), F::I32(1))); - bitmap.push((tag(&super::tag(b"Sta", c)), F::U8s(states))); - bitmap.push(( - tag(&super::tag(b"Idx", c)), - F::Shared(vec![F::Def(c as u32, vec![tag(b"Blck")], vec![(tag(b"Data"), F::Entry(format!("d/{c}")))])]), - )); - } - let mut crop = vec![0x17]; - crop.extend(tag(b"BitR").0.to_le_bytes()); - crop.extend([250i32, 0, 270, 2].into_iter().flat_map(i32::to_le_bytes)); - let raster = F::Def( - 10, - vec![tag(b"Rstr")], - vec![ - (tag(b"Bitm"), F::Obj(tag(b"DyBm"), bitmap)), - (tag(b"BitR"), F::Raw(crop)), - (tag(b"Xfrm"), F::F64s(vec![0.0, -2.0, 10.0, 2.0, 0.0, 20.0])), - ], - ); - let spread = F::Def(11, vec![tag(b"Sprd")], vec![(tag(b"Chld"), F::Shared(vec![raster]))]); - let doc = synth::stream(&[(tag(b"DocR"), F::Obj(tag(b"DocN"), vec![(tag(b"Chld"), F::Shared(vec![spread]))]))]); - let mut blob = vec![0x2d]; - blob.extend(tag(b"Data").0.to_le_bytes()); - blob.extend((source.len() as u32).to_le_bytes()); - blob.extend(source); - let block = synth::stream(&[(tag(b"Data"), F::Raw(blob))]); - let tiles: Vec<_> = [200u8, 10, 30, 255, 255].into_iter().map(|v| vec![v; TILE_BYTES]).collect(); - let names: Vec = (1..=channels).map(|c| format!("d/{c}")).collect(); - let mut entries = vec![("doc.dat", doc.as_slice(), Method::Zlib), ("c/1", block.as_slice(), Method::Zlib)]; - for (name, tile) in names.iter().zip(&tiles) { - entries.push((name.as_str(), tile.as_slice(), Method::Zlib)); - } - synth::container(&entries, None) - } - - #[test] - fn a_cmyk_layer_whose_colours_are_only_in_an_unreadable_original_is_left_out_not_white() { - let doc = crate::read(&fixture_in(b"\0\0\0\x18ftypheic not decodable", 0, true), crate::Limits::default()).unwrap(); - assert!(doc.warnings.iter().any(|w| w.starts_with("placed images whose pixels are only in an original")), "{:?}", doc.warnings); - assert!(matches!(doc.spreads[0].nodes[0].kind, Kind::Unsupported), "{:?}", doc.spreads[0].nodes[0].kind); - } - - #[test] - fn layers_over_the_pixel_budget_are_read_at_a_lower_resolution() { - let bytes = fixture(&png(), 0); - let mut archive = crate::Archive::open(&bytes, crate::Limits::default()).unwrap(); - let doc = archive.read("doc.dat").unwrap(); - let s = stream::parse(&doc).unwrap(); - let bitmap = s.objects.iter().position(|o| o.class == Tag::of(b"DyBm")).unwrap(); - let mut r = Reader::new(&s, &mut archive, Affine::IDENTITY, 0); - // 20 × 2 pixels over a budget of 10: every other pixel of every other row. - let image = decode_within(&mut r, bitmap, (250, 0, 270, 2), Affine::IDENTITY, 10).unwrap().unwrap(); - assert_eq!((image.width, image.height), (10, 1)); - assert_eq!(image.transform, Affine([2.0, 0.0, 0.0, 2.0, 250.0, 0.0]), "each pixel covers two"); - let Pixels::Rgba8(pixels) = &image.pixels else { panic!() }; - for x in 0..10 { - let sx = 2 * x; - let expected = if sx + 250 < 256 { [((sx + 250) % 251) as u8, 0, 77, 255] } else { [200, 10, 30, 255] }; - assert_eq!(&pixels[x * 4..x * 4 + 4], &expected, "pixel {x}"); - } - assert!(r.warnings.contains_key("pixel layers larger than 64 megapixels (read at a lower resolution)")); - // Within budget, nothing changes. - let image = decode_within(&mut r, bitmap, (250, 0, 270, 2), Affine::IDENTITY, 40).unwrap().unwrap(); - assert_eq!((image.width, image.height), (20, 2)); - } - - #[test] - fn source_tiles_and_cached_edits_survive_crop_rotation_and_tile_boundaries() { - let doc = crate::read(&fixture(&png(), 0), crate::Limits::default()).unwrap(); - assert_eq!(doc.warnings, ["edited placed images use their stored pixels"]); - let Kind::Image(image) = &doc.spreads[0].nodes[0].kind else { panic!() }; - assert_eq!((image.width, image.height), (20, 2)); - assert_eq!(image.transform, Affine([0.0, 2.0, -2.0, 0.0, 10.0, 520.0])); - let Pixels::Rgba8(pixels) = &image.pixels else { panic!() }; - for y in 0..2 { - for x in 0..20 { - let expected = if x + 250 < 256 { [((x + 250) % 251) as u8, (y * 31) as u8, 77, 255] } else { [200, 10, 30, 255] }; - assert_eq!(&pixels[(y * 20 + x) * 4..(y * 20 + x + 1) * 4], &expected); - } - } - } - - #[test] - fn unreadable_sources_and_unknown_origins_preserve_cached_edits_and_warn() { - for bytes in [fixture(b"invalid image", 0), fixture(&png(), 1)] { - let doc = crate::read(&bytes, crate::Limits::default()).unwrap(); - assert!(doc.warnings.iter().any(|w| w == "pixel layers drawn from an embedded image (left empty) (4×)")); - let Kind::Image(image) = &doc.spreads[0].nodes[0].kind else { panic!() }; - let Pixels::Rgba8(pixels) = &image.pixels else { panic!() }; - assert_eq!(&pixels[..4], &[0, 0, 0, 0]); - assert_eq!(&pixels[6 * 4..7 * 4], &[200, 10, 30, 255]); - } - } - - /// Pixel layers of one flat colour: nothing in the archive but `doc.dat` (state 2 is a tile - /// of 0xFF). Written by hand for the reader, like [`fixture`]. - fn flat_layers(count: u32, side: i32) -> Vec { - let layer = |i: u32| { - let mut bitmap = vec![(tag(b"Frmt"), F::Enum(0, 0)), (tag(b"BmpW"), F::I32(side)), (tag(b"BmpH"), F::I32(side))]; - for c in 1..=4 { - bitmap.push((tag(&super::tag(b"TWi", c)), F::I32(1))); - bitmap.push((tag(&super::tag(b"THi", c)), F::I32(1))); - bitmap.push((tag(&super::tag(b"Sta", c)), F::U8s(vec![2]))); - } - F::Def(10 + i, vec![tag(b"Rstr")], vec![(tag(b"Bitm"), F::Obj(tag(b"DyBm"), bitmap))]) - }; - let spread = F::Def(1, vec![tag(b"Sprd")], vec![(tag(b"Chld"), F::Shared((0..count).map(layer).collect()))]); - let doc = synth::stream(&[(tag(b"DocR"), F::Obj(tag(b"DocN"), vec![(tag(b"Chld"), F::Shared(vec![spread]))]))]); - synth::container(&[("doc.dat", &doc, Method::Zlib)], None) - } - - /// #1704: the pixels of all pixel layers together are bounded, also when the archive holds - /// no data for them: the layers past the allowance are left out with a note. - #[test] - fn pixel_layers_share_one_allowance_for_the_whole_document() { - let file = flat_layers(5, 16); - let layers = |pixels: u64| { - let doc = crate::model::read_within(&file, crate::Limits::default(), pixels).unwrap(); - let n = doc.spreads[0].nodes.iter().filter(|n| matches!(n.kind, Kind::Image(_))).count(); - (n, doc.warnings) - }; - assert_eq!(layers(5 * 256), (5, vec![])); - let (kept, warnings) = layers(3 * 256 + 255); - assert_eq!(kept, 3); - assert_eq!(warnings.len(), 1); - assert!(warnings[0].contains("pixel layers beyond the pixels one document may hold"), "{warnings:?}"); - assert_eq!(crate::read(&file, crate::Limits::default()).unwrap().spreads[0].nodes.len(), 5); - } - - #[test] - fn embedded_source_dimensions_and_pixel_budget_are_checked_before_decode() { - let bytes = png(); - assert!(matches!(source_pixels(&bytes, 299, 2), Err(Error::Malformed(_)))); - assert!(matches!(source_pixels(&bytes, u32::MAX, u32::MAX), Err(Error::Limit(_)))); - assert_eq!(source_pixels(&bytes, 300, 2).unwrap().len(), 300 * 2 * 4); - } -} diff --git a/crates/affinity/src/shapes.rs b/crates/affinity/src/shapes.rs deleted file mode 100644 index a2503539f4..0000000000 --- a/crates/affinity/src/shapes.rs +++ /dev/null @@ -1,292 +0,0 @@ -//! Parametric shapes: Affinity stores the shape's parameters and its box, never the outline. -//! Formulas were fitted to Affinity's own renders (the document thumbnails) of public files. - -use std::f64::consts::{FRAC_PI_2, PI, TAU}; - -use crate::model::{Affine, Path, Point, Reader, SubPath}; -use crate::stream::{ObjId, Tag, Value}; - -/// Handle length of a quarter circle of radius 1. -const KAPPA: f64 = 0.552_284_749_830_793_4; -/// Vertices of a polygon or star. -const MAX_SIDES: i64 = 10_000; - -/// The last value of a tag: a shape changed from one kind to another keeps a stale first block. -fn last<'a>(r: &'a Reader, id: ObjId, tag: &[u8; 4]) -> Option<&'a Value> { - r.s.object(id)?.get_last(Tag::of(tag)) -} - -fn num(r: &Reader, id: ObjId, tag: &[u8; 4]) -> Option { - match last(r, id, tag)? { - Value::Float(f) if f.is_finite() => Some(*f), - Value::UInt(u) => Some(*u as f64), - Value::Int(i) => Some(*i as f64), - _ => None, - } -} - -fn sides(r: &Reader, id: ObjId, tag: &[u8; 4], default: f64) -> usize { - let n = num(r, id, tag).unwrap_or(default).round(); - n.clamp(3.0, MAX_SIDES as f64) as usize -} - -fn pt(x: f64, y: f64) -> Point { - Point { x, y } -} - -fn polygon(pts: impl IntoIterator) -> Option { - let mut it = pts.into_iter(); - let start = it.next()?; - let segments = it.map(|p| [p, p, p]).collect(); - Some(SubPath { start, segments, closed: true }) -} - -/// Outline of `shape` (a `Shpe` object) in the node box `b` = (x0, y0, x1, y1). -pub(crate) fn shape(r: &mut Reader, shape: ObjId, b: [f64; 4], world: Affine) -> Option { - let [x0, y0, x1, y1] = b; - let (w, h) = (x1 - x0, y1 - y0); - let (cx, cy, rx, ry) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0, w / 2.0, h / 2.0); - let on_ellipse = |a: f64, f: f64| pt(cx + f * rx * a.cos(), cy + f * ry * a.sin()); - let class = r.s.class(shape)?; - let sub = match &class.0.to_be_bytes() { - b"ShNR" | b"ShRR" => { - // Only the four corners' entries can matter: longer arrays are read no further. - let types: Vec> = match last(r, shape, b"CTyp") { - Some(Value::Array(a)) => a.iter().take(4).map(|t| if let Value::Enum { id, .. } = t { Some(*id) } else { None }).collect(), - _ => Vec::new(), - }; - let radii: Vec = match last(r, shape, b"ShCR") { - Some(Value::Floats(v)) => v.iter().take(4).map(|f| if f.is_finite() && *f > 0.0 { *f } else { 0.0 }).collect(), - _ => Vec::new(), - }; - // Corners follow the first one (top left) unless they were unlocked; then each has - // its own radius and type, clockwise from the top left. - let locked = !matches!(last(r, shape, b"Lock"), Some(Value::Bool(false))); - let corners: [(f64, Option); 4] = std::array::from_fn(|i| { - let i = if locked { 0 } else { i }; - (radii.get(i).copied().unwrap_or(0.0), types.get(i).copied().flatten()) - }); - if types.is_empty() || corners.iter().all(|(f, _)| *f == 0.0) { - polygon([pt(x0, y0), pt(x1, y0), pt(x1, y1), pt(x0, y1)])? - } else { - if corners.iter().any(|(f, t)| *f > 0.0 && !matches!(t, Some(0 | 1 | 4))) { - r.warn("rectangles with concave or other corner types (imported with round corners)"); - } - let absolute = r.s.bool(shape, b"AbSz") == Some(true); - let [a, b2, c, d, ..] = world.0; - let (sx, sy) = ((a * a + b2 * b2).sqrt(), (c * c + d * d).sqrt()); - cornered_rect( - b, - corners.map(|(f, t)| { - let (crx, cry) = if !absolute { - (f * w.min(h), f * w.min(h)) - } else if sx > 0.0 && sy > 0.0 { - // An absolute radius is in document pixels, whatever the node's scale. - (f / sx, f / sy) - } else { - (0.0, 0.0) - }; - (crx, cry, t == Some(1)) - }), - ) - } - } - b"ShpE" => ellipse(cx, cy, rx, ry), - b"ShPy" => { - let n = sides(r, shape, b"Side", 5.0); - let a = |i: usize| -FRAC_PI_2 + TAU * i as f64 / n as f64; - if r.s.object(shape).is_some_and(|_| matches!(last(r, shape, b"Smth"), Some(Value::Bool(true)))) { - // Smoothed: tangent handles of length curv·4/3·tan(π/2n) along the inscribed ellipse. - let k = num(r, shape, b"Curv").unwrap_or(0.0) * 4.0 / 3.0 * (PI / (2.0 * n as f64)).tan(); - let v = |i: usize| on_ellipse(a(i), 1.0); - let t = |i: usize| pt(-rx * a(i).sin(), ry * a(i).cos()); - let segments = (0..n) - .map(|i| { - let (p, q, tp, tq) = (v(i), v(i + 1), t(i), t(i + 1)); - [pt(p.x + k * tp.x, p.y + k * tp.y), pt(q.x - k * tq.x, q.y - k * tq.y), q] - }) - .collect(); - SubPath { start: v(0), segments, closed: true } - } else { - polygon((0..n).map(|i| on_ellipse(a(i), 1.0)))? - } - } - b"ShSt" => { - let n = sides(r, shape, b"Pnts", 5.0); - let q = num(r, shape, b"IRad").unwrap_or(0.382).clamp(0.0, 1.0); - if [b"CrcI", b"CrcO", b"CrvL", b"CrvR"].iter().any(|t| num(r, shape, t).is_some_and(|v| v.abs() > 1e-9)) { - r.warn("stars with rounded or curved points (imported with sharp points)"); - } - polygon((0..2 * n).map(|i| on_ellipse(-FRAC_PI_2 + PI * i as f64 / n as f64, if i % 2 == 0 { 1.0 } else { q })))? - } - b"ShSS" => { - let n = sides(r, shape, b"Side", 5.0); - let ri = num(r, shape, b"COut").unwrap_or(0.5).clamp(0.0, 1.0); - let step = PI / n as f64; - let (l, hw, inner) = (step.cos(), ri * step.sin(), ri * step.cos()); - polygon((0..n).flat_map(|k| { - let phi = -FRAC_PI_2 + step + TAU * k as f64 / n as f64; - let (c, s) = (phi.cos(), phi.sin()); - [(inner, -hw), (l, -hw), (l, hw), (inner, hw)].map(|(u, v)| pt(cx + rx * (u * c - v * s), cy + ry * (u * s + v * c))) - }))? - } - b"ShPi" => { - let raw_start = num(r, shape, b"AngS").unwrap_or(0.0); - let raw_end = num(r, shape, b"AngE").unwrap_or(TAU); - // Normalize in constant time. Repeatedly adding TAU can hang on finite values - // large enough that floating-point addition no longer changes the endpoint. - let start = raw_start.rem_euclid(TAU); - let delta = raw_end - raw_start; - let sweep = if raw_end >= raw_start { - delta.min(TAU) - } else if delta.is_finite() { - delta.rem_euclid(TAU) - } else { - (raw_end.rem_euclid(TAU) - start).rem_euclid(TAU) - }; - let inner = num(r, shape, b"IRad").unwrap_or(0.0).clamp(0.0, 1.0); - pie(cx, cy, rx, ry, start, start + sweep, inner) - } - b"ShpT" => { - let p = num(r, shape, b"Pos ").unwrap_or(0.5); - polygon([pt(x0 + p * w, y0), pt(x1, y1), pt(x0, y1)])? - } - b"ShTz" => { - let (l, rr) = (num(r, shape, b"PosL").unwrap_or(0.25), num(r, shape, b"PosR").unwrap_or(0.75)); - polygon([pt(x0 + l * w, y0), pt(x0 + rr * w, y0), pt(x1, y1), pt(x0, y1)])? - } - _ => { - r.warn("cloud, heart, cog, callout, arrow, tear and other special shapes (imported as their bounding ellipse)"); - ellipse(cx, cy, rx, ry) - } - }; - Some(Path { subpaths: vec![sub] }) -} - -pub(crate) fn rectangle(x0: f64, y0: f64, x1: f64, y1: f64) -> SubPath { - SubPath { start: pt(x0, y0), segments: [pt(x1, y0), pt(x1, y1), pt(x0, y1)].map(|p| [p, p, p]).to_vec(), closed: true } -} - -fn ellipse(cx: f64, cy: f64, rx: f64, ry: f64) -> SubPath { - let (kx, ky) = (KAPPA * rx, KAPPA * ry); - SubPath { - start: pt(cx + rx, cy), - segments: vec![ - [pt(cx + rx, cy + ky), pt(cx + kx, cy + ry), pt(cx, cy + ry)], - [pt(cx - kx, cy + ry), pt(cx - rx, cy + ky), pt(cx - rx, cy)], - [pt(cx - rx, cy - ky), pt(cx - kx, cy - ry), pt(cx, cy - ry)], - [pt(cx + kx, cy - ry), pt(cx + rx, cy - ky), pt(cx + rx, cy)], - ], - closed: true, - } -} - -/// A rectangle whose corners (top left, top right, bottom right, bottom left) are each rounded, -/// or cut straight across, by their (horizontal, vertical) radii. Two radii that don't fit along -/// one side shrink in proportion until they do. -fn cornered_rect([x0, y0, x1, y1]: [f64; 4], corners: [(f64, f64, bool); 4]) -> SubPath { - let fit = |r: f64, pair: f64, side: f64| if pair > side { side * (r / pair) } else { r }; - let [tl, tr, br, bl] = corners; - let (w, h) = (x1 - x0, y1 - y0); - let rx = [fit(tl.0, tl.0 + tr.0, w), fit(tr.0, tl.0 + tr.0, w), fit(br.0, bl.0 + br.0, w), fit(bl.0, bl.0 + br.0, w)]; - let ry = [fit(tl.1, tl.1 + bl.1, h), fit(tr.1, tr.1 + br.1, h), fit(br.1, tr.1 + br.1, h), fit(bl.1, tl.1 + bl.1, h)]; - let (kx, ky) = (rx.map(|r| (1.0 - KAPPA) * r), ry.map(|r| (1.0 - KAPPA) * r)); - // (where the corner leaves the previous side, its two handles, where it joins the next side) - let arcs = [ - [pt(x1 - rx[1], y0), pt(x1 - kx[1], y0), pt(x1, y0 + ky[1]), pt(x1, y0 + ry[1])], - [pt(x1, y1 - ry[2]), pt(x1, y1 - ky[2]), pt(x1 - kx[2], y1), pt(x1 - rx[2], y1)], - [pt(x0 + rx[3], y1), pt(x0 + kx[3], y1), pt(x0, y1 - ky[3]), pt(x0, y1 - ry[3])], - [pt(x0, y0 + ry[0]), pt(x0, y0 + ky[0]), pt(x0 + kx[0], y0), pt(x0 + rx[0], y0)], - ]; - let mut segments = Vec::with_capacity(8); - for ([s, c1, c2, e], straight) in arcs.into_iter().zip([tr.2, br.2, bl.2, tl.2]) { - segments.push([s, s, s]); - if s != e { - segments.push(if straight { [e, e, e] } else { [c1, c2, e] }); - } - } - SubPath { start: pt(x0 + rx[0], y0), segments, closed: true } -} - -/// Elliptical arc from angle `a0` to `a1` (radians, measured y-up as Affinity's pie angles are), -/// as cubic segments of at most a quarter turn. -fn arc(cx: f64, cy: f64, rx: f64, ry: f64, a0: f64, a1: f64, out: &mut Vec<[Point; 3]>) { - let n = ((a1 - a0).abs() / FRAC_PI_2).ceil().clamp(1.0, 8.0) as usize; - let step = (a1 - a0) / n as f64; - let k = 4.0 / 3.0 * (step / 4.0).tan(); - let p = |a: f64| pt(cx + rx * a.cos(), cy - ry * a.sin()); - let d = |a: f64| pt(-rx * a.sin(), -ry * a.cos()); - for i in 0..n { - let (s, e) = (a0 + step * i as f64, a0 + step * (i + 1) as f64); - let (ps, pe, ds, de) = (p(s), p(e), d(s), d(e)); - out.push([pt(ps.x + k * ds.x, ps.y + k * ds.y), pt(pe.x - k * de.x, pe.y - k * de.y), pe]); - } -} - -fn pie(cx: f64, cy: f64, rx: f64, ry: f64, a0: f64, a1: f64, inner: f64) -> SubPath { - let start = pt(cx + rx * a0.cos(), cy - ry * a0.sin()); - let mut segments = Vec::new(); - arc(cx, cy, rx, ry, a0, a1, &mut segments); - if inner > 0.0 { - let p = pt(cx + inner * rx * a1.cos(), cy - inner * ry * a1.sin()); - segments.push([p, p, p]); - arc(cx, cy, inner * rx, inner * ry, a1, a0, &mut segments); - } else { - let c = pt(cx, cy); - segments.push([c, c, c]); - } - SubPath { start, segments, closed: true } -} - -/// A polyline with circular corners of the given radii (Affinity's live corners on curves). -pub(crate) fn fillet(pts: &[(Point, f64)], closed: bool) -> SubPath { - let n = pts.len(); - let get = |i: isize| -> Option { - if closed { pts.get(i.rem_euclid(n as isize) as usize).map(|p| p.0) } else { usize::try_from(i).ok().and_then(|i| pts.get(i)).map(|p| p.0) } - }; - let mut corners: Vec<(Point, Point, Point, Point)> = Vec::with_capacity(n); - for (i, (p, radius)) in pts.iter().enumerate() { - let (prev, next) = (get(i as isize - 1), get(i as isize + 1)); - let (Some(a), Some(b)) = (prev, next) else { - corners.push((*p, *p, *p, *p)); - continue; - }; - let (u1, l1) = unit(*p, a); - let (u2, l2) = unit(*p, b); - let cos = (u1.x * u2.x + u1.y * u2.y).clamp(-1.0, 1.0); - let phi = cos.acos(); - if *radius <= 0.0 || phi < 1e-6 || (PI - phi) < 1e-6 { - corners.push((*p, *p, *p, *p)); - continue; - } - let t = (radius / (phi / 2.0).tan()).min(l1 / 2.0).min(l2 / 2.0); - let r = t * (phi / 2.0).tan(); - let k = 4.0 / 3.0 * ((PI - phi) / 4.0).tan() * r; - let s = pt(p.x + u1.x * t, p.y + u1.y * t); - let e = pt(p.x + u2.x * t, p.y + u2.y * t); - corners.push((s, pt(s.x - u1.x * k, s.y - u1.y * k), pt(e.x - u2.x * k, e.y - u2.y * k), e)); - } - let Some(first) = corners.first().copied() else { return SubPath { start: pt(0.0, 0.0), segments: vec![], closed } }; - let mut segments = Vec::with_capacity(2 * n); - let mut cur = first.0; - let start = cur; - for (i, (s, c1, c2, e)) in corners.iter().enumerate() { - if i > 0 { - segments.push([cur, *s, *s]); - } - if s != e { - segments.push([*c1, *c2, *e]); - } - cur = *e; - } - if closed && cur != start { - segments.push([cur, start, start]); - } - SubPath { start, segments, closed } -} - -fn unit(from: Point, to: Point) -> (Point, f64) { - let (dx, dy) = (to.x - from.x, to.y - from.y); - let l = (dx * dx + dy * dy).sqrt(); - if l > 0.0 { (pt(dx / l, dy / l), l) } else { (pt(0.0, 0.0), 0.0) } -} diff --git a/crates/affinity/src/stream.rs b/crates/affinity/src/stream.rs deleted file mode 100644 index 9d31f35e70..0000000000 --- a/crates/affinity/src/stream.rs +++ /dev/null @@ -1,491 +0,0 @@ -//! The tagged object stream inside `doc.dat`: a self-describing tree of objects whose fields carry -//! a type code and a four-character tag. Parsing needs no schema; unknown fields are kept, so the -//! document mapping can name what it could not import. - -use crate::Error; -use crate::container::Cursor; - -/// A four-character tag in its readable order (`Desc`, `Chld`). -#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] -pub struct Tag(pub u32); - -impl Tag { - pub const fn of(s: &[u8; 4]) -> Self { - Self(u32::from_be_bytes(*s)) - } -} - -impl std::fmt::Debug for Tag { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", String::from_utf8_lossy(&self.0.to_be_bytes())) - } -} - -impl std::fmt::Display for Tag { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - std::fmt::Debug::fmt(self, f) - } -} - -/// Index of an object in [`Stream::objects`]. -pub type ObjId = usize; - -#[derive(Debug, Clone, PartialEq)] -pub enum Value { - Int(i64), - UInt(u64), - Float(f64), - Bool(bool), - Enum { - id: u16, - version: u16, - }, - Str(String), - /// Fixed-length vectors of i32/f32/f64 (points, rectangles, transforms). - Ints(Vec), - Floats(Vec), - /// Fixed-size record (curve nodes, ids) or fixed-size struct (colour components). - Bytes(Vec), - Blob(Vec), - /// Name of another archive entry (raster tiles, embedded files). - Entry(String), - Flags(u64), - /// `None` is a null object. - Obj(Option), - Array(Vec), -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Kind { - Root, - /// Defined once and referenced by id elsewhere. - Shared, - Inline, - /// Untagged fields identified by position (curve data). - Positional, -} - -#[derive(Debug, Clone, PartialEq)] -pub struct Object { - pub class: Tag, - pub kind: Kind, - /// Class chain, most derived first (`ShpN`, `VNod`, `Node`). - pub chain: Vec, - /// Fields in stream order; positional fields have tag 0. - pub fields: Vec<(Tag, Value)>, - /// For objects with many fields: each tag with the positions of its first and last field, - /// sorted by tag, so a lookup isn't a scan of every field (a shared object is looked up - /// again on every visit). Built by [`Object::index`]; empty for small objects. - index: Vec<(Tag, u32, u32)>, -} - -/// Objects with more fields than this get an [`Object::index`]; fewer are scanned. -const INDEXED_FIELDS: usize = 16; - -impl Object { - pub fn new(class: Tag, kind: Kind, chain: Vec, fields: Vec<(Tag, Value)>) -> Self { - let mut o = Self { class, kind, chain, fields, index: Vec::new() }; - o.index(); - o - } - - /// (Re)build the tag index after `fields` changed. - fn index(&mut self) { - self.index.clear(); - if self.fields.len() <= INDEXED_FIELDS { - return; - } - let mut index: Vec<(Tag, u32, u32)> = Vec::new(); - if index.try_reserve_exact(self.fields.len()).is_err() { - return; - } - // Fields beyond u32 positions are impossible: a stream holds at most MAX_VALUES values. - index.extend(self.fields.iter().enumerate().filter_map(|(i, (t, _))| u32::try_from(i).ok().map(|i| (*t, i, i)))); - // Stable: equal tags stay in stream order, so the run of a tag starts at its first field. - index.sort_by_key(|(t, _, _)| *t); - index.dedup_by(|later, first| { - if later.0 == first.0 { - first.2 = later.2; - true - } else { - false - } - }); - index.shrink_to_fit(); - self.index = index; - } - - fn position(&self, tag: Tag, last: bool) -> Option { - if self.index.is_empty() { - let mut fields = self.fields.iter().enumerate(); - let hit = if last { fields.rev().find(|(_, (t, _))| *t == tag) } else { fields.find(|(_, (t, _))| *t == tag) }; - return hit.map(|(i, _)| i); - } - let at = self.index.binary_search_by_key(&tag, |(t, _, _)| *t).ok()?; - let (_, first, end) = self.index.get(at)?; - usize::try_from(if last { *end } else { *first }).ok() - } - - /// The first field tagged `tag`. - pub fn get(&self, tag: Tag) -> Option<&Value> { - self.fields.get(self.position(tag, false)?).map(|(_, v)| v) - } - - /// The last field tagged `tag` (a shape changed from one kind to another keeps a stale first one). - pub fn get_last(&self, tag: Tag) -> Option<&Value> { - self.fields.get(self.position(tag, true)?).map(|(_, v)| v) - } -} - -#[derive(Debug)] -pub struct Stream { - pub root: ObjId, - pub objects: Vec, -} - -/// Deepest object nesting accepted; real documents stay well below (each layer level adds three). -pub const MAX_DEPTH: usize = 384; - -const MAX_OBJECTS: usize = 8_000_000; - -/// Most values (fields and array elements) one stream may decode. A value takes about 40 bytes -/// in memory however few it took in the file (a bool array packs eight in a byte), so the size -/// of the input alone doesn't bound what parsing allocates: a small compressed entry could -/// otherwise ask for tens of gigabytes. Real documents stay far below. -pub const MAX_VALUES: usize = 1 << 24; - -struct Parser<'a> { - c: Cursor<'a>, - objects: Vec, - /// Shared ids, defined at first use and referenced backwards. - shared: std::collections::HashMap, - depth: usize, - /// Values decoded so far, against [`MAX_VALUES`]. - values: usize, -} - -/// Parse a stream (`00 FF 4B 53` header). Bytes after the root's terminator are ignored. -pub fn parse(bytes: &[u8]) -> Result { - let mut c = Cursor::new(bytes, 0); - if c.take(4)? != b"\x00\xffKS" { - return Err(Error::Malformed("document stream signature")); - } - let version = c.u16()?; - if version > 2 { - return Err(Error::Unsupported("document stream version")); - } - let class = Tag(c.u32()?); - c.u16()?; - if version == 2 { - c.u32()?; - } - let mut p = Parser { c, objects: Vec::new(), shared: std::collections::HashMap::new(), depth: 0, values: 0 }; - let root = p.push(Object::new(class, Kind::Root, vec![class], Vec::new()))?; - let fields = p.fields(true, class)?; - if let Some(o) = p.objects.get_mut(root) { - o.fields = fields; - o.index(); - } - Ok(Stream { root, objects: p.objects }) -} - -impl Parser<'_> { - fn push(&mut self, o: Object) -> Result { - if self.objects.len() >= MAX_OBJECTS { - return Err(Error::Limit("too many objects")); - } - self.objects.push(o); - Ok(self.objects.len() - 1) - } - - /// Counts `n` more values against [`MAX_VALUES`], before anything is allocated for them. - fn spend(&mut self, n: usize) -> Result<(), Error> { - self.values = self.values.checked_add(n).filter(|&v| v <= MAX_VALUES).ok_or(Error::Limit("too many values in the document stream"))?; - Ok(()) - } - - /// An empty array with room for `n` values, paid for first; an allocation that still fails - /// is an error, not an abort. - fn vec(&mut self, n: usize) -> Result, Error> { - self.spend(n)?; - let mut v = Vec::new(); - v.try_reserve_exact(n).map_err(|_| Error::Limit("not enough memory for the document stream"))?; - Ok(v) - } - - /// Element count of an array: each element takes at least `min` bytes, so a count the - /// remaining input cannot hold is rejected before anything is allocated. - fn count(&mut self, min: usize) -> Result { - let n = usize::try_from(self.c.u32()?).map_err(|_| Error::Malformed("array length"))?; - if n.checked_mul(min.max(1)).is_none_or(|bytes| bytes > self.c.remaining()) { - return Err(Error::Malformed("array longer than its data")); - } - Ok(n) - } - - fn fields(&mut self, tagged: bool, class: Tag) -> Result, Error> { - self.depth += 1; - if self.depth > MAX_DEPTH { - return Err(Error::Limit("objects nested too deeply")); - } - let mut out = Vec::new(); - loop { - let t = self.c.u8()?; - let code = t & 0x7F; - if code == 0 { - break; - } - self.spend(1)?; - let tag = if tagged { Tag(self.c.u32()?) } else { Tag(0) }; - let v = if t & 0x80 != 0 { self.array(code, class)? } else { self.scalar(code, tagged, class)? }; - out.push((tag, v)); - } - self.depth -= 1; - Ok(out) - } - - fn string(&mut self) -> Result { - let n = usize::try_from(self.c.u32()?).map_err(|_| Error::Malformed("string length"))?; - Ok(String::from_utf8_lossy(self.c.take(n)?).into_owned()) - } - - fn floats(&mut self, n: usize, wide: bool) -> Result { - let mut v = Vec::with_capacity(n); - for _ in 0..n { - v.push(if wide { f64::from_le_bytes(self.c.array()?) } else { f64::from(f32::from_le_bytes(self.c.array()?)) }); - } - Ok(Value::Floats(v)) - } - - fn scalar(&mut self, code: u8, tagged: bool, class: Tag) -> Result { - let c = &mut self.c; - Ok(match code { - 0x01 => Value::UInt(c.u8()?.into()), - 0x02 => Value::UInt(c.u16()?.into()), - 0x03 | 0x2f | 0x34 => Value::UInt(c.u32()?.into()), - 0x04 => Value::UInt(c.u64()?), - 0x05 => Value::Int(i8::from_le_bytes(c.array()?).into()), - 0x06 => Value::Int(i16::from_le_bytes(c.array()?).into()), - 0x07 => Value::Int(i32::from_le_bytes(c.array()?).into()), - 0x08 => Value::Int(i64::from_le_bytes(c.array()?)), - 0x09 => Value::Float(f32::from_le_bytes(c.array()?).into()), - 0x0a => Value::Float(f64::from_le_bytes(c.array()?)), - 0x15..=0x19 => { - let n = usize::from(code - 0x13); - let mut v = Vec::with_capacity(n); - for _ in 0..n { - v.push(i32::from_le_bytes(c.array()?).into()); - } - Value::Ints(v) - } - 0x1f..=0x23 => return self.floats(usize::from(code - 0x1d), false), - 0x24..=0x28 => return self.floats(usize::from(code - 0x22), true), - 0x29 => Value::Bool(c.u8()? != 0), - 0x2a => Value::Enum { id: c.u16()?, version: c.u16()? }, - 0x2b | 0x2e => Value::Str(self.string()?), - 0x2c => { - let n = usize::from(c.u16()?); - Value::Bytes(c.take(n)?.to_vec()) - } - 0x35..=0x74 => Value::Bytes(c.take(usize::from(code - 0x34))?.to_vec()), - 0x2d => { - let n = usize::try_from(c.u32()?).map_err(|_| Error::Malformed("blob length"))?; - Value::Blob(c.take(n)?.to_vec()) - } - 0x33 => { - c.u32()?; - let n = usize::try_from(c.u32()?).map_err(|_| Error::Malformed("entry name length"))?; - Value::Entry(String::from_utf8_lossy(c.take(n)?).into_owned()) - } - 0x75 => { - c.u16()?; - let n = usize::from(c.u8()?); - if n > 8 { - return Err(Error::Malformed("flags wider than 64 bits")); - } - let mut b = [0u8; 8]; - b.get_mut(..n).ok_or(Error::Malformed("flags"))?.copy_from_slice(c.take(n)?); - Value::Flags(u64::from_le_bytes(b)) - } - 0x30 => { - let fields = self.fields(false, class)?; - let id = self.push(Object::new(class, Kind::Positional, Vec::new(), fields))?; - Value::Obj(Some(id)) - } - 0x31 | 0x32 if !tagged => return Err(Error::Malformed("object without a field tag")), - 0x31 => self.shared()?, - 0x32 => self.inline(None)?, - _ => return Err(Error::Unsupported("unknown field type in document stream")), - }) - } - - fn array(&mut self, code: u8, class: Tag) -> Result { - let min = match code { - 0x01 | 0x05 | 0x29 => 1, - 0x02 | 0x06 => 2, - 0x03 | 0x07 | 0x09 | 0x2f | 0x34 => 4, - 0x04 | 0x08 | 0x0a => 8, - 0x15..=0x19 => 4 * usize::from(code - 0x13), - 0x1f..=0x23 => 4 * usize::from(code - 0x1d), - 0x24..=0x28 => 8 * usize::from(code - 0x22), - 0x35..=0x74 => usize::from(code - 0x34), - _ => 1, - }; - match code { - 0x29 => { - let n = usize::try_from(self.c.u32()?).map_err(|_| Error::Malformed("array length"))?; - let bits = self.c.take(n.div_ceil(8))?; - let mut v = self.vec(n)?; - v.extend((0..n).map(|i| Value::Bool(bits.get(i / 8).is_some_and(|b| b >> (i % 8) & 1 != 0)))); - Ok(Value::Array(v)) - } - 0x2a => { - let n = self.count(2)?; - let version = self.c.u16()?; - let mut v = self.vec(n)?; - for _ in 0..n { - v.push(Value::Enum { id: self.c.u16()?, version }); - } - Ok(Value::Array(v)) - } - 0x2b | 0x2e => { - self.c.u32()?; - let n = self.count(4)?; - let mut v = self.vec(n)?; - for _ in 0..n { - v.push(Value::Str(self.string()?)); - } - Ok(Value::Array(v)) - } - 0x2c => { - let n = usize::try_from(self.c.u32()?).map_err(|_| Error::Malformed("array length"))?; - let size = usize::from(self.c.u16()?); - // Records of no bytes take nothing from the data, whatever their number. - if n > 0 && size == 0 { - return Err(Error::Malformed("array of records without bytes")); - } - if n.checked_mul(size).is_none_or(|b| b > self.c.remaining()) { - return Err(Error::Malformed("array longer than its data")); - } - let mut v = self.vec(n)?; - for _ in 0..n { - v.push(Value::Bytes(self.c.take(size)?.to_vec())); - } - Ok(Value::Array(v)) - } - 0x32 => { - let n = self.count(1)?; - let class = Tag(self.c.u32()?); - self.c.u16()?; - let mut v = self.vec(n)?; - for _ in 0..n { - v.push(self.inline(Some(class))?); - } - Ok(Value::Array(v)) - } - 0x2d | 0x33 | 0x75 => Err(Error::Malformed("array of an unarrayable type")), - _ => { - let n = self.count(min)?; - let mut v = self.vec(n)?; - for _ in 0..n { - v.push(self.scalar(code, true, class)?); - } - Ok(Value::Array(v)) - } - } - } - - /// Inline object; `class` is given once for a whole array of them. - fn inline(&mut self, class: Option) -> Result { - match self.c.u8()? { - 0 => return Ok(Value::Obj(None)), - 1 => {} - _ => return Err(Error::Malformed("object marker")), - } - let class = match class { - Some(c) => c, - None => { - let c = Tag(self.c.u32()?); - self.c.u16()?; - c - } - }; - let fields = self.fields(true, class)?; - let id = self.push(Object::new(class, Kind::Inline, vec![class], fields))?; - Ok(Value::Obj(Some(id))) - } - - fn shared(&mut self) -> Result { - let flag = self.c.u8()?; - if flag == 0 { - return Ok(Value::Obj(None)); - } - let key = self.c.u32()?; - match flag { - 2 => return self.shared.get(&key).map(|id| Value::Obj(Some(*id))).ok_or(Error::Malformed("reference to an undefined object")), - 1 => {} - _ => return Err(Error::Malformed("object marker")), - } - if self.shared.contains_key(&key) { - return Err(Error::Malformed("object defined twice")); - } - // Register before the fields: an object's own fields may refer back to it. - let id = self.push(Object::new(Tag(0), Kind::Shared, Vec::new(), Vec::new()))?; - self.shared.insert(key, id); - let mut chain = Vec::new(); - let mut fields = Vec::new(); - loop { - match self.c.u8()? { - 0 => { - let tag = Tag(self.c.u32()?); - self.c.u16()?; - chain.push(tag); - fields.extend(self.fields(true, tag)?); - } - 1 => { - chain.push(Tag(self.c.u32()?)); - break; - } - 2 => break, - _ => return Err(Error::Malformed("object class chain")), - } - if chain.len() > 64 { - return Err(Error::Limit("object class chain too long")); - } - } - let class = chain.first().copied().unwrap_or(Tag(0)); - fields.extend(self.fields(true, class)?); - if let Some(o) = self.objects.get_mut(id) { - *o = Object::new(class, Kind::Shared, chain, fields); - } - Ok(Value::Obj(Some(id))) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn lookups_in_a_large_object_find_the_first_and_last_fields_of_a_tag() { - let tag = |i: u32| Tag(0x4100_0000 + i); - let mut fields: Vec<(Tag, Value)> = (0..1000).map(|i| (tag(i % 300), Value::UInt(u64::from(i)))).collect(); - fields.push((tag(7), Value::Str("last".into()))); - let o = Object::new(Tag::of(b"Grup"), Kind::Shared, Vec::new(), fields.clone()); - assert!(!o.index.is_empty()); - // The index has one entry per distinct tag, not per field. - assert_eq!(o.index.len(), 300); - for t in 0..300 { - let first = fields.iter().find(|(k, _)| *k == tag(t)).map(|(_, v)| v); - let last = fields.iter().rev().find(|(k, _)| *k == tag(t)).map(|(_, v)| v); - assert_eq!(o.get(tag(t)), first); - assert_eq!(o.get_last(tag(t)), last); - } - assert_eq!(o.get(tag(300)), None); - assert_eq!(o.get_last(tag(7)), Some(&Value::Str("last".into()))); - let small = Object::new(Tag::of(b"Grup"), Kind::Shared, Vec::new(), vec![(tag(1), Value::Bool(true)), (tag(1), Value::Bool(false))]); - assert!(small.index.is_empty()); - assert_eq!(small.get(tag(1)), Some(&Value::Bool(true))); - assert_eq!(small.get_last(tag(1)), Some(&Value::Bool(false))); - } -} diff --git a/crates/affinity/src/synth.rs b/crates/affinity/src/synth.rs deleted file mode 100644 index 5b75ca0bff..0000000000 --- a/crates/affinity/src/synth.rs +++ /dev/null @@ -1,259 +0,0 @@ -//! Synthetic containers for tests and fuzz seeds (cargo feature `synth`). -//! -//! These builders write the layout the reader accepts, so tests can describe documents in a few -//! lines. They are **not** an Affinity exporter: nothing written here has been opened in Affinity. -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] - -use crate::stream::Tag; - -/// A field value to encode. -#[derive(Debug, Clone)] -pub enum F { - U8(u8), - U32(u32), - I32(i32), - F32(f32), - F64(f64), - Bool(bool), - Enum(u16, u16), - Str(String), - /// f64 vector of 2..6 values (points, rectangles, transforms). - F64s(Vec), - /// Fixed-size struct (colour components), 1..64 bytes. - Struct(Vec), - /// Array of fixed-size records, all `size` bytes. - Records(u16, Vec>), - U8s(Vec), - Entry(String), - /// Shared object: `Def` defines id with class chain and fields, `Ref` links back. - Def(u32, Vec, Vec<(Tag, F)>), - Ref(u32), - Null, - /// Inline object. - Obj(Tag, Vec<(Tag, F)>), - /// Positional (untagged) object. - Pos(Vec), - /// Array of shared objects / links. - Shared(Vec), - /// Array of inline objects of one class. - Objs(Tag, Vec>), - /// Raw bytes appended verbatim (malformed-input tests). - Raw(Vec), -} - -pub fn tag(s: &[u8; 4]) -> Tag { - Tag::of(s) -} - -fn put_tag(out: &mut Vec, t: Tag) { - out.extend(t.0.to_le_bytes()); -} - -fn code(f: &F) -> u8 { - match f { - F::U8(_) => 0x01, - F::U32(_) => 0x03, - F::I32(_) => 0x07, - F::F32(_) => 0x09, - F::F64(_) => 0x0a, - F::Bool(_) => 0x29, - F::Enum(..) => 0x2a, - F::Str(_) => 0x2b, - F::F64s(v) => 0x22 + v.len() as u8, - F::Struct(b) => 0x34 + b.len() as u8, - F::Records(..) => 0x80 | 0x2c, - F::U8s(_) => 0x80 | 0x01, - F::Entry(_) => 0x33, - F::Def(..) | F::Ref(_) => 0x31, - F::Null => 0x31, - F::Obj(..) => 0x32, - F::Pos(_) => 0x30, - F::Shared(_) => 0x80 | 0x31, - F::Objs(..) => 0x80 | 0x32, - F::Raw(_) => 0, - } -} - -fn payload(out: &mut Vec, f: &F) { - match f { - F::U8(v) => out.push(*v), - F::U32(v) => out.extend(v.to_le_bytes()), - F::I32(v) => out.extend(v.to_le_bytes()), - F::F32(v) => out.extend(v.to_le_bytes()), - F::F64(v) => out.extend(v.to_le_bytes()), - F::Bool(v) => out.push(u8::from(*v)), - F::Enum(id, ver) => { - out.extend(id.to_le_bytes()); - out.extend(ver.to_le_bytes()); - } - F::Str(s) => { - out.extend((s.len() as u32).to_le_bytes()); - out.extend(s.as_bytes()); - } - F::F64s(v) => v.iter().for_each(|x| out.extend(x.to_le_bytes())), - F::Struct(b) => out.extend(b), - F::Records(size, recs) => { - out.extend((recs.len() as u32).to_le_bytes()); - out.extend(size.to_le_bytes()); - recs.iter().for_each(|r| out.extend(r)); - } - F::U8s(v) => { - out.extend((v.len() as u32).to_le_bytes()); - out.extend(v); - } - F::Entry(name) => { - put_tag(out, tag(b"Data")); - out.extend((name.len() as u32).to_le_bytes()); - out.extend(name.as_bytes()); - } - F::Def(id, chain, fields) => { - out.push(1); - out.extend(id.to_le_bytes()); - // Class chain: each level but the last carries no fields here; the last ends the chain. - let (last, rest) = chain.split_last().expect("class chain"); - for t in rest { - out.push(0); - put_tag(out, *t); - out.extend(0u16.to_le_bytes()); - out.push(0); - } - out.push(1); - put_tag(out, *last); - fields_into(out, fields, true); - } - F::Ref(id) => { - out.push(2); - out.extend(id.to_le_bytes()); - } - F::Null => out.push(0), - F::Obj(class, fields) => { - out.push(1); - put_tag(out, *class); - out.extend(0u16.to_le_bytes()); - fields_into(out, fields, true); - } - F::Pos(items) => { - for f in items { - out.push(code(f)); - payload(out, f); - } - out.push(0); - } - F::Shared(items) => { - out.extend((items.len() as u32).to_le_bytes()); - items.iter().for_each(|f| payload(out, f)); - } - F::Objs(class, items) => { - out.extend((items.len() as u32).to_le_bytes()); - put_tag(out, *class); - out.extend(0u16.to_le_bytes()); - for fields in items { - out.push(1); - fields_into(out, fields, true); - } - } - F::Raw(b) => out.extend(b), - } -} - -fn fields_into(out: &mut Vec, fields: &[(Tag, F)], tagged: bool) { - for (t, f) in fields { - if let F::Raw(b) = f { - out.extend(b); - continue; - } - out.push(code(f)); - if tagged { - put_tag(out, *t); - } - payload(out, f); - } - out.push(0); -} - -/// A `doc.dat` stream with root class `Pers`. -pub fn stream(root: &[(Tag, F)]) -> Vec { - let mut out = b"\x00\xffKS".to_vec(); - out.extend(2u16.to_le_bytes()); - put_tag(&mut out, tag(b"Pers")); - out.extend(0u16.to_le_bytes()); - out.extend(30u32.to_le_bytes()); - fields_into(&mut out, root, true); - out -} - -/// How an entry is stored. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Method { - Stored, - Zlib, - Zstd, -} - -/// A version-12 container with one `#FT4` table holding `entries`, then an optional thumbnail record. -pub fn container(entries: &[(&str, &[u8], Method)], thumbnail_png: Option<&[u8]>) -> Vec { - let mut out = vec![0u8; 72]; - out[..4].copy_from_slice(crate::container::MAGIC); - out[4..6].copy_from_slice(&12u16.to_le_bytes()); - out[6..8].copy_from_slice(&4u16.to_le_bytes()); - out[8..12].copy_from_slice(b"nsrP"); - out[12..16].copy_from_slice(b"#Inf"); - out[64..68].copy_from_slice(b"Prot"); - let mut records = Vec::new(); - for (i, (name, data, method)) in entries.iter().enumerate() { - let packed = match method { - Method::Stored => data.to_vec(), - Method::Zlib => { - use std::io::Write; - let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::fast()); - e.write_all(data).unwrap(); - e.finish().unwrap() - } - Method::Zstd => ruzstd::encoding::compress_to_vec(*data, ruzstd::encoding::CompressionLevel::Fastest), - }; - let offset = out.len() as u64; - out.extend(b"#Fil"); - out.extend(&packed); - let mut r = Vec::new(); - r.extend((i as u32 + 1).to_le_bytes()); - r.push(0); - r.extend(offset.to_le_bytes()); - r.extend((data.len() as u64).to_le_bytes()); - r.extend((packed.len() as u64).to_le_bytes()); - r.extend(crc32fast::hash(data).to_le_bytes()); - r.push(match method { - Method::Stored => 0, - Method::Zlib => 1, - Method::Zstd => 2, - }); - r.extend(0u32.to_le_bytes()); - r.extend(0u32.to_le_bytes()); - r.extend((name.len() as u16).to_le_bytes()); - r.extend(name.as_bytes()); - records.push(r); - } - let fat = out.len() as u64; - out.extend(b"#FT4"); - out.extend(0u64.to_le_bytes()); - out.extend(1_700_000_000u64.to_le_bytes()); - out.extend([0u8; 24]); - out.extend((records.len() as u32).to_le_bytes()); - out.extend([0u8; 8]); - out.extend(0u16.to_le_bytes()); - out.push(0); - records.iter().for_each(|r| out.extend(r)); - let thumb = out.len() as u64; - out[16..24].copy_from_slice(&fat.to_le_bytes()); - if let Some(png) = thumbnail_png { - out[24..32].copy_from_slice(&thumb.to_le_bytes()); - out.extend(b"\xff\xff\xff\xffThmb"); - out.extend(1u32.to_le_bytes()); - out.extend((png.len() as u32 + 13).to_le_bytes()); - out.extend(29u32.to_le_bytes()); - out.extend(0u32.to_le_bytes()); - out.extend((png.len() as u32).to_le_bytes()); - out.push(1); - out.extend(png); - } - out -} diff --git a/crates/affinity/src/tests.rs b/crates/affinity/src/tests.rs deleted file mode 100644 index 75b6b7b146..0000000000 --- a/crates/affinity/src/tests.rs +++ /dev/null @@ -1,408 +0,0 @@ -//! Unit tests on synthetic inputs; `tests/it/real_files.rs` covers public Affinity documents. - -mod preview { - use crate::container::header; - use crate::*; - use proptest::prelude::*; - - fn fixture() -> Vec { - let mut png = b"\x89PNG\r\n\x1a\n".to_vec(); - png.extend(13u32.to_be_bytes()); - png.extend(b"IHDR"); - png.extend(2u32.to_be_bytes()); - png.extend(1u32.to_be_bytes()); - png.extend([8, 6, 0, 0, 0]); - png.extend(crc32fast::hash(&png[12..]).to_be_bytes()); - png.extend([0; 4]); - png.extend(b"IDAT"); - png.extend(crc32fast::hash(b"IDAT").to_be_bytes()); - png.extend([0; 4]); - png.extend(b"IEND"); - png.extend(crc32fast::hash(b"IEND").to_be_bytes()); - let mut b = vec![0; 72]; - b[..4].copy_from_slice(MAGIC); - b[4..6].copy_from_slice(&12u16.to_le_bytes()); - b[8..12].copy_from_slice(b"nsrP"); - b[12..16].copy_from_slice(b"#Inf"); - b[24..32].copy_from_slice(&72u64.to_le_bytes()); - b[64..68].copy_from_slice(b"Prot"); - b.extend(b"\xff\xff\xff\xffThmb"); - b.extend(1u32.to_le_bytes()); - b.extend((png.len() as u32 + 13).to_le_bytes()); - b.extend(29u32.to_le_bytes()); - b.extend(0u32.to_le_bytes()); - b.extend((png.len() as u32).to_le_bytes()); - b.push(1); - b.extend(png); - b - } - - #[test] - fn indexed_preview_and_header() { - let b = fixture(); - assert_eq!(header(&b).unwrap().version, 12); - let p = preview(&b).unwrap(); - assert_eq!((p.width, p.height), (2, 1)); - assert_eq!(p.png, &b[101..]); - } - - #[test] - fn every_truncation_is_rejected() { - let b = fixture(); - for end in 0..b.len() { - assert!(preview(&b[..end]).is_err(), "{end}"); - } - } - - #[test] - fn rejects_assets_versions_offsets_lengths_and_bombs() { - let b = fixture(); - for (offset, value) in [ - (4, 13u64.to_le_bytes().to_vec()), - (8, b"urBR".to_vec()), - (24, u64::MAX.to_le_bytes().to_vec()), - (24, 1u64.to_le_bytes().to_vec()), - (24, 0u64.to_le_bytes().to_vec()), - (84, u32::MAX.to_le_bytes().to_vec()), - (88, 30u32.to_le_bytes().to_vec()), - (96, u32::MAX.to_le_bytes().to_vec()), - (117, 5000u32.to_be_bytes().to_vec()), - ] { - let mut broken = b.clone(); - broken[offset..offset + value.len()].copy_from_slice(&value); - assert!(preview(&broken).is_err(), "offset {offset}"); - } - // Versions 8 to 11 store the same record (checked on public Affinity 1 and 2 files). - for version in 8..12 { - let mut legacy = b.clone(); - legacy[4..6].copy_from_slice(&(version as u16).to_le_bytes()); - assert!(preview(&legacy).is_ok()); - } - // Flags 4 and 8 occur in real files; the low two bits mark other container variants. - for (flags, ok) in [(4u16, true), (8, true), (1, false), (2, false)] { - let mut variant = b.clone(); - variant[6..8].copy_from_slice(&flags.to_le_bytes()); - assert_eq!(preview(&variant).is_ok(), ok, "flags {flags}"); - } - let mut old = b.clone(); - old[4..6].copy_from_slice(&7u16.to_le_bytes()); - assert!(matches!(preview(&old), Err(Error::Unsupported(_)))); - } - - #[test] - fn an_unindexed_png_or_resource_is_never_used() { - let mut b = fixture(); - b[24..32].copy_from_slice(&0u64.to_le_bytes()); - assert!(preview(&b).is_err()); - b[24..32].copy_from_slice(&72u64.to_le_bytes()); - b[76..80].copy_from_slice(b"Meta"); - assert!(preview(&b).is_err()); - } - - #[test] - fn every_chunk_checksum_including_the_end_is_checked() { - let b = fixture(); - for at in [130, b.len() - 1] { - let mut damaged = b.clone(); - damaged[at] ^= 1; - assert_eq!(preview(&damaged).unwrap_err(), Error::Malformed("PNG chunk checksum")); - } - let mut ancillary = vec![0; 4]; - ancillary.extend(b"tEXt"); - ancillary.extend(crc32fast::hash(b"tEXt").to_be_bytes()); - let mut with_ancillary = b.clone(); - let at = b.len() - 12; - with_ancillary.splice(at..at, ancillary); - let png_length = (with_ancillary.len() - 101) as u32; - with_ancillary[84..88].copy_from_slice(&(png_length + 13).to_le_bytes()); - with_ancillary[96..100].copy_from_slice(&png_length.to_le_bytes()); - assert!(preview(&with_ancillary).is_ok()); - with_ancillary[at + 8] ^= 1; - assert_eq!(preview(&with_ancillary).unwrap_err(), Error::Malformed("PNG chunk checksum")); - } - - #[test] - fn compressed_metadata_and_animation_are_not_preview_support() { - for kind in [b"zTXt", b"iTXt", b"iCCP", b"acTL", b"fcTL", b"fdAT"] { - let mut extra = vec![0; 4]; - extra.extend(kind); - extra.extend(crc32fast::hash(kind).to_be_bytes()); - let mut b = fixture(); - let at = b.len() - 12; - b.splice(at..at, extra); - let length = (b.len() - 101) as u32; - b[84..88].copy_from_slice(&(length + 13).to_le_bytes()); - b[96..100].copy_from_slice(&length.to_le_bytes()); - assert!(matches!(preview(&b), Err(Error::Unsupported(_)))); - } - } - - #[test] - fn critical_chunks_follow_a_single_complete_png_layout() { - fn with_chunks(kinds: &[&[u8; 4]]) -> Vec { - let original = fixture(); - let mut b = original[..134].to_vec(); // File, record and complete first IHDR. - for kind in kinds { - b.extend([0; 4]); - b.extend(*kind); - b.extend(crc32fast::hash(*kind).to_be_bytes()); - } - let length = (b.len() - 101) as u32; - b[84..88].copy_from_slice(&(length + 13).to_le_bytes()); - b[96..100].copy_from_slice(&length.to_le_bytes()); - b - } - assert!(preview(&with_chunks(&[b"IDAT", b"IDAT", b"IEND"])).is_ok()); - // PNG readers must not reject an otherwise valid unknown ancillary chunk just - // because its reserved (third-letter) bit is set; future versions can define it. - assert!(preview(&with_chunks(&[b"abct", b"IDAT", b"IEND"])).is_ok()); - for kinds in [ - vec![b"IEND"], - vec![b"IDAT", b"IHDR", b"IEND"], - vec![b"PLTE", b"PLTE", b"IDAT", b"IEND"], - vec![b"IDAT", b"PLTE", b"IEND"], - vec![b"IDAT", b"tEXt", b"IDAT", b"IEND"], - vec![b"ABCD", b"IDAT", b"IEND"], - vec![b"IDAT", b"IEND", b"tEXt"], - ] { - assert!(preview(&with_chunks(&kinds)).is_err(), "{kinds:?}"); - } - } - - proptest! { - #![proptest_config(ProptestConfig::with_cases(256))] - #[test] - fn arbitrary_input_never_panics(b in prop::collection::vec(any::(), 0..2048)) { - let _ = header(&b); - let _ = preview(&b); - } - #[test] - fn mutations_never_panic(edits in prop::collection::vec((0usize..200, any::()), 0..32)) { - let mut b = fixture(); - for (i, value) in edits { if let Some(v) = b.get_mut(i) { *v = value; } } - let _ = preview(&b); - } - } -} - -mod archive { - use crate::Error; - use crate::container::{Archive, Limits}; - use crate::stream::{self, Kind, Tag, Value}; - use crate::synth::{self, F, Method, tag}; - use proptest::prelude::*; - - fn doc() -> Vec { - synth::stream(&[ - (tag(b"Desc"), F::Str("Document".into())), - (tag(b"Visi"), F::Bool(true)), - (tag(b"Xfrm"), F::F64s(vec![1.0, 0.0, 5.0, 0.0, 1.0, -2.0])), - (tag(b"Colr"), F::Def(7, vec![tag(b"RGBA")], vec![(tag(b"_col"), F::Struct([0u8; 16].to_vec()))])), - (tag(b"Same"), F::Ref(7)), - (tag(b"Null"), F::Null), - (tag(b"Kids"), F::Shared(vec![F::Def(8, vec![tag(b"Grup"), tag(b"Node")], vec![(tag(b"Desc"), F::Str("g".into()))]), F::Ref(8)])), - ( - tag(b"Crvs"), - F::Obj(tag(b"PCvD"), vec![(tag(b"Data"), F::Pos(vec![F::U8(0), F::U32(1), F::Bool(true), F::Records(18, vec![vec![0; 18]; 4])]))]), - ), - (tag(b"Enum"), F::Enum(2, 1)), - (tag(b"Tile"), F::Entry("d/3".into())), - (tag(b"Stat"), F::U8s(vec![4, 0, 2])), - ]) - } - - #[test] - fn every_method_round_trips_with_checksums() { - let d = doc(); - for method in [Method::Stored, Method::Zlib, Method::Zstd] { - let file = synth::container(&[("doc.dat", &d, method), ("d/3", b"tile", method)], None); - let mut a = Archive::open(&file, Limits::default()).unwrap(); - assert_eq!(a.header.version, 12); - assert_eq!(a.read("doc.dat").unwrap(), d); - assert_eq!(a.read("d/3").unwrap(), b"tile"); - assert_eq!(a.extracted(), d.len() + 4); - assert!(a.read("missing").is_err()); - } - } - - #[test] - fn the_stream_parses_into_shared_objects_and_links() { - let s = stream::parse(&doc()).unwrap(); - let root = &s.objects[s.root]; - assert_eq!(root.class, Tag::of(b"Pers")); - assert_eq!(root.get(Tag::of(b"Desc")), Some(&Value::Str("Document".into()))); - assert_eq!(root.get(Tag::of(b"Xfrm")), Some(&Value::Floats(vec![1.0, 0.0, 5.0, 0.0, 1.0, -2.0]))); - let (Some(Value::Obj(Some(a))), Some(Value::Obj(Some(b)))) = (root.get(Tag::of(b"Colr")), root.get(Tag::of(b"Same"))) else { panic!() }; - assert_eq!(a, b); - assert_eq!(s.objects[*a].class, Tag::of(b"RGBA")); - assert_eq!(s.objects[*a].kind, Kind::Shared); - let Some(Value::Array(kids)) = root.get(Tag::of(b"Kids")) else { panic!() }; - assert_eq!(kids[0], kids[1]); - let Value::Obj(Some(g)) = kids[0] else { panic!() }; - assert_eq!(s.objects[g].chain, vec![Tag::of(b"Grup"), Tag::of(b"Node")]); - assert_eq!(root.get(Tag::of(b"Enum")), Some(&Value::Enum { id: 2, version: 1 })); - assert_eq!(root.get(Tag::of(b"Tile")), Some(&Value::Entry("d/3".into()))); - assert_eq!(root.get(Tag::of(b"Null")), Some(&Value::Obj(None))); - } - - #[test] - fn checksums_sizes_and_budgets_are_enforced() { - let d = doc(); - let file = synth::container(&[("doc.dat", &d, Method::Zstd)], None); - // Flip a byte inside the compressed payload, past the "#Fil" tag at offset 72. - let mut broken = file.clone(); - broken[90] ^= 0x55; - let mut a = Archive::open(&broken, Limits::default()).unwrap(); - assert!(a.read("doc.dat").is_err()); - let mut a = Archive::open(&file, Limits { max_entry: d.len() - 1, max_total: usize::MAX }).unwrap(); - assert!(matches!(a.read("doc.dat"), Err(Error::Limit(_)))); - let mut a = Archive::open(&file, Limits { max_entry: usize::MAX, max_total: d.len() + 1 }).unwrap(); - a.read("doc.dat").unwrap(); - assert!(matches!(a.read("doc.dat"), Err(Error::Limit(_)))); - } - - #[test] - fn an_entry_that_fails_its_checksum_is_charged_once_and_not_decompressed_again() { - let d = doc(); - let file = synth::container(&[("doc.dat", &d, Method::Zstd)], None); - let mut broken = file.clone(); - broken[90] ^= 0x55; - let mut a = Archive::open(&broken, Limits::default()).unwrap(); - let first = a.read("doc.dat").unwrap_err(); - // The work was done, so it counts against the import even though it failed. - assert_eq!(a.extracted(), d.len()); - assert_eq!(a.read("doc.dat").unwrap_err(), first); - assert_eq!(a.extracted(), d.len()); - // A budget that only covers one attempt is not exceeded by asking again. - let mut a = Archive::open(&broken, Limits { max_entry: usize::MAX, max_total: d.len() }).unwrap(); - assert!(a.read("doc.dat").is_err()); - assert_eq!(a.read("doc.dat").unwrap_err(), first); - } - - #[test] - fn the_table_index_has_a_budget_for_records_and_names() { - let d = doc(); - let long = "n".repeat(300); - let file = synth::container(&[("doc.dat", &d, Method::Stored), (&long, b"tile", Method::Stored)], None); - Archive::open_within(&file, Limits::default(), 2, 307).unwrap(); - assert_eq!(Archive::open_within(&file, Limits::default(), 1, 1 << 20).unwrap_err(), Error::Limit("too many archive entries")); - assert_eq!(Archive::open_within(&file, Limits::default(), 2, 306).unwrap_err(), Error::Limit("archive entry names too long")); - } - - // Regression test for #1710: ruzstd 0.9.0 let a block decompress to more than its frame's - // window allows (RUSTSEC-2026-0344), so a crafted entry made the decoder produce far more than - // the format permits for a block. 0.9.1 refuses it. - #[test] - fn a_zstd_block_larger_than_its_frames_window_is_refused() { - const LEN: u32 = 100_000; - let plain = vec![0x61u8; LEN as usize]; - let file = synth::container(&[("doc.dat", &plain, Method::Zstd)], None); - // A Zstandard frame with a 1 KiB window (descriptor byte 0, window byte 0) holding one RLE - // block, the last, that repeats a byte LEN times: block header = last | RLE << 1 | LEN << 3. - let mut frame = vec![0x28, 0xB5, 0x2F, 0xFD, 0x00, 0x00]; - frame.extend((1 | (1 << 1) | (LEN << 3)).to_le_bytes().get(..3).unwrap()); - frame.push(0x61); - // Swap it in for the entry's compressed bytes (they follow the "#Fil" tag at offset 72). - let fat = u64::from_le_bytes(file[16..24].try_into().unwrap()) as usize; - let old_len = u64::from_le_bytes(file[fat + 59 + 21..fat + 59 + 29].try_into().unwrap()) as usize; - let mut swapped = file[..76].to_vec(); - swapped.extend(&frame); - swapped.extend(&file[76 + old_len..]); - let new_fat = fat - old_len + frame.len(); - swapped[16..24].copy_from_slice(&(new_fat as u64).to_le_bytes()); - swapped[new_fat + 59 + 21..new_fat + 59 + 29].copy_from_slice(&(frame.len() as u64).to_le_bytes()); - let mut a = Archive::open(&swapped, Limits::default()).unwrap(); - assert!(a.read("doc.dat").is_err(), "a block of {LEN} bytes was decompressed from a frame with a 1 KiB window"); - } - - #[test] - fn a_declared_size_smaller_than_the_data_is_rejected_not_truncated() { - let big = vec![7u8; 1 << 20]; - let mut file = synth::container(&[("doc.dat", &big, Method::Zlib)], None); - // Rewrite the declared size in the table to 1 KiB: decoding must stop and fail. - let fat = u64::from_le_bytes(file[16..24].try_into().unwrap()) as usize; - let size_at = fat + 59 + 5 + 8; - file[size_at..size_at + 8].copy_from_slice(&1024u64.to_le_bytes()); - let mut a = Archive::open(&file, Limits::default()).unwrap(); - assert_eq!(a.read("doc.dat").unwrap_err(), Error::Malformed("archive entry size mismatch")); - } - - #[test] - fn libraries_and_cyclic_tables_are_rejected() { - let d = doc(); - let mut file = synth::container(&[("doc.dat", &d, Method::Stored)], None); - let mut library = file.clone(); - library[8..12].copy_from_slice(b"rAsA"); - assert!(matches!(Archive::open(&library, Limits::default()), Err(Error::Unsupported(_)))); - let fat = u64::from_le_bytes(file[16..24].try_into().unwrap()); - let at = fat as usize + 4; - file[at..at + 8].copy_from_slice(&fat.to_le_bytes()); - assert_eq!(Archive::open(&file, Limits::default()).unwrap_err(), Error::Malformed("allocation tables form a cycle")); - } - - #[test] - fn hostile_streams_fail_cleanly() { - let deep = (0..2000).fold(Vec::new(), |inner, _| vec![(tag(b"Chld"), F::Obj(tag(b"Grup"), inner))]); - assert_eq!(stream::parse(&synth::stream(&deep)).unwrap_err(), Error::Limit("objects nested too deeply")); - // An array claiming four billion elements in a few bytes. - let huge = synth::stream(&[(tag(b"Big_"), F::Raw(vec![0x81, b'_', b'g', b'i', b'B', 0xff, 0xff, 0xff, 0xff, 0]))]); - assert_eq!(stream::parse(&huge).unwrap_err(), Error::Malformed("array longer than its data")); - let forward = synth::stream(&[(tag(b"Link"), F::Ref(99))]); - assert!(stream::parse(&forward).is_err()); - let twice = synth::stream(&[(tag(b"A___"), F::Def(1, vec![tag(b"RGBA")], vec![])), (tag(b"B___"), F::Def(1, vec![tag(b"RGBA")], vec![]))]); - assert!(stream::parse(&twice).is_err()); - let unknown = synth::stream(&[(tag(b"X___"), F::Raw(vec![0x0b, 1, 2, 3, 4]))]); - assert!(matches!(stream::parse(&unknown), Err(Error::Unsupported(_)))); - let d = doc(); - for end in 0..d.len() { - assert!(stream::parse(&d[..end]).is_err(), "{end}"); - } - } - - #[test] - fn a_small_compressed_entry_cannot_make_the_stream_allocate_gigabytes() { - // Each decoded value takes about 40 bytes, and a bool array packs eight in a byte: 16 MiB - // of zero bits, a few KiB once compressed, would ask for 2^27 values (about 4 GiB). An - // array of one-byte values just past the budget fails the same way, before allocating. - let field = |code: u8, n: u32, data: usize| { - let mut f = vec![0x80 | code]; - f.extend(tag(b"Big_").0.to_le_bytes()); - f.extend(n.to_le_bytes()); - f.resize(f.len() + data, 0); - F::Raw(f) - }; - let bools = 1u32 << 27; - let bytes = u32::try_from(stream::MAX_VALUES).unwrap() + 1; - for f in [field(0x29, bools, (bools / 8) as usize), field(0x01, bytes, bytes as usize)] { - let d = synth::stream(&[(tag(b"Big_"), f)]); - let file = synth::container(&[("doc.dat", &d, Method::Zstd)], None); - assert!(file.len() < d.len() / 100, "{} of {}", file.len(), d.len()); - let entry = Archive::open(&file, Limits::default()).unwrap().read("doc.dat").unwrap(); - assert_eq!(stream::parse(&entry).unwrap_err(), Error::Limit("too many values in the document stream")); - } - } - - proptest! { - #![proptest_config(ProptestConfig::with_cases(512))] - #[test] - fn mutated_containers_and_streams_never_panic(edits in prop::collection::vec((0usize..4096, any::()), 1..24)) { - let d = doc(); - for method in [Method::Stored, Method::Zlib, Method::Zstd] { - let mut file = synth::container(&[("doc.dat", &d, method)], None); - for (i, v) in &edits { - let n = file.len(); - file[i % n] = *v; - } - if let Ok(bytes) = Archive::open(&file, Limits::default()).and_then(|mut a| a.read("doc.dat")) { - let _ = stream::parse(&bytes); - } - } - let mut s = d.clone(); - for (i, v) in &edits { - let n = s.len(); - s[i % n] = *v; - } - let _ = stream::parse(&s); - } - } -} diff --git a/crates/affinity/src/text.rs b/crates/affinity/src/text.rs deleted file mode 100644 index d2bb55ca0c..0000000000 --- a/crates/affinity/src/text.rs +++ /dev/null @@ -1,564 +0,0 @@ -//! Artistic and frame text: the story's characters with their font, size, colour, tracking and -//! leading, the paragraph alignment and the first baseline. Layout (line breaks in frames, kerning, -//! OpenType features) is left to the importing application. - -use crate::model::{Affine, Align, Paragraph, Point, Reader, Table, TableCell, Text, TextRun, VAlign, rect}; -use crate::paint::{self, Color, Paint}; -use crate::stream::{ObjId, Value}; - -/// Characters read per text node (stories are split into blocks; this caps hostile ones). -const MAX_CHARS: usize = 1 << 20; -/// Shared character attributes must not amplify into unbounded font/feature/gradient data. -const MAX_ATTRIBUTE_BYTES: usize = 16 << 20; - -/// Ends a table cell in a table's story (Affinity's break glyph of kind 4). -pub const CELL_BREAK: char = '\u{1F}'; - -pub(crate) fn read(r: &mut Reader, id: ObjId, world: Affine) -> Option { - let s = r.s; - let story = s.obj(id, b"StSt")?; - let frame = s.obj(id, b"TxtH")?; - let artistic = s.is(frame, b"ArFr"); - let bounds = s.floats::<4>(frame, b"FrmB").map(rect)?; - let (runs, align) = story_runs(r, story, world); - let first_baseline = bounds.y0 + s.f64(frame, b"ArtV").unwrap_or(0.0); - let anchor_x = match align { - Align::Center => (bounds.x0 + bounds.x1) / 2.0, - Align::Right => bounds.x1, - _ => bounds.x0, - }; - if !artistic { - if s.objs(frame, b"ColW").len() > 1 || matches!(s.field(frame, b"ColW"), Some(Value::Array(a)) if a.len() > 1) { - r.warn("text frames with several columns (imported as one column)"); - } - if s.class(id) == Some(crate::stream::Tag::of(b"TxtC")) { - r.warn("text frames with a curved outline (imported as rectangular frames)"); - } - } - let text_transform = if artistic { world } else { text_scale(r, id).then(r.type_base) }; - Some(Text { - runs, - align, - anchor: Point { x: anchor_x, y: first_baseline }, - frame: if artistic { None } else { Some(bounds) }, - transform: world, - text_transform, - }) -} - -/// Rows and columns a table may have. -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 { - let s = r.s; - let story = s.obj(id, b"StSt")?; - let tabl = s.obj(id, b"TxtH").and_then(|h| s.obj(h, b"Tabl"))?; - let bounds = |pos: Option| -> Option> { - let Some(Value::Array(a)) = pos.and_then(|p| s.field(p, b"Posn")) else { return None }; - let v: Vec = a.iter().take(MAX_TABLE_LINES + 2).map(float).collect::>()?; - (v.len() >= 2 && v.len() <= MAX_TABLE_LINES + 1 && v.windows(2).all(|w| w[1] >= w[0])).then_some(v) - }; - let columns = bounds(s.obj(tabl, b"CPos"))?; - let rows = bounds(s.obj(tabl, b"RPos"))?; - let (ncols, nrows) = (columns.len() - 1, rows.len() - 1); - let count = ncols.checked_mul(nrows)?; - if count > MAX_TABLE_CELLS { - r.warn("tables with more than 65536 cells (left out)"); - return None; - } - let Some(left) = r.budget.cells.checked_sub(count) else { - r.warn("tables beyond the cells one document may hold (left out)"); - return None; - }; - r.budget.cells = left; - let cell_objs = s.obj(tabl, b"Cell").map(|c| s.objs(c, b"Cell")).unwrap_or_default(); - // Formatting that doesn't match the grid would land on the wrong cells (and merging them, - // move text between cells): only text then. - let cell_objs = if cell_objs.len() == count { - cell_objs - } else { - r.warn("tables whose cells don't match their grid (cell formatting left out)"); - Vec::new() - }; - let blank = || TableCell { runs: Vec::new(), inset: [0.0; 4], valign: VAlign::Top, merged_left: false }; - let mut cells: Vec = (0..count).map(|_| blank()).collect(); - for (i, (cell, obj)) in cells.iter_mut().zip(&cell_objs).enumerate() { - if let Some(inset) = s.floats::<4>(*obj, b"Inse").filter(|v| v.iter().all(|x| x.is_finite() && *x >= 0.0)) { - cell.inset = inset; - } - cell.valign = match s.enumeration(*obj, b"AliY").map(|(i, _)| i) { - Some(1) => VAlign::Center, - Some(2) => VAlign::Bottom, - _ => VAlign::Top, - }; - // A cell merged into the one on its left; the first column has nothing to its left. - cell.merged_left = i % ncols != 0 && s.bool(*obj, b"BrLf") == Some(true); - } - // The story holds the text of every cell that isn't merged away, row by row, each ended by a - // cell break. - let owner_list: Vec = (0..count).filter(|i| cells.get(*i).is_some_and(|c| !c.merged_left)).collect(); - let mut owners = owner_list.into_iter(); - let mut target = owners.next(); - let mut extra = false; - let (runs, _) = story_runs(r, story, world); - for run in runs { - 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) 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() { - target = owners.next(); - } - } - } - if extra { - r.warn("table text beyond its last cell (left out)"); - } - let mut edges = |tag: &[u8; 4], expected: usize| -> Vec> { - let objs = s.obj(tabl, tag).map(|e| s.objs(e, b"Edge")).unwrap_or_default(); - if objs.len() != expected { - r.warn("tables whose lines don't match their grid (lines left out)"); - return Vec::new(); - } - objs.into_iter() - .map(|e| match (s.obj(e, b"Fill"), s.obj(e, b"Line")) { - (Some(pen), Some(line)) => paint::stroke(r, pen, line, world, false), - _ => None, - }) - .collect() - }; - let vertical = edges(b"CEdg", (ncols + 1) * nrows); - let horizontal = edges(b"REdg", ncols * (nrows + 1)); - if let Some(format) = s.obj(tabl, b"TFmt") { - let filled = - s.objs(format, b"Clls").into_iter().filter_map(|c| s.obj(c, b"Fill")).any(|f| s.obj(f, b"FDeF").is_some_and(|d| !s.is(d, b"FilN"))); - if filled { - r.warn("table cell fills (left out)"); - } - } - let text_transform = text_scale(r, id).then(r.type_base); - Some(Table { columns, rows, cells, vertical, horizontal, transform: world, text_transform }) -} - -/// A story's character runs, each with its paragraph's format, and the first paragraph's -/// alignment. Table cells end with [`CELL_BREAK`]. -pub(crate) fn story_runs(r: &mut Reader, story: ObjId, world: Affine) -> (Vec, Align) { - let s = r.s; - let mut runs = Vec::new(); - let mut first_align = None; - let mut total = 0usize; - 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; - }; - // Bound collection itself, including placeholders, before allocating the character buffer: - // by the story's limit and by what the document's other stories left. - let budget = (MAX_CHARS - total).min(r.budget.chars.saturating_sub(total)); - - let mut chars: Vec = match s.str(glyphs, b"Utf8") { - Some(t) => t.chars().take(budget + 1).collect(), - None => { - // Inline objects (page numbers, anchors, cell ends) each take one index before - // the segment text. - let segments = s.objs(glyphs, b"Mixd"); - if segments.is_empty() { - r.warn("a text block without readable characters (left out)"); - continue; - } - let mut v = Vec::new(); - for seg in segments { - for inline in s.objs(seg, b"Glys") { - if v.len() > budget { - break; - } - if s.is(inline, b"BrGl") && s.enumeration(inline, b"HdBk").is_some_and(|(kind, _)| kind == 4) { - v.push(CELL_BREAK); - } else { - v.push('\u{FFFC}'); - placeholders = true; - } - } - v.extend(s.str(seg, b"Utf8").unwrap_or_default().chars().take((budget + 1).saturating_sub(v.len()))); - if v.len() > budget { - break; - } - } - v - } - }; - let truncated = chars.len() > budget; - if truncated { - chars.truncate(budget); - if budget < MAX_CHARS - total { - r.warn("text beyond the characters one document may hold (truncated)"); - } else { - r.warn("text longer than a million characters (truncated)"); - } - } - total += chars.len(); - // 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 = None; - 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); - match s.int(run, b"Indx").and_then(|v| usize::try_from(v).ok()) { - Some(end) => paragraphs.push((end, a)), - None => match open { - None => open = Some(a), - Some(first) if first != a => r.warn("mixed paragraph formats in one block (the first is used)"), - _ => {} - }, - } - } - // Sorted by end (they are in order in every file), so both lookups below are binary - // searches: a block can have as many paragraphs and runs as characters. - paragraphs.sort_by_key(|(end, _)| *end); - let align_at = |i: usize| paragraphs.get(paragraphs.partition_point(|(end, _)| *end <= i)).map(|(_, a)| *a).or(open).unwrap_or_default(); - let mut cuts: Vec = paragraphs.iter().map(|(end, _)| *end).filter(|e| *e < chars.len()).collect(); - cuts.dedup(); - let push = |r: &mut Reader, runs: &mut Vec, attrs: Option, from: usize, to: usize, budget: &mut Option| { - // Split at paragraph ends so every run has one paragraph format. - let inside = cuts.get(cuts.partition_point(|c| *c <= from)..cuts.partition_point(|c| *c < to)).unwrap_or_default(); - let mut a = from; - for &c in inside.iter().chain(std::iter::once(&to)) { - push_run(r, runs, attrs, characters(&chars, a, c), world, budget, align_at(a)); - a = c; - } - }; - let mut start = 0usize; - 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; - }; - let end = index.min(chars.len()); - if index > chars.len() || end < start { - r.warn("invalid text attribute range (bounded; unassigned characters use defaults)"); - } - if end <= start { - continue; - } - push(r, &mut runs, s.obj(run, b"Item"), start, end, &mut attribute_budget); - start = end; - } - if start < chars.len() { - push(r, &mut runs, None, start, chars.len(), &mut attribute_budget); - } - if truncated { - break; - } - } - r.budget.chars = r.budget.chars.saturating_sub(total); - if placeholders { - r.warn("text fields such as page numbers (left out of the text)"); - } - (runs, first_align.unwrap_or(Align::Left)) -} - -fn characters(chars: &[char], start: usize, end: usize) -> String { - chars.get(start..end).unwrap_or_default().iter().filter(|c| **c != '\0' && **c != '\u{FFFC}').collect() -} - -fn push_run( - r: &mut Reader, - runs: &mut Vec, - attrs: Option, - text: String, - world: Affine, - attribute_budget: &mut Option, - paragraph: Paragraph, -) { - if text.is_empty() { - return; - } - let run = match attrs { - Some(attrs) if attribute_budget.is_some() => TextRun { paragraph, ..run_attrs(r, attrs, text, world, attribute_budget) }, - _ => { - // This is a recovery policy, not an assertion about unspecified Affinity attributes. - if attrs.is_none() { - r.warn("text without character attributes (characters preserved with default attributes)"); - } - TextRun { - text, - postscript: String::new(), - family: String::new(), - weight: 400, - italic: false, - features: Vec::new(), - all_caps: false, - underline: false, - strikethrough: false, - size: 12.0 * r.dpi / 72.0, - tracking: 0.0, - h_scale: 1.0, - leading: None, - fill: Paint::Solid(Color::Gray { v: 0.0, a: 1.0 }), - stroke: None, - paragraph, - } - } - }; - runs.push(run); -} - -fn slot(v: Option<&Value>, i: usize, f: impl Fn(&Value) -> Option) -> Option { - match v? { - Value::Array(a) => a.get(i).and_then(f), - _ => None, - } -} - -fn float(v: &Value) -> Option { - match v { - Value::Float(f) if f.is_finite() => Some(*f), - _ => None, - } -} - -fn int(v: &Value) -> Option { - match v { - Value::Int(i) => Some(*i), - Value::UInt(u) => i64::try_from(*u).ok(), - _ => None, - } -} - -fn run_attrs(r: &mut Reader, attrs: ObjId, text: String, world: Affine, attribute_budget: &mut Option) -> TextRun { - let s = r.s; - let doubles = s.field(attrs, b"Doub"); - let ints = s.field(attrs, b"Ints"); - let size = slot(doubles, 0, float).filter(|v| *v > 0.0 && *v < 1e6).unwrap_or(12.0 * r.dpi / 72.0); - let tracking = slot(doubles, 4, float).unwrap_or(0.0); - let leading = (slot(ints, 4, int) == Some(1)).then(|| slot(doubles, 13, float)).flatten().filter(|v| *v > 0.0); - let objects = match s.field(attrs, b"Objs") { - Some(Value::Array(a)) => a.iter().take(8).map(|v| if let Value::Obj(o) = v { *o } else { None }).collect(), - _ => Vec::new(), - }; - let mut fill = match objects.first().copied().flatten().and_then(|f| paint::descriptor(r, f, world)) { - Some(fill) => fill, - None => { - r.warn("text without readable fill attributes (default black used)"); - Paint::Solid(Color::Gray { v: 0.0, a: 1.0 }) - } - }; - // A single descriptor decode is bounded by paint::MAX_STOPS. Charge its owned stop data - // before keeping it; subsequent runs skip attribute decoding once the budget is exhausted. - if let Paint::Gradient(gradient) = &fill { - let bytes = gradient.stops.len().saturating_mul(std::mem::size_of::()); - if !charge_attributes(r, attribute_budget, bytes) { - fill = Paint::Solid(Color::Gray { v: 0.0, a: 1.0 }); - } - } - // Outlined characters: `Objs` 1 is the outline's paint, 2 its line style (as for shapes). - let mut stroke = match (attribute_budget.is_some(), objects.get(1).copied().flatten(), objects.get(2).copied().flatten()) { - (true, Some(pen), Some(style)) => paint::stroke(r, pen, style, Affine::IDENTITY, false), - _ => None, - }; - // Its gradient stops and dashes are owned data too, charged like the fill's. - if let Some(st) = &stroke { - let stops = match &st.paint { - Paint::Gradient(g) => g.stops.len().saturating_mul(std::mem::size_of::()), - _ => 0, - }; - let dash = st.dash.as_ref().map_or(0, |(d, _)| d.len().saturating_mul(std::mem::size_of::())); - if !charge_attributes(r, attribute_budget, stops.saturating_add(dash)) { - stroke = None; - } - } - // Underline (slot 0) and strikethrough (slot 1): 1 is a single line. - let mut decoration = |i: usize| match slot(ints, i, int) { - Some(1) => true, - Some(0) | None => false, - Some(_) => { - r.warn("text decorations of an unknown kind (left out)"); - false - } - }; - let (underline, strikethrough) = (decoration(0), decoration(1)); - let h_scale = slot(doubles, 10, float).filter(|h| *h > 0.0 && *h < 100.0).unwrap_or(1.0); - // A resolved font is populated on the emoji run of the public Affinity 3 text-runs file - // (Courier New requested, Segoe UI Emoji stored in RFnt). Empty RFnt records are common. - // Source: https://github.com/SethRobinson/Patchy/tree/de84eab550758b30fa062e479f5778cce7693b73/test-fixtures/af - let requested = s.obj(attrs, b"DFnt"); - let resolved = - s.obj(attrs, b"RFnt").filter(|f| !s.str(*f, b"Famy").unwrap_or_default().is_empty() || !s.str(*f, b"Post").unwrap_or_default().is_empty()); - let font = resolved.or(requested); - if let Some(resolved) = resolved { - let differs = [b"Famy", b"Post"] - .iter() - .any(|tag| s.str(resolved, tag).unwrap_or_default() != requested.and_then(|f| s.str(f, tag)).unwrap_or_default()); - if differs { - r.warn("text uses a stored fallback font (imported with that font)"); - } - } - if font.and_then(|f| s.int(f, b"Widh")).is_some_and(|w| w != 5) { - r.warn("font width variants (exact face depends on the installed PostScript font)"); - } - let postscript = font_name(r, attribute_budget, font.and_then(|f| s.str(f, b"Post")).unwrap_or_default()); - let family = font_name(r, attribute_budget, font.and_then(|f| s.str(f, b"Famy")).unwrap_or_default()); - let (features, all_caps) = font_features(r, objects.get(7).copied().flatten(), attribute_budget); - let weight = font.and_then(|f| s.int(f, b"Wegt")).unwrap_or(400); - let weight = if (1..=1000).contains(&weight) { - weight - } else { - r.warn("invalid font weight (imported as regular)"); - 400 - }; - TextRun { - text, - postscript, - family, - weight, - italic: font.and_then(|f| s.bool(f, b"Ital")).unwrap_or(false), - features, - all_caps, - underline, - strikethrough, - size, - tracking, - h_scale, - leading, - fill, - stroke, - paragraph: Paragraph::default(), - } -} - -fn charge_attributes(r: &mut Reader, budget: &mut Option, bytes: usize) -> bool { - let Some(remaining) = *budget else { return false }; - match remaining.checked_sub(bytes) { - Some(remaining) => { - *budget = Some(remaining); - true - } - None => { - *budget = None; - r.warn("text attribute budget exceeded (excess font names, features and gradients left out)"); - false - } - } -} - -/// Longest font name kept (OpenType names are far shorter); every run and paragraph carries it. -const MAX_FONT_NAME: usize = 256; - -fn font_name(r: &mut Reader, budget: &mut Option, value: &str) -> String { - if value.len() > MAX_FONT_NAME { - r.warn("font names longer than 256 bytes (the default font is used)"); - return String::new(); - } - metadata_string(r, budget, value) -} - -fn metadata_string(r: &mut Reader, budget: &mut Option, value: &str) -> String { - let bytes = value.len().saturating_add(std::mem::size_of::()); - if value.is_empty() || !charge_attributes(r, budget, bytes) { String::new() } else { value.to_owned() } -} - -/// The public Affinity 3 caps fixture stores `smcp` and the private `CAP\x01` selector in -/// OtAt/Setn. Only the observed all-caps selector and boolean OpenType tags are mapped; other -/// values are reported, never guessed. Standard tag syntax: https://learn.microsoft.com/en-us/typography/opentype/spec/featuretags -fn font_features(r: &mut Reader, attrs: Option, attribute_budget: &mut Option) -> (Vec, bool) { - let mut features = Vec::new(); - let mut all_caps = false; - if attribute_budget.is_none() { - return (features, all_caps); - } - let s = r.s; - let Some(Value::Array(settings)) = attrs.and_then(|a| s.field(a, b"Setn")) else { return (features, all_caps) }; - for (index, setting) in settings.iter().take(257).enumerate() { - if index == 256 { - r.warn("more than 256 text feature settings (truncated)"); - break; - } - let Value::Obj(Some(setting)) = setting else { - r.warn("unreadable text feature settings (imported with defaults)"); - continue; - }; - let setting = *setting; - let tag = s.int(setting, b"Feat").and_then(|v| u32::try_from(v).ok()).map(u32::to_be_bytes); - let value = r.s.int(setting, b"Valu"); - match (tag, value) { - (Some([b'C', b'A', b'P', 1]), Some(0 | 1)) => all_caps = value == Some(1), - (Some(tag), Some(value @ (0 | 1))) if tag.iter().all(u8::is_ascii_alphanumeric) => { - if !charge_attributes(r, attribute_budget, std::mem::size_of::() + if value == 0 { 5 } else { 4 }) { - break; - } - let name = String::from_utf8_lossy(&tag); - features.push(if value == 0 { format!("-{name}") } else { name.into_owned() }); - } - _ => r.warn("text feature selectors or non-boolean OpenType settings (imported with defaults)"), - } - } - (features, all_caps) -} - -/// A paragraph's alignment, indents, spacing and leading. The `Doub` slots: 0 the automatic -/// leading as a multiple of the font's line height (1 in every document checked), 1 fixed leading -/// (when `Ints` slot 1 is 2; in every paragraph checked the two go together), 2 indent of the -/// lines after the first, 3 right indent, 4 indent of the first line, 5 space before, 6 space -/// after. Slots 2, 4, 5 and 6 were identified on the public MIT text-indent and text-para-spacing -/// fixtures (Patchy) by measuring their thumbnails, slot 1 by measuring the baseline pitch in the -/// thumbnail of a document whose owner made it earlier. -fn paragraph(r: &mut Reader, p: ObjId) -> Paragraph { - let doubles = r.s.field(p, b"Doub"); - let ints = r.s.field(p, b"Ints"); - let at = |i: usize| slot(doubles, i, float).filter(|v| v.abs() < 1e6).unwrap_or(0.0); - let align = match slot(ints, 0, int) { - Some(1) => Align::Center, - Some(2) => Align::Right, - Some(3) => Align::Justify, - Some(0) | None => Align::Left, - Some(_) => { - r.warn("an unknown paragraph alignment (imported as left)"); - Align::Left - } - }; - let leading = match slot(ints, 1, int) { - Some(2) => Some(at(1)).filter(|l| *l > 0.0), - Some(0) | None => None, - Some(_) => { - r.warn("paragraph leading of an unknown kind (imported as automatic)"); - None - } - }; - let auto_leading = slot(doubles, 0, float).filter(|v| *v > 0.0 && *v < 100.0).unwrap_or(1.0); - Paragraph { align, left: at(2), right: at(3), first: at(4), space_before: at(5).max(0.0), space_after: at(6).max(0.0), leading, auto_leading } -} - -/// The scale a text frame or table gives its type (`FTxS`, stored like `Xfrm`): none unless set. -/// Neither the frame's own transform nor its groups' scale its type (checked against the -/// thumbnails of tables and frames inside scaled groups). -fn text_scale(r: &mut Reader, id: ObjId) -> Affine { - match r.s.floats::<6>(id, b"FTxS").map(Affine::from_xfrm) { - Some(m) if m.is_finite() && m.scale() > 1e-9 => Affine([m.0[0], m.0[1], m.0[2], m.0[3], 0.0, 0.0]), - Some(_) => { - r.warn("text frames with an invalid text scale (imported unscaled)"); - Affine::IDENTITY - } - None => Affine::IDENTITY, - } -} diff --git a/crates/affinity/tests/it/outline_limits.rs b/crates/affinity/tests/it/outline_limits.rs index 74151c192f..15e08eb6be 100644 --- a/crates/affinity/tests/it/outline_limits.rs +++ b/crates/affinity/tests/it/outline_limits.rs @@ -20,6 +20,10 @@ fn shape(id: u32, class: &[u8; 4], parameters: Vec<(vectorcraft_affinity::stream } fn read(definitions: Vec, top: u32) -> Document { + try_read(definitions, top).unwrap() +} + +fn try_read(definitions: Vec, top: u32) -> Result { let data = synth::stream(&[ (tag(b"Defs"), F::Shared(definitions)), ( @@ -39,7 +43,7 @@ fn read(definitions: Vec, top: u32) -> Document { ), ]); let bytes = synth::container(&[("doc.dat", &data, Method::Zlib)], None); - vectorcraft_affinity::read(&bytes, Limits::default()).unwrap() + vectorcraft_affinity::read(&bytes, Limits::default()) } fn path(document: &Document) -> &Path { @@ -200,3 +204,79 @@ fn unlocked_rectangle_corners_keep_their_own_radius_and_type() { assert_eq!(sub.segments.len(), 8); assert_eq!(sub.segments[3][2], p(5.0, 20.0)); } + +/// The special shapes come in as their own outlines: one closed contour of finite points inside +/// (or, for a callout's tail, just below) the node's box, and none as the bounding ellipse. +#[test] +fn special_shapes_have_their_own_closed_outlines() { + for class in [b"ShCl", b"ShHt", b"ShCg", b"ShCR", b"ShCE", b"ShDA", b"ShDS", b"ShTr", b"ShCr", b"ShpD", b"ShSg"] { + let name = String::from_utf8_lossy(class).into_owned(); + let document = read(vec![shape(100, class, vec![])], 100); + assert!(!document.warnings.iter().any(|w| w.contains("bounding ellipse")), "{name}: {:?}", document.warnings); + let (Kind::Shape { path, even_odd, .. }, cog) = (&document.spreads[0].nodes[0].kind, class == b"ShCg") else { panic!("{name}: no shape") }; + // A cog is its teeth and its hole, filled even-odd. + assert_eq!((path.subpaths.len(), *even_odd), if cog { (2, true) } else { (1, false) }, "{name}"); + for sub in &path.subpaths { + assert!(sub.closed && sub.segments.len() >= 2, "{name}"); + for p in std::iter::once(sub.start).chain(sub.segments.iter().flatten().copied()) { + assert!(p.x.is_finite() && p.y.is_finite(), "{name}: {p:?}"); + assert!((-5.0..=15.0).contains(&p.x) && (-10.0..=30.0).contains(&p.y), "{name}: {p:?}"); + } + } + } + // A class the reader does not know is still its bounding ellipse, and said. + let document = read(vec![shape(100, b"ShZZ", vec![])], 100); + assert!(document.warnings.iter().any(|w| w.contains("unrecognized parametric shape")), "{:?}", document.warnings); +} + +fn group(id: u32, children: Vec) -> F { + F::Def(id, vec![tag(b"Grup")], vec![(tag(b"Chld"), F::Shared(children))]) +} + +/// A list's null slots yield no node, operand or segment, but each visit of a shared object scans +/// them all: they are charged to the document's work before the scan. +#[test] +fn null_slots_of_shared_lists_are_charged_for_every_visit() { + // A compound of a million null operands, placed 20 times: 20 million slots, over the 2^24. + let document = read(vec![compound(100, vec![F::Null; 1_000_000]), group(200, vec![F::Ref(100); 20])], 200); + assert!(document.warnings.iter().any(|w| w.contains("geometry work limit")), "{:?}", document.warnings); + let shapes = document.spreads[0].nodes[0].children.iter().filter(|n| matches!(n.kind, Kind::Shape { .. })).count(); + assert_eq!(shapes, 16, "each placement costs a million slots of the 2^24"); + // A group of a million null children, placed 20 times, fails the read like too many layers. + let result = try_read(vec![group(100, vec![F::Null; 1_000_000]), group(200, vec![F::Ref(100); 20])], 200); + assert!(matches!(result, Err(vectorcraft_affinity::Error::Limit(_))), "{:?}", result.map(|d| d.warnings)); + // Within the work of one document the same lists are read, nulls skipped. + let document = read(vec![group(100, vec![F::Null; 1_000]), group(200, vec![F::Ref(100); 20])], 200); + assert_eq!((document.spreads[0].nodes[0].children.len(), document.warnings.len()), (20, 0)); +} + +fn boxed(class: &[u8; 4], b: Vec) -> F { + F::Def(100, vec![tag(b"ShpN")], vec![(tag(b"ShpB"), F::F64s(b)), (tag(b"Shpe"), F::Def(10_100, vec![tag(class)], vec![]))]) +} + +/// A callout rectangle (`ShCR`) whose box runs right to left (x0 > x1) panicked in `f64::clamp` +/// (min > max), found by the `stream` fuzz target. It reads, inside its box. +#[test] +fn callout_rectangle_with_a_reversed_box_reads_inside_it() { + for b in [vec![10.0_f64, 0.0, 0.0, 20.0], vec![6.8e38, 0.0, 10.0, 20.0]] { + let (lo, hi) = (b[0].min(b[2]), b[0].max(b[2])); + let document = read(vec![boxed(b"ShCR", b)], 100); + let sub = &path(&document).subpaths[0]; + let points = std::iter::once(&sub.start).chain(sub.segments.iter().flatten()); + assert!(points.into_iter().all(|q| q.x.is_finite() && q.y.is_finite() && (lo..=hi).contains(&q.x)), "{sub:?}"); + } +} + +/// A box with finite corners whose width overflows gave infinite and NaN outline points. Such a +/// shape imports as its box, with a warning. +#[test] +fn a_shape_too_large_to_compute_imports_as_its_box() { + for class in [b"ShCR", b"ShpE", b"ShCg"] { + let document = read(vec![boxed(class, vec![f64::MAX, 0.0, -f64::MAX, 20.0])], 100); + let sub = &path(&document).subpaths; + assert_eq!(sub.len(), 1, "{class:?}"); + let corners: Vec = std::iter::once(sub[0].start).chain(sub[0].segments.iter().map(|s| s[2])).collect(); + assert!(corners.iter().all(|p| p.x.abs() == f64::MAX && (p.y == 0.0 || p.y == 20.0)), "{class:?}: {corners:?}"); + assert!(document.warnings.iter().any(|w| w.contains("too large to compute")), "{:?}", document.warnings); + } +} diff --git a/crates/affinity/tests/support/affinity3-signatures.txt b/crates/affinity/tests/support/affinity3-signatures.txt index 13e8f0c53a..79ed6df5ec 100644 --- a/crates/affinity/tests/support/affinity3-signatures.txt +++ b/crates/affinity/tests/support/affinity3-signatures.txt @@ -19,7 +19,7 @@ patchy-lazy-placed.af dpi=72;spreads=1;model_crc32=8776a8a0;counts={"depth": 1, patchy-live-filter.af dpi=72;spreads=1;model_crc32=12235fe9;counts={"depth": 2, "fills": 2, "gradients": 0, "nodes": 4, "segments": 6, "shapes": 2, "strokes": 0, "subpaths": 2, "unsupported": 2};boards=[];fonts={};warnings=["adjustment layers", "unknown layers"] patchy-rgba16.af dpi=72;spreads=1;model_crc32=688b2475;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] patchy-rgba8.af dpi=72;spreads=1;model_crc32=688b2475;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] -patchy-shapes-2.af dpi=72;spreads=1;model_crc32=886e9852;counts={"depth": 1, "fills": 12, "gradients": 0, "nodes": 12, "segments": 62, "shapes": 12, "strokes": 0, "subpaths": 12};boards=[];fonts={};warnings=["cloud, heart, cog, callout, arrow, tear and other special shapes (imported as their bounding ellipse) (9×)"] +patchy-shapes-2.af dpi=72;spreads=1;model_crc32=6f174318;counts={"depth": 1, "fills": 12, "gradients": 0, "nodes": 12, "segments": 168, "shapes": 12, "strokes": 0, "subpaths": 13};boards=[];fonts={};warnings=[] patchy-shapes.af dpi=72;spreads=1;model_crc32=c1790e97;counts={"depth": 1, "fills": 4, "gradients": 0, "nodes": 4, "segments": 28, "shapes": 4, "strokes": 0, "subpaths": 4};boards=[];fonts={};warnings=[] patchy-text-artistic.af dpi=72;spreads=1;model_crc32=1d33192c;counts={"depth": 1, "nodes": 1, "text_chars": 5, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialMT:400:false"};warnings=[] patchy-text-caps.af dpi=72;spreads=1;model_crc32=24e52518;counts={"depth": 1, "nodes": 2, "text_chars": 21, "text_runs": 2, "texts": 2};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font) (2×)"] diff --git a/crates/apischema/src/lib.rs b/crates/apischema/src/lib.rs index 5db24230e1..cff749e84f 100644 --- a/crates/apischema/src/lib.rs +++ b/crates/apischema/src/lib.rs @@ -250,7 +250,8 @@ impl ParamSchema { /// What is wrong with the schema itself, or `None`: a parameter name that is empty, repeated /// or holds `.`, `[` or `]`; a required parameter with a default; a default that isn't JSON or /// doesn't pass its parameter's type; an enum with no names or a repeated name; a range with - /// an end that isn't finite or that no value can be in; nesting past [`MAX_DEPTH`]. + /// an end that isn't finite or that no value can be in; nesting past [`MAX_DEPTH`], or a + /// [`Type::Ids`] or [`Type::Point`], whose values are all lists, at the nesting limit. pub fn definition_problem(&self) -> Option { object_problem("", self.params, 0) } @@ -319,7 +320,9 @@ pub enum Problem { Missing, /// The value is not of the parameter's type: `expected` says what it must be. WrongType { expected: String, got: String }, - /// The schema nests deeper than [`MAX_DEPTH`] here ([`ParamSchema::definition_problem`]). + /// The value nests deeper than [`MAX_DEPTH`] here: a list given for a [`Type::Color`] at the + /// nesting limit, or any value under a schema that nests too deeply itself + /// ([`ParamSchema::definition_problem`]). TooDeep, } @@ -779,6 +782,8 @@ fn type_problem(at: &str, ty: &Type, depth: usize) -> Option { Type::Object(params) => object_problem(at, params, depth + 1), Type::Array(_) if depth >= MAX_DEPTH => Some(format!("`{at}` nests deeper than {MAX_DEPTH} levels")), Type::Array(item) => type_problem(&format!("{at}[]"), item, depth + 1), + // Every value of these is a list, and a list at the nesting limit is refused. + Type::Ids | Type::Point if depth >= MAX_DEPTH => Some(format!("`{at}` nests deeper than {MAX_DEPTH} levels")), _ => None, } } diff --git a/crates/apischema/src/tests.rs b/crates/apischema/src/tests.rs index 30b939879a..4b8d51d8b0 100644 --- a/crates/apischema/src/tests.rs +++ b/crates/apischema/src/tests.rs @@ -156,6 +156,36 @@ fn id_lists_points_and_color_lists_count_toward_the_nesting_limit() { assert!(check(MAX_DEPTH, &Type::Color, &json!("#ff0000")).is_ok()); } +/// `ty` inside `levels` lists. +fn in_lists(levels: usize, ty: Type) -> Type { + (0..levels).fold(ty, |inner, _| Type::Array(Box::leak(Box::new(inner)))) +} + +/// `v` inside `levels` lists. +fn wrapped(levels: usize, v: Value) -> Value { + (0..levels).fold(v, |inner, _| Value::Array(vec![inner])) +} + +/// The schema check and the value check agree on the fixed-shape lists at the nesting limit: an id +/// list or a point there could take no value, so the schema is wrong in itself, and a color there +/// takes a string, while a color list is refused as nested too deeply, at its path. +#[test] +fn fixed_shape_lists_at_the_nesting_limit_follow_the_schema_check() { + for ty in [Type::Ids, Type::Point, Type::Color] { + assert_eq!(one(in_lists(MAX_DEPTH - 1, ty)).definition_problem(), None, "{ty:?}"); + } + for ty in [Type::Ids, Type::Point] { + let problem = one(in_lists(MAX_DEPTH, ty)).definition_problem(); + assert!(problem.as_deref().is_some_and(|p| p.contains("nests deeper")), "{ty:?}: {problem:?}"); + } + let color = one(in_lists(MAX_DEPTH, Type::Color)); + assert_eq!(color.definition_problem(), None); + assert_eq!(color.validate(&json!({"x": wrapped(MAX_DEPTH, json!("#ff0000"))})).unwrap(), None); + let e = color.validate(&json!({"x": wrapped(MAX_DEPTH, json!([1, 0, 0]))})).unwrap_err(); + assert_eq!(e.problem, Problem::TooDeep); + assert_eq!(e.path, format!("x{}", "[0]".repeat(MAX_DEPTH))); +} + #[test] fn a_saved_retired_key_past_the_nesting_limit_is_refused() { let params = holding("older", nested_lists(500_000)); diff --git a/crates/brush/src/lib.rs b/crates/brush/src/lib.rs index 448b2c2ba0..f25615c589 100644 --- a/crates/brush/src/lib.rs +++ b/crates/brush/src/lib.rs @@ -370,11 +370,14 @@ pub struct ArtBrush { pub scale: ArtScale, /// Width in percent. pub width: f64, - /// How the width varies along a stroke: `None` (Fixed) always `width`; Pressure goes from - /// `width` at the lightest pen pressure to [`Self::width_max`] at the heaviest. + /// How the width varies along a stroke: `None` (Fixed) always `width`; a mode that follows the + /// pen goes from `width` to [`Self::width_max`] over the ranges [`Variation`] gives: Pressure + /// from the lightest pressure to the heaviest, Tilt from the pen lying flat to upright, Bearing + /// and Rotation from −180° to 180° (half way at 0°). #[serde(skip_serializing_if = "Option::is_none")] pub width_mode: Option, - /// The width at the heaviest pen pressure (%), for Pressure (`width` without one). + /// The second width (%) of a mode that follows the pen: at the heaviest pressure, upright, or + /// at 180° (`width` without one). #[serde(skip_serializing_if = "Option::is_none")] pub width_max: Option, pub flip_along: bool, @@ -388,11 +391,11 @@ impl ArtBrush { /// The range of the width (%). pub const WIDTH_RANGE: (f64, f64) = (1.0, 1000.0); - /// The widths (%) at the lightest and the heaviest pen pressure: `width` for both unless the - /// width follows the pressure. + /// The widths (%) where the pen reads 0 and 1 for the width's mode (the lightest and the + /// heaviest pressure, for Pressure): `width` for both unless the width follows the pen. pub fn width_range(&self) -> (f64, f64) { match self.width_mode { - Some(Variation::Pressure) => (self.width, self.width_max.unwrap_or(self.width)), + Some(m) if m.follows_pen() => (self.width, self.width_max.unwrap_or(self.width)), _ => (self.width, self.width), } } @@ -713,8 +716,8 @@ impl Brush { } BrushKind::Art(a) => { a.width = within(a.width, ArtBrush::WIDTH_RANGE, 100.0); - // The width follows the pen's pressure or stays fixed. - if a.width_mode != Some(Variation::Pressure) { + // The width follows the pen (its pressure, tilt, bearing or rotation) or stays fixed. + if !a.width_mode.is_some_and(Variation::follows_pen) { a.width_mode = None; } a.width_max = a.width_max.map(|w| within(w, ArtBrush::WIDTH_RANGE, a.width)); @@ -806,7 +809,7 @@ pub fn stroke_pieces(doc: &Document, brush: &Brush, bp: &BezPath, stroke: &Strok let mut out = match &brush.kind { BrushKind::Calligraphic(c) => calli::calligraphic(c, bp, w, stroke, &brush.name), BrushKind::Bristle(b) => calli::bristle(b, bp, w, &stroke.paint, &brush.name), - BrushKind::Art(a) => warp::art(a, bp, w, stroke.pressure.as_ref()), + BrushKind::Art(a) => warp::art(a, bp, w, stroke), BrushKind::Scatter(s) => warp::scatter(s, bp, w, stroke, &brush.name), BrushKind::Pattern(p) => warp::pattern(p, bp, w), }; diff --git a/crates/brush/src/tests.rs b/crates/brush/src/tests.rs index 11c83d97bc..affd2fa6b7 100644 --- a/crates/brush/src/tests.rs +++ b/crates/brush/src/tests.rs @@ -1371,6 +1371,62 @@ fn art_brush_width_follows_the_pressure() { assert!(plain.get("width_mode").is_none() && plain.get("width_max").is_none(), "{plain}"); } +/// Art Brush Options: Width on Tilt goes from Width with the pen lying flat to the second width +/// upright, and on Bearing or Rotation from Width at −180° to the second width at 180°, along the +/// stroke as the pen recorded it; each mode reads only its own input. +#[test] +fn art_brush_width_follows_tilt_bearing_and_rotation() { + let brush = |mode: Variation| { + let mut b = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch); + if let BrushKind::Art(a) = &mut b.kind { + (a.width, a.width_mode, a.width_max) = (50.0, Some(mode), Some(300.0)); + } + b + }; + let bp = line(0.0, 0.0, 100.0, 0.0); + let draw = |b: &Brush, st: &StrokeLayer| stroke_pieces(&Document::new(1.0, 1.0), b, &bp, st); + // Tilt, upright at the start (300 %: 6 pt either side of 4 pt art) to flat at the end (50 %: 1 pt). + let upright_to_flat = StrokeLayer { tilt: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, 0.0), (1.0, 1.0)] }), ..stroke(1.0) }; + let out = draw(&brush(Variation::Tilt), &upright_to_flat); + assert!(near(half_width(&out, 0.0, 1.0), 6.0, 0.1), "{}", half_width(&out, 0.0, 1.0)); + assert!(near(half_width(&out, 99.0, 100.0), 1.0, 0.1), "{}", half_width(&out, 99.0, 100.0)); + assert!(near(half_width(&out, 49.0, 51.0), 3.5, 0.15), "{}", half_width(&out, 49.0, 51.0)); + // Bearing and Rotation: half way at 0°, a quarter of the way at −90°, three quarters at 90°. + for (mode, angle, half) in [ + (Variation::Bearing, 0.0, 3.5), + (Variation::Bearing, -90.0, 2.25), + (Variation::Bearing, 90.0, 4.75), + (Variation::Rotation, -90.0, 2.25), + (Variation::Rotation, 90.0, 4.75), + ] { + let st = if mode == Variation::Bearing { posed(Some(0.5), Some(angle), None) } else { posed(None, None, Some(angle)) }; + let h = bounds(&draw(&brush(mode), &st)).height(); + assert!(near(h, 2.0 * half, 1e-6), "{mode:?} {angle}: {h}"); + } + // Each mode reads its own input: without it (the pressure, or another of the pen's values + // recorded instead), the art is half way between the two widths. + let others = [ + (Variation::Tilt, posed(None, Some(90.0), Some(90.0))), + (Variation::Tilt, pressed(vec![(0.0, 0.0), (1.0, 1.0)])), + (Variation::Bearing, posed(Some(0.0), None, Some(90.0))), + (Variation::Rotation, posed(Some(0.0), Some(90.0), None)), + (Variation::Pressure, posed(Some(0.0), Some(90.0), Some(90.0))), + ]; + for (mode, st) in others { + let h = bounds(&draw(&brush(mode), &st)).height(); + assert!(near(h, 7.0, 1e-6), "{mode:?}: {h}"); + } + // The pen's modes are kept when a definition is read, and Random is read as Fixed. + let lib = parse_library(&serde_json::json!([ + {"name": "t", "type": "art", "art": rect_art(10.0, 4.0), "width_mode": "tilt", "width_max": 300.0}, + {"name": "b", "type": "art", "art": rect_art(10.0, 4.0), "width_mode": "bearing", "width_max": 300.0}, + {"name": "r", "type": "art", "art": rect_art(10.0, 4.0), "width_mode": "rotation", "width_max": 300.0}, + {"name": "x", "type": "art", "art": rect_art(10.0, 4.0), "width_mode": "random", "width_max": 300.0}, + ])); + let modes: Vec<_> = lib.iter().map(|b| if let BrushKind::Art(a) = &b.kind { a.width_mode } else { None }).collect(); + assert_eq!(modes, [Some(Variation::Tilt), Some(Variation::Bearing), Some(Variation::Rotation), None]); +} + /// Definitions from files and commands are kept within their ranges. #[test] fn sanitize_keeps_values_within_their_ranges() { diff --git a/crates/brush/src/warp.rs b/crates/brush/src/warp.rs index b34a1cf31e..c72e1c33f8 100644 --- a/crates/brush/src/warp.rs +++ b/crates/brush/src/warp.rs @@ -8,7 +8,7 @@ use std::sync::Arc; use kurbo::ParamCurveNearest; -use vectorcraft_doc::{Appearance, Node, NodeId, NodeKind, PressureProfile, StrokeLayer}; +use vectorcraft_doc::{Appearance, Node, NodeId, NodeKind, StrokeLayer}; use vectorcraft_geom::{Affine, BezPath, CubicBez, ParamCurve, PathData, PathEl, Point, Rect, SubPath, Vec2}; use crate::track::{Rng, Track, normal, seed_of, tracks}; @@ -503,9 +503,10 @@ fn art_on_run( bend_widened(t, art, b, along, cross, widen) } -/// An art brush's art along `bp`. With a width that follows the pen's pressure, the art is as -/// wide as the pressure recorded at each point of the stroke gives (half way without a recording). -pub(crate) fn art(a: &ArtBrush, bp: &BezPath, weight: f64, pressure: Option<&PressureProfile>) -> Vec { +/// An art brush's art along `bp`. With a width that follows the pen (its pressure, tilt, bearing +/// or rotation), the art is as wide as what `stroke` recorded at each point gives (half way +/// without a recording). +pub(crate) fn art(a: &ArtBrush, bp: &BezPath, weight: f64, stroke: &StrokeLayer) -> Vec { let Some((art, b)) = oriented(&a.art, a.direction, a.flip_along, a.flip_across) else { return vec![] }; let (light, heavy) = a.width_range(); let width = light.max(heavy); @@ -522,7 +523,7 @@ pub(crate) fn art(a: &ArtBrush, bp: &BezPath, weight: f64, pressure: Option<&Pre } // A run past the start of a closed track wraps round to it. let at = if s > l { s - l } else { s }; - let p = pressure.map_or(PressureProfile::MID, |p| p.at(at / l)).clamp(0.0, 1.0); + let p = a.width_mode.and_then(|m| PenAt::of(stroke, at / l).control(m)).unwrap_or(0.5); (light + (heavy - light) * p) / width }; let runs = if a.overlap { art_runs(&t) } else { vec![(0.0, l)] }; diff --git a/crates/cad/Cargo.toml b/crates/cad/Cargo.toml index 2ea6dea4fb..34f77ec929 100644 --- a/crates/cad/Cargo.toml +++ b/crates/cad/Cargo.toml @@ -3,7 +3,7 @@ name = "vectorcraft-cad" version.workspace = true edition.workspace = true license.workspace = true -description = "VectorCraft CAD interchange: a hand-written ASCII DXF writer (R12 to 2018)" +description = "VectorCraft CAD interchange: a hand-written ASCII DXF writer (R12 to 2018) and an HP-GL/2 plot file reader and writer" [lints] workspace = true diff --git a/crates/cad/src/hpgl.rs b/crates/cad/src/hpgl.rs new file mode 100644 index 0000000000..9494fbee46 --- /dev/null +++ b/crates/cad/src/hpgl.rs @@ -0,0 +1,202 @@ +//! HP-GL import: a plotter file (HP-GL/2, `.plt`, `.hpgl`, `.hgl`, `.hpg`) as a document. Older +//! HP-GL files are read by the HP-GL/2 rules for the instructions the two share. +//! +//! The pen's moves become paths: each run drawn with the pen down is one stroked path in the +//! selected pen's color and width (0.35 mm unless PW sets another), with the line type as a dash +//! pattern and the line attributes as caps and joins. Circles, arcs, wedges, rectangles and Bézier +//! curves are drawn as curves (the chord angle isn't used). Filled rectangles, wedges and polygons +//! (polygon mode, FP) become filled paths, edged ones stroked paths. Plotter units (1016 to the +//! inch, y up) become points, through user units (SC, IP, IR) and the rotation (RO). The artboard +//! is the bounds of what the art paints, its strokes included. +//! +//! VectorCraft's own rules where the device decides: before the first SP the pen is pen 1 (a +//! device draws nothing until SP), and the hard-clip limits are 11 × 8.5 in from the origin, so +//! P2 lies there when the file sets no scaling points. SP0 draws nothing. Labels, symbol mode's symbols and raster +//! images (HP RTL) aren't drawn, the input window doesn't clip, hatched fills are filled solid, +//! and the art of every page goes on one artboard; each comes back as a warning. Printer escape +//! sequences and PJL lines around the instructions are skipped. +//! +//! [`export`] writes the visible art over a region as an HP-GL or HP-GL/2 plot, and +//! [`export_regions`] one plot per region with one pen numbering: see [`write`]. +//! +//! - `lex`: the bytes as instructions, numbers, labels and PE data. +//! - `plot`: the instructions played on the pen, as shapes. +//! - `write`: the writer, paths to pen moves. + +mod lex; +mod plot; +pub mod write; + +pub use write::{HpglOptions, HpglOutput, Origin, Version, export, export_regions}; + +use std::sync::Arc; + +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, AppearanceItem, Dash, Document, FillLayer, LayerColor, Node, NodeId, NodeKind, StrokeLayer}; +use vectorcraft_geom::{Affine, PathData, Rect}; + +use crate::Imported; +use lex::Lexer; +use plot::Plot; + +/// Points per plotter unit. +const PT_PER_PLU: f64 = 72.0 / 1016.0; +/// The weight of a zero-width pen (one device dot), in points. +const THINNEST: f64 = 0.25; + +/// Instructions the reader knows and draws nothing for (their parameters are read and dropped). +const IGNORED: &[[u8; 2]] = &[ + *b"AC", *b"AD", *b"AF", *b"AH", *b"AP", *b"AS", *b"CA", *b"CF", *b"CM", *b"CP", *b"CS", *b"CT", *b"CV", *b"DC", *b"DI", *b"DL", *b"DP", *b"DR", + *b"DS", *b"DV", *b"EC", *b"ES", *b"FI", *b"FN", *b"FS", *b"GM", *b"IM", *b"IV", *b"KY", *b"LM", *b"LO", *b"MC", *b"MG", *b"MT", *b"NR", *b"OA", + *b"OC", *b"OD", *b"OE", *b"OF", *b"OG", *b"OH", *b"OI", *b"OL", *b"OP", *b"OS", *b"OT", *b"OW", *b"PB", *b"PP", *b"PS", *b"PT", *b"QL", *b"RF", + *b"RP", *b"SA", *b"SB", *b"SD", *b"SG", *b"SI", *b"SL", *b"SR", *b"SS", *b"ST", *b"SV", *b"TD", *b"TL", *b"TR", *b"UC", *b"VA", *b"VN", *b"VS", + *b"XT", *b"YT", +]; + +/// Instructions the reader plays. +const PLAYED: &[[u8; 2]] = &[ + *b"AA", *b"AR", *b"AT", *b"BL", *b"BP", *b"BR", *b"BZ", *b"CI", *b"CO", *b"CR", *b"DF", *b"DT", *b"EA", *b"EP", *b"ER", *b"EW", *b"FP", *b"FR", + *b"FT", *b"IN", *b"IP", *b"IR", *b"IW", *b"LA", *b"LB", *b"LT", *b"NP", *b"PA", *b"PC", *b"PD", *b"PE", *b"PG", *b"PM", *b"PR", *b"PU", *b"PW", + *b"RA", *b"RO", *b"RR", *b"RT", *b"SC", *b"SM", *b"SP", *b"UL", *b"WD", *b"WG", *b"WU", +]; + +/// Instructions a plot file starts with. +const FIRST: &[[u8; 2]] = &[ + *b"IN", *b"DF", *b"BP", *b"CO", *b"PS", *b"SP", *b"PU", *b"PD", *b"PA", *b"PR", *b"IP", *b"IR", *b"SC", *b"NP", *b"PC", *b"PW", *b"WU", *b"RO", + *b"QL", *b"MC", *b"PP", *b"TR", *b"CR", *b"LT", *b"LA", *b"FT", *b"VS", *b"FS", *b"AC", *b"PG", *b"PE", *b"DT", +]; + +/// Does `bytes` start like an HP-GL file? After any printer escapes and PJL lines (however long), +/// it must hold nothing but instructions the reader knows, the first one of those a plot file +/// starts with, up to the eighth instruction or 4 KB past the first. Their parameters must be +/// numbers, but for a comment's quoted string and the text, characters and encoded data of LB, BL, +/// WD, DT, SM and PE. An instruction the reader doesn't know counts when its numbers end with a +/// semicolon. +pub fn is_hpgl(bytes: &[u8]) -> bool { + holds_instructions(bytes, true) +} + +/// Does `bytes` hold HP-GL instructions as [`is_hpgl`] checks? When `strict` is false, any of them +/// may come first: a file picked by its extension may start with one a plot file seldom starts +/// with (`SI`, `DI`). Either way, at least one of the instructions checked must be one the reader +/// knows. +fn holds_instructions(bytes: &[u8], strict: bool) -> bool { + let mut lex = Lexer::new(bytes); + let mut terminator = lex::ETX; + let mut first = 0; + let mut any_known = false; + for n in 0..8 { + if n > 0 && lex.pos() > first + 4096 { + return any_known; + } + let Some(op) = lex.op(true) else { return n > 0 && any_known && lex.done() }; + if n == 0 { + first = lex.pos(); + } + if strict && n == 0 && !FIRST.contains(&op) { + return false; + } + let known = PLAYED.contains(&op) || IGNORED.contains(&op); + any_known |= known; + match &op { + b"CO" => { + if !lex.comment() { + return false; + } + } + b"LB" | b"BL" | b"WD" => lex.label(terminator), + b"DT" => { + terminator = lex.char().unwrap_or(lex::ETX); + lex.params(); + } + b"SM" => { + // The symbol character is read so it isn't taken for an instruction. + let _ = lex.char(); + } + b"PE" => lex.skip_pe(), + _ if known => lex.params(), + // An instruction the reader doesn't know (of an older or a device's own set) counts + // when numbers and a semicolon follow it. + _ => { + if !lex.closed_params() { + return false; + } + } + } + } + any_known +} + +/// Read an HP-GL file. It may start with any instruction the reader knows, or one of another set +/// that a semicolon ends; the rest of [`is_hpgl`]'s check applies, and at least one instruction the +/// reader knows must be among those it checks. +pub fn import(bytes: &[u8]) -> Result { + if !holds_instructions(bytes, false) { + return Err("not an HP-GL file".into()); + } + let mut lex = Lexer::new(bytes); + let mut plot = Plot::new(); + while !plot.full + && let Some(op) = lex.op(false) + { + plot.op(op, &mut lex); + } + Ok(build(plot.finish(lex.raster))) +} + +fn rgb(c: [u8; 3]) -> Paint { + Paint::solid(Color::rgb8(c[0], c[1], c[2])) +} + +/// The plot's shapes as paths on one layer, the artboard round what they paint. +fn build(plot: Plot) -> Imported { + // Plotter units, y up, to points, y down. + let flip = Affine::scale_non_uniform(PT_PER_PLU, -PT_PER_PLU); + let mut nodes: Vec = plot.shapes.iter().map(|s| node(s, flip)).collect(); + // The strokes' caps and miter joins included. + let finite = |r: &Rect| [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()); + let frame = nodes.iter().filter_map(Node::visual_bounds).filter(finite).reduce(|a, b| a.union(b)).unwrap_or(Rect::new(0.0, 0.0, 612.0, 792.0)); + let mut doc = Document::new(frame.width().max(1.0), frame.height().max(1.0)); + doc.layers.clear(); + let shift = Affine::translate(-frame.origin().to_vec2()); + for n in &mut nodes { + n.id = doc.alloc_id(); + if let NodeKind::Path { path, .. } = &mut n.kind { + path.transform(shift); + } + } + let mut layer = Node::layer(doc.alloc_id(), "Layer 1", LayerColor::Preset(0)); + if let Some(c) = layer.children_mut() { + *c = nodes.into_iter().map(Arc::new).collect(); + } + doc.layers = vec![Arc::new(layer)]; + Imported { document: doc, warnings: plot.warnings } +} + +/// A shape as a path, its plotter units through `to_points`. +fn node(s: &plot::Shape, to_points: Affine) -> Node { + let mut path = s.path.clone(); + path.apply_affine(to_points); + let mut items = vec![]; + if let Some((c, _)) = s.fill { + items.push(AppearanceItem::Fill(FillLayer::new(rgb(c)))); + } + if let Some(st) = &s.stroke { + let mut layer = StrokeLayer::new(rgb(st.color), (st.width * PT_PER_PLU).max(THINNEST)); + (layer.cap, layer.join, layer.miter_limit) = (st.cap, st.join, st.miter); + layer.dash = st.dash.as_ref().map(|d| Dash { + pattern: d.pattern.iter().map(|v| v * PT_PER_PLU).collect(), + offset: d.offset * PT_PER_PLU, + align_corners: d.adaptive, + }); + items.push(AppearanceItem::Stroke(layer)); + } + let mut n = Node::path(NodeId(0), PathData::from_bezpath(&path), Appearance { items, ..Appearance::default() }); + if let (NodeKind::Path { rule, .. }, Some((_, r))) = (&mut n.kind, s.fill) { + *rule = r; + } + n +} + +#[cfg(test)] +mod tests; diff --git a/crates/cad/src/hpgl/lex.rs b/crates/cad/src/hpgl/lex.rs new file mode 100644 index 0000000000..5025d07c6f --- /dev/null +++ b/crates/cad/src/hpgl/lex.rs @@ -0,0 +1,428 @@ +//! The bytes of an HP-GL file as instructions: two-letter mnemonics and the parameters that follow +//! them, read one at a time as the plot asks for them. Printer escape sequences (PCL, HP RTL, the +//! HP-GL device-control escapes) and PJL lines around and between the instructions are skipped, +//! with the data their escapes carry. + +/// The end-of-text character, the default label terminator. +pub(super) const ETX: u8 = 3; +const ESC: u8 = 0x1b; + +/// The most digits of a number that count: longer ones are read as their first digits. +const MAX_DIGITS: usize = 18; + +/// What the bytes being read hold. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Mode { + /// HP-GL instructions. + Hpgl, + /// PCL or HP RTL: escape sequences and their data, nothing to draw. + Pcl, + /// After a Universal Exit Language: PJL lines until a language starts. + Pjl, +} + +/// One item of a PE (Polyline Encoded) instruction. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) enum PeItem { + /// Select pen. + Pen(i64), + /// Rectangle mode: the following coordinates come in fours. + Rect, + /// A coordinate pair, after a pen-up flag (`up`) and an absolute flag (`absolute`). + Point { x: f64, y: f64, up: bool, absolute: bool }, +} + +/// The state of one PE instruction being read. +#[derive(Clone, Copy, Debug, Default)] +pub(super) struct Pe { + seven_bit: bool, + fraction_bits: u32, + up: bool, + absolute: bool, +} + +pub(super) struct Lexer<'a> { + b: &'a [u8], + at: usize, + mode: Mode, + /// The file holds HP RTL or PCL raster image data. + pub raster: bool, +} + +/// Is `c` a byte that separates numeric parameters (or white space between instructions)? +fn separator(c: u8) -> bool { + matches!(c, b' ' | b',' | b'\t' | b'\r' | b'\n' | 0) +} + +impl<'a> Lexer<'a> { + pub fn new(b: &'a [u8]) -> Self { + Self { b, at: 0, mode: Mode::Hpgl, raster: false } + } + + fn peek(&self) -> Option { + self.b.get(self.at).copied() + } + + /// Whether everything has been read. + pub fn done(&self) -> bool { + self.at >= self.b.len() + } + + /// How many bytes have been read. + pub fn pos(&self) -> usize { + self.at + } + + /// The next instruction's mnemonic, in upper case; `strict`: only white space, semicolons and + /// escape sequences may come before it (anything else gives `None`, as the end does). + pub fn op(&mut self, strict: bool) -> Option<[u8; 2]> { + loop { + let c = self.peek()?; + if c == ESC { + self.escape(); + continue; + } + match self.mode { + Mode::Pcl => { + self.at += 1; + continue; + } + Mode::Pjl => { + if separator(c) { + self.at += 1; + } else if c == b'@' { + self.pjl_line(); + } else { + self.mode = Mode::Hpgl; + } + continue; + } + Mode::Hpgl => {} + } + let next = self.b.get(self.at + 1).copied(); + if c.is_ascii_alphabetic() + && let Some(n) = next.filter(u8::is_ascii_alphabetic) + { + self.at += 2; + return Some([c.to_ascii_uppercase(), n.to_ascii_uppercase()]); + } + if strict && !(separator(c) || c == b';' || c < 0x20) { + return None; + } + self.at += 1; + } + } + + /// One `@PJL` line: an `ENTER LANGUAGE` command picks what follows. + fn pjl_line(&mut self) { + let rest = &self.b[self.at..]; + let end = rest.iter().position(|&c| c == b'\n').map_or(rest.len(), |n| n + 1); + // A command names its language within its first 256 bytes; longer lines aren't copied. + let line = String::from_utf8_lossy(&rest[..end.min(256)]).to_ascii_uppercase(); + if let Some(lang) = line.split_once("LANGUAGE").map(|(_, l)| l.trim_start_matches([' ', '=']).trim()) { + self.mode = if lang.starts_with("HPGL") { Mode::Hpgl } else { Mode::Pcl }; + } + self.at += end; + } + + /// An escape sequence at the current byte, with the data it carries. + fn escape(&mut self) { + self.at += 1; + let Some(c) = self.peek() else { return }; + self.at += 1; + match c { + // Universal Exit Language (`ESC%-12345X`) and the language switches (`ESC%#B` to HP-GL, + // `ESC%#A` to PCL or HP RTL). + b'%' => { + let (_, end) = self.value(); + match end { + Some(b'X') => self.mode = Mode::Pjl, + Some(b'B') => self.mode = Mode::Hpgl, + Some(b'A') => self.mode = Mode::Pcl, + _ => {} + } + } + // Reset: PCL follows, until a language switch. + b'E' => self.mode = Mode::Pcl, + // HP-GL device control: `ESC.` and a letter, with parameters up to a colon. + b'.' => { + let Some(kind) = self.peek() else { return }; + self.at += 1; + if !b"()YZBEJKLORUX".contains(&kind) { + let rest = &self.b[self.at..self.b.len().min(self.at + 80)]; + if let Some(n) = rest.iter().position(|&c| c == b':') + && rest[..n].iter().all(|c| c.is_ascii_digit() || matches!(c, b';' | b' ' | b',')) + { + self.at += n + 1; + } + } + } + // Parameterized PCL: a group character, then values each ending in a letter (upper case + // ends the sequence); `W`, `*b…V` (raster data by plane) and `&p…X` (transparent print + // data) are followed by that many bytes of data. Without a group character (`ESC(8U`, + // `ESC)0N`), one value and the letter ending it. + 0x21..=0x2f => { + let Some(group) = self.peek().filter(|g| (0x60..=0x7e).contains(g)) else { + self.value(); + return; + }; + self.at += 1; + loop { + let (v, end) = self.value(); + let Some(end) = end else { return }; + let upper = end.to_ascii_uppercase(); + if upper == b'W' || (c, group, upper) == (b'*', b'b', b'V') || (c, group, upper) == (b'&', b'p', b'X') { + let n = v.max(0.0).min((self.b.len() - self.at) as f64) as usize; + if (c, group) == (b'*', b'b') && n > 0 { + self.raster = true; + } + self.at += n; + } + if (c, group, end) == (b'*', b'r', b'A') { + self.raster = true; + } + if !end.is_ascii_lowercase() { + return; + } + } + } + // A two-character escape. + _ => {} + } + } + + /// A PCL value (`[+-]digits[.digits]`, any part missing) and the character that ends it; `None` + /// when that is not a letter or `@` (which is then left unread). + fn value(&mut self) -> (f64, Option) { + let v = self.number_here().unwrap_or(0.0); + match self.peek() { + Some(c) if c.is_ascii_alphabetic() || c == b'@' => { + self.at += 1; + (v, Some(c)) + } + _ => (v, None), + } + } + + /// A number starting at the current byte (`[+-]digits[.digits]`), `None` when it has no digit + /// (its sign and point are read all the same). + fn number_here(&mut self) -> Option { + let mut neg = false; + if let Some(c @ (b'+' | b'-')) = self.peek() { + neg = c == b'-'; + self.at += 1; + } + let (mut v, mut digits, mut scale) = (0.0f64, 0usize, 1.0f64); + let mut point = false; + while let Some(c) = self.peek() { + if c.is_ascii_digit() { + if digits < MAX_DIGITS { + if point { + scale /= 10.0; + v += f64::from(c - b'0') * scale; + } else { + v = v * 10.0 + f64::from(c - b'0'); + } + } else if !point { + // Past the digits that count, an integer part keeps its size. + v *= 10.0; + } + digits += 1; + } else if c == b'.' && !point { + point = true; + } else { + break; + } + self.at += 1; + } + let v = v.min(f64::MAX); + (digits > 0).then_some(if neg { -v } else { v }) + } + + /// The next numeric parameter of the instruction being read, or `None` at its end (a semicolon + /// ending it is read). + pub fn number(&mut self) -> Option { + loop { + let c = self.peek()?; + if separator(c) { + self.at += 1; + } else if c.is_ascii_digit() || matches!(c, b'+' | b'-' | b'.') { + if let Some(v) = self.number_here() { + return Some(v); + } + } else { + if c == b';' { + self.at += 1; + } + return None; + } + } + } + + /// Up to `out.len()` numeric parameters into `out` (the rest are read and dropped) → how many. + pub fn numbers(&mut self, out: &mut [f64]) -> usize { + let mut n = 0; + while let Some(v) = self.number() { + if let Some(slot) = out.get_mut(n) { + *slot = v; + } + n += 1; + } + n.min(out.len()) + } + + /// Read and drop the parameters of the instruction being read: numbers and quoted strings. + pub fn params(&mut self) { + loop { + while self.number().is_some() {} + if self.peek() != Some(b'"') { + return; + } + self.quoted(); + } + } + + /// Read and drop numeric parameters → whether a semicolon ended them (an instruction the reader + /// doesn't know, written out in full). + pub fn closed_params(&mut self) -> bool { + while self.number().is_some() {} + self.at > 0 && self.b.get(self.at - 1) == Some(&b';') + } + + /// A comment (CO): its quoted string or nothing, then the terminator or the end → whether it + /// is one. + pub fn comment(&mut self) -> bool { + while self.peek().is_some_and(separator) { + self.at += 1; + } + match self.peek() { + Some(b'"') => self.quoted(), + Some(b';') => { + self.at += 1; + true + } + None => true, + Some(_) => false, + } + } + + /// The text of a label, up to and including `terminator` (or the end). + pub fn label(&mut self, terminator: u8) { + let rest = &self.b[self.at..]; + self.at += rest.iter().position(|&c| c == terminator).map_or(rest.len(), |n| n + 1); + } + + /// A quoted string (CO): the parameters up to its closing quote, then the terminator → whether + /// there was one. + pub fn quoted(&mut self) -> bool { + while self.peek().is_some_and(separator) { + self.at += 1; + } + let found = self.peek() == Some(b'"'); + if found { + self.at += 1; + let rest = &self.b[self.at..]; + self.at += rest.iter().position(|&c| c == b'"').map_or(rest.len(), |n| n + 1); + } + if self.peek() == Some(b';') { + self.at += 1; + } + found + } + + /// The character right after the mnemonic (DT, SM), `None` when it is a semicolon or the end + /// (the semicolon is read). + pub fn char(&mut self) -> Option { + let c = self.peek()?; + self.at += 1; + (c != b';').then_some(c) + } + + /// The next item of a PE instruction, `None` at its end (its semicolon is read). + pub fn pe(&mut self, st: &mut Pe) -> Option { + loop { + let raw = self.peek()?; + let c = raw & 0x7f; + // Spaces, deletes, control characters and bytes 128 to 160 and 255 are ignored. + if raw <= 32 || raw == 127 || (128..=160).contains(&raw) || raw == 255 { + self.at += 1; + continue; + } + match c { + b';' => { + self.at += 1; + return None; + } + // Flags keep their meaning with the eighth bit set; digits are 63 and up (191 and up). + b':' | b'<' | b'>' | b'=' | b'7' | b'9' if raw < 63 || (0xb7..191).contains(&raw) => { + self.at += 1; + match c { + b':' => return self.pe_value(st).map(PeItem::Pen).or_else(|| self.end_pe()), + b'<' => st.up = true, + b'>' => match self.pe_value(st) { + Some(n) => st.fraction_bits = n.clamp(0, 52) as u32, + None => return self.end_pe(), + }, + b'=' => st.absolute = true, + b'7' => st.seven_bit = true, + _ => return Some(PeItem::Rect), + } + } + _ => { + let scale = 0.5f64.powi(st.fraction_bits as i32); + let (Some(x), Some(y)) = (self.pe_value(st), self.pe_value(st)) else { return self.end_pe() }; + let item = PeItem::Point { x: x as f64 * scale, y: y as f64 * scale, up: st.up, absolute: st.absolute }; + (st.up, st.absolute) = (false, false); + return Some(item); + } + } + } + } + + /// The rest of a PE instruction that can't be decoded: see [`Lexer::skip_pe`]. + fn end_pe(&mut self) -> Option { + self.skip_pe(); + None + } + + /// The data of a PE instruction, up to and including its semicolon, unread: its data is never + /// read as instructions. + pub fn skip_pe(&mut self) { + let rest = &self.b[self.at..]; + self.at += rest.iter().position(|&c| c == b';').map_or(rest.len(), |n| n + 1); + } + + /// One encoded PE number, `None` when the instruction ends inside it (or a byte that is no + /// digit comes first, which is read). + fn pe_value(&mut self, st: &Pe) -> Option { + let (base, low, high): (u64, std::ops::RangeInclusive, std::ops::RangeInclusive) = + if st.seven_bit { (32, 63..=94, 95..=126) } else { (64, 63..=126, 191..=254) }; + let (mut v, mut place) = (0u64, 1u64); + loop { + let raw = self.peek()?; + let c = if st.seven_bit { raw & 0x7f } else { raw }; + if raw <= 32 || raw == 127 || (128..=160).contains(&raw) || raw == 255 { + self.at += 1; + continue; + } + if c == b';' { + return None; + } + self.at += 1; + let (digit, last) = if low.contains(&c) { + (u64::from(c - 63), false) + } else if high.contains(&c) { + (u64::from(c - high.start()), true) + } else { + return None; + }; + v = v.saturating_add(digit.saturating_mul(place)); + place = place.saturating_mul(base); + if last { + // The low bit is the sign. + let n = i64::try_from(v >> 1).unwrap_or(i64::MAX); + return Some(if v & 1 == 1 { -n } else { n }); + } + } + } +} diff --git a/crates/cad/src/hpgl/plot.rs b/crates/cad/src/hpgl/plot.rs new file mode 100644 index 0000000000..2ee70da75c --- /dev/null +++ b/crates/cad/src/hpgl/plot.rs @@ -0,0 +1,1331 @@ +//! The HP-GL/2 instructions played on a model of the plotter: the coordinate system (scaling +//! points, user units, rotation), the pen (position, up or down, number, width, color), the line +//! and fill attributes and the polygon buffer. What the pen draws is collected as shapes in +//! rotated plotter units, y up. + +use std::collections::HashMap; + +use kurbo::{Affine, BezPath, PathEl, Point, Shape as _, Vec2}; +use vectorcraft_doc::{LineCap, LineJoin}; +use vectorcraft_geom::FillRule; + +use super::lex::{ETX, Lexer, Pe, PeItem}; + +/// Plotter units per millimeter (0.025 mm each). +pub(super) const PLU_PER_MM: f64 = 40.0; +/// The hard-clip limits taken for P1 and P2 when the file sets none (plotter units): 11 × 8.5 in. +pub(super) const HARD_CLIP: Point = Point::new(11176.0, 8636.0); +/// The pen width after IN, in millimeters. +const DEFAULT_WIDTH_MM: f64 = 0.35; +/// The default line pattern length, in percent of the P1-P2 diagonal. +const DEFAULT_PATTERN: f64 = 4.0; +/// How far from the origin art may lie (plotter units, twice the range the format defines). +pub(super) const LIMIT: f64 = 16_777_216.0; +/// The widest pen (plotter units): 409.6 mm, the least a device must take before it draws its own +/// widest pen instead. +const MAX_WIDTH: f64 = 16_384.0; +/// The most objects an import makes. +const MAX_SHAPES: usize = 1 << 20; +/// The most path elements an import makes. +const MAX_ELEMENTS: usize = if cfg!(test) { 200_000 } else { 4_000_000 }; +/// The most pens a palette holds. +const MAX_PENS: i64 = 32_768; + +pub(super) const LABELS: &str = "labels were left out"; +pub(super) const SYMBOLS: &str = "symbols drawn at plotted points (symbol mode) were left out"; +pub(super) const RASTER: &str = "raster images in the file were left out"; +pub(super) const HATCHES: &str = "hatched and patterned fills are filled solid"; +pub(super) const WINDOW: &str = "the input window doesn't clip the art"; +pub(super) const PAGES: &str = "the art of later pages is drawn over the first page"; +pub(super) const FAR_AWAY: &str = "objects far outside the drawing were left out"; +pub(super) const TOO_MANY: &str = "the file has more than 1,048,576 objects: the rest are left out"; +pub(super) const TOO_MANY_POINTS: &str = "the file has more than 4,000,000 path points: the rest are left out"; + +/// The instructions polygon mode plays (the others are ignored there). +const POLYGON_MODE: &[[u8; 2]] = + &[*b"AA", *b"AR", *b"AT", *b"BP", *b"BR", *b"BZ", *b"CI", *b"CO", *b"DF", *b"IN", *b"PA", *b"PD", *b"PE", *b"PM", *b"PR", *b"PU", *b"RT"]; + +/// The colors of pens 0 to 7 until PC sets others. +const PALETTE: [[u8; 3]; 8] = [[255, 255, 255], [0, 0, 0], [255, 0, 0], [0, 255, 0], [255, 255, 0], [0, 0, 255], [255, 0, 255], [0, 255, 255]]; + +/// Line types 1 to 8: pen-down and pen-up lengths in percent of the pattern length. +const LINE_TYPES: [&[f64]; 8] = [ + &[0.0, 100.0], + &[50.0, 50.0], + &[70.0, 30.0], + &[80.0, 10.0, 0.0, 10.0], + &[70.0, 10.0, 10.0, 10.0], + &[50.0, 10.0, 10.0, 10.0, 10.0, 10.0], + &[70.0, 10.0, 0.0, 10.0, 0.0, 10.0], + &[50.0, 10.0, 0.0, 10.0, 10.0, 10.0, 0.0, 10.0], +]; + +/// A stroke as the pen draws it (lengths in plotter units). +#[derive(Clone, Debug, PartialEq)] +pub(super) struct Stroke { + pub color: [u8; 3], + pub width: f64, + pub cap: LineCap, + pub join: LineJoin, + pub miter: f64, + pub dash: Option, +} + +/// A line type as dashes (lengths in plotter units). +#[derive(Clone, Debug, PartialEq)] +pub(super) struct LinePattern { + /// Dash, gap, dash, gap…: an even number of lengths. + pub pattern: Vec, + /// How far into the pattern each line starts. + pub offset: f64, + /// The pattern stretches to fit each line, half its first dash at each end (adaptive line + /// types). + pub adaptive: bool, +} + +impl LinePattern { + /// The pattern of `percent` (pen-down and pen-up stretches, in turn, starting pen down) of + /// `length`. A pen-down stretch of zero is a dot, a vector one plotter unit long that the gap + /// after it gives up. An odd count repeats with its last pen-down stretch running into the + /// first one, which the pattern then starts within. + fn new(percent: &[f64], length: f64, adaptive: bool) -> Self { + let mut pattern: Vec = percent.iter().map(|p| p / 100.0 * length).collect(); + for pair in pattern.chunks_mut(2) { + if let [dash, rest @ ..] = pair + && *dash == 0.0 + { + *dash = 1.0; + if let Some(gap) = rest.first_mut() { + *gap = (*gap - 1.0).max(0.0); + } + } + } + let mut offset = 0.0; + if pattern.len() % 2 == 1 { + match pattern.len() { + // One pen-down stretch: a solid line. + 1 => pattern.push(0.0), + _ => { + let last = pattern.pop().unwrap_or(0.0); + if let Some(first) = pattern.first_mut() { + *first += last; + } + offset = last; + } + } + } + Self { pattern, offset, adaptive } + } +} + +/// What the plot draws: an outline with a fill, a stroke or both. +#[derive(Clone, Debug)] +pub(super) struct Shape { + pub path: BezPath, + pub fill: Option<([u8; 3], FillRule)>, + pub stroke: Option, +} + +/// A piece of a line the pen moves along, by its end. +#[derive(Clone, Copy, Debug)] +enum Piece { + Line(Point), + Curve(Point, Point, Point), +} + +impl Piece { + fn end(self) -> Point { + match self { + Self::Line(p) | Self::Curve(_, _, p) => p, + } + } + + fn push(self, bp: &mut BezPath) { + match self { + Self::Line(p) => bp.line_to(p), + Self::Curve(a, b, c) => bp.curve_to(a, b, c), + } + } +} + +/// User units: an SC instruction in force. +#[derive(Clone, Copy, Debug)] +enum Scaling { + /// The user ranges mapped onto P1 and P2; isotropic with the left and bottom percentages. + Fit { x0: f64, x1: f64, y0: f64, y1: f64, iso: Option<(f64, f64)> }, + /// P1's user coordinates and the plotter units per user unit. + Factor { x0: f64, fx: f64, y0: f64, fy: f64 }, +} + +/// How areas are filled. +#[derive(Clone, Copy, Debug, PartialEq)] +enum FillKind { + Solid, + /// The pen's color at this percentage, on white. + Shade(f64), + /// Hatching and patterns, filled solid. + Pattern, +} + +/// The polygon buffer: its outline for filling (every edge) and for edging (pen-down edges only). +#[derive(Clone, Debug, Default)] +struct Poly { + fill: BezPath, + edge: BezPath, + /// A subpolygon is open, from `start`; its last point. + open: bool, + start: Point, + last: Point, + /// The open subpolygon's points, and where its elements start in `fill` and `edge`. + points: usize, + marks: (usize, usize), + /// Where the edge outline ends (`None`: it has to move before drawing). + edge_at: Option, + /// After PM1 or a circle: the next move starts a subpolygon. + fresh: bool, +} + +impl Poly { + fn add(&mut self, a: Point, pieces: &[Piece], down: bool) { + let Some(end) = pieces.last().map(|p| p.end()) else { return }; + // The move after PM1 goes to the next subpolygon's first point with the pen up, whatever + // the pen's state (an arc's first chord aside): it is neither filled nor edged. + if std::mem::take(&mut self.fresh) && matches!(pieces, [Piece::Line(_)]) { + (self.start, self.last) = (end, end); + return; + } + if !self.open { + self.marks = (self.fill.elements().len(), self.edge.elements().len()); + self.fill.move_to(a); + (self.start, self.open, self.points) = (a, true, 1); + } + pieces.iter().for_each(|p| p.push(&mut self.fill)); + self.points += pieces.len(); + if down { + if self.edge_at != Some(a) { + self.edge.move_to(a); + } + pieces.iter().for_each(|p| p.push(&mut self.edge)); + self.edge_at = Some(end); + } else { + self.edge_at = None; + } + self.last = end; + } + + /// Close the open subpolygon, adding a point at its start when it ends elsewhere; the edge to + /// that point is drawn when `down`. A subpolygon of fewer than three points (that one + /// included) is neither filled nor edged. → The point added. + fn close(&mut self, down: bool) -> Option { + if !self.open { + return None; + } + let closure = self.last != self.start; + if self.points + usize::from(closure) < 3 { + self.fill.truncate(self.marks.0); + self.edge.truncate(self.marks.1); + } else { + if closure && down { + if self.edge_at != Some(self.last) { + self.edge.move_to(self.last); + } + self.edge.line_to(self.start); + } + self.fill.close_path(); + } + (self.open, self.edge_at) = (false, None); + closure.then_some(self.start) + } + + /// A closed outline of its own (a circle): the open subpolygon is closed with the pen up + /// first, and the next move starts a subpolygon. + fn closed(&mut self, path: &BezPath) { + self.close(false); + self.fill.extend(path.iter()); + self.edge.extend(path.iter()); + self.fresh = true; + } +} + +/// The line drawn so far with the pen down, not yet a shape. +struct Run { + path: BezPath, + stroke: Stroke, + start: Point, + end: Point, +} + +pub(super) struct Plot { + pub shapes: Vec, + pub warnings: Vec, + /// A budget ran out: nothing more is drawn. + pub full: bool, + elements: usize, + // The coordinate system. + p1: Point, + p2: Point, + scaling: Option, + /// User units to plotter units (identity when scaling is off). + user: Affine, + /// The RO rotation (rotated plotter units to where the art lies) and its angle. + rot: Affine, + ro: u16, + // The pen. + relative: bool, + down: bool, + /// The pen's position, in plotter units before rotation. + pos: Point, + /// The pen SP selected (`None`: none yet, which draws with pen 1). + pen: Option, + pens: i64, + colors: HashMap, + ranges: [(f64, f64); 3], + width: f64, + widths: HashMap, + relative_widths: bool, + // Line and fill attributes. + line_type: Option, + saved_line_type: Option, + pattern: f64, + pattern_mm: bool, + user_types: [Option>; 8], + cap: LineCap, + join: LineJoin, + miter: f64, + fill: FillKind, + // Polygons. + poly: Option, + buffer: Option, + run: Option, + terminator: u8, + /// Instructions of kinds the reader doesn't know. + pub unknown: usize, + /// How many shapes there were at the first page advance. + page_end: Option, +} + +impl Plot { + pub fn new() -> Self { + let mut p = Self { + shapes: vec![], + warnings: vec![], + full: false, + elements: 0, + p1: Point::ZERO, + p2: HARD_CLIP, + scaling: None, + user: Affine::IDENTITY, + rot: Affine::IDENTITY, + ro: 0, + relative: false, + down: false, + pos: Point::ZERO, + pen: None, + pens: 8, + colors: HashMap::new(), + ranges: [(0.0, 255.0); 3], + width: DEFAULT_WIDTH_MM * PLU_PER_MM, + widths: HashMap::new(), + relative_widths: false, + line_type: None, + saved_line_type: None, + pattern: DEFAULT_PATTERN, + pattern_mm: false, + user_types: Default::default(), + cap: LineCap::Butt, + join: LineJoin::Miter, + miter: 5.0, + fill: FillKind::Solid, + poly: None, + buffer: None, + run: None, + terminator: ETX, + unknown: 0, + page_end: None, + }; + p.init(); + p + } + + pub fn warn(&mut self, w: &str) { + if !self.warnings.iter().any(|x| x == w) { + self.warnings.push(w.to_string()); + } + } + + // ---------- defaults ---------- + + /// DF: the line and fill attributes, scaling, plotting mode and polygon mode as they start. + fn defaults(&mut self) { + self.flush(); + self.relative = false; + (self.line_type, self.saved_line_type, self.pattern, self.pattern_mm) = (None, None, DEFAULT_PATTERN, false); + self.user_types = Default::default(); + (self.cap, self.join, self.miter) = (LineCap::Butt, LineJoin::Miter, 5.0); + self.fill = FillKind::Solid; + (self.poly, self.buffer) = (None, None); + self.scaling = None; + self.ranges = [(0.0, 255.0); 3]; + self.terminator = ETX; + self.update_user(); + } + + /// IN: DF, and the pen up at the origin, default widths, palette and scaling points, no + /// rotation. The selected pen stays. + fn init(&mut self) { + self.defaults(); + (self.pos, self.down) = (Point::ZERO, false); + (self.width, self.relative_widths) = (DEFAULT_WIDTH_MM * PLU_PER_MM, false); + self.widths.clear(); + (self.rot, self.ro) = (Affine::IDENTITY, 0); + (self.p1, self.p2) = (Point::ZERO, HARD_CLIP); + self.pens = 8; + self.colors.clear(); + self.update_user(); + } + + // ---------- coordinates ---------- + + /// User units to plotter units for the scaling in force; scaling that maps everything onto one + /// point is ignored. + fn update_user(&mut self) { + let (p1, p2) = (self.p1, self.p2); + let user = match self.scaling { + None => Affine::IDENTITY, + Some(Scaling::Factor { x0, fx, y0, fy }) => { + Affine::translate(p1.to_vec2()) * Affine::scale_non_uniform(fx, fy) * Affine::translate((-x0, -y0)) + } + Some(Scaling::Fit { x0, x1, y0, y1, iso }) => { + let (w, h, ux, uy) = (p2.x - p1.x, p2.y - p1.y, x1 - x0, y1 - y0); + let (mut sx, mut sy, mut off) = (w / ux, h / uy, Vec2::ZERO); + if let Some((left, bottom)) = iso { + let s = sx.abs().min(sy.abs()); + let (extra_x, extra_y) = (w.abs() - ux.abs() * s, h.abs() - uy.abs() * s); + off = Vec2::new(extra_x * left / 100.0 * w.signum(), extra_y * bottom / 100.0 * h.signum()); + (sx, sy) = (s * sx.signum(), s * sy.signum()); + } + Affine::translate(p1.to_vec2() + off) * Affine::scale_non_uniform(sx, sy) * Affine::translate((-x0, -y0)) + } + }; + let det = user.determinant(); + self.user = if det.is_finite() && det != 0.0 && user.as_coeffs().iter().all(|c| c.is_finite()) { user } else { Affine::IDENTITY }; + } + + /// A point in current units, in plotter units. + fn to_plu(&self, x: f64, y: f64) -> Point { + self.user * Point::new(x, y) + } + + /// An increment in current units, in plotter units. + fn delta(&self, x: f64, y: f64) -> Vec2 { + self.to_plu(x, y) - self.to_plu(0.0, 0.0) + } + + /// The pen's position in current units. + fn pos_user(&self) -> Point { + self.user.inverse() * self.pos + } + + /// Plotter units (before rotation) to where the art lies. + fn dev(&self, p: Point) -> Point { + self.rot * p + } + + /// User units to where the art lies. + fn user_dev(&self) -> Affine { + self.rot * self.user + } + + /// The far corner of the hard-clip limits in the current orientation (their sides swap at 90 + /// and 270 degrees). + fn hard_clip(&self) -> Point { + if self.ro % 180 == 90 { Point::new(HARD_CLIP.y, HARD_CLIP.x) } else { HARD_CLIP } + } + + /// RO: plotter units rotated `angle` degrees (0, 90, 180 or 270) to where the art lies, shifted + /// so the hard-clip limits stay where they were. + fn rotation(angle: u16) -> Affine { + let (w, h) = (HARD_CLIP.x, HARD_CLIP.y); + match angle { + 90 => Affine::new([0.0, 1.0, -1.0, 0.0, w, 0.0]), + 180 => Affine::new([-1.0, 0.0, 0.0, -1.0, w, h]), + 270 => Affine::new([0.0, -1.0, 1.0, 0.0, 0.0, h]), + _ => Affine::IDENTITY, + } + } + + fn diagonal(&self) -> f64 { + (self.p2 - self.p1).hypot().max(1.0) + } + + // ---------- pens and attributes ---------- + + /// The palette entry the selected pen draws with (`None`: pen 0, no pen). + fn pen_index(&self) -> Option { + let n = self.pen.unwrap_or(1); + if n <= 0 { + return None; + } + Some((n - 1) % (self.pens - 1).max(1) + 1) + } + + fn color(&self, i: i64) -> [u8; 3] { + let default = usize::try_from(i).ok().and_then(|i| PALETTE.get(i)).copied().unwrap_or([0; 3]); + self.colors.get(&i).copied().unwrap_or(default) + } + + /// The stroke the selected pen draws (`None` for no pen). + fn stroke(&self) -> Option { + let i = self.pen_index()?; + let width = self.widths.get(&i).copied().unwrap_or(self.width).clamp(0.0, MAX_WIDTH); + let dash = self.line_type.filter(|k| *k != 0).map(|k| { + let index = k.unsigned_abs().clamp(1, 8) as usize - 1; + let length = if self.pattern_mm { self.pattern * PLU_PER_MM } else { self.pattern / 100.0 * self.diagonal() }; + match &self.user_types[index] { + Some(pct) => LinePattern::new(pct, length, k < 0), + None => LinePattern::new(LINE_TYPES[index], length, k < 0), + } + }); + Some(Stroke { color: self.color(i), width, cap: self.cap, join: self.join, miter: self.miter, dash }) + } + + /// The color the selected pen fills with (`None` for no pen). + fn fill_color(&mut self) -> Option<[u8; 3]> { + let c = self.color(self.pen_index()?); + match self.fill { + FillKind::Solid => Some(c), + FillKind::Pattern => { + self.warn(HATCHES); + Some(c) + } + FillKind::Shade(level) => { + let t = (level / 100.0).clamp(0.0, 1.0); + Some(c.map(|v| (255.0 - (255.0 - f64::from(v)) * t).round() as u8)) + } + } + } + + // ---------- output ---------- + + /// Count `n` path elements against the budget → whether they fit. + fn spend(&mut self, n: usize) -> bool { + self.elements += n; + if self.elements > MAX_ELEMENTS { + self.warn(TOO_MANY_POINTS); + self.full = true; + } + !self.full + } + + fn push(&mut self, shape: Shape) { + if shape.path.elements().len() < 2 { + return; + } + if self.shapes.len() >= MAX_SHAPES { + self.warn(TOO_MANY); + self.full = true; + return; + } + let b = shape.path.bounding_box(); + if ![b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite() && v.abs() <= LIMIT) { + return self.warn(FAR_AWAY); + } + self.shapes.push(shape); + } + + /// End the line being drawn. + fn flush(&mut self) { + let Some(run) = self.run.take() else { return }; + let mut els = run.path.into_elements(); + // Vectors of no length alone draw a dot: a vector one plotter unit long. + if els.len() == 1 { + els.push(PathEl::LineTo(run.start + Vec2::new(1.0, 0.0))); + } + // A line that ends where it started is closed, so its ends join. + if els.len() > 3 && run.end == run.start { + if matches!(els.last(), Some(PathEl::LineTo(p)) if *p == run.start) { + els.pop(); + } + els.push(PathEl::ClosePath); + } + self.push(Shape { path: BezPath::from_vec(els), fill: None, stroke: Some(run.stroke) }); + } + + /// A dot (a vector one plotter unit long) at `at`, drawn with the selected pen. + fn dot(&mut self, at: Point) { + if let Some(stroke) = self.stroke() { + let mut path = BezPath::new(); + path.move_to(at); + path.line_to(at + Vec2::new(1.0, 0.0)); + self.push(Shape { path, fill: None, stroke: Some(stroke) }); + } + } + + /// The pen moves from `a` along `pieces` (where the art lies), drawing when `down`; in polygon + /// mode the move goes into the polygon buffer. + fn trace(&mut self, a: Point, pieces: &[Piece], down: bool) { + // Only what goes into a path counts against the budget: outside polygon mode, moves with the + // pen up or with no pen (SP0) make nothing. + let draws = down && self.pen_index().is_some(); + if pieces.is_empty() || self.full || (!draws && self.poly.is_none()) || !self.spend(pieces.len()) { + return; + } + if let Some(poly) = &mut self.poly { + return poly.add(a, pieces, down); + } + let Some(stroke) = self.stroke() else { return }; + if self.line_type == Some(0) { + // Line type 0 draws a dot at each point given (an arc's or a curve's end). + self.flush(); + if let Some(p) = pieces.last() { + self.dot(p.end()); + } + return; + } + if self.run.as_ref().is_some_and(|r| r.stroke != stroke || r.end != a) { + self.flush(); + } + let run = self.run.get_or_insert_with(|| { + let mut path = BezPath::new(); + path.move_to(a); + Run { path, stroke, start: a, end: a } + }); + for p in pieces { + // A vector of no length adds nothing to a line (a line of nothing else is a dot). + if matches!(p, Piece::Line(b) if *b == run.end) { + continue; + } + p.push(&mut run.path); + run.end = p.end(); + } + } + + /// Move the pen to `target` (plotter units), drawing when it is down. + fn line_to(&mut self, target: Point) { + if !(target.x.is_finite() && target.y.is_finite()) { + return; + } + let (a, b) = (self.dev(self.pos), self.dev(target)); + let down = self.down; + self.trace(a, &[Piece::Line(b)], down); + self.pos = target; + } + + /// The curves of an arc around `center` (user units) from `start` through `sweep` degrees, + /// where the art lies, and its end (user units). `None` when it has no radius or sweep. + fn arc(&self, center: Point, start: Point, sweep: f64) -> Option<(Vec, Point)> { + let r = (start - center).hypot(); + let sweep = sweep.clamp(-32768.0, 32767.0).to_radians(); + if !(r > 0.0 && r.is_finite() && sweep != 0.0 && sweep.is_finite()) { + return None; + } + let a0 = (start - center).atan2(); + let arc = kurbo::Arc { center, radii: Vec2::new(r, r), start_angle: a0, sweep_angle: sweep, x_rotation: 0.0 }; + let m = self.user_dev(); + let pieces = arc + .append_iter(r * 1e-6) + .filter_map(|el| match el { + PathEl::CurveTo(a, b, c) => Some(Piece::Curve(m * a, m * b, m * c)), + PathEl::LineTo(p) => Some(Piece::Line(m * p)), + _ => None, + }) + .collect(); + Some((pieces, center + Vec2::from_angle(a0 + sweep) * r)) + } + + /// An arc from the pen around `center` (user units), drawn with the pen as it is. + fn arc_from_pen(&mut self, center: Point, sweep: f64) { + let start = self.pos_user(); + match self.arc(center, start, sweep) { + Some((pieces, end)) => { + let (a, down) = (self.dev(self.pos), self.down); + self.trace(a, &pieces, down); + self.pos = self.user * end; + } + None => { + let at = self.dev(self.pos); + let down = self.down; + self.trace(at, &[Piece::Line(at)], down); + } + } + } + + /// A closed outline through `pieces` from `a` (where the art lies). + fn outline(a: Point, pieces: &[Piece]) -> BezPath { + let mut path = BezPath::new(); + path.move_to(a); + pieces.iter().for_each(|p| p.push(&mut path)); + path.close_path(); + path + } + + /// A circle of `radius` (current units) around the pen, starting at 0 degrees (180 for a + /// negative radius), where the art lies. + fn circle(&self, radius: f64) -> Option { + let c = self.pos_user(); + let start = c + Vec2::new(radius, 0.0); + let (pieces, _) = self.arc(c, start, 360.0)?; + Some(Self::outline(self.user_dev() * start, &pieces)) + } + + /// A wedge of `radius` (current units) around the pen, from `start` through `sweep` degrees. + fn wedge(&self, radius: f64, start: f64, sweep: f64) -> Option { + let c = self.pos_user(); + let reference = if radius < 0.0 { 180.0 } else { 0.0 }; + let sweep = sweep.clamp(-360.0, 360.0); + let first = c + Vec2::from_angle((reference + start.clamp(-32768.0, 32767.0) % 360.0).to_radians()) * radius.abs(); + let m = self.user_dev(); + if sweep.abs() >= 360.0 { + let (pieces, _) = self.arc(c, first, sweep)?; + return Some(Self::outline(m * first, &pieces)); + } + let mut pieces = vec![Piece::Line(m * first)]; + if let Some((arc, _)) = self.arc(c, first, sweep) { + pieces.extend(arc); + } + (radius != 0.0).then(|| Self::outline(m * c, &pieces)) + } + + /// The rectangle from the pen to `corner` (plotter units), where the art lies. + fn rect(&self, corner: Point) -> BezPath { + let (a, b) = (self.pos_user(), self.user.inverse() * corner); + let m = self.user_dev(); + let pieces = [Point::new(b.x, a.y), b, Point::new(a.x, b.y)].map(|p| Piece::Line(m * p)); + Self::outline(m * a, &pieces) + } + + /// `path` as the polygon buffer, filled (`fill`) or edged. + fn buffer_and_draw(&mut self, path: Option, fill: bool) { + self.flush(); + if self.poly.is_some() { + return; + } + let Some(path) = path else { + return self.dot(self.dev(self.pos)); + }; + if !self.spend(path.elements().len()) { + return; + } + let mut poly = Poly::default(); + poly.closed(&path); + self.buffer = Some(poly); + if fill { self.fill_polygon(FillRule::EvenOdd) } else { self.edge_polygon() } + } + + /// FP: the polygon buffer filled (each fill is a copy of the buffer, counted against the + /// budget). + fn fill_polygon(&mut self, rule: FillRule) { + self.flush(); + let n = self.buffer.as_ref().map_or(0, |b| b.fill.elements().len()); + if n == 0 || !self.spend(n) { + return; + } + let Some(c) = self.fill_color() else { return }; + let Some(path) = self.buffer.as_ref().map(|b| b.fill.clone()) else { return }; + self.push(Shape { path, fill: Some((c, rule)), stroke: None }); + } + + /// EP: the pen-down edges of the polygon buffer stroked (counted as FP's are). + fn edge_polygon(&mut self) { + self.flush(); + let n = self.buffer.as_ref().map_or(0, |b| b.edge.elements().len()); + if n == 0 || !self.spend(n) { + return; + } + let Some(stroke) = self.stroke() else { return }; + let Some(path) = self.buffer.as_ref().map(|b| b.edge.clone()) else { return }; + self.push(Shape { path, fill: None, stroke: Some(stroke) }); + } + + // ---------- instructions ---------- + + /// Read and play the instruction `op`. + pub fn op(&mut self, op: [u8; 2], lex: &mut Lexer) { + if self.poly.is_some() && !POLYGON_MODE.contains(&op) { + return self.skip_op(op, lex); + } + match &op { + b"IN" | b"BP" | b"DF" | b"PU" | b"PD" | b"PA" | b"PR" | b"SP" => self.setup_op(op, lex), + b"PW" | b"WU" | b"NP" | b"PC" | b"CR" => self.pen_op(op, lex), + b"LT" | b"UL" => self.line_type_op(op, lex), + b"LA" | b"FT" | b"SC" => self.attribute_op(op, lex), + b"IP" | b"IR" | b"RO" | b"CI" => self.frame_op(op, lex), + b"AA" | b"AR" | b"AT" | b"RT" | b"BZ" | b"BR" => self.curve_op(op, lex), + b"EA" | b"ER" | b"RA" | b"RR" | b"EW" | b"WG" | b"PM" | b"FP" | b"EP" | b"PE" => self.area_op(op, lex), + _ => self.other_op(op, lex), + } + } + + /// An instruction polygon mode ignores: its parameters (or text) are read. + fn skip_op(&mut self, op: [u8; 2], lex: &mut Lexer) { + match &op { + b"LB" | b"BL" | b"WD" => lex.label(self.terminator), + b"DT" => { + lex.char(); + lex.params(); + } + b"SM" => { + lex.char(); + } + _ => lex.params(), + } + } + + /// Initialization, pen moves and pen selection. + fn setup_op(&mut self, op: [u8; 2], lex: &mut Lexer) { + let mut v = [0.0f64; 8]; + match &op { + b"IN" | b"BP" => { + lex.params(); + self.init(); + } + b"DF" => { + lex.params(); + self.defaults(); + } + b"PU" | b"PD" => { + self.down = op[1] == b'D'; + self.points(lex); + } + b"PA" | b"PR" => { + self.relative = op[1] == b'R'; + self.points(lex); + } + b"SP" => { + let n = lex.numbers(&mut v); + self.flush(); + self.pen = Some(if n == 0 { 0 } else { v[0].round().clamp(-1.0, 1e9) as i64 }); + } + _ => {} + } + } + + /// Pen widths, the palette and its colors. + fn pen_op(&mut self, op: [u8; 2], lex: &mut Lexer) { + let mut v = [0.0f64; 8]; + match &op { + b"PW" => { + let n = lex.numbers(&mut v); + self.flush(); + let width = |s: &Self, w: f64| if s.relative_widths { w / 100.0 * s.diagonal() } else { w * PLU_PER_MM }; + let default = if self.relative_widths { 0.1 } else { DEFAULT_WIDTH_MM }; + let w = width(self, if n == 0 { default } else { v[0].clamp(0.0, 32767.0) }); + if n >= 2 { + let pen = v[1].round().clamp(0.0, 1e9) as i64; + if pen > 0 && pen < self.pens.max(8) { + self.widths.insert(pen, w); + } + } else { + self.width = w; + self.widths.clear(); + } + } + b"WU" => { + let n = lex.numbers(&mut v); + self.flush(); + self.relative_widths = n > 0 && v[0].round() == 1.0; + self.width = if self.relative_widths { 0.1 / 100.0 * self.diagonal() } else { DEFAULT_WIDTH_MM * PLU_PER_MM }; + self.widths.clear(); + } + b"NP" => { + let n = lex.numbers(&mut v); + self.flush(); + if n == 0 { + self.pens = 8; + } else if v[0] >= 2.0 { + self.pens = i64::from((v[0].min(MAX_PENS as f64).ceil() as u32).next_power_of_two()).min(MAX_PENS); + } + } + b"PC" => { + let n = lex.numbers(&mut v); + self.flush(); + let pen = v[0].round().clamp(0.0, 1e9) as i64; + match n { + 0 => self.colors.clear(), + 1 => { + self.colors.remove(&pen); + } + // Two or three parameters: the instruction is ignored. + 2 | 3 => {} + _ if pen < MAX_PENS => { + let channel = |i: usize| { + let (b, w) = self.ranges[i]; + let t = if w == b { 0.0 } else { ((v[i + 1] - b) / (w - b)).clamp(0.0, 1.0) }; + (t * 255.0).round() as u8 + }; + let c = [channel(0), channel(1), channel(2)]; + self.colors.insert(pen, c); + } + _ => {} + } + } + b"CR" => { + let n = lex.numbers(&mut v); + if n == 0 { + self.ranges = [(0.0, 255.0); 3]; + } else if n >= 6 { + self.ranges = [(v[0], v[1]), (v[2], v[3]), (v[4], v[5])]; + } + } + _ => {} + } + } + + /// Line types and their patterns. + fn line_type_op(&mut self, op: [u8; 2], lex: &mut Lexer) { + let mut v = [0.0f64; 8]; + match &op { + b"LT" => { + let n = lex.numbers(&mut v); + self.flush(); + if n == 0 { + if self.line_type.is_some() { + self.saved_line_type = self.line_type; + } + self.line_type = None; + return; + } + let k = v[0].round().clamp(-100.0, 100.0) as i32; + if k == 99 { + if self.line_type.is_none() { + self.line_type = self.saved_line_type; + } + return; + } + if !(-8..=8).contains(&k) { + return; + } + // A pattern length of 0 or less, or a mode other than 0 and 1, makes the instruction ignored. + if (n >= 2 && !(v[1] > 0.0 && v[1] <= 32767.0)) || (n >= 3 && !matches!(v[2].round() as i32, 0 | 1)) { + return; + } + self.line_type = Some(k); + if n >= 2 { + self.pattern = v[1]; + } + if n >= 3 { + self.pattern_mm = v[2].round() == 1.0; + } + } + b"UL" => { + let mut gaps = [0.0f64; 21]; + let n = lex.numbers(&mut gaps); + self.flush(); + let index = gaps[0].round().abs(); + if n == 0 { + self.user_types = Default::default(); + } else if (1.0..=8.0).contains(&index) { + let slot = index as usize - 1; + let values = &gaps[1..n]; + let sum: f64 = values.iter().sum(); + self.user_types[slot] = if n == 1 { + None + } else if values.iter().all(|g| *g >= 0.0) && sum > 0.0 { + Some(values.iter().map(|g| g / sum * 100.0).collect()) + } else { + return; + }; + } + } + _ => {} + } + } + + /// Line ends and joins, the fill type and scaling. + fn attribute_op(&mut self, op: [u8; 2], lex: &mut Lexer) { + let mut v = [0.0f64; 8]; + match &op { + b"LA" => { + let n = lex.numbers(&mut v[..6]); + self.flush(); + if n == 0 { + (self.cap, self.join, self.miter) = (LineCap::Butt, LineJoin::Miter, 5.0); + } + for pair in v[..n - n % 2].chunks(2) { + let value = pair[1].round() as i32; + match (pair[0].round() as i32, value) { + (1, 1) => self.cap = LineCap::Butt, + (1, 2) => self.cap = LineCap::Square, + (1, 3 | 4) => self.cap = LineCap::Round, + (2, 1 | 2) => self.join = LineJoin::Miter, + (2, 4) => self.join = LineJoin::Round, + (2, 3 | 5 | 6) => self.join = LineJoin::Bevel, + (3, _) => self.miter = pair[1].clamp(1.0, 32767.0), + _ => {} + } + } + } + b"FT" => { + let n = lex.numbers(&mut v[..3]); + let kind = if n == 0 { 1 } else { v[0].round() as i32 }; + self.fill = match kind { + 1 | 2 => FillKind::Solid, + 10 => FillKind::Shade(if n >= 2 { v[1] } else { 100.0 }), + 3 | 4 | 11 | 21 | 22 => FillKind::Pattern, + _ => self.fill, + }; + } + b"SC" => { + let n = lex.numbers(&mut v[..7]); + self.flush(); + let kind = if n >= 5 { v[4].round() as i32 } else { 0 }; + self.scaling = match (n, kind) { + (0, _) => None, + (5, 2) if v[1] != 0.0 && v[3] != 0.0 => Some(Scaling::Factor { x0: v[0], fx: v[1], y0: v[2], fy: v[3] }), + (4..=7, 0 | 1) if v[0] != v[1] && v[2] != v[3] => { + let iso = (kind == 1).then(|| if n >= 7 { (v[5].clamp(0.0, 100.0), v[6].clamp(0.0, 100.0)) } else { (50.0, 50.0) }); + Some(Scaling::Fit { x0: v[0], x1: v[1], y0: v[2], y1: v[3], iso }) + } + _ => return, + }; + self.update_user(); + } + _ => {} + } + } + + /// The scaling points, the rotation and circles. + fn frame_op(&mut self, op: [u8; 2], lex: &mut Lexer) { + let mut v = [0.0f64; 8]; + match &op { + b"IP" | b"IR" => { + let n = lex.numbers(&mut v[..4]); + self.flush(); + // IR's percentages and the defaults are of the hard-clip limits in the current + // orientation. Scaling points past the art's range are held at its edge, so lengths + // taken from them stay finite. + let clip = self.hard_clip(); + let at = |x: f64, y: f64| { + let p = if op[1] == b'R' { Point::new(x / 100.0 * clip.x, y / 100.0 * clip.y) } else { Point::new(x, y) }; + Point::new(p.x.clamp(-LIMIT, LIMIT), p.y.clamp(-LIMIT, LIMIT)) + }; + match n { + 0 => (self.p1, self.p2) = (Point::ZERO, clip), + 2 | 3 => { + let p1 = at(v[0], v[1]); + (self.p1, self.p2) = (p1, p1 + (self.p2 - self.p1)); + } + 4 => { + let (p1, mut p2) = (at(v[0], v[1]), at(v[2], v[3])); + // A coordinate of P2 equal to P1's is one plotter unit more. + if p2.x == p1.x { + p2.x += 1.0; + } + if p2.y == p1.y { + p2.y += 1.0; + } + (self.p1, self.p2) = (p1, p2); + } + _ => {} + } + self.update_user(); + } + b"RO" => { + let n = lex.numbers(&mut v[..1]); + self.flush(); + let angle = if n == 0 { 0.0 } else { v[0].round().rem_euclid(360.0) }; + if [0.0, 90.0, 180.0, 270.0].contains(&angle) { + let ro = angle as u16; + let rot = Self::rotation(ro); + // The pen keeps its place on the page, its coordinates changing with the axes; + // P1 and P2 keep their coordinates, and the polygon buffer turns with the axes. + let turn = rot * self.rot.inverse(); + self.pos = rot.inverse() * (self.rot * self.pos); + if let Some(b) = &mut self.buffer { + b.fill.apply_affine(turn); + b.edge.apply_affine(turn); + } + (self.rot, self.ro) = (rot, ro); + } + } + b"CI" => { + let n = lex.numbers(&mut v[..2]); + if n == 0 { + return; + } + let path = self.circle(v[0]); + // In polygon mode the circle is a subpolygon of its own; the pen stays at its + // center. + if self.poly.is_some() { + if let Some(path) = path + && self.spend(path.elements().len()) + && let Some(poly) = &mut self.poly + { + poly.closed(&path); + } + return; + } + self.flush(); + // Line type 0 draws a dot at the center. + if self.line_type == Some(0) { + return self.dot(self.dev(self.pos)); + } + let Some(path) = path else { return self.dot(self.dev(self.pos)) }; + if self.spend(path.elements().len()) + && let Some(stroke) = self.stroke() + { + self.push(Shape { path, fill: None, stroke: Some(stroke) }); + } + } + _ => {} + } + } + + /// Arcs and Bézier curves from the pen. + fn curve_op(&mut self, op: [u8; 2], lex: &mut Lexer) { + let mut v = [0.0f64; 8]; + match &op { + b"AA" | b"AR" => { + if lex.numbers(&mut v[..4]) < 3 { + return; + } + let center = if op[1] == b'R' { self.pos_user() + Vec2::new(v[0], v[1]) } else { Point::new(v[0], v[1]) }; + self.arc_from_pen(center, v[2]); + } + b"AT" | b"RT" => { + if lex.numbers(&mut v[..5]) < 4 { + return; + } + let a = self.pos_user(); + let off = if op[0] == b'R' { a.to_vec2() } else { Vec2::ZERO }; + let (b, c) = (Point::new(v[0], v[1]) + off, Point::new(v[2], v[3]) + off); + self.three_point_arc(a, b, c); + } + b"BZ" | b"BR" => { + while let Some(x) = lex.number() { + let mut p = [x, 0.0, 0.0, 0.0, 0.0, 0.0]; + for slot in &mut p[1..] { + let Some(n) = lex.number() else { return }; + *slot = n; + } + let a = self.pos_user(); + let off = if op[1] == b'R' { a.to_vec2() } else { Vec2::ZERO }; + let [c1, c2, end] = [0, 2, 4].map(|i| Point::new(p[i], p[i + 1]) + off); + let m = self.user_dev(); + let (from, down) = (self.dev(self.pos), self.down); + self.trace(from, &[Piece::Curve(m * c1, m * c2, m * end)], down); + self.pos = self.user * end; + } + } + _ => {} + } + } + + /// Rectangles, wedges, polygon mode and encoded polylines. + fn area_op(&mut self, op: [u8; 2], lex: &mut Lexer) { + let mut v = [0.0f64; 8]; + match &op { + b"EA" | b"ER" | b"RA" | b"RR" => { + if lex.numbers(&mut v[..2]) < 2 { + return; + } + let corner = if op[1] == b'R' { self.pos + self.delta(v[0], v[1]) } else { self.to_plu(v[0], v[1]) }; + let path = self.rect(corner); + self.buffer_and_draw(Some(path), op[0] == b'R'); + } + b"EW" | b"WG" => { + if lex.numbers(&mut v[..4]) < 3 { + return; + } + let path = self.wedge(v[0], v[1], v[2]); + self.buffer_and_draw(path, op[0] == b'W'); + } + b"PM" => { + let n = lex.numbers(&mut v[..1]); + self.flush(); + // The point that closes a subpolygon moves the pen there: PM1 closes it with the + // pen up, PM2 with the pen as it is. + let mut closure = None; + match if n == 0 { 0 } else { v[0].round() as i32 } { + 0 if self.poly.is_none() => { + let at = self.dev(self.pos); + self.poly = Some(Poly { start: at, last: at, ..Poly::default() }); + self.buffer = None; + } + 1 => { + if let Some(p) = &mut self.poly { + closure = p.close(false); + p.fresh = true; + } + } + 2 => { + if let Some(mut p) = self.poly.take() { + closure = p.close(self.down); + self.buffer = Some(p); + } + } + _ => {} + } + if let Some(at) = closure { + self.pos = self.rot.inverse() * at; + } + } + b"FP" => { + let n = lex.numbers(&mut v[..1]); + self.fill_polygon(if n > 0 && v[0].round() == 1.0 { FillRule::NonZero } else { FillRule::EvenOdd }); + } + b"EP" => { + lex.params(); + self.edge_polygon(); + } + b"PE" => self.polyline_encoded(lex), + _ => {} + } + } + + /// Labels, comments, pages, the input window, and instructions that draw nothing. + fn other_op(&mut self, op: [u8; 2], lex: &mut Lexer) { + let mut v = [0.0f64; 4]; + match &op { + b"LB" | b"BL" | b"WD" => { + lex.label(self.terminator); + self.warn(LABELS); + } + b"DT" => { + self.terminator = lex.char().unwrap_or(ETX); + lex.params(); + } + b"SM" => { + // The symbol character is read so it isn't taken for an instruction; symbols + // aren't drawn. + if lex.char().is_some() { + self.warn(SYMBOLS); + } + } + b"CO" => { + lex.quoted(); + } + b"PG" | b"FR" => { + lex.params(); + self.flush(); + self.page_end.get_or_insert(self.shapes.len()); + // The next page starts with the pen up at the origin (FR also empties the + // polygon buffer). + (self.pos, self.down) = (Point::ZERO, false); + if op[0] == b'F' { + self.buffer = None; + } + } + b"IW" => { + if lex.numbers(&mut v) == 4 { + self.warn(WINDOW); + } + } + _ if super::IGNORED.contains(&op) => lex.params(), + _ => { + lex.params(); + self.unknown += 1; + } + } + } + + /// The coordinate pairs of PU, PD, PA and PR, plotted in the current mode. + fn points(&mut self, lex: &mut Lexer) { + while let Some(x) = lex.number() { + let Some(y) = lex.number() else { return }; + let target = if self.relative { self.pos + self.delta(x, y) } else { self.to_plu(x, y) }; + self.line_to(target); + if self.full { + return; + } + } + } + + /// AT and RT: the arc from `a` through `b` to `c` (user units). + fn three_point_arc(&mut self, a: Point, b: Point, c: Point) { + let d = 2.0 * (a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y)); + let center = if a == c { + // Back to the start: the circle whose diameter ends at the start and the middle point. + Some(a.midpoint(b)) + } else if d.abs() > 1e-12 * (b - a).hypot2().max((c - a).hypot2()).max(1.0) { + let (a2, b2, c2) = (a.to_vec2().hypot2(), b.to_vec2().hypot2(), c.to_vec2().hypot2()); + Some(Point::new( + (a2 * (b.y - c.y) + b2 * (c.y - a.y) + c2 * (a.y - b.y)) / d, + (a2 * (c.x - b.x) + b2 * (a.x - c.x) + c2 * (b.x - a.x)) / d, + )) + } else { + None + }; + let Some(center) = center.filter(|p| p.x.is_finite() && p.y.is_finite()) else { + // Points in a line: a line to the end. + return self.line_to(self.user * c); + }; + let tau = std::f64::consts::TAU; + let angle = |p: Point| (p - center).atan2(); + let sweep = if a == c { + tau + } else { + let (s, t) = ((angle(c) - angle(a)).rem_euclid(tau), (angle(b) - angle(a)).rem_euclid(tau)); + if t < s { s } else { s - tau } + }; + self.arc_from_pen(center, sweep.to_degrees()); + if a != c { + self.pos = self.user * c; + } + } + + /// PE: encoded pen moves, pen selections and rectangles. + fn polyline_encoded(&mut self, lex: &mut Lexer) { + let mut st = Pe::default(); + let (mut rect, mut corner) = (false, false); + while let Some(item) = lex.pe(&mut st) { + if self.full { + continue; + } + match item { + PeItem::Pen(n) => { + if self.poly.is_none() { + self.flush(); + self.pen = Some(n.clamp(-1, 1_000_000_000)); + } + } + PeItem::Rect => (rect, corner) = (true, false), + PeItem::Point { x, y, up, absolute } => { + if up { + rect = false; + } + let target = if absolute { self.to_plu(x, y) } else { self.pos + self.delta(x, y) }; + if rect && corner { + // The second pair of a rectangle: its opposite corner, relative. It is filled + // as RR fills one, so polygon mode, which doesn't allow RR, ignores it. + let path = self.rect(self.pos + self.delta(x, y)); + self.buffer_and_draw(Some(path), true); + corner = false; + } else if rect { + self.down = false; + self.line_to(target); + corner = true; + } else { + self.down = !up; + self.line_to(target); + } + } + } + } + if rect { + self.down = false; + } + } + + /// The plot's end: the last line drawn, and notes on what wasn't read. + pub fn finish(mut self, raster: bool) -> Self { + self.flush(); + if let Some(n) = self.page_end + && self.shapes.len() > n + { + self.warn(PAGES); + } + if raster { + self.warn(RASTER); + } + if self.unknown > 0 { + let n = self.unknown; + self.warnings.push(format!( + "{n} instruction{} of kinds VectorCraft doesn't read {} skipped", + if n == 1 { "" } else { "s" }, + if n == 1 { "was" } else { "were" } + )); + } + self + } +} diff --git a/crates/cad/src/hpgl/tests.rs b/crates/cad/src/hpgl/tests.rs new file mode 100644 index 0000000000..9a350707a6 --- /dev/null +++ b/crates/cad/src/hpgl/tests.rs @@ -0,0 +1,630 @@ +//! HP-GL import: units and the y axis, pens, runs, curves, filled and edged areas, polygon mode, +//! line types, scaling, rotation, encoded polylines, escapes around the instructions, what is +//! skipped with a warning, which files are taken to be HP-GL, and hostile files. + +use kurbo::{BezPath, PathEl, Point, Shape as _}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{AppearanceItem, Document, LineCap, LineJoin, Node, NodeKind, StrokeLayer}; +use vectorcraft_geom::FillRule; + +use super::plot::{FAR_AWAY, HATCHES, LABELS, PAGES, RASTER, SYMBOLS, TOO_MANY_POINTS, WINDOW}; +use super::*; + +/// Points per millimeter. +const MM: f64 = 72.0 / 25.4; + +fn plot(s: &str) -> Imported { + plot_bytes(s.as_bytes()) +} + +fn plot_bytes(b: &[u8]) -> Imported { + match import(b) { + Ok(i) => i, + Err(e) => panic!("{e}: {:?}", String::from_utf8_lossy(b)), + } +} + +/// Every object, in paint order. +fn leaves(doc: &Document) -> Vec { + let mut out = vec![]; + doc.walk(|n| { + if n.children().is_none() { + out.push(n.clone()); + } + }); + out +} + +fn bez(n: &Node) -> BezPath { + match &n.kind { + NodeKind::Path { path, .. } => path.to_bezpath(), + k => panic!("a path, got {k:?}"), + } +} + +fn stroke(n: &Node) -> StrokeLayer { + n.appearance.items.iter().find_map(|i| if let AppearanceItem::Stroke(s) = i { Some(s.clone()) } else { None }).expect("a stroke") +} + +fn fill(n: &Node) -> Option { + n.appearance.items.iter().find_map(|i| if let AppearanceItem::Fill(f) = i { Some(f.paint.clone()) } else { None }) +} + +fn rule(n: &Node) -> FillRule { + match &n.kind { + NodeKind::Path { rule, .. } => *rule, + k => panic!("a path, got {k:?}"), + } +} + +fn rgb(r: u8, g: u8, b: u8) -> Paint { + Paint::solid(Color::rgb8(r, g, b)) +} + +/// The end points of `bp`'s elements. +fn ends(bp: &BezPath) -> Vec { + bp.elements().iter().filter_map(|e| e.end_point()).collect() +} + +fn near(a: Point, b: Point) -> bool { + (a - b).hypot() < 1e-6 +} + +fn assert_points(got: &[Point], want: &[(f64, f64)]) { + assert_eq!(got.len(), want.len(), "{got:?}"); + for (g, w) in got.iter().zip(want) { + assert!(near(*g, Point::new(w.0, w.1)), "{got:?} != {want:?}"); + } +} + +/// A PE number as the reference guide's encoding writes it (base 64, or base 32 for 7-bit data). +fn pe_number(v: i64, seven_bit: bool) -> Vec { + let mut n = if v >= 0 { 2 * v as u64 } else { 2 * v.unsigned_abs() + 1 }; + let (base, high) = if seven_bit { (32, 95) } else { (64, 191) }; + let mut out = vec![]; + while n >= base { + out.push(63 + (n % base) as u8); + n /= base; + } + out.push(high + n as u8); + out +} + +#[test] +fn plotter_units_become_points_with_y_down() { + // An inch right and an inch up, with the thinnest pen (0.25 pt): the artboard reaches 0.125 pt + // past the line at the corner's miter, and stops at the line's butt ends. + let i = plot("IN;SP1;PW0;PU0,0;PD1016,0,1016,1016;PU;"); + let doc = &i.document; + let r = doc.artboards[0].rect; + assert!((r.width() - 72.125).abs() < 1e-9 && (r.height() - 72.125).abs() < 1e-9, "{r:?}"); + let shapes = leaves(doc); + assert_eq!(shapes.len(), 1); + assert_points(&ends(&bez(&shapes[0])), &[(0.0, 72.0), (72.0, 72.0), (72.0, 0.0)]); + let s = stroke(&shapes[0]); + assert_eq!((s.width, s.paint.clone(), s.cap, s.join, s.miter_limit), (0.25, rgb(0, 0, 0), LineCap::Butt, LineJoin::Miter, 5.0)); + assert!(fill(&shapes[0]).is_none() && i.warnings.is_empty(), "{:?}", i.warnings); + + // The artboard holds what the strokes paint, the tip of a sharp miter join included. + let i = plot("IN;SP1;PW2;PD2032,0,0,1000;"); + let r = i.document.artboards[0].rect; + let painted = leaves(&i.document)[0].visual_bounds().unwrap(); + let path = bez(&leaves(&i.document)[0]).bounding_box(); + assert!(painted.x1 - path.x1 > 2.0 * MM, "the miter reaches past half the width: {painted:?} {path:?}"); + let inside = r.x0 <= painted.x0 + 1e-9 && r.y0 <= painted.y0 + 1e-9 && r.x1 >= painted.x1 - 1e-9 && r.y1 >= painted.y1 - 1e-9; + assert!(inside, "{r:?} {painted:?}"); +} + +#[test] +fn pens_pick_colors_and_widths() { + // Before any SP the pen is pen 1; SP0 draws nothing; pens past the palette wrap round it. + let i = plot("IN;PD0,0,100,0;PU;SP2;PD0,100,100,100;PU;SP0;PD0,200,100,200;PU;SP9;PD0,300,100,300;PU;SP3;PD0,400,100,400;PU;"); + let colors: Vec = leaves(&i.document).iter().map(|n| stroke(n).paint).collect(); + assert_eq!(colors, [rgb(0, 0, 0), rgb(255, 0, 0), rgb(255, 0, 0), rgb(0, 255, 0)]); + + // PC gives a pen a color in the color range; PC with the pen alone gives back its default. + let i = plot("IN;CR0,1,0,1,0,1;PC3,0,0,1;SP3;PD0,0,10,0;PU;PC3;PD0,10,10,10;PU;"); + let colors: Vec = leaves(&i.document).iter().map(|n| stroke(n).paint).collect(); + assert_eq!(colors, [rgb(0, 0, 255), rgb(0, 255, 0)]); + + // PW in millimeters for every pen, or for one; IN gives back 0.35 mm. + let i = plot("IN;SP1;PW1;PD0,0,10,0;PU;PW2,2;SP2;PD0,10,10,10;PU;SP1;PD0,20,10,20;PU;IN;SP1;PD0,30,10,30;"); + let widths: Vec = leaves(&i.document).iter().map(|n| stroke(n).width).collect(); + let want = [MM, 2.0 * MM, MM, 0.35 * MM]; + assert!(widths.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-9), "{widths:?}"); +} + +#[test] +fn each_run_with_the_pen_down_is_one_path() { + // Relative moves; a run that comes back to its start is closed; a pen-up move elsewhere starts + // another path, and one back to where the line ended continues it. + let i = plot("IN;SP1;PW0;PA0,0;PR;PD1016,0,0,1016,-1016,0,0,-1016;PU2032,0;PD0,1016;PU0,1016;PU0,-1016;PD508,0;PU0,500;PD0,500;"); + let shapes = leaves(&i.document); + assert_eq!(shapes.len(), 3, "{shapes:#?}"); + let NodeKind::Path { path: square, .. } = &shapes[0].kind else { panic!("a path") }; + assert_eq!((square.subpaths.len(), square.subpaths[0].anchors.len(), square.subpaths[0].closed), (1, 4, true)); + assert_eq!(ends(&bez(&shapes[1])).len(), 3, "the run went on from where it ended"); + assert_eq!(ends(&bez(&shapes[2])).len(), 2); + + // A pen-down move of no length draws a dot. + let i = plot("IN;SP1;PA500,500;PD;PA500,500;PU;"); + let shapes = leaves(&i.document); + assert_eq!(shapes.len(), 1); + let b = bez(&shapes[0]).bounding_box(); + assert!((b.width() - 72.0 / 1016.0).abs() < 1e-9, "{b:?}"); +} + +#[test] +fn circles_arcs_and_curves_are_drawn_as_curves() { + // A circle of an inch round the pen, which stays at its center (the next line starts there). + let i = plot("IN;SP1;PW0;PA2032,2032;CI1016;PD3048,2032;"); + let shapes = leaves(&i.document); + assert_eq!(shapes.len(), 2); + let c = bez(&shapes[0]); + assert!(c.elements().iter().any(|e| matches!(e, PathEl::CurveTo(..))) && matches!(c.elements().last(), Some(PathEl::ClosePath))); + // The curves stay within a thousandth of a point of the circle. + let b = c.bounding_box(); + assert!((b.width() - 144.0).abs() < 1e-3 && (b.height() - 144.0).abs() < 1e-3, "{b:?}"); + let line = ends(&bez(&shapes[1])); + assert!((line[0] - b.center()).hypot() < 1e-3, "{line:?} {b:?}"); + + // AA: a quarter turn counterclockwise round (0, 0) from (1016, 0) ends at (0, 1016), and the + // pen goes on from there. AR takes its center relative to the pen. + for s in ["IN;SP1;PW0;PA1016,0;PD;AA0,0,90;PA0,2032;", "IN;SP1;PW0;PA1016,0;PD;AR-1016,0,90;PA0,2032;"] { + let shapes = leaves(&plot(s).document); + assert_eq!(shapes.len(), 1, "{s}"); + let p = bez(&shapes[0]); + let pts = ends(&p); + // y down: (1016, 0) is at the bottom right, the arc's end on the left a quarter turn up. + let (start, end) = (pts[0], pts[pts.len() - 2]); + assert!(near(start, Point::new(72.125, 144.0)) && near(end, Point::new(0.125, 72.0)), "{s}: {pts:?}"); + assert!(near(*pts.last().unwrap(), Point::new(0.125, 0.0)), "{s}: {pts:?}"); + } + + // AT: the arc from the pen through a point to an end; points in a line give a line. + let shapes = leaves(&plot("IN;SP1;PW0;PA1016,0;PD;AT0,1016,-1016,0;").document); + let pts = ends(&bez(&shapes[0])); + let b = bez(&shapes[0]).bounding_box(); + assert!((b.width() - 144.0).abs() < 1e-6 && (b.height() - 72.0).abs() < 1e-6, "a half circle: {b:?}"); + assert!(near(pts[0], Point::new(144.125, 72.125)) && near(*pts.last().unwrap(), Point::new(0.125, 72.125)), "{pts:?}"); + let shapes = leaves(&plot("IN;SP1;PW0;PA0,0;PD;AT508,0,1016,0;").document); + assert_eq!(ends(&bez(&shapes[0])).len(), 2); + + // BZ and BR: cubic Béziers, BR's points relative to each curve's start. + for s in [ + "IN;SP1;PW0;PA0,0;PD;BZ0,1016,1016,1016,1016,0,1016,-1016,2032,-1016,2032,0;", + "IN;SP1;PW0;PA0,0;PD;BR0,1016,1016,1016,1016,0,0,-1016,1016,-1016,1016,0;", + ] { + let shapes = leaves(&plot(s).document); + let els = bez(&shapes[0]).elements().to_vec(); + assert_eq!(els.iter().filter(|e| matches!(e, PathEl::CurveTo(..))).count(), 2, "{s}"); + // The curves reach 762 plotter units (three quarters of their control points) up and down. + assert!(near(els.last().and_then(PathEl::end_point).unwrap(), Point::new(144.125, 54.125)), "{s}: {els:?}"); + } +} + +#[test] +fn rectangles_wedges_and_polygons_fill_and_edge() { + // RA fills, EA edges; neither moves the pen. + let i = plot("IN;SP2;PW0;PA0,0;RA1016,1016;EA1016,1016;PD508,0;"); + let shapes = leaves(&i.document); + assert_eq!(shapes.len(), 3); + assert_eq!((fill(&shapes[0]), shapes[0].appearance.items.len()), (Some(rgb(255, 0, 0)), 1)); + assert!(fill(&shapes[1]).is_none() && stroke(&shapes[1]).paint == rgb(255, 0, 0)); + assert!(near(ends(&bez(&shapes[2]))[0], Point::new(0.125, 72.125)), "the line starts where the pen was"); + + // WG fills a wedge, EW edges one; a whole turn is a circle. + let i = plot("IN;SP1;PA0,0;WG1016,0,90;EW1016,0,360;"); + let shapes = leaves(&i.document); + let wedge = bez(&shapes[0]); + assert!(fill(&shapes[0]).is_some() && ends(&wedge).len() >= 3); + let ring = bez(&shapes[1]).bounding_box(); + assert!((ring.width() - 144.0).abs() < 1e-6); + + // Polygon mode: two squares, one inside the other; FP fills even-odd by default, FP1 + // non-zero; EP edges only what was drawn with the pen down. + let poly = "IN;SP1;PW0;PA0,0;PM0;PD3048,0,3048,3048,0,3048,0,0;PM1;PU1016,1016;PD2032,1016;PU2032,2032;PD1016,2032,1016,1016;PM2;"; + let i = plot(&format!("{poly}FP;FP1;EP;")); + let shapes = leaves(&i.document); + assert_eq!(shapes.len(), 3); + assert_eq!((rule(&shapes[0]), rule(&shapes[1])), (FillRule::EvenOdd, FillRule::NonZero)); + let filled = bez(&shapes[0]); + assert_eq!(filled.elements().iter().filter(|e| matches!(e, PathEl::ClosePath)).count(), 2); + let edged = bez(&shapes[2]); + assert_eq!(edged.elements().iter().filter(|e| matches!(e, PathEl::MoveTo(..))).count(), 3, "the pen-up side isn't edged: {edged:?}"); + // Nothing is drawn in polygon mode itself. + assert!(leaves(&plot(poly).document).is_empty()); + + // A circle in polygon mode is a subpolygon of its own; CI and RA after PM2 work as before. + let i = plot("IN;SP1;PA2032,2032;PM0;CI1016;PM2;FP;"); + assert_eq!(leaves(&i.document).len(), 1); + + // Fill types: shading mixes the pen with white; hatching fills solid with a warning. + let i = plot("IN;SP5;PA0,0;FT10,50;RA100,100;FT3,10,45;RA200,200;"); + let shapes = leaves(&i.document); + assert_eq!((fill(&shapes[0]), fill(&shapes[1])), (Some(rgb(128, 128, 255)), Some(rgb(0, 0, 255)))); + assert_eq!(i.warnings, [HATCHES]); +} + +#[test] +fn line_types_become_dash_patterns() { + // A 10 mm pattern of line type 2 is 5 mm on, 5 mm off. + let i = plot("IN;SP1;LT2,10,1;PD0,0,4000,0;"); + let d = stroke(&leaves(&i.document)[0]).dash.expect("dashed"); + assert!(d.pattern.iter().all(|v| (v - 5.0 * MM).abs() < 1e-9) && d.pattern.len() == 2 && !d.align_corners, "{d:?}"); + // The default length is 4% of the P1-P2 diagonal; IP sets P1 and P2. + let i = plot("IN;IP0,0,3000,4000;SP1;LT3;PD0,0,4000,0;"); + let d = stroke(&leaves(&i.document)[0]).dash.expect("dashed"); + let total = 200.0 * 72.0 / 1016.0; + assert!((d.pattern[0] - 0.7 * total).abs() < 1e-9 && (d.pattern[1] - 0.3 * total).abs() < 1e-9, "{d:?}"); + // Adaptive types stretch to each line; a zero length is a dot one plotter unit long. + let i = plot("IN;SP1;LT-4,10,1;PD0,0,4000,0;"); + let d = stroke(&leaves(&i.document)[0]).dash.expect("dashed"); + assert!(d.align_corners && (d.pattern[2] - 72.0 / 1016.0).abs() < 1e-12, "{d:?}"); + // UL redefines a type; LT; draws solid and LT99 gives the type back. + let i = plot("IN;SP1;UL2,1,3;LT2,10,1;PD0,0,4000,0;PU;LT;PD0,100,4000,100;PU;LT99;PD0,200,4000,200;"); + let shapes = leaves(&i.document); + let d = stroke(&shapes[0]).dash.expect("dashed"); + assert!((d.pattern[0] - 2.5 * MM).abs() < 1e-9 && (d.pattern[1] - 7.5 * MM).abs() < 1e-9, "{d:?}"); + assert!(stroke(&shapes[1]).dash.is_none() && stroke(&shapes[2]).dash.is_some()); + // Line type 0 draws a dot at each point. + let i = plot("IN;SP1;LT0;PD0,0,1000,0,2000,0;"); + assert_eq!(leaves(&i.document).len(), 3); + // LA sets the caps, joins and miter limit. + let s = stroke(&leaves(&plot("IN;SP1;LA1,4,2,4,3,9;PD0,0,100,0;").document)[0]); + assert_eq!((s.cap, s.join, s.miter_limit), (LineCap::Round, LineJoin::Round, 9.0)); +} + +#[test] +fn scaling_maps_user_units_onto_p1_and_p2() { + // Anisotropic: 100 user units across an inch. + let size = |s: &str| { + let shapes = leaves(&plot(s).document); + bez(&shapes[0]).bounding_box().size() + }; + let s = size("IN;IP0,0,1016,2032;SC0,100,0,100;SP1;PD0,0,100,100;"); + assert!((s.width - 72.0).abs() < 1e-9 && (s.height - 144.0).abs() < 1e-9, "{s:?}"); + // Isotropic: the smaller of the two scales on both axes. + let s = size("IN;IP0,0,1016,2032;SC0,100,0,100,1;SP1;PU0,0;PD100,100;"); + assert!((s.width - 72.0).abs() < 1e-9 && (s.height - 72.0).abs() < 1e-9, "{s:?}"); + // Point factor: 10 plotter units per user unit. + let s = size("IN;SC0,10,0,10,2;SP1;PD0,0,101.6,50.8;"); + assert!((s.width - 72.0).abs() < 1e-9 && (s.height - 36.0).abs() < 1e-9, "{s:?}"); + // Without IP, P2 lies 11 × 8.5 in from the origin. + let s = size("IN;SC0,11,0,8.5;SP1;PD0,0,1,1;"); + assert!((s.width - 72.0).abs() < 1e-9 && (s.height - 72.0).abs() < 1e-9, "{s:?}"); + // SC; goes back to plotter units; scaling that makes no area is ignored. + let s = size("IN;SC0,1,0,1;SC;SC0,0,0,1;SP1;PD0,0,1016,1016;"); + assert!((s.width - 72.0).abs() < 1e-9, "{s:?}"); + // RO turns the coordinate system: x runs up. + let shapes = leaves(&plot("IN;RO90;SP1;PW0;PA0,0;PD1016,0;").document); + let b = bez(&shapes[0]).bounding_box(); + assert!(b.width() < 1e-9 && (b.height() - 72.0).abs() < 1e-9, "{b:?}"); +} + +#[test] +fn polyline_encoded_data_is_read() { + let mut f = b"IN;SP1;PW0;PE".to_vec(); + // Pen 2, a pen-up move to the absolute (1016, 0), then a relative line an inch up. + f.push(b':'); + f.extend(pe_number(2, false)); + f.extend(b"<="); + f.extend(pe_number(1016, false)); + f.extend(pe_number(0, false)); + f.extend(pe_number(0, false)); + f.extend(pe_number(1016, false)); + f.push(b';'); + let i = plot_bytes(&f); + let shapes = leaves(&i.document); + assert_eq!(shapes.len(), 1); + assert_eq!(stroke(&shapes[0]).paint, rgb(255, 0, 0)); + assert_points(&ends(&bez(&shapes[0])), &[(0.125, 72.0), (0.125, 0.0)]); + + // 7-bit data with two fractional bits: 4064 / 4 = 1016. + let mut f = b"IN;SP1;PW0;PE7>".to_vec(); + f.extend(pe_number(2, true)); + f.extend(pe_number(-4064, true)); + f.extend(pe_number(0, true)); + f.push(b';'); + let b = bez(&leaves(&plot_bytes(&f).document)[0]).bounding_box(); + assert!((b.width() - 72.0).abs() < 1e-9, "{b:?}"); + + // Data that can't be decoded ends the instruction at its semicolon: none of it is read as + // instructions. + let shapes = leaves(&plot("IN;SP1;PE#PD5000,5000;PD1016,0;").document); + assert_eq!(shapes.len(), 1); + assert!((bez(&shapes[0]).bounding_box().width() - 72.0).abs() < 1e-9); + + // Rectangle mode: a pen-up move, then a filled rectangle relative to it. + let mut f = b"IN;SP3;PE9".to_vec(); + for v in [100, 100, 1016, 508] { + f.extend(pe_number(v, false)); + } + f.push(b';'); + let shapes = leaves(&plot_bytes(&f).document); + assert_eq!(fill(&shapes[0]), Some(rgb(0, 255, 0))); + let b = bez(&shapes[0]).bounding_box(); + assert!((b.width() - 72.0).abs() < 1e-9 && (b.height() - 36.0).abs() < 1e-9, "{b:?}"); +} + +#[test] +fn printer_escapes_and_job_lines_are_skipped() { + let mut f = b"\x1b%-12345X@PJL JOB\r\n@PJL ENTER LANGUAGE=PCL\r\n\x1bE\x1b%0BIN;SP1;PW0;PD0,0,1016,0;PU;\x1b%0A".to_vec(); + // An HP RTL raster image whose data spells out instructions. + f.extend(b"\x1b*r1A\x1b*b11WPD9999,9999\x1b*rC"); + f.extend(b"\x1b%1BPD1016,1016;\x1b%-12345X@PJL EOJ\r\n"); + assert!(is_hpgl(&f)); + let i = plot_bytes(&f); + let shapes = leaves(&i.document); + // The pen went up and came down where the line ended, so the line goes on. + assert_eq!(shapes.len(), 1, "{shapes:#?}"); + assert_eq!(ends(&bez(&shapes[0])).len(), 3); + assert_eq!(i.warnings, [RASTER], "{:?}", i.warnings); + let r = i.document.artboards[0].rect; + assert!((r.width() - 72.125).abs() < 1e-9 && (r.height() - 72.125).abs() < 1e-9, "{r:?}"); + + // The device-control escapes of older plotters. + let f = b"\x1b.(\x1b.I81;;17:\x1b.N;19:IN;SP1;PD0,0,1016,0;\x1b.)"; + assert!(is_hpgl(f)); + assert_eq!(leaves(&plot_bytes(f).document).len(), 1); +} + +#[test] +fn labels_comments_and_unknown_instructions_are_skipped() { + // A label's text, up to its terminator (ETX, or the one DT sets), isn't read as instructions. + let i = plot("IN;SP1;LBPD9999,9999\x03DT*,1;LBPU0,0;PD5000,5000*CO\"PD8000,8000\";PD1016,0;PU;ZZ1,2;QQ;"); + let shapes = leaves(&i.document); + assert_eq!(shapes.len(), 1); + assert_eq!(i.warnings, [LABELS.to_string(), "2 instructions of kinds VectorCraft doesn't read were skipped".to_string()]); + // Symbol mode's symbols aren't drawn, with a warning; its lines are. + let i = plot("IN;SP1;SM*;PD100,0;SM;"); + assert_eq!((i.warnings.clone(), leaves(&i.document).len()), (vec![SYMBOLS.to_string()], 1)); + // Later pages and the input window are warned about. + let i = plot("IN;IW0,0,10,10;SP1;PD100,0;PU;PG;PD0,100;PG;"); + assert_eq!(i.warnings, [WINDOW, PAGES]); + // A page advance raises the pen at the origin: nothing joins the pages. + let i = plot("IN;SP1;PD100,0;PG;PA200,0;PD300,0;"); + let shapes = leaves(&i.document); + assert_eq!(shapes.len(), 2); + assert_eq!(ends(&bez(&shapes[1])).len(), 2, "the second page's line starts at (200, 0)"); + // A page advance at the end changes nothing. + assert!(plot("IN;SP1;PD100,0;PG;").warnings.is_empty()); + // A file that draws nothing opens as a letter-size page. + let i = plot("IN;SP1;PU100,100;"); + assert!(leaves(&i.document).is_empty() && i.document.artboards[0].rect.size() == kurbo::Size::new(612.0, 792.0)); +} + +#[test] +fn only_plot_files_are_taken_for_hpgl() { + for f in [ + &b"IN;SP1;PU0,0;PD100,100;"[..], + b"in;sp1;pu0,0;pd100,100;", + b";IN;\r\nSP1;\r\nPA100,100;", + b"\x03IN;", + b"SP1PD0,0,10,10PU", + b"IN", + b"CO\"made by hand\";IN;", + b"IN;SP1;DT*;LBhello world*PA0,0;SMx;PA1,1;SM;", + b"IN;SP1;PE<=\xbf\xbf;PU;", + b"\x1b%-12345X@PJL ENTER LANGUAGE=HPGL2\nIN;SP1;", + ] { + assert!(is_hpgl(f), "{:?}", String::from_utf8_lossy(f)); + } + for f in [ + &b""[..], + b"IN THE BEGINNING", + b"set terminal png\nplot sin(x)\n", + b"Paris, 10 to 12", + b"SPDX-License-Identifier: MIT", + b"CONTENTS", + b"CO \"a comment\";hello world", + b"DT*;LBtext*nope", + b"\x89PNG\r\n\x1a\n", + b"IN;SP1;PD0,0;hello world", + b"\x1b%-12345X@PJL ENTER LANGUAGE=PCL\n\x1bE\x1b*r1A", + ] { + assert!(!is_hpgl(f), "{:?}", String::from_utf8_lossy(f)); + assert_eq!(import(f).err().as_deref(), Some("not an HP-GL file"), "{:?}", String::from_utf8_lossy(f)); + } + // A comment needs no string; instructions of an older or a device's own set count when a + // semicolon ends them. + for f in [&b"CO;IN;SP1;PD0,0,10,10;"[..], b"IN;CO;SP1;PD0,0,10,10;", b"IN;SP1;VA;VS10;PU0,0;PD1016,0;", b"IN;GC5;SP1;PD0,0,10,0;"] { + assert!(is_hpgl(f), "{:?}", String::from_utf8_lossy(f)); + } + assert!(!is_hpgl(b"IN;GC5") && !is_hpgl(b"IN;Hello, world;")); + // A printer prolog of any length comes before the first instruction. + let long = [&b"\x1b%-12345X"[..], &b"@PJL COMMENT a job line of some length\r\n".repeat(400), b"\x1bE\x1b%0BIN;SP1;PD100,0;"].concat(); + assert!(long.len() > 16_000 && is_hpgl(&long)); + assert_eq!(leaves(&plot_bytes(&long).document).len(), 1); + // Instructions of any kind may follow the first eight, garbage included. + assert!(is_hpgl(b"IN;SP1;PU;PD;PU;PD;PU;PD;hello world")); +} + +/// A file read as HP-GL (picked by its extension) may start with any instruction the reader knows, +/// or one of another set that a semicolon ends; its content alone doesn't make it HP-GL. +#[test] +fn a_plot_file_may_start_with_any_instruction() { + for f in [&b"SI0.2,0.3;SP1;PA0,0;PD1016,0;"[..], b"DI1,0;SP1;PA0,0;PD1016,0;", b"GC5;SP1;PA0,0;PD1016,0;"] { + assert!(!is_hpgl(f), "{:?}", String::from_utf8_lossy(f)); + assert_eq!(leaves(&plot_bytes(f).document).len(), 1, "{:?}", String::from_utf8_lossy(f)); + } + for f in [&b"GC5"[..], b"SIhello world", b"set terminal png\n"] { + assert_eq!(import(f).err().as_deref(), Some("not an HP-GL file"), "{:?}", String::from_utf8_lossy(f)); + } + // Instructions of another set alone, however many or long, are not taken for HP-GL. + let long = [&b"GC"[..], "1".repeat(5000).as_bytes(), b";ZZ1;"].concat(); + for f in [&b"GC5;"[..], b"GC5;ZZ1;", b"GC5;ZZ1;YY2;XX3;WW4;VV5;UU6;TT7;", &long] { + assert_eq!(import(f).err().as_deref(), Some("not an HP-GL file"), "{:?}", String::from_utf8_lossy(f)); + } +} + +#[test] +fn escapes_that_carry_values_or_data_are_skipped_whole() { + // A reset leaves HP-GL until a language switch; symbol-set escapes carry a value and a letter. + for f in [ + &b"\x1bE\x1b(8U\x1b%1BIN;SP1;PD0,0,1016,0;"[..], + b"\x1bE\x1b(10U\x1b)0N\x1b%1BIN;SP1;PD0,0,1016,0;", + b"\x1bEHello\x1b%1BIN;SP1;PD0,0,1016,0;", + ] { + assert!(is_hpgl(f), "{:?}", String::from_utf8_lossy(f)); + assert_eq!(leaves(&plot_bytes(f).document).len(), 1, "{:?}", String::from_utf8_lossy(f)); + } + // A letter left over from an escape doesn't join the next mnemonic. + let i = plot_bytes(b"IN;SP1;\x1b(8UPD0,0,1016,0;"); + assert!(i.warnings.is_empty() && leaves(&i.document).len() == 1, "{:?}", i.warnings); + // Raster data by plane and transparent print data are skipped by their byte counts, however + // they read. + let line = |data_escape: &[u8]| { + let data = b"\x1b%1BPD0,5000;"; + let mut f = b"IN;SP1;PW0;PD0,0,0,1016;\x1b%0A".to_vec(); + f.extend(data_escape); + f.extend(data.len().to_string().as_bytes()); + f.extend(if data_escape.ends_with(b"b") { &b"V"[..] } else { b"X" }); + f.extend(data); + f.extend(b"\x1b*rC\x1b%1BPD0,0;"); + bez(&leaves(&plot_bytes(&f).document)[0]).bounding_box() + }; + for escape in [&b"\x1b*r1A\x1b*b"[..], b"\x1b&p"] { + let b = line(escape); + assert!((b.height() - 72.0).abs() < 1e-9, "{:?}: {b:?}", String::from_utf8_lossy(escape)); + } +} + +#[test] +fn polygon_mode_follows_its_own_rules() { + // The point after a circle starts a new subpolygon: the triangle after it doesn't reach back + // to the circle's center, filled or edged. + let i = plot("IN;SP1;PW0;PA1000,1000;PM0;CI200;PD2000,1000,2000,2000,1000,2000;PM2;FP;EP;"); + let shapes = leaves(&i.document); + assert_eq!(shapes.len(), 2); + for s in &shapes { + let p = bez(s); + let first = p.elements().iter().position(|e| matches!(e, PathEl::ClosePath)).unwrap_or(p.elements().len()); + let circle = BezPath::from_vec(p.elements()[..first].to_vec()).bounding_box(); + let center = circle.center(); + assert!(ends(&p).iter().all(|e| !near(*e, center)), "{p:?}"); + } + // PM1 closes with the pen up: EP draws two sides of the triangle, not the third; PM2 closes + // with the pen as it is. + let sides = |s: &str| { + let p = bez(&leaves(&plot(s).document)[0]); + p.elements().iter().filter(|e| matches!(e, PathEl::LineTo(..))).count() + }; + assert_eq!(sides("IN;SP1;PA0,0;PM0;PD1000,0,1000,1000;PM1;PM2;EP;"), 2); + assert_eq!(sides("IN;SP1;PA0,0;PM0;PD1000,0,1000,1000;PM2;EP;"), 3); + // The closing point moves the pen: a relative move after PM1 starts from the start. + let i = plot("IN;SP1;PA0,0;PM0;PD1000,0,1000,1000;PM1;PU;PR0,2000;PD1000,0,0,1000;PM2;FP;"); + let b = bez(&leaves(&i.document)[0]).bounding_box(); + assert!((b.height() - 3000.0 * PT_PER_PLU).abs() < 1e-9, "{b:?}"); + // A subpolygon of fewer than three points (the closing point counted) is neither filled nor + // edged. + assert!(leaves(&plot("IN;SP1;PA0,0;PM0;PD0,0;PM2;FP;EP;").document).is_empty()); + let i = plot("IN;SP1;PA0,0;PM0;PR0,0;PM1;PA;PD1000,0,0,1000,0,0;PM2;FP;"); + let filled = bez(&leaves(&i.document)[0]); + assert_eq!(filled.elements().iter().filter(|e| matches!(e, PathEl::ClosePath)).count(), 1, "{filled:?}"); + // Polygon mode ignores the instructions it doesn't allow: pens, scaling and labels. + let i = plot("IN;SP1;PA0,0;PM0;SP2;SC0,1,0,1;LBPD9999,9999\x03PD1016,0,1016,1016;PM2;FP;"); + let shapes = leaves(&i.document); + assert_eq!((shapes.len(), fill(&shapes[0])), (1, Some(rgb(0, 0, 0)))); + assert!((bez(&shapes[0]).bounding_box().width() - 72.0).abs() < 1e-9 && i.warnings.is_empty(), "{:?}", i.warnings); +} + +#[test] +fn rotation_keeps_the_pen_and_turns_the_defaults() { + // After RO90, IP's default P2 is the rotated hard-clip corner: the user square spans 8.5 in + // across its rotated x axis and 11 in up it, which lie up and across the page. + let i = plot("IN;RO90;IP;SC0,100,0,100;SP1;PW0;PA0,0;PD100,0,100,100,0,100,0,0;"); + let b = bez(&leaves(&i.document)[0]).bounding_box(); + assert!((b.width() - 792.0).abs() < 1e-9 && (b.height() - 612.0).abs() < 1e-9, "{b:?}"); + // IR's percentages are of the rotated limits too. + let i = plot("IN;RO90;IR0,0,100,100;SC0,1,0,1;SP1;PW0;PA0,0;PD1,1;"); + let b = bez(&leaves(&i.document)[0]).bounding_box(); + assert!((b.width() - 792.0).abs() < 1e-9 && (b.height() - 612.0).abs() < 1e-9, "{b:?}"); + // The pen stays where it was on the page: a line after RO starts where the one before ended. + let i = plot("IN;SP1;PW0;PD0,0,1016,0;PU;RO90;PD;PR1016,0;"); + let all = leaves(&i.document).iter().map(|n| bez(n).bounding_box()).reduce(|a, b| a.union(b)).unwrap(); + assert!((all.width() - 72.0).abs() < 1e-9 && (all.height() - 72.0).abs() < 1e-9, "{all:?}"); +} + +#[test] +fn line_type_zero_and_odd_patterns_follow_the_reference() { + // Line type 0: one dot for an arc (at its end) and one for a circle (at its center). + for s in ["IN;SP1;LT0;PA0,0;PD;AA1016,0,180;", "IN;SP1;LT0;PA0,0;CI500;"] { + let shapes = leaves(&plot(s).document); + assert_eq!(shapes.len(), 1, "{s}"); + assert!(bez(&shapes[0]).bounding_box().width() < 0.1, "{s}"); + } + // An odd number of gaps repeats with the last pen-down stretch running into the first. + let i = plot("IN;SP1;UL3,50,25,25;LT3,10,1;PD0,0,4000,0;"); + let d = stroke(&leaves(&i.document)[0]).dash.expect("dashed"); + assert!((d.pattern[0] - 7.5 * MM).abs() < 1e-9 && (d.pattern[1] - 2.5 * MM).abs() < 1e-9 && d.pattern.len() == 2, "{d:?}"); + assert!((d.offset - 2.5 * MM).abs() < 1e-9, "{d:?}"); + // One pen-down stretch is a solid line; a dot keeps the pattern's length. + let d = stroke(&leaves(&plot("IN;SP1;UL3,100;LT3,10,1;PD0,0,4000,0;").document)[0]).dash.expect("dashed"); + assert_eq!(d.pattern[1], 0.0); + let d = stroke(&leaves(&plot("IN;SP1;LT4,10,1;PD0,0,4000,0;").document)[0]).dash.expect("dashed"); + assert!((d.pattern.iter().sum::() - 10.0 * MM).abs() < 1e-9, "{d:?}"); +} + +#[test] +fn pen_colors_ignore_two_or_three_parameters() { + let i = plot("IN;PC3,0,0,255;PC3,255;PC3,255,0;SP3;PD0,0,10,0;"); + assert_eq!(stroke(&leaves(&i.document)[0]).paint, rgb(0, 0, 255)); +} + +#[test] +fn hostile_files_import_without_panics() { + let mut cases: Vec> = vec![ + // Coordinates past any plotter's range, and numbers with too many digits. + b"IN;SP1;PD99999999999999999999999999999,0;PU0,0;PD1016,1016;".to_vec(), + b"IN;SP1;PD0.000000000000000000000000001,1e999,--,++,..;".to_vec(), + // Unterminated labels, comments and encoded polylines. + b"IN;SP1;LBno end".to_vec(), + b"IN;CO\"no end".to_vec(), + b"IN;SP1;PE<=\xff\xff\xff\xfe\xfe".to_vec(), + b"IN;SP1;PE>\x7e\x7e\x7e\x7e\x7e\x7e\x7e\x7e\x7e\x7e\x7e\x7e\xfe\x40\xc0;".to_vec(), + // Arcs and wedges of every degenerate kind, with huge sweeps. + b"IN;SP1;PD;AA0,0,32767;AR0,0,90;AT0,0,0,0;RT1,1,2,2;CI0;CI-5;WG0,0,0;EW5,99999,-99999;WG-5,0,360;CI99999999999999;".to_vec(), + // Scaling onto one point, rotations the format doesn't define, huge palettes and pens. + b"IN;IP5,5,5,5;SC0,1,0,1,1;SP1;PD1,1;SC0,0,0,0,2;RO45;NP99999999;SP99999999999;PC99999999,1,2,3;PW99999,99999;PD2,2;".to_vec(), + // Polygon mode left open, PM1 and PM2 without PM0, FP and EP with nothing buffered. + b"IN;SP1;FP;EP;PM1;PM2;PM0;PD10,10;PM1;PM1;PM1;CI5;PE<\xc0\xc0;".to_vec(), + // Escapes cut short, and data lengths past the end. + b"\x1b%-12345X@PJL".to_vec(), + b"IN;SP1;PD0,0;\x1b*b99999999999W".to_vec(), + b"IN;\x1b".to_vec(), + b"IN;\x1b.".to_vec(), + ]; + // A job line with no end. + cases.push([&b"\x1b%-12345X@PJL "[..], &b"x".repeat(1 << 20)].concat()); + // Bytes of every value after a valid start. + cases.push([&b"IN;SP1;PD"[..], &(0..=255u8).collect::>()].concat()); + for f in &cases { + let r = std::panic::catch_unwind(|| import(f)); + assert!(r.is_ok(), "{:?}", String::from_utf8_lossy(f)); + } + let far = import(&cases[0]).unwrap(); + assert!(far.warnings.iter().any(|w| w == FAR_AWAY), "{:?}", far.warnings); + assert_eq!(leaves(&far.document).len(), 1, "the line in range is kept"); + + // Past the budget for path points, the rest is left out with a warning; pen-up moves, which + // make no path, don't count. + let many = format!("IN;SP1;PR;PD{}", "1,0,".repeat(300_000)); + let i = plot(&many); + assert!(i.warnings.iter().any(|w| w == TOO_MANY_POINTS), "{:?}", i.warnings); + // Scaling points past any range give relative pen widths no wider than the widest pen. + let i = plot("IN;IP-99999999999999999999,0,99999999999999999999,0;WU1;PW32767;SP1;PD100,0;"); + let r = i.document.artboards[0].rect; + assert!(r.width().is_finite() && r.height() <= 16384.0 * 72.0 / 1016.0 + 1e-6, "{r:?}"); + assert!((stroke(&leaves(&i.document)[0]).width - 16384.0 * 72.0 / 1016.0).abs() < 1e-9); + + // Each fill of the polygon buffer is a copy of it, and counts. + let big = format!("IN;SP1;PM0;PR;PD{}PM2;{}", "1,1,".repeat(1000), "FP;EP;".repeat(1000)); + let i = plot(&big); + assert!(i.warnings.iter().any(|w| w == TOO_MANY_POINTS) && leaves(&i.document).len() < 400, "{:?}", i.warnings); + for pen in ["SP1;PU", "SP0;PD"] { + let moves = format!("IN;{pen}{};SP1;PU0,0;PD1016,0;", "1,0,".repeat(300_000)); + let i = plot(&moves); + assert!(i.warnings.is_empty() && leaves(&i.document).len() == 1, "{pen}: {:?}", i.warnings); + } +} diff --git a/crates/cad/src/hpgl/write.rs b/crates/cad/src/hpgl/write.rs new file mode 100644 index 0000000000..6ab80c8ba0 --- /dev/null +++ b/crates/cad/src/hpgl/write.rs @@ -0,0 +1,1138 @@ +//! HP-GL export: the visible art over a region as pen moves, for pen plotters and cutters. +//! +//! Every visible path is drawn once along its own line: its fills and strokes are not painted, so +//! a filled shape is its closed outline (what a cutter cuts) and a stroke is its center line. Each +//! color is a pen: by default pen 1 is the first color the plot draws in, pen 2 the next new one, +//! and so on; with a pen table each path takes the pen whose color is nearest its own. The plots +//! of one export ([`export_regions`]) share the numbering. A path's color is its topmost visible +//! stroke's, else its topmost visible fill's (one at 0% opacity does not count); a gradient is the +//! average of its stops and a pattern its first visible solid fill (gray without one). Curves are +//! flattened to straight moves within a tolerance. Type is drawn as its glyph outlines, a gradient +//! mesh as its outline in the average of its shown points' colors, clipping masks cut what they clip, +//! and the art is cut at the region's edges. Hidden and non-printing layers, hidden objects, +//! objects at 0% opacity, template layers, guides and placed images are left out. +//! +//! Coordinates are plotter units (1016 to the inch, y up) from the region's bottom-left corner or +//! its center, rounded to whole units. Art past ±8,388,607 units (2²³ − 1, the smallest range +//! the HP-GL/2 reference asks a device to take for encoded polylines) from the origin is cut off. +//! An HP-GL plot with a coordinate outside −32,768 to 32,767 (16-bit numbers, the range older +//! devices read) gets a warning; HP-GL/2's encoded polylines take the wider range. +//! The pens are drawn in turn (pen 1's paths, then pen 2's), each in paint order or, with +//! `sort`, each next path the one that starts nearest where the pen stopped. With `inside_first`, +//! a pen draws a path only after every path of its own that lies inside it (a letter's counter +//! before the letter, a hole before the part). +//! +//! HP-GL writes `IN;`, then for each pen `PU;SP;` and per path `PUx,y;PDx,y,…;`, then `PU;SP0;`. +//! HP-GL/2 also writes the palette (`NP` and a `PC` color for each pen) and draws each pen's paths +//! as one encoded polyline (`PE`, base 64). + +mod clip; +mod nest; + +use std::cmp::Reverse; +use std::collections::{BinaryHeap, HashSet}; +use std::sync::Arc; + +use kurbo::PathEl; +use vectorcraft_color::Paint; +use vectorcraft_doc::{AppearanceItem, Document, Node, NodeKind, StrokeLayer, SymbolBoxes}; +use vectorcraft_geom::{Affine, BezPath, FillRule, Point, Rect}; + +use crate::MAX_NEST; +use clip::Region; + +/// Plotter units per point. +const PLU_PER_PT: f64 = 1016.0 / 72.0; +/// The largest coordinate written, plotter units. +pub const MAX_COORD: i64 = (1 << 23) - 1; +/// The coordinates an HP-GL plot keeps to without a warning: 16-bit numbers, plotter units. +const CLASSIC_RANGE: std::ops::RangeInclusive = -32_768..=32_767; +/// The curve tolerance a path is flattened to by default, points. +pub const DEFAULT_TOLERANCE: f64 = 0.1; +/// The smallest and largest curve tolerance, points. +pub const TOLERANCE_RANGE: std::ops::RangeInclusive = 0.01..=10.0; +/// The most pens: a pen table's length, and the colors that get a pen of their own. +pub const MAX_PENS: usize = 255; +/// The most points the plots of one export hold. +const MAX_POINTS: usize = if cfg!(test) { 100_000 } else { 10_000_000 }; +/// The most work sorting paths and finding which lie inside others may take, over the whole plot: +/// one for each point or box compared. +const MAX_SORT_WORK: u64 = if cfg!(test) { 100_000 } else { 500_000_000 }; +/// The most edge tests clipping masks may take, over the whole plot. +const MAX_CLIP_TESTS: u64 = if cfg!(test) { 1_000_000 } else { 200_000_000 }; +/// The most points the clipping masks around an object may hold, together. +const MAX_MASK_POINTS: usize = if cfg!(test) { 10_000 } else { 10_000_000 }; +/// The most objects live art (blends, envelopes, repeats) may make for a plot, together, as one +/// evaluation of live art may make ([`vectorcraft_doc::live::MAX_GENERATED`]). +const MAX_GENERATED: u64 = if cfg!(test) { 1_000 } else { vectorcraft_doc::live::MAX_GENERATED as u64 }; + +const TEXT_OUTLINES: &str = "type is plotted as its glyph outlines"; +const INLINE_GRAPHICS: &str = "inline graphics in type are left out"; +const IMAGES: &str = "placed images are left out: a pen draws only lines"; +const MASKS: &str = "opacity masks are left out"; +const RASTER_FX: &str = "raster effects (shadows, glows, blurs, feathering) are left out"; +const STROKE_LOOK: &str = "stroke widths, dashes, brushes and arrowheads are left out: each path is drawn once along its own line"; +const TOO_MANY_POINTS: &str = "the export is too large: the art past its first 10 million points was left out"; +const CLIP_WORK: &str = "clipping masks are too complex to apply in full: the art past that point is drawn whole"; +const MASK_POINTS: &str = "clipping masks past 10 million points together are left out: the art they clip is drawn unclipped by them"; +const OUT_OF_RANGE: &str = "art past 8,388,607 plotter units (about 210 m) from the origin is cut off"; +const PAST_CLASSIC_RANGE: &str = "the plot has coordinates past 32,767 plotter units (about 82 cm) from the origin, which older HP-GL devices may not read: HP-GL/2 takes a wider range"; +const MANY_COLORS: &str = "the art has more than 255 colors: the colors past those draw with the pen of the nearest color"; +const UNSORTED: &str = "the plot has too many paths to sort in full: the rest are drawn in paint order"; +const UNSORTED_INSIDE: &str = "the plot has too many paths to sort in full: the rest are drawn in paint order, each after the paths inside it"; +const UNNESTED: &str = "the plot has too many paths to find in full which lie inside others: from the pen where that stopped, a path may be drawn before the paths inside it"; +const TOO_DEEP: &str = "symbols, blends, envelopes and repeats nested more than 8 deep were left out"; +const LIVE_LEFT_OUT: &str = "blends, envelopes and repeats make too many objects: the art past 4 million objects was left out"; +const SYMBOLS_LEFT_OUT: &str = "symbols placed inside symbols hold too many objects: the instances past that were left out"; + +/// The language written. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Version { + /// `IN`, `SP`, `PU` and `PD` only. + #[default] + Hpgl, + /// HP-GL/2: pen colors (`NP`, `PC`) and encoded polylines (`PE`). + Hpgl2, +} + +impl Version { + pub const ALL: [Self; 2] = [Self::Hpgl, Self::Hpgl2]; + + /// The `hpglVersion` param value. + pub fn id(self) -> &'static str { + match self { + Self::Hpgl => "hpgl", + Self::Hpgl2 => "hpgl2", + } + } + + pub fn label(self) -> &'static str { + match self { + Self::Hpgl => "HP-GL", + Self::Hpgl2 => "HP-GL/2", + } + } + + /// A version by id (`hpgl`, `hpgl2`; `hp-gl` and `hp-gl/2` also read), any case. + pub fn from_id(s: &str) -> Option { + let s = s.trim(); + Self::ALL.into_iter().find(|v| s.eq_ignore_ascii_case(v.id()) || s.eq_ignore_ascii_case(v.label())) + } +} + +/// Where the plot's origin (0, 0) lies on the region. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Origin { + #[default] + BottomLeft, + Center, +} + +impl Origin { + pub const ALL: [Self; 2] = [Self::BottomLeft, Self::Center]; + + /// The `origin` param value. + pub fn id(self) -> &'static str { + match self { + Self::BottomLeft => "bottomLeft", + Self::Center => "center", + } + } + + /// An origin by id, any case. + pub fn from_id(s: &str) -> Option { + Self::ALL.into_iter().find(|o| s.trim().eq_ignore_ascii_case(o.id())) + } +} + +/// The HP-GL export settings. +#[derive(Clone, Debug)] +pub struct HpglOptions { + pub version: Version, + /// How far a flattened curve may lie from the curve, points ([`TOLERANCE_RANGE`]; a value + /// outside it is an error). + pub tolerance: f64, + /// The pen table: pen 1's color first, up to [`MAX_PENS`] (more is an error). Empty: a pen for + /// each color the art draws in. + pub pens: Vec<[u8; 3]>, + pub origin: Origin, + /// Draw each pen's paths nearest first, instead of in paint order. + pub sort: bool, + /// Draw a path only after the pen's paths that lie inside it. + pub inside_first: bool, + /// The area plotted (document space): its bottom-left corner or center is the origin, and the + /// art is cut at its edges. + pub region: Rect, +} + +impl Default for HpglOptions { + fn default() -> Self { + Self { + version: Version::default(), + tolerance: DEFAULT_TOLERANCE, + pens: vec![], + origin: Origin::default(), + sort: false, + inside_first: false, + region: Rect::ZERO, + } + } +} + +/// A written plot. +#[derive(Clone, Debug, Default)] +pub struct HpglOutput { + pub bytes: Vec, + /// The pens' colors, pen 1's first. + pub pens: Vec<[u8; 3]>, + /// What was approximated or left out. + pub warnings: Vec, + /// Notes on the options: sorting the paths or drawing the inner paths first was applied only + /// in part. + pub setting_notes: Vec, +} + +/// Write the visible art of `doc` over `opts.region` as an HP-GL plot. Live geometry effects are +/// applied first. +pub fn export(doc: &Document, opts: &HpglOptions) -> Result { + Ok(export_regions(doc, opts, &[opts.region])?.pop().unwrap_or_default()) +} + +/// Write the visible art of `doc` over each of `regions` as an HP-GL plot, one per region, as +/// [`export`] does with `opts.region`. The plots share one pen numbering, so a color is the same +/// pen in each, and one point budget. +pub fn export_regions(doc: &Document, opts: &HpglOptions, regions: &[Rect]) -> Result, String> { + let regions: Vec = regions.iter().map(|r| r.abs()).collect(); + if regions.iter().any(|r| ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) || r.width() <= 0.0 || r.height() <= 0.0) { + return Err("the export region is empty".into()); + } + if !TOLERANCE_RANGE.contains(&opts.tolerance) { + return Err("the curve tolerance must be from 0.01 to 10 points".into()); + } + if opts.pens.len() > MAX_PENS { + return Err("the pen table holds more than 255 pens".into()); + } + let tolerance = opts.tolerance; + // Layers the plot leaves out go first: baking can wrap one in art that would be drawn (its + // crop marks). + let shown = plotted(&doc.layers, false).map(|layers| { + let mut d = doc.clone(); + d.layers = layers; + d + }); + let doc = shown.as_ref().unwrap_or(doc); + let baked = vectorcraft_effects::bake_document(doc); + let doc = baked.as_ref().unwrap_or(doc); + // Each plot's lines in plotter units, with the points a move doesn't change dropped, and its + // warnings. + let mut plots: Vec<(Lines, Vec)> = Vec::with_capacity(regions.len()); + let mut points = 0; + for r in regions { + // Document space to plotter units, y up. + let o = match opts.origin { + Origin::BottomLeft => Point::new(r.x0, r.y1), + Origin::Center => r.center(), + }; + let span = MAX_COORD as f64 / PLU_PER_PT; + let range = Rect::new(o.x - span, o.y - span, o.x + span, o.y + span); + let mut walk = Walk::new(doc, r.intersect(range), tolerance); + walk.points = points; + // Only a region past the range can have art the range cuts off. + if r.intersect(range) != r { + walk.range = Some((range, r)); + walk.asked = Region::new(vec![corners(r)], FillRule::NonZero); + } + for l in &doc.layers { + walk.node(l, false); + } + points = walk.points; + let Walk { runs, warnings, .. } = walk; + let to_plu = |p: Point| { + let x = ((p.x - o.x) * PLU_PER_PT).round().clamp(-(MAX_COORD as f64), MAX_COORD as f64) as i64; + let y = ((o.y - p.y) * PLU_PER_PT).round().clamp(-(MAX_COORD as f64), MAX_COORD as f64) as i64; + (x, y) + }; + let lines = runs + .into_iter() + .filter_map(|run| { + let mut pts: Vec<(i64, i64)> = Vec::with_capacity(run.points.len()); + for p in run.points { + let q = to_plu(p); + if pts.last() != Some(&q) { + pts.push(q); + } + } + // A line shorter than a plotter unit draws nothing and takes no pen. + (pts.len() >= 2).then_some((run.rgb, pts)) + }) + .collect(); + plots.push((lines, warnings)); + } + let mut pen_warnings = vec![]; + let colors: Vec<[u8; 3]> = plots.iter().flat_map(|(lines, _)| lines.iter().map(|(c, _)| *c)).collect(); + let (pens, of_line) = assign_pens(&colors, &opts.pens, &mut pen_warnings); + let mut of_line = of_line.into_iter(); + let mut out = Vec::with_capacity(plots.len()); + for (lines, mut warnings) in plots { + let mut by_pen: Vec>> = vec![vec![]; pens.len()]; + for ((_, pts), pen) in lines.into_iter().zip(of_line.by_ref()) { + if let Some(paths) = by_pen.get_mut(pen) { + paths.push(pts); + } + } + if !by_pen.iter().all(Vec::is_empty) { + pen_warnings.iter().for_each(|w| warn(&mut warnings, w)); + } + let mut setting_notes = vec![]; + if opts.sort || opts.inside_first { + let (mut at, mut work) = ((0, 0), MAX_SORT_WORK); + for paths in &mut by_pen { + at = reorder(paths, at, &mut work, opts.sort, opts.inside_first, &mut setting_notes); + } + } + if opts.version == Version::Hpgl && by_pen.iter().flatten().flatten().any(|(x, y)| !CLASSIC_RANGE.contains(x) || !CLASSIC_RANGE.contains(y)) { + warn(&mut warnings, PAST_CLASSIC_RANGE); + } + let bytes = match opts.version { + Version::Hpgl => plain(&by_pen), + Version::Hpgl2 => encoded(&by_pen, &pens), + }; + out.push(HpglOutput { bytes, pens: pens.clone(), warnings, setting_notes }); + } + Ok(out) +} + +/// A plot's lines in plotter units, each with its color. +type Lines = Vec<([u8; 3], Vec<(i64, i64)>)>; + +fn warn(warnings: &mut Vec, w: &str) { + if !warnings.iter().any(|x| x == w) { + warnings.push(w.to_string()); + } +} + +/// The corners of `r`, as a clipping ring. +fn corners(r: Rect) -> Vec { + vec![Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)] +} + +/// Does `r` hold `p`, its edges included? +fn holds(r: Rect, p: Point) -> bool { + p.x >= r.x0 && p.x <= r.x1 && p.y >= r.y0 && p.y <= r.y1 +} + +/// The pens and each line's pen (0-based), from the lines' `colors`: with a table, the table and +/// the nearest of its colors; else each new color a pen of its own, up to [`MAX_PENS`], and the +/// nearest after that. +fn assign_pens(colors: &[[u8; 3]], table: &[[u8; 3]], warnings: &mut Vec) -> (Vec<[u8; 3]>, Vec) { + let mut pens: Vec<[u8; 3]> = table.iter().take(MAX_PENS).copied().collect(); + let fixed = !pens.is_empty(); + let mut of_line = Vec::with_capacity(colors.len()); + for &rgb in colors { + let pen = match pens.iter().position(|c| *c == rgb) { + Some(i) => i, + None if !fixed && pens.len() < MAX_PENS => { + pens.push(rgb); + pens.len() - 1 + } + None => { + if !fixed { + warn(warnings, MANY_COLORS); + } + nearest(&pens, rgb) + } + }; + of_line.push(pen); + } + (pens, of_line) +} + +/// The index of the color in `pens` nearest `c` (the first of equally near ones). +fn nearest(pens: &[[u8; 3]], c: [u8; 3]) -> usize { + let d = |p: &[u8; 3]| (0..3).map(|i| (i32::from(p[i]) - i32::from(c[i])).pow(2)).sum::(); + pens.iter().enumerate().min_by_key(|(_, p)| d(p)).map_or(0, |(i, _)| i) +} + +fn dist2(a: (i64, i64), b: (i64, i64)) -> i128 { + let (dx, dy) = (i128::from(a.0) - i128::from(b.0), i128::from(a.1) - i128::from(b.1)); + dx * dx + dy * dy +} + +/// The squared distance from `p` to box `b` (`[x0, y0, x1, y1]`), 0 inside it. +fn box_dist2(p: (i64, i64), b: [i64; 4]) -> i128 { + let d = |v: i64, lo: i64, hi: i64| i128::from(lo.saturating_sub(v).max(v.saturating_sub(hi)).max(0)); + let (dx, dy) = (d(p.0, b[0], b[2]), d(p.1, b[1], b[3])); + dx * dx + dy * dy +} + +/// `paths` (one pen's) reordered from `at`. With `nearest`, each next path is the one nearest +/// where the pen stopped, by its start or, for an open path (then drawn backwards), its end, or +/// for a closed path any of its points (where it then starts); without, the first in paint order. +/// With `inside_first`, a path is drawn only once every path lying inside it ([`nest::outer`]) is. +/// Once `work` is spent, the paths left keep paint order, each after the paths inside it with +/// `inside_first`, with a note in `notes`. Returns where the pen stops. +fn reorder( + paths: &mut Vec>, + mut at: (i64, i64), + work: &mut u64, + nearest: bool, + inside_first: bool, + notes: &mut Vec, +) -> (i64, i64) { + let boxes: Vec<[i64; 4]> = paths.iter().map(|p| nest::bounds(p)).collect(); + // The paths each path lies inside, and how many paths inside each are still to draw. + let outer = inside_first.then(|| nest::outer(paths, &boxes, work)).flatten(); + if inside_first && outer.is_none() { + warn(notes, UNNESTED); + } + let mut waiting = vec![0usize; paths.len()]; + for o in outer.iter().flatten().flatten() { + if let Some(w) = waiting.get_mut(*o) { + *w += 1; + } + } + if !nearest { + if let Some(outer) = &outer { + let all = std::mem::take(paths).into_iter().enumerate().collect(); + inner_first(all, outer, &mut waiting, paths); + } + return at; + } + // Each path with its index and box. + let mut left: Vec<_> = std::mem::take(paths).into_iter().zip(boxes).enumerate().map(|(i, (p, b))| (i, p, b)).collect(); + while !left.is_empty() { + // (index, reversed, the closed path's point to start at, distance) + let mut best: (usize, bool, Option, i128) = (usize::MAX, false, None, i128::MAX); + for (i, (j, p, b)) in left.iter().enumerate() { + let (Some(&s), Some(&e)) = (p.first(), p.last()) else { continue }; + *work = work.saturating_sub(1); + if waiting.get(*j).is_some_and(|w| *w > 0) { + continue; + } + if s == e && p.len() > 2 { + if box_dist2(at, *b) >= best.3 { + continue; + } + *work = work.saturating_sub(p.len() as u64); + if let Some((k, d)) = p.iter().enumerate().map(|(k, q)| (k, dist2(at, *q))).min_by_key(|(_, d)| *d) + && d < best.3 + { + best = (i, false, Some(k), d); + } + continue; + } + let (ds, de) = (dist2(at, s), dist2(at, e)); + if ds < best.3 { + best = (i, false, None, ds); + } + if de < best.3 { + best = (i, true, None, de); + } + } + // Spent, or no path free to draw (which only a fault could cause): the rest in paint + // order, each after the paths inside it. + if *work == 0 || best.0 >= left.len() { + match &outer { + Some(outer) => { + warn(notes, UNSORTED_INSIDE); + inner_first(left.into_iter().map(|(j, p, _)| (j, p)).collect(), outer, &mut waiting, paths); + } + None => { + warn(notes, UNSORTED); + paths.extend(left.into_iter().map(|(_, p, _)| p)); + } + } + return at; + } + let (j, mut p, _) = left.remove(best.0); + for o in outer.as_ref().and_then(|outer| outer.get(j)).into_iter().flatten() { + if let Some(w) = waiting.get_mut(*o) { + *w = w.saturating_sub(1); + } + } + if best.1 { + p.reverse(); + } else if let Some(k) = best.2 { + // A closed path starts at its point nearest the pen. + p.pop(); + let k = k.min(p.len().saturating_sub(1)); + p.rotate_left(k); + if let Some(&s) = p.first() { + p.push(s); + } + } + if let Some(&e) = p.last() { + at = e; + } + paths.push(p); + } + at +} + +/// Appends `left` (each path with its index among the pen's paths) to `paths` in paint order, +/// each after the paths lying inside it: `outer` lists the paths each lies inside, and `waiting` +/// counts, for each, the paths inside it still to draw. [`nest::outer`] puts a path only inside +/// larger ones, so every path comes free; a path left waiting by a fault is drawn last. +fn inner_first(left: Vec<(usize, Vec<(i64, i64)>)>, outer: &[Vec], waiting: &mut [usize], paths: &mut Vec>) { + let mut held: Vec>> = (0..outer.len()).map(|_| None).collect(); + let mut free = BinaryHeap::new(); + for (j, p) in left { + if let Some(h) = held.get_mut(j) { + if waiting.get(j).is_none_or(|w| *w == 0) { + free.push(Reverse(j)); + } + *h = Some(p); + } else { + paths.push(p); + } + } + while let Some(Reverse(j)) = free.pop() { + let Some(p) = held.get_mut(j).and_then(Option::take) else { continue }; + paths.push(p); + for &o in outer.get(j).into_iter().flatten() { + if let Some(w) = waiting.get_mut(o) { + *w = w.saturating_sub(1); + if *w == 0 { + free.push(Reverse(o)); + } + } + } + } + paths.extend(held.into_iter().flatten()); +} + +/// HP-GL: `IN;`, each pen's paths as `PU` and `PD`, `PU;SP0;`. +fn plain(by_pen: &[Vec>]) -> Vec { + let mut s = String::from("IN;"); + for (i, paths) in by_pen.iter().enumerate().filter(|(_, p)| !p.is_empty()) { + s.push_str(&format!("PU;SP{};", i + 1)); + for path in paths { + let Some(((x, y), rest)) = path.split_first() else { continue }; + s.push_str(&format!("PU{x},{y};PD")); + for (k, (x, y)) in rest.iter().enumerate() { + if k > 0 { + s.push(','); + } + s.push_str(&format!("{x},{y}")); + } + s.push(';'); + } + } + s.push_str("PU;SP0;"); + s.into_bytes() +} + +/// HP-GL/2: `IN;`, the palette, each pen's paths as one `PE`, `PU;SP0;`. +fn encoded(by_pen: &[Vec>], pens: &[[u8; 3]]) -> Vec { + let mut out = b"IN;".to_vec(); + if !pens.is_empty() { + // Pens 1 to n on a plotter, and on a raster device (whose pens are 0 to NP − 1) too. + let np = (pens.len() + 1).next_power_of_two().max(2); + out.extend(format!("NP{np};").bytes()); + for (i, [r, g, b]) in pens.iter().enumerate() { + out.extend(format!("PC{},{r},{g},{b};", i + 1).bytes()); + } + } + let mut at: Option<(i64, i64)> = None; + for (i, paths) in by_pen.iter().enumerate().filter(|(_, p)| !p.is_empty()) { + out.extend(format!("PU;SP{};PE", i + 1).bytes()); + for path in paths { + for (k, &p) in path.iter().enumerate() { + if k == 0 { + out.push(b'<'); + } + // The first move of the plot is absolute, and so is one longer than the range a + // device takes for each number; every other is relative. + match at.map(|a| (p.0 - a.0, p.1 - a.1)).filter(|d| d.0.abs() <= MAX_COORD && d.1.abs() <= MAX_COORD) { + None => { + out.push(b'='); + pe_number(&mut out, p.0); + pe_number(&mut out, p.1); + } + Some((dx, dy)) => { + pe_number(&mut out, dx); + pe_number(&mut out, dy); + } + } + at = Some(p); + } + } + out.push(b';'); + } + out.extend(b"PU;SP0;"); + out +} + +/// `v` as a base-64 PE number: the sign in the low bit, the low digits from 63 up and the last +/// digit from 191 up. +fn pe_number(out: &mut Vec, v: i64) { + let mut n = (v.unsigned_abs() << 1) | u64::from(v < 0); + while n >= 64 { + out.push(63 + (n % 64) as u8); + n /= 64; + } + out.push(191 + n as u8); +} + +/// One line the pen draws, in document space, and its color. +struct Run { + rgb: [u8; 3], + points: Vec, +} + +/// The document walk: each visible path becomes runs, clipped, in paint order. +struct Walk<'a> { + doc: &'a Document, + symbols: SymbolBoxes<'a>, + /// The region the art is cut at. + region: Rect, + edge: Option, + /// The plotter's range and the region asked for, when that reaches past the range. + range: Option<(Rect, Rect)>, + /// The region asked for, to cut a line at before testing it against the range. + asked: Option, + tolerance: f64, + /// The clipping masks around the current object, outermost first. + clips: Vec, + /// The points those masks hold ([`MAX_MASK_POINTS`]). + mask_points: usize, + runs: Vec, + points: usize, + clip_tests: u64, + warnings: Vec, + nest: u32, + /// Objects the symbol instances written held, together ([`vectorcraft_doc::MAX_SYMBOL_NODES`]). + symbol_nodes: u64, + /// Objects the live art written made, together ([`MAX_GENERATED`]). + generated: u64, + /// A copy of the document without its layers, to bake symbol art in ([`Walk::baked`]). + scratch: Option, + /// The symbols whose art holds geometry effects ([`Walk::baked`]), or instances of such + /// symbols. + effect_symbols: HashSet, +} + +impl<'a> Walk<'a> { + fn new(doc: &'a Document, region: Rect, tolerance: f64) -> Self { + Self { + doc, + symbols: doc.symbol_boxes().quick(), + region, + edge: Region::new(vec![corners(region)], FillRule::NonZero), + range: None, + asked: None, + tolerance, + clips: vec![], + mask_points: 0, + runs: vec![], + points: 0, + clip_tests: 0, + warnings: vec![], + nest: 0, + symbol_nodes: 0, + generated: 0, + scratch: None, + effect_symbols: effect_symbols(doc), + } + } + + fn warn(&mut self, w: &str) { + warn(&mut self.warnings, w); + } + + fn full(&self) -> bool { + self.points >= MAX_POINTS + } + + fn node(&mut self, n: &Node, force: bool) { + if n.is_ruler_guide() || n.is_template() { + return; + } + if self.full() { + self.warn(TOO_MANY_POINTS); + return; + } + if !force && !n.visible { + return; + } + // Art at no opacity shows nothing, and nor does anything inside it. + if n.opacity <= 0.0 { + return; + } + // Bounds don't measure the effects in symbol art, which apply only once an instance is + // placed: an instance of such art, and what holds one, is not skipped by its bounds. + let unmeasured = !self.effect_symbols.is_empty() && holds_instance_of(n, &self.effect_symbols); + // The box round all the object can paint, a blend's steps on its spine included. + if !n.is_layer() && !unmeasured { + match n.reach_bounds_with(&self.symbols) { + Some(b) if !overlaps(b, self.region) => { + // Art over the asked-for region but past the plotter's range is cut off. + if self.range.is_some_and(|(_, whole)| overlaps(b, whole)) { + self.warn(OUT_OF_RANGE); + } + return; + } + None if !n.is_container() => return, + _ => {} + } + } + if n.extras().mask.as_ref().is_some_and(|m| !m.disabled) { + self.warn(MASKS); + } + let raster = |fx: &[vectorcraft_doc::Effect]| fx.iter().any(|e| e.visible && vectorcraft_effects::is_raster(&e.id)); + if raster(&n.appearance.effects) || n.appearance.items.iter().any(|i| raster(i.effects())) { + self.warn(RASTER_FX); + } + match &n.kind { + // Non-printing layers aren't plotted. + NodeKind::Layer { children, printable, clip, .. } => { + if *printable { + self.children(children, *clip); + } + } + NodeKind::Group { children, clip } => self.children(children, *clip), + NodeKind::Path { path, guide, .. } => { + if !*guide { + self.shape(n, &path.to_bezpath()); + } + } + NodeKind::Compound { children, .. } => { + let mut bp = BezPath::new(); + for p in children.iter().filter_map(|c| c.path_data()) { + bp.extend(p.to_bezpath()); + } + self.shape(n, &bp); + } + NodeKind::Text(t) => { + if t.runs.iter().any(|r| r.inline.is_some()) { + self.warn(INLINE_GRAPHICS); + } + if let Some(o) = vectorcraft_effects::outline_text(n) { + self.warn(TEXT_OUTLINES); + self.node(&o, true); + } + } + NodeKind::Image(_) => self.warn(IMAGES), + NodeKind::SymbolInstance { symbol, xf } => self.symbol(n, symbol, *xf), + // A gradient mesh is its outline, in the average of its shown points' colors: its + // patches are shading, not lines. A mesh whose every point is at 0% opacity shows + // nothing. + NodeKind::Mesh(m) => { + let shown: Vec<[u8; 3]> = m.points.iter().filter(|p| p.opacity > 0.0).map(|p| rgb8(&p.color)).collect(); + if !shown.is_empty() { + self.draw(average(shown.into_iter()), &m.outline().to_bezpath(), true); + } + } + // Live blends, envelopes and repeats are drawn as their evaluated art, a level at a + // time, so a gradient mesh a blend makes is its outline too. + NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Repeat(_) | NodeKind::PlacedDocument(_) | NodeKind::Intertwine { .. } => { + if self.nest >= MAX_NEST { + self.warn(TOO_DEEP); + return; + } + // Once the budget is spent, nothing more is evaluated. + if self.generated >= MAX_GENERATED { + self.warn(LIVE_LEFT_OUT); + return; + } + let art = vectorcraft_effects::expand_live(Some(self.doc), n); + let count = art.iter().map(|c| c.count() as u64).sum::(); + if self.generated.saturating_add(count) > MAX_GENERATED { + self.generated = MAX_GENERATED; + self.warn(LIVE_LEFT_OUT); + return; + } + self.generated += count; + self.nest += 1; + art.iter().for_each(|c| self.node(c, false)); + self.nest -= 1; + } + NodeKind::RulerGuide { .. } => {} + } + } + + /// A symbol instance's art, placed (clip groups included), within the budget for the export. + fn symbol(&mut self, n: &Node, symbol: &str, xf: Affine) { + let doc = self.doc; + if self.symbol_nodes >= vectorcraft_doc::MAX_SYMBOL_NODES { + self.warn(SYMBOLS_LEFT_OUT); + return; + } + let Some(sym) = doc.symbols.iter().find(|s| s.name == symbol) else { return }; + if self.nest >= MAX_NEST { + self.warn(TOO_DEEP); + return; + } + // The instance's own changes and its stain, as the canvas draws it. + let art = vectorcraft_brush::instance_art(&sym.art, n); + let count = art.count_with_masks() as u64; + let most = doc.symbol_slice_map(symbol, xf).map_or(count, |m| m.most_placed(&art, doc)); + let placed = vectorcraft_doc::charge_symbol_art(&mut self.symbol_nodes, most, || { + let placed = doc.place_symbol_art(symbol, &art, xf); + let n = placed.as_ref().map_or(0, |a| a.count_with_masks() as u64); + (placed, n) + }); + match placed { + Some(Some(art)) => { + let art = self.baked(art); + self.nest += 1; + self.node(&art, true); + self.nest -= 1; + } + Some(None) => {} + None => { + self.symbol_nodes = vectorcraft_doc::MAX_SYMBOL_NODES; + self.warn(SYMBOLS_LEFT_OUT); + } + } + } + + /// Placed symbol art with its geometry effects applied: the document's bake reaches the + /// layers, not the symbols' art. + fn baked(&mut self, art: Node) -> Node { + if !vectorcraft_effects::needs_bake(&art) { + return art; + } + // Guides and layers left out go first, as for the document's layers. + let art = Arc::new(art); + let art = match plotted(std::slice::from_ref(&art), false) { + Some(mut kept) => match kept.pop() { + Some(a) => a, + None => return Node::group(vectorcraft_doc::NodeId(0), vec![]), + }, + None => art, + }; + let art = Arc::unwrap_or_clone(art); + let doc = self.doc; + let scratch = self.scratch.get_or_insert_with(|| { + let mut d = doc.clone(); + d.layers.clear(); + d + }); + scratch.layers = vec![Arc::new(art)]; + let baked = vectorcraft_effects::bake_document(scratch).and_then(|b| b.layers.into_iter().next()); + let art = std::mem::take(&mut scratch.layers).into_iter().next(); + baked.or(art).map(Arc::unwrap_or_clone).unwrap_or_else(|| Node::group(vectorcraft_doc::NodeId(0), vec![])) + } + + /// A container's children. A clipping container's first child cuts the rest; it is drawn + /// itself, once and whole, when it paints: where its stroke paints (over the clipped art) when + /// it has one, else where its fill paints (below it). Nothing to clip by hides the clipped art, + /// as on the canvas. + fn children(&mut self, children: &[Arc], clip: bool) { + let Some((first, rest)) = children.split_first().filter(|_| clip) else { + children.iter().for_each(|c| self.node(c, false)); + return; + }; + let mut paint = first.clip_paint(); + // A stroke at 0% opacity isn't drawn, so the clipping path is drawn in its fill. + let type_stroke = |s: &Node| matches!(&s.kind, NodeKind::Text(t) if t.runs.iter().any(|r| r.style.has_stroke())); + paint.stroke = paint.stroke.filter(|s| top_stroke(s).is_some() || type_stroke(s)); + if paint.stroke.is_none() + && let Some(fill) = &paint.fill + { + self.node(fill, false); + } + match vectorcraft_effects::clip_outline(first).map(|(bp, rule)| (self.rings(&bp), rule)) { + Some((Some(rings), rule)) => { + let held: usize = rings.iter().map(Vec::len).sum(); + if let Some(region) = Region::new(rings, rule) { + self.mask_points += held; + self.clips.push(region); + rest.iter().for_each(|c| self.node(c, false)); + self.clips.pop(); + self.mask_points -= held; + } + } + // A mask past the budget isn't built: the art it would clip is drawn unclipped by it. + Some((None, _)) => { + self.warn(MASK_POINTS); + rest.iter().for_each(|c| self.node(c, false)); + } + None => {} + } + // Drawn whole where its stroke paints: a fill closes its outline, and type's characters + // without a stroke are drawn too. + if paint.stroke.is_some() { + self.node(first, false); + } + } + + /// `bp` flattened into closed rings for a clipping mask; `None` when they would take the + /// masks around it past [`MAX_MASK_POINTS`]. + fn rings(&self, bp: &BezPath) -> Option>> { + let left = MAX_MASK_POINTS.saturating_sub(self.mask_points); + let (mut rings, whole) = self.flatten_within(bp, true, left); + if !whole || rings.iter().map(Vec::len).sum::() > left { + return None; + } + for r in &mut rings { + r.pop(); + } + Some(rings) + } + + /// A path drawn in its color: the topmost stroke's that paints, else the topmost fill's that + /// paints (visible, with a paint and some opacity). A filled path's every subpath is closed, + /// as its fill closes it, also when its stroke gives the color. + fn shape(&mut self, n: &Node, bp: &BezPath) { + if bp.elements().is_empty() { + return; + } + let fill = top_fill(n); + let paint = match (top_stroke(n), fill) { + (Some(s), _) => { + if s.dash.as_ref().is_some_and(|d| d.is_dashed()) + || s.brush.is_some() + || s.profile.is_some() + || s.start_arrow.is_some() + || s.end_arrow.is_some() + { + self.warn(STROKE_LOOK); + } + &s.paint + } + (None, Some(f)) => f, + (None, None) => return, + }; + let rgb = self.flat(paint); + self.draw(rgb, bp, fill.is_some()); + } + + /// `bp` drawn in `rgb`: flattened (with `close` every subpath closed), then cut and added. + fn draw(&mut self, rgb: [u8; 3], bp: &BezPath, close: bool) { + // Bounded by the plot's point budget; each curve by its own segment cap. + let budget = MAX_POINTS.saturating_sub(self.points).saturating_mul(4).max(4); + let (lines, whole) = self.flatten_within(bp, close, budget); + if !whole { + self.warn(TOO_MANY_POINTS); + } + for line in lines { + self.add(rgb, line); + } + } + + /// One color for a paint: a solid color, the average of a gradient's stops, or a pattern's + /// first solid fill (gray without one). + fn flat(&self, p: &Paint) -> [u8; 3] { + match p { + Paint::None => [0; 3], + Paint::Solid { color, .. } => rgb8(color), + Paint::Gradient(g) => average(g.gradient.stops.iter().map(|s| rgb8(&s.color))), + Paint::Pattern { pattern, .. } => { + self.doc.pattern(pattern).and_then(|def| def.art.iter().find_map(|a| first_solid(a))).map_or([128; 3], |c| rgb8(&c)) + } + } + } + + /// `bp` as polylines (each subpath one), within the tolerance, stopping once about `budget` + /// moves are made; with `close` every subpath ends at its start, else those that close. Also + /// whether every element of `bp` was flattened. + fn flatten_within(&self, bp: &BezPath, close: bool, budget: usize) -> (Vec>, bool) { + let mut out: Vec> = vec![]; + let mut cur: Vec = vec![]; + let end = |cur: &mut Vec, out: &mut Vec>, closing: bool| { + if (closing || close) + && let Some(&s) = cur.first() + && cur.last() != Some(&s) + { + cur.push(s); + } + out.push(std::mem::take(cur)); + }; + let (made, taken) = (std::cell::Cell::new(0usize), std::cell::Cell::new(0usize)); + let elements = bp.iter().take_while(|_| made.get() < budget).inspect(|_| taken.set(taken.get() + 1)); + vectorcraft_geom::flatten(elements, self.tolerance, |el| { + made.set(made.get() + 1); + match el { + PathEl::MoveTo(p) => { + end(&mut cur, &mut out, false); + cur.push(p); + } + PathEl::LineTo(p) => { + if cur.last() != Some(&p) { + cur.push(p); + } + } + PathEl::ClosePath => { + let s = cur.first().copied(); + end(&mut cur, &mut out, true); + // A subpath that goes on after its close starts where it closed. + if let Some(s) = s { + cur.push(s); + } + } + _ => {} + } + }); + let whole = taken.get() == bp.elements().len(); + // A subpath the budget cut short stays open: a move back to its start isn't on its outline. + if whole { + end(&mut cur, &mut out, false); + } else { + out.push(cur); + } + out.retain(|l| l.len() >= 2); + (out, whole) + } + + /// A polyline drawn in `rgb`, cut by the region and the clipping masks around it. + fn add(&mut self, rgb: [u8; 3], line: Vec) { + // Only the part over the region asked for counts: the rest is cut off anyway. + if let (Some((range, _)), Some(asked)) = (self.range, &self.asked) + && !self.warnings.iter().any(|w| w == OUT_OF_RANGE) + { + let mut unlimited = u64::MAX; + if asked.cut(&line, &mut unlimited).unwrap_or_default().iter().flatten().any(|p| !holds(range, *p)) { + self.warn(OUT_OF_RANGE); + } + } + // The region has four edges, so its cut costs a few tests a point and needs no limit. + let mut unlimited = u64::MAX; + let mut pieces = self.edge.as_ref().and_then(|edge| edge.cut(&line, &mut unlimited)).unwrap_or_default(); + for clip in &self.clips { + let mut left = MAX_CLIP_TESTS.saturating_sub(self.clip_tests); + let cut: Option>>> = pieces.iter().map(|p| clip.cut(p, &mut left)).collect(); + self.clip_tests = MAX_CLIP_TESTS.saturating_sub(left); + match cut { + Some(cut) => pieces = cut.into_iter().flatten().collect(), + None => { + // Spent: this art keeps the parts this mask and the ones inside it would cut, + // and later art that reaches a mask isn't clipped either. + self.clip_tests = MAX_CLIP_TESTS; + warn(&mut self.warnings, CLIP_WORK); + break; + } + } + } + for mut points in pieces { + let left = MAX_POINTS.saturating_sub(self.points); + if points.len() > left { + self.warn(TOO_MANY_POINTS); + points.truncate(left); + } + if points.len() < 2 { + return; + } + self.points += points.len(); + self.runs.push(Run { rgb, points }); + } + } +} + +fn overlaps(a: Rect, b: Rect) -> bool { + a.x0 <= b.x1 && b.x0 <= a.x1 && a.y0 <= b.y1 && b.y0 <= a.y1 +} + +/// `nodes` (the children of a clipping container when `clipping`) without the layers and +/// sublayers a plot leaves out (hidden, non-printing, template or at 0% opacity) and without +/// guides, in layers and groups at any depth, so that baking can't wrap one in art that is drawn +/// (its Crop Marks); `None` when nothing changes. A guide that is a clipping path keeps its place +/// without its effects. +fn plotted(nodes: &[Arc], clipping: bool) -> Option>> { + let mut changed = false; + let mut out = Vec::with_capacity(nodes.len()); + for (i, n) in nodes.iter().enumerate() { + match &n.kind { + NodeKind::Layer { printable, template, .. } if !(n.visible && n.opacity > 0.0 && *printable && !*template) => { + changed = true; + continue; + } + NodeKind::Path { guide: true, .. } => { + changed = true; + if clipping && i == 0 { + let mut g = (**n).clone(); + g.appearance.effects.clear(); + out.push(Arc::new(g)); + } + continue; + } + _ => {} + } + let inner = match &n.kind { + NodeKind::Layer { children, clip, .. } | NodeKind::Group { children, clip } => plotted(children, *clip), + _ => None, + }; + match inner { + Some(children) => { + changed = true; + let mut c = (**n).clone(); + if let Some(ch) = c.children_mut() { + *ch = children; + } + out.push(Arc::new(c)); + } + None => out.push(n.clone()), + } + } + changed.then_some(out) +} + +/// The symbols of `doc` whose art holds geometry effects, and those whose art holds instances of +/// them, as deep as symbols are drawn ([`MAX_NEST`]). +fn effect_symbols(doc: &Document) -> HashSet { + let mut set: HashSet = doc.symbols.iter().filter(|s| vectorcraft_effects::needs_bake(&s.art)).map(|s| s.name.clone()).collect(); + for _ in 0..MAX_NEST { + if set.is_empty() { + break; + } + let more: Vec = + doc.symbols.iter().filter(|s| !set.contains(&s.name) && holds_instance_of(&s.art, &set)).map(|s| s.name.clone()).collect(); + if more.is_empty() { + break; + } + set.extend(more); + } + set +} + +/// Is `n`, or anything in it, an instance of one of `symbols`? +fn holds_instance_of(n: &Node, symbols: &HashSet) -> bool { + match &n.kind { + NodeKind::SymbolInstance { symbol, .. } => symbols.contains(symbol), + _ => n.children().into_iter().flatten().any(|c| holds_instance_of(c, symbols)), + } +} + +fn rgb8(c: &vectorcraft_color::Color) -> [u8; 3] { + let [r, g, b, _] = c.to_rgba8(1.0); + [r, g, b] +} + +/// The average of `colors` (black without any). +fn average(colors: impl Iterator) -> [u8; 3] { + let (sum, n) = colors.fold(([0.0; 3], 0.0), |(a, n), c| ([0, 1, 2].map(|i| a[i] + f64::from(c[i])), n + 1.0)); + sum.map(|v| (v / f64::max(n, 1.0)).round().clamp(0.0, 255.0) as u8) +} + +/// The first visible solid fill color in `n` (a pattern tile's art), hidden objects and objects +/// or fills at 0% opacity left out. +fn first_solid(n: &Node) -> Option { + if !n.visible || n.opacity <= 0.0 { + return None; + } + let own = n.appearance.items.iter().find_map(|i| match i { + AppearanceItem::Fill(f) if f.visible && f.opacity > 0.0 => f.paint.color(), + _ => None, + }); + own.or_else(|| n.children().into_iter().flatten().find_map(|c| first_solid(c))) +} + +/// The topmost stroke of `n` that paints: visible, with a paint, a weight and some opacity. +fn top_stroke(n: &Node) -> Option<&StrokeLayer> { + n.appearance.items.iter().rev().find_map(|i| match i { + AppearanceItem::Stroke(s) if s.visible && !s.paint.is_none() && s.width > 0.0 && s.opacity > 0.0 => Some(s), + _ => None, + }) +} + +/// The paint of the topmost fill of `n` that paints: visible, with a paint and some opacity. +fn top_fill(n: &Node) -> Option<&Paint> { + n.appearance.items.iter().rev().find_map(|i| match i { + AppearanceItem::Fill(f) if f.visible && !f.paint.is_none() && f.opacity > 0.0 => Some(&f.paint), + _ => None, + }) +} + +#[cfg(test)] +mod tests; diff --git a/crates/cad/src/hpgl/write/clip.rs b/crates/cad/src/hpgl/write/clip.rs new file mode 100644 index 0000000000..235032ee2b --- /dev/null +++ b/crates/cad/src/hpgl/write/clip.rs @@ -0,0 +1,265 @@ +//! Polylines cut by a region: each segment is split where it crosses the region's edges, and the +//! pieces whose middle lies inside are kept, joined where they meet. + +use vectorcraft_geom::{FillRule, Point, Rect}; + +/// A clipping region: closed rings (each closes implicitly) and the rule that decides inside. +pub(super) struct Region { + rings: Vec>, + rule: FillRule, + bounds: Rect, +} + +impl Region { + /// The region of `rings` under `rule`; `None` when it has no ring of three points or more. + pub fn new(rings: Vec>, rule: FillRule) -> Option { + let rings: Vec> = rings.into_iter().filter(|r| r.len() >= 3).collect(); + let bounds = rings.iter().flatten().fold(None, |b: Option, p| Some(b.map_or(Rect::from_points(*p, *p), |b| b.union_pt(*p))))?; + Some(Self { rings, rule, bounds }) + } + + /// The edges this region has, which [`Region::cut`] tests each segment against. + fn edges(&self) -> u64 { + self.rings.iter().map(|r| r.len() as u64).sum() + } + + /// Does `p` lie on one of the region's edges (within a millionth of a point)? + fn on_edge(&self, p: Point) -> bool { + self.rings.iter().any(|ring| { + ring.iter().enumerate().any(|(i, &a)| { + let b = ring[(i + 1) % ring.len()]; + let ab = b - a; + let len2 = ab.hypot2(); + let t = if len2 > 0.0 { ((p - a).dot(ab) / len2).clamp(0.0, 1.0) } else { 0.0 }; + (a + ab * t).distance(p) <= 1e-6 + }) + }) + } + + /// Is `p` inside (non-zero winding or an odd number of crossings), or on an edge? + fn contains(&self, p: Point) -> bool { + if self.on_edge(p) { + return true; + } + let mut winding = 0i64; + for ring in &self.rings { + for (i, &a) in ring.iter().enumerate() { + let b = ring[(i + 1) % ring.len()]; + if a.y <= p.y { + if b.y > p.y && cross(a, b, p) > 0.0 { + winding += 1; + } + } else if b.y <= p.y && cross(a, b, p) < 0.0 { + winding -= 1; + } + } + } + match self.rule { + FillRule::NonZero => winding != 0, + FillRule::EvenOdd => winding % 2 != 0, + } + } + + /// Where segment `a`–`b` crosses this region's edges, as fractions of its length strictly + /// between 0 and 1, sorted. + fn crossings(&self, a: Point, b: Point) -> Vec { + let mut ts = vec![]; + for ring in &self.rings { + for (i, &c) in ring.iter().enumerate() { + let d = ring[(i + 1) % ring.len()]; + if let Some(t) = intersect(a, b, c, d) + && t > 1e-12 + && t < 1.0 - 1e-12 + { + ts.push(t); + } + } + } + ts.sort_by(f64::total_cmp); + ts.dedup_by(|x, y| (*x - *y).abs() <= 1e-12); + ts + } + + /// The parts of polyline `line` inside the region, each a polyline of two points or more. + /// Every test of a point or a segment against an edge takes one from `budget`; `None` when + /// the budget runs out first. + pub fn cut(&self, line: &[Point], budget: &mut u64) -> Option>> { + let edges = self.edges(); + let mut out: Vec> = vec![]; + let mut cur: Vec = vec![]; + for w in line.windows(2) { + let (a, b) = (w[0], w[1]); + // A segment wholly off the region's box lies outside it. + let near = overlaps(Rect::from_points(a, b), self.bounds); + let ts = if near { + spend(budget, edges)?; + self.crossings(a, b) + } else { + vec![] + }; + let mut from = 0.0; + for to in ts.into_iter().chain([1.0]) { + let (p, q) = (a.lerp(b, from), a.lerp(b, to)); + // Each piece between crossings is tested on its own: its edge and winding tests. + let inside = if near { + spend(budget, edges.saturating_mul(2))?; + self.contains(p.midpoint(q)) + } else { + false + }; + if inside { + if cur.last().is_none_or(|l| l.distance(p) > 1e-9) { + flush(&mut out, &mut cur); + cur.push(p); + } + cur.push(q); + } else { + flush(&mut out, &mut cur); + } + from = to; + } + } + flush(&mut out, &mut cur); + // A closed line that leaves the region and comes back: its last piece ends where its + // first starts, at the line's start, and the two are one piece. + if line.len() > 2 + && line.first() == line.last() + && out.len() >= 2 + && let (Some(end), Some(start)) = (out.last().and_then(|l| l.last()), out.first().and_then(|l| l.first())) + && end.distance(*start) <= 1e-9 + { + let first = out.remove(0); + if let Some(last) = out.last_mut() { + last.extend(first.into_iter().skip(1)); + } + } + Some(out) + } +} + +/// Take `n` from `budget`; `None` when it holds less. +fn spend(budget: &mut u64, n: u64) -> Option<()> { + *budget = budget.checked_sub(n)?; + Some(()) +} + +fn flush(out: &mut Vec>, cur: &mut Vec) { + let line = std::mem::take(cur); + if line.len() >= 2 { + out.push(line); + } +} + +fn overlaps(a: Rect, b: Rect) -> bool { + a.x0 <= b.x1 && b.x0 <= a.x1 && a.y0 <= b.y1 && b.y0 <= a.y1 +} + +/// Which side of line `a`–`b` point `p` lies on (positive: left). +fn cross(a: Point, b: Point, p: Point) -> f64 { + (b.x - a.x) * (p.y - a.y) - (p.x - a.x) * (b.y - a.y) +} + +/// Where segment `a`–`b` crosses segment `c`–`d`, as a fraction of `a`–`b`; `None` when they +/// are parallel or don't meet. +fn intersect(a: Point, b: Point, c: Point, d: Point) -> Option { + let (r, s) = (b - a, d - c); + let den = r.x * s.y - r.y * s.x; + if den.abs() <= f64::EPSILON * (r.hypot() * s.hypot()).max(f64::MIN_POSITIVE) { + return None; + } + let ac = c - a; + let t = (ac.x * s.y - ac.y * s.x) / den; + let u = (ac.x * r.y - ac.y * r.x) / den; + ((0.0..=1.0).contains(&t) && (0.0..=1.0).contains(&u)).then_some(t) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn square(x0: f64, y0: f64, x1: f64, y1: f64) -> Vec { + vec![Point::new(x0, y0), Point::new(x1, y0), Point::new(x1, y1), Point::new(x0, y1)] + } + + /// `line` cut by `r` with no limit on the work. + fn cut(r: &Region, line: &[Point]) -> Vec> { + let mut unlimited = u64::MAX; + r.cut(line, &mut unlimited).unwrap() + } + + #[test] + fn a_line_across_a_square_keeps_its_middle() { + let r = Region::new(vec![square(0.0, 0.0, 10.0, 10.0)], FillRule::NonZero).unwrap(); + let pieces = cut(&r, &[Point::new(-5.0, 5.0), Point::new(15.0, 5.0)]); + assert_eq!(pieces, vec![vec![Point::new(0.0, 5.0), Point::new(10.0, 5.0)]]); + // Wholly outside, nothing; wholly inside, the line as it is. + assert!(cut(&r, &[Point::new(20.0, 0.0), Point::new(30.0, 0.0)]).is_empty()); + let inside = vec![Point::new(1.0, 1.0), Point::new(9.0, 1.0), Point::new(9.0, 9.0)]; + assert_eq!(cut(&r, &inside), vec![inside]); + } + + /// Each piece between crossings costs a pass over the edges: a line through the teeth of a + /// comb spends far more than its two points times the edges. + #[test] + fn every_piece_between_crossings_is_paid_for() { + let mut ring = vec![]; + for i in 0..100 { + let x = f64::from(i) * 4.0; + ring.extend([Point::new(x, 0.0), Point::new(x + 2.0, 0.0), Point::new(x + 2.0, 10.0), Point::new(x + 4.0, 10.0)]); + } + ring.extend([Point::new(400.0, 20.0), Point::new(0.0, 20.0)]); + let r = Region::new(vec![ring], FillRule::NonZero).unwrap(); + let line = [Point::new(-1.0, 5.0), Point::new(401.0, 5.0)]; + // 402 edges, 200 crossings, 201 pieces: 402 + 201 × 2 × 402 tests. + let need = 402 + 201 * 2 * 402; + let mut budget = need; + assert_eq!(r.cut(&line, &mut budget).map(|p| p.len()), Some(100)); + assert_eq!(budget, 0); + let mut short = need - 1; + assert!(r.cut(&line, &mut short).is_none()); + // A segment off the region's box costs nothing. + assert_eq!(r.cut(&[Point::new(0.0, 30.0), Point::new(9.0, 30.0)], &mut 0), Some(vec![])); + } + + /// A line along any of the region's edges is inside it. + #[test] + fn a_line_on_an_edge_is_kept() { + let r = Region::new(vec![square(0.0, 0.0, 10.0, 10.0)], FillRule::NonZero).unwrap(); + for line in [ + [Point::new(0.0, 0.0), Point::new(10.0, 0.0)], + [Point::new(10.0, 0.0), Point::new(10.0, 10.0)], + [Point::new(10.0, 10.0), Point::new(0.0, 10.0)], + [Point::new(0.0, 10.0), Point::new(0.0, 0.0)], + ] { + assert_eq!(cut(&r, &line), vec![line.to_vec()], "{line:?}"); + } + } + + #[test] + fn a_line_leaving_and_coming_back_is_two_pieces() { + let r = Region::new(vec![square(0.0, 0.0, 10.0, 10.0)], FillRule::NonZero).unwrap(); + let line = [Point::new(5.0, 5.0), Point::new(15.0, 5.0), Point::new(15.0, 8.0), Point::new(5.0, 8.0)]; + assert_eq!(cut(&r, &line), vec![vec![Point::new(5.0, 5.0), Point::new(10.0, 5.0)], vec![Point::new(10.0, 8.0), Point::new(5.0, 8.0)]]); + } + + /// A closed line that starts inside, leaves and comes back is one piece: the part after it + /// comes back runs on into the part before it left. + #[test] + fn a_closed_line_cut_once_stays_one_piece() { + let r = Region::new(vec![square(0.0, 0.0, 10.0, 10.0)], FillRule::NonZero).unwrap(); + let line = [Point::new(5.0, 5.0), Point::new(15.0, 5.0), Point::new(15.0, 8.0), Point::new(5.0, 8.0), Point::new(5.0, 5.0)]; + assert_eq!(cut(&r, &line), vec![vec![Point::new(10.0, 8.0), Point::new(5.0, 8.0), Point::new(5.0, 5.0), Point::new(10.0, 5.0)]]); + } + + #[test] + fn the_fill_rule_decides_a_hole() { + let rings = vec![square(0.0, 0.0, 10.0, 10.0), square(3.0, 3.0, 7.0, 7.0)]; + let line = [Point::new(-1.0, 5.0), Point::new(11.0, 5.0)]; + // Both rings wind the same way: even-odd cuts a hole, non-zero doesn't. + let even_odd = cut(&Region::new(rings.clone(), FillRule::EvenOdd).unwrap(), &line); + assert_eq!(even_odd, vec![vec![Point::new(0.0, 5.0), Point::new(3.0, 5.0)], vec![Point::new(7.0, 5.0), Point::new(10.0, 5.0)]]); + let non_zero = cut(&Region::new(rings, FillRule::NonZero).unwrap(), &line); + assert_eq!(non_zero.len(), 1); + assert!(Region::new(vec![vec![Point::ZERO, Point::new(1.0, 1.0)]], FillRule::NonZero).is_none()); + } +} diff --git a/crates/cad/src/hpgl/write/nest.rs b/crates/cad/src/hpgl/write/nest.rs new file mode 100644 index 0000000000..eee4630ff3 --- /dev/null +++ b/crates/cad/src/hpgl/write/nest.rs @@ -0,0 +1,357 @@ +//! Which of a pen's paths lie inside which of its closed paths, in plotter units, for drawing the +//! inner paths first. + +/// The box of `p`: `[x0, y0, x1, y1]`. +pub(super) fn bounds(p: &[(i64, i64)]) -> [i64; 4] { + p.iter().fold([i64::MAX, i64::MAX, i64::MIN, i64::MIN], |b, q| [b[0].min(q.0), b[1].min(q.1), b[2].max(q.0), b[3].max(q.1)]) +} + +/// For each of `paths` (`boxes` are their [`bounds`]), the closed paths it lies inside: none of +/// its segments crosses the closed path's line, each part of it between the points where it meets +/// that line lies inside the closed path (by the even-odd rule) or on the line, and at least one +/// part lies inside. A path touching the line of the one around it is inside it, a path crossing +/// it is not, and copies of one outline are not inside each other. A path is tested only against +/// closed paths larger than it (by the area of their box, then the area they enclose, then paint +/// order), so no two paths are each inside the other, and only against the closed paths in the +/// [`Grid`] cell of its box's first corner. `None` once `work` is spent: a grid cell filled and a +/// box compared cost one each, and each segment tested costs the closed path's points for its +/// crossings and again for each part of it. +pub(super) fn outer(paths: &[Vec<(i64, i64)>], boxes: &[[i64; 4]], work: &mut u64) -> Option>> { + let size: Vec<(i128, i128)> = paths + .iter() + .zip(boxes) + .map(|(p, b)| { + let box_area = (i128::from(b[2]) - i128::from(b[0])) * (i128::from(b[3]) - i128::from(b[1])); + (box_area, if closed(p) { twice_area(p) } else { 0 }) + }) + .collect(); + let rings: Vec = (0..paths.len()).filter(|&i| paths.get(i).is_some_and(|p| closed(p))).collect(); + let mut out = vec![vec![]; paths.len()]; + if rings.is_empty() { + return Some(out); + } + let grid = Grid::new(&rings, boxes, work)?; + for (a, (p, ab)) in paths.iter().zip(boxes).enumerate() { + for &r in grid.at(ab[0], ab[1]) { + spend(work, 1)?; + let (Some(rb), Some(ring)) = (boxes.get(r), paths.get(r)) else { continue }; + let smaller = (size.get(a), a) < (size.get(r), r); + if !smaller || rb[0] > ab[0] || rb[1] > ab[1] || rb[2] < ab[2] || rb[3] < ab[3] { + continue; + } + if inside(p, ring, work)? + && let Some(o) = out.get_mut(a) + { + o.push(r); + } + } + } + Some(out) +} + +/// The most cells along each side of a [`Grid`]. +const MAX_GRID_SIDE: usize = 512; +/// The most cells of a [`Grid`] a closed path is listed in; one whose box covers more is listed +/// once, among the wide ones. A closed path has 4 points or more, so the grid lists no more +/// entries than the pen has points. +const MAX_CELLS_PER_PATH: usize = 4; + +/// A grid over the boxes of a pen's closed paths, about one cell for each, up to +/// [`MAX_GRID_SIDE`] a side: each cell lists, in paint order, the closed paths whose box covers +/// it, and the closed paths whose box covers more than [`MAX_CELLS_PER_PATH`] cells are listed +/// apart. A closed path whose box holds a point is among the wide ones or in that point's cell. +struct Grid { + /// The first corner of the closed paths' boxes together. + x0: i128, + y0: i128, + /// Their width and height, plus one. + w: i128, + h: i128, + /// Cells along each side. + side: usize, + /// The cells row by row. + cells: Vec>, + /// The closed paths whose box covers more than [`MAX_CELLS_PER_PATH`] cells. + wide: Vec, +} + +impl Grid { + /// The grid of the closed paths `rings` (indices into `boxes`). `None` once `work` is spent. + fn new(rings: &[usize], boxes: &[[i64; 4]], work: &mut u64) -> Option { + let all = rings + .iter() + .filter_map(|&r| boxes.get(r)) + .fold([i64::MAX, i64::MAX, i64::MIN, i64::MIN], |e, b| [e[0].min(b[0]), e[1].min(b[1]), e[2].max(b[2]), e[3].max(b[3])]); + let side = ((rings.len() as f64).sqrt().ceil() as usize).clamp(1, MAX_GRID_SIDE); + let (x0, y0) = (i128::from(all[0]), i128::from(all[1])); + let mut grid = Self { + x0, + y0, + w: (i128::from(all[2]) - x0 + 1).max(1), + h: (i128::from(all[3]) - y0 + 1).max(1), + side, + cells: vec![vec![]; side * side], + wide: vec![], + }; + for &r in rings { + let Some(b) = boxes.get(r) else { continue }; + let (Some((cx0, cy0)), Some((cx1, cy1))) = (grid.cell(b[0], b[1]), grid.cell(b[2], b[3])) else { continue }; + let covered = (cx1 - cx0 + 1) * (cy1 - cy0 + 1); + if covered > MAX_CELLS_PER_PATH { + spend(work, 1)?; + grid.wide.push(r); + continue; + } + spend(work, covered as u64)?; + for cy in cy0..=cy1 { + for cell in grid.cells.get_mut(cy * side + cx0..=cy * side + cx1).into_iter().flatten() { + cell.push(r); + } + } + } + Some(grid) + } + + /// The column and row of the cell holding `(x, y)`, `None` outside the grid. + fn cell(&self, x: i64, y: i64) -> Option<(usize, usize)> { + let (dx, dy) = (i128::from(x) - self.x0, i128::from(y) - self.y0); + if dx < 0 || dy < 0 || dx >= self.w || dy >= self.h { + return None; + } + let side = self.side as i128; + Some(((dx * side / self.w) as usize, (dy * side / self.h) as usize)) + } + + /// The wide closed paths, then those listed in the cell holding `(x, y)`. + fn at(&self, x: i64, y: i64) -> impl Iterator { + let cell = self.cell(x, y).and_then(|(cx, cy)| self.cells.get(cy * self.side + cx)).map_or(&[][..], Vec::as_slice); + self.wide.iter().chain(cell) + } +} + +/// Takes `n` from `work`; `None`, with `work` at 0, when it has less. +fn spend(work: &mut u64, n: u64) -> Option<()> { + let left = work.checked_sub(n); + *work = left.unwrap_or(0); + left.map(|_| ()) +} + +/// Does `p` start and end at one point, with three other points or more? +fn closed(p: &[(i64, i64)]) -> bool { + p.len() > 3 && p.first() == p.last() +} + +/// Twice the area the closed path `p` encloses. +fn twice_area(p: &[(i64, i64)]) -> i128 { + let sum: i128 = p + .windows(2) + .map(|w| match w { + [a, b] => i128::from(a.0) * i128::from(b.1) - i128::from(b.0) * i128::from(a.1), + _ => 0, + }) + .sum(); + sum.abs() +} + +/// Does `p` lie inside the closed path `ring`, as [`outer`] decides? `None` once `work` is spent. +fn inside(p: &[(i64, i64)], ring: &[(i64, i64)], work: &mut u64) -> Option { + let mut any = false; + for w in p.windows(2) { + let [s, e] = w else { continue }; + spend(work, ring.len() as u64)?; + // Where the segment meets the line without crossing it: its ends and the ring's points on + // it. Between two of these the segment is all inside or all outside. + let mut stops = vec![*s, *e]; + for edge in ring.windows(2) { + let [a, b] = edge else { continue }; + if crosses((*s, *e), (*a, *b)) { + return Some(false); + } + if a != s && a != e && on((*s, *e), *a) { + stops.push(*a); + } + } + let along = |q: &(i64, i64)| { + (i128::from(q.0) - i128::from(s.0)) * (i128::from(e.0) - i128::from(s.0)) + + (i128::from(q.1) - i128::from(s.1)) * (i128::from(e.1) - i128::from(s.1)) + }; + stops.sort_by_key(along); + stops.dedup(); + for part in stops.windows(2) { + let [m, n] = part else { continue }; + spend(work, ring.len() as u64)?; + // The part's middle, doubled so it is whole. + match locate((i128::from(m.0) + i128::from(n.0), i128::from(m.1) + i128::from(n.1)), ring) { + Some(false) => return Some(false), + Some(true) => any = true, + None => {} + } + } + } + Some(any) +} + +/// Which side of the line through `a` and `b` `c` is on: 1 left, -1 right, 0 on it. +fn side(a: (i64, i64), b: (i64, i64), c: (i64, i64)) -> i128 { + let d = (i128::from(b.0) - i128::from(a.0)) * (i128::from(c.1) - i128::from(a.1)) + - (i128::from(b.1) - i128::from(a.1)) * (i128::from(c.0) - i128::from(a.0)); + d.signum() +} + +/// Do segments `u` and `v` cross at a point inside both, each passing from one side of the other +/// to the other side? +fn crosses(u: ((i64, i64), (i64, i64)), v: ((i64, i64), (i64, i64))) -> bool { + side(u.0, u.1, v.0) * side(u.0, u.1, v.1) < 0 && side(v.0, v.1, u.0) * side(v.0, v.1, u.1) < 0 +} + +/// Does `q` lie on segment `u`? +fn on(u: ((i64, i64), (i64, i64)), q: (i64, i64)) -> bool { + let ((x0, y0), (x1, y1)) = u; + side(u.0, u.1, q) == 0 && q.0 >= x0.min(x1) && q.0 <= x0.max(x1) && q.1 >= y0.min(y1) && q.1 <= y0.max(y1) +} + +/// Where the doubled point `q` lies against the closed path `ring`: `Some(true)` inside by the +/// even-odd rule, `Some(false)` outside, `None` on its line. +fn locate(q: (i128, i128), ring: &[(i64, i64)]) -> Option { + let mut inside = false; + for w in ring.windows(2) { + let [a, b] = w else { continue }; + let (a, b) = ((2 * i128::from(a.0), 2 * i128::from(a.1)), (2 * i128::from(b.0), 2 * i128::from(b.1))); + // Which side of the segment's line `q` is on, 0 on it. + let side = (b.0 - a.0) * (q.1 - a.1) - (b.1 - a.1) * (q.0 - a.0); + if side == 0 && q.0 >= a.0.min(b.0) && q.0 <= a.0.max(b.0) && q.1 >= a.1.min(b.1) && q.1 <= a.1.max(b.1) { + return None; + } + // A segment crossing the level of `q` to its right. + if (a.1 > q.1) != (b.1 > q.1) && (side > 0) == (b.1 > a.1) { + inside = !inside; + } + } + Some(inside) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn square(x0: i64, y0: i64, x1: i64, y1: i64) -> Vec<(i64, i64)> { + vec![(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)] + } + + fn nest(paths: &[Vec<(i64, i64)>]) -> Option>> { + let boxes: Vec<[i64; 4]> = paths.iter().map(|p| bounds(p)).collect(); + let mut work = u64::MAX; + outer(paths, &boxes, &mut work) + } + + #[test] + fn points_inside_outside_and_on_the_line() { + let ring = square(0, 0, 10, 10); + assert_eq!(locate((10, 10), &ring), Some(true)); + assert_eq!(locate((30, 10), &ring), Some(false)); + assert_eq!(locate((10, -2), &ring), Some(false)); + assert_eq!(locate((20, 10), &ring), None); + assert_eq!(locate((0, 0), &ring), None); + } + + #[test] + fn a_path_inside_another_lies_inside_it_and_not_the_other_way() { + let paths = [square(0, 0, 100, 100), square(10, 10, 20, 20), vec![(30, 30), (40, 40)]]; + assert_eq!(nest(&paths), Some(vec![vec![], vec![0], vec![0]])); + } + + #[test] + fn touching_counts_as_inside_and_crossing_does_not() { + // A square with a corner on the outline's left edge, a triangle whose corners lie on the + // outline's edges, and a square that crosses the outline. + let paths = [square(0, 0, 100, 100), square(0, 40, 20, 60), vec![(0, 50), (50, 0), (100, 50), (0, 50)], square(90, 90, 120, 95)]; + assert_eq!(nest(&paths), Some(vec![vec![], vec![0], vec![0], vec![]])); + } + + /// Every point of a copy lies on the other's line, and none inside it. + #[test] + fn copies_of_one_outline_do_not_lie_inside_each_other() { + let paths = [square(0, 0, 10, 10), square(0, 0, 10, 10), vec![(10, 10), (10, 0), (0, 0), (0, 10), (10, 10)]]; + assert_eq!(nest(&paths), Some(vec![vec![], vec![], vec![]])); + } + + /// A line whose ends and middle lie inside an outline but which crosses a slot cut into it. + #[test] + fn a_line_across_a_slot_is_not_inside() { + let slotted = vec![(0, 0), (100, 0), (100, 100), (14, 100), (14, 40), (12, 40), (12, 100), (0, 100), (0, 0)]; + assert_eq!(nest(&[slotted, vec![(10, 50), (40, 50)]]), Some(vec![vec![], vec![]])); + } + + /// A line that leaves an outline and comes back through two of its corners, crossing none of + /// its sides, and one that runs along the bottom of a slot. + #[test] + fn a_line_through_corners_is_inside_only_where_it_stays_inside() { + let v_slot = vec![(0, 0), (100, 0), (100, 100), (20, 100), (20, 50), (15, 40), (10, 50), (10, 100), (0, 100), (0, 0)]; + assert_eq!(nest(&[v_slot, vec![(5, 50), (40, 50)]]), Some(vec![vec![], vec![]])); + let slot = vec![(0, 0), (100, 0), (100, 100), (20, 100), (20, 50), (10, 50), (10, 100), (0, 100), (0, 0)]; + assert_eq!(nest(&[slot, vec![(5, 50), (40, 50)]]), Some(vec![vec![], vec![0]])); + } + + /// An outline that crosses itself encloses no area by its signed sum, yet a line in one of its + /// lobes lies inside it. + #[test] + fn a_line_inside_a_lobe_of_a_crossed_outline_lies_inside_it() { + let bow = vec![(0, 0), (100, 100), (0, 100), (100, 0), (0, 0)]; + assert_eq!(twice_area(&bow), 0); + assert_eq!(nest(&[bow, vec![(40, 80), (60, 80)]]), Some(vec![vec![], vec![0]])); + } + + #[test] + fn a_ring_inside_a_ring_inside_a_ring_lies_inside_both() { + let paths = [square(20, 20, 80, 80), square(0, 0, 100, 100), square(40, 40, 60, 60)]; + assert_eq!(nest(&paths), Some(vec![vec![1], vec![], vec![0, 1]])); + } + + /// 10,000 parts in rows, each with a hole: each hole is tested against the few closed paths + /// near it, not against every part. + #[test] + fn parts_in_rows_are_tested_only_against_the_closed_paths_near_them() { + let mut paths = vec![]; + for row in 0..100 { + for col in 0..100 { + let (x, y) = (col * 30, row * 30); + paths.push(square(x, y, x + 20, y + 20)); + paths.push(square(x + 5, y + 5, x + 15, y + 15)); + } + } + let boxes: Vec<[i64; 4]> = paths.iter().map(|p| bounds(p)).collect(); + let mut work = 5_000_000; + let found = outer(&paths, &boxes, &mut work); + let want: Vec> = (0..paths.len()).map(|i| if i % 2 == 1 { vec![i - 1] } else { vec![] }).collect(); + assert_eq!(found, Some(want)); + } + + /// 400 closed paths that each cover most of the grid are listed once each, not in every cell + /// they cover. + #[test] + fn closed_paths_covering_many_cells_are_listed_once() { + let mut paths: Vec> = (0..400).map(|i| square(i, i, 1000 + i, 1000 + i)).collect(); + paths.extend((0..400).map(|i| { + let (x, y) = ((i % 20) * 50, (i / 20) * 50); + square(x, y, x + 10, y + 10) + })); + let boxes: Vec<[i64; 4]> = paths.iter().map(|p| bounds(p)).collect(); + let rings: Vec = (0..paths.len()).collect(); + let mut work = u64::MAX; + let Some(grid) = Grid::new(&rings, &boxes, &mut work) else { panic!("the budget ran out") }; + assert_eq!(grid.wide, (0..400).collect::>()); + assert!(grid.cells.iter().map(Vec::len).sum::() <= 400 * MAX_CELLS_PER_PATH); + } + + #[test] + fn finding_what_lies_inside_stops_at_its_budget() { + let paths: Vec> = (0..50).map(|i| square(-i, -i, 100 + i, 100 + i)).collect(); + let boxes: Vec<[i64; 4]> = paths.iter().map(|p| bounds(p)).collect(); + let mut work = 1_000; + assert_eq!(outer(&paths, &boxes, &mut work), None); + assert_eq!(work, 0); + let mut work = u64::MAX; + let found = outer(&paths, &boxes, &mut work); + assert_eq!(found.map(|o| o.iter().map(Vec::len).sum::()), Some(50 * 49 / 2)); + } +} diff --git a/crates/cad/src/hpgl/write/tests.rs b/crates/cad/src/hpgl/write/tests.rs new file mode 100644 index 0000000000..9cb4f7d727 --- /dev/null +++ b/crates/cad/src/hpgl/write/tests.rs @@ -0,0 +1,1110 @@ +//! HP-GL export: the instructions written, pens, origins, what is cut and left out, limits, and +//! plots read back by the HP-GL reader. + +use std::sync::Arc; + +use kurbo::{PathEl, Shape as _}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, AppearanceItem, CharStyle, Document, LayerColor, Node, NodeKind, TextObject}; +use vectorcraft_geom::{PathData, Point, Rect, shapes}; + +use super::*; + +/// A 200 × 100 pt document whose first layer holds what `nodes` makes. +fn doc_with(nodes: impl FnOnce(&mut Document) -> Vec) -> Document { + let mut d = Document::new(200.0, 100.0); + let nodes = nodes(&mut d); + let layer = d.layers[0].id; + for n in nodes { + d.insert(Some(layer), usize::MAX, n).unwrap(); + } + d +} + +fn stroked(d: &mut Document, p: PathData, c: Color) -> Node { + Node::path(d.alloc_id(), p, Appearance::basic(Paint::None, Paint::solid(c), 1.0)) +} + +fn filled(d: &mut Document, p: PathData, c: Color) -> Node { + Node::path(d.alloc_id(), p, Appearance::basic(Paint::solid(c), Paint::None, 1.0)) +} + +fn line(a: (f64, f64), b: (f64, f64)) -> PathData { + let mut bp = BezPath::new(); + bp.move_to(a); + bp.line_to(b); + PathData::from_bezpath(&bp) +} + +fn rect(x0: f64, y0: f64, x1: f64, y1: f64) -> PathData { + shapes::rectangle(Rect::new(x0, y0, x1, y1)) +} + +/// The options with the first artboard as the region. +fn opts(d: &Document) -> HpglOptions { + HpglOptions { region: d.artboards[0].rect, ..HpglOptions::default() } +} + +fn plot(d: &Document, o: &HpglOptions) -> HpglOutput { + match export(d, o) { + Ok(out) => out, + Err(e) => panic!("{e}"), + } +} + +fn text(out: &HpglOutput) -> String { + String::from_utf8(out.bytes.clone()).expect("ASCII") +} + +/// A black square outline, a red line and a blue ellipse filled without a stroke. +fn three() -> Document { + doc_with(|d| { + vec![ + stroked(d, rect(10.0, 10.0, 60.0, 40.0), Color::BLACK), + stroked(d, line((70.0, 20.0), (150.0, 80.0)), Color::rgb8(255, 0, 0)), + filled(d, shapes::ellipse(Rect::new(70.0, 30.0, 130.0, 70.0)), Color::rgb8(0, 0, 255)), + ] + }) +} + +/// Every instruction in the HP-GL reference guide's form: a two-letter mnemonic, integer +/// parameters separated by commas, and a semicolon (https://support.hp.com/sg-en/document/c01121263). +#[test] +fn a_plot_is_pen_moves_in_plotter_units_from_the_bottom_left() { + let d = doc_with(|d| vec![stroked(d, rect(10.0, 10.0, 60.0, 40.0), Color::BLACK)]); + let out = plot(&d, &opts(&d)); + // 1016 units to the inch, y up from the artboard's bottom edge; the square closes. + assert_eq!(text(&out), "IN;PU;SP1;PU141,1270;PD847,1270,847,847,141,847,141,1270;PU;SP0;"); + for i in text(&out).split_terminator(';') { + let (op, params) = i.split_at(2); + assert!(op.bytes().all(|c| c.is_ascii_uppercase()), "{i}"); + assert!(params.is_empty() || params.split(',').all(|v| v.parse::().is_ok()), "{i}"); + } + assert_eq!(out.pens, [[0, 0, 0]]); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); +} + +#[test] +fn the_origin_can_be_the_center() { + let d = doc_with(|d| vec![stroked(d, rect(10.0, 10.0, 60.0, 40.0), Color::BLACK)]); + let out = plot(&d, &HpglOptions { origin: Origin::Center, ..opts(&d) }); + // The artboard's center is (100, 50): x from -1270, y from 564 (40 pt up). + assert_eq!(text(&out), "IN;PU;SP1;PU-1270,564;PD-564,564,-564,141,-1270,141,-1270,564;PU;SP0;"); +} + +#[test] +fn each_new_color_is_the_next_pen_and_pens_draw_in_turn() { + let d = doc_with(|d| { + vec![ + stroked(d, line((10.0, 10.0), (20.0, 10.0)), Color::rgb8(255, 0, 0)), + stroked(d, line((10.0, 20.0), (20.0, 20.0)), Color::BLACK), + stroked(d, line((10.0, 30.0), (20.0, 30.0)), Color::rgb8(255, 0, 0)), + ] + }); + let out = plot(&d, &opts(&d)); + assert_eq!(out.pens, [[255, 0, 0], [0, 0, 0]]); + assert_eq!(text(&out), "IN;PU;SP1;PU141,1270;PD282,1270;PU141,988;PD282,988;PU;SP2;PU141,1129;PD282,1129;PU;SP0;"); + // A pen table: each color takes the nearest pen's (red is as near black as blue, and black + // comes first). + let table = plot(&d, &HpglOptions { pens: vec![[0, 0, 0], [0, 0, 255]], ..opts(&d) }); + assert_eq!(table.pens, [[0, 0, 0], [0, 0, 255]]); + assert!(text(&table).starts_with("IN;PU;SP1;PU141,1270;"), "{}", text(&table)); + assert!(!text(&table).contains("SP2"), "{}", text(&table)); +} + +#[test] +fn a_filled_path_is_its_closed_outline_and_a_stroke_its_line() { + let d = doc_with(|d| { + let mut open = BezPath::new(); + open.move_to((10.0, 10.0)); + open.line_to((20.0, 10.0)); + open.line_to((20.0, 20.0)); + let open = PathData::from_bezpath(&open); + let both = Node::path(d.alloc_id(), open.clone(), Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::rgb8(255, 0, 0)), 1.0)); + vec![filled(d, open.clone(), Color::BLACK), stroked(d, open, Color::BLACK), both] + }); + let out = plot(&d, &opts(&d)); + let t = text(&out); + assert!(t.contains("PU141,1270;PD282,1270,282,1129,141,1270;"), "the fill closes: {t}"); + assert!(t.contains("PU141,1270;PD282,1270,282,1129;PU;"), "the stroke doesn't: {t}"); + // A path with a fill and a stroke is closed too, in its stroke's color. + assert_eq!(out.pens, [[0, 0, 0], [255, 0, 0]]); + assert!(t.ends_with("SP2;PU141,1270;PD282,1270,282,1129,141,1270;PU;SP0;"), "{t}"); +} + +/// A gradient mesh is its outline, once, in the average of its points' colors. +#[test] +fn a_gradient_mesh_is_its_outline() { + let d = doc_with(|d| { + let mesh = vectorcraft_doc::live::GradientMesh::from_surface(4, 4, &|u, v| Point::new(10.0 + u * 50.0, 10.0 + v * 50.0), &|u, _| { + if u < 0.5 { Color::rgb8(255, 0, 0) } else { Color::rgb8(0, 0, 255) } + }); + vec![Node::new(d.alloc_id(), NodeKind::Mesh(mesh))] + }); + let out = plot(&d, &opts(&d)); + let t = text(&out); + assert_eq!(t.matches("PD").count(), 1, "{t}"); + assert!(t.starts_with("IN;PU;SP1;PU"), "{t}"); + // The square's four corners are on the line it draws. + for corner in ["141,1270", "847,1270", "847,564", "141,564"] { + assert!(t.contains(corner), "{corner} in {t}"); + } + let [r, g, b] = out.pens[0]; + assert!(r > 0 && b > 0 && g == 0, "{:?}", out.pens); +} + +/// A square gradient mesh, 30 pt a side, at `x`. +fn mesh_at(x: f64) -> vectorcraft_doc::live::GradientMesh { + vectorcraft_doc::live::GradientMesh::from_surface(4, 4, &|u, v| Point::new(x + u * 30.0, 10.0 + v * 30.0), &|_, _| Color::BLACK) +} + +fn blend_of(d: &mut Document, keys: Vec, steps: u32) -> Node { + let spec = vectorcraft_doc::BlendSpec { spacing: vectorcraft_doc::BlendSpacing::Steps(steps), ..Default::default() }; + Node::new(d.alloc_id(), NodeKind::Blend { children: keys.into_iter().map(Arc::new).collect(), spec: Box::new(spec) }) +} + +/// A mesh inside a blend is its outline too: a blend of two meshes with one step between them +/// draws three outlines. A mesh whose every point is at 0% opacity draws nothing. +#[test] +fn meshes_in_blends_are_outlines_and_clear_meshes_draw_nothing() { + let d = doc_with(|d| { + let keys = vec![Node::new(d.alloc_id(), NodeKind::Mesh(mesh_at(10.0))), Node::new(d.alloc_id(), NodeKind::Mesh(mesh_at(110.0)))]; + let mut clear = mesh_at(60.0); + clear.points.iter_mut().for_each(|p| p.opacity = 0.0); + vec![blend_of(d, keys, 1), Node::new(d.alloc_id(), NodeKind::Mesh(clear))] + }); + let t = text(&plot(&d, &opts(&d))); + assert_eq!(t.matches("PD").count(), 3, "{t}"); +} + +/// Live art that makes more objects than the plot's limit (1,000 in tests) is left out with a +/// warning. +#[test] +fn live_art_past_its_limit_is_left_out() { + let d = doc_with(|d| { + let keys = vec![stroked(d, line((10.0, 10.0), (10.0, 20.0)), Color::BLACK), stroked(d, line((190.0, 10.0), (190.0, 20.0)), Color::BLACK)]; + vec![blend_of(d, keys, 1_200)] + }); + let out = plot(&d, &opts(&d)); + assert!(out.warnings.iter().any(|w| w == LIVE_LEFT_OUT), "{:?}", out.warnings); + assert_eq!(text(&out), "IN;PU;SP0;"); +} + +/// A line shorter than a plotter unit draws nothing and takes no pen. +#[test] +fn a_line_that_draws_nothing_takes_no_pen() { + let d = doc_with(|d| { + vec![stroked(d, line((10.0, 10.0), (10.01, 10.0)), Color::rgb8(255, 0, 0)), stroked(d, rect(10.0, 10.0, 60.0, 40.0), Color::BLACK)] + }); + let out = plot(&d, &opts(&d)); + assert_eq!(out.pens, [[0, 0, 0]]); + assert!(text(&out).starts_with("IN;PU;SP1;PU141,1270;"), "{}", text(&out)); + let two = plot(&d, &HpglOptions { version: Version::Hpgl2, ..opts(&d) }); + assert!(two.bytes.starts_with(b"IN;NP2;PC1,0,0,0;PU;SP1;PE"), "{:?}", String::from_utf8_lossy(&two.bytes)); +} + +/// The plots of one export share the pens: a color is the same pen in each, numbered in the +/// order the plots first draw in it. +#[test] +fn the_plots_of_one_export_share_their_pens() { + let d = doc_with(|d| { + vec![ + stroked(d, line((10.0, 10.0), (20.0, 10.0)), Color::BLACK), + stroked(d, line((110.0, 10.0), (120.0, 10.0)), Color::rgb8(255, 0, 0)), + stroked(d, line((110.0, 20.0), (120.0, 20.0)), Color::BLACK), + ] + }); + let regions = [Rect::new(0.0, 0.0, 100.0, 100.0), Rect::new(100.0, 0.0, 200.0, 100.0)]; + let plots = export_regions(&d, &HpglOptions::default(), ®ions).unwrap(); + assert_eq!(plots.len(), 2); + for p in &plots { + assert_eq!(p.pens, [[0, 0, 0], [255, 0, 0]]); + } + assert_eq!(text(&plots[0]), "IN;PU;SP1;PU141,1270;PD282,1270;PU;SP0;"); + assert_eq!(text(&plots[1]), "IN;PU;SP1;PU141,1129;PD282,1129;PU;SP2;PU141,1270;PD282,1270;PU;SP0;"); +} + +#[test] +fn hidden_and_non_printing_art_is_left_out() { + let mut d = doc_with(|d| { + let mut hidden = stroked(d, rect(10.0, 10.0, 20.0, 20.0), Color::BLACK); + hidden.visible = false; + let none = Node::path(d.alloc_id(), rect(30.0, 10.0, 40.0, 20.0), Appearance::basic(Paint::None, Paint::None, 1.0)); + vec![hidden, none] + }); + let mut layer = Node::layer(d.alloc_id(), "Notes", LayerColor::Preset(1)); + if let NodeKind::Layer { printable, .. } = &mut layer.kind { + *printable = false; + } + let art = stroked(&mut d, rect(50.0, 10.0, 60.0, 20.0), Color::BLACK); + layer.children_mut().unwrap().push(Arc::new(art)); + d.layers.push(Arc::new(layer)); + assert_eq!(text(&plot(&d, &opts(&d))), "IN;PU;SP0;"); +} + +/// Hidden and template layers, guides of either kind and placed images draw nothing; an image +/// comes back as a warning. +#[test] +fn layers_guides_and_images_that_draw_nothing_are_left_out() { + let mut d = doc_with(|d| { + let mut guide = stroked(d, rect(10.0, 10.0, 20.0, 20.0), Color::BLACK); + if let NodeKind::Path { guide, .. } = &mut guide.kind { + *guide = true; + } + let ruler = Node::new(d.alloc_id(), NodeKind::RulerGuide { vertical: true, pos: 50.0, artboard: None }); + let image = vectorcraft_doc::ImageObject { + key: "raster-1".into(), + width: 4, + height: 2, + xf: Affine::translate((10.0, 20.0)) * Affine::scale(5.0), + link: None, + placement: Default::default(), + pixels: None, + }; + vec![ruler, guide, Node::new(d.alloc_id(), NodeKind::Image(Box::new(image)))] + }); + let hidden = d.add_layer(Some("Notes")); + let template = d.add_layer(Some("Tracing")); + for l in [hidden, template] { + let n = stroked(&mut d, rect(30.0, 10.0, 40.0, 20.0), Color::BLACK); + d.insert(Some(l), 0, n).unwrap(); + } + if let Some(n) = d.node_mut(hidden) { + n.visible = false; + } + if let Some(NodeKind::Layer { template, .. }) = d.node_mut(template).map(|n| &mut n.kind) { + *template = true; + } + let out = plot(&d, &opts(&d)); + assert_eq!(text(&out), "IN;PU;SP0;"); + assert_eq!(out.warnings, [IMAGES]); +} + +/// A non-printing layer's Crop Marks are left out with the layer, and so is a template layer's. +#[test] +fn the_crop_marks_of_a_layer_left_out_are_left_out() { + for template in [false, true] { + let mut d = doc_with(|d| vec![stroked(d, rect(10.0, 10.0, 60.0, 40.0), Color::BLACK)]); + let layer = d.layers[0].id; + if let Some(n) = d.node_mut(layer) { + n.appearance.effects.push(vectorcraft_doc::Effect { id: "cropMarks".into(), params: serde_json::json!({}), visible: true }); + if let NodeKind::Layer { printable, template: t, .. } = &mut n.kind { + (*printable, *t) = (template, template); + } + } + assert_eq!(text(&plot(&d, &opts(&d))), "IN;PU;SP0;", "template: {template}"); + } +} + +/// A guide's Crop Marks are left out with the guide, in the layers and in a symbol's art. +#[test] +fn the_crop_marks_of_a_guide_are_left_out() { + let guide = |d: &mut Document| { + let mut g = stroked(d, rect(10.0, 10.0, 60.0, 40.0), Color::BLACK); + g.appearance.effects.push(vectorcraft_doc::Effect { id: "cropMarks".into(), params: serde_json::json!({}), visible: true }); + if let NodeKind::Path { guide, .. } = &mut g.kind { + *guide = true; + } + g + }; + let d = doc_with(|d| { + let g = guide(d); + vec![Node::group(d.alloc_id(), vec![Arc::new(g)])] + }); + assert_eq!(text(&plot(&d, &opts(&d))), "IN;PU;SP0;"); + let mut d = Document::new(200.0, 100.0); + let g = guide(&mut d); + let art = Node::group(d.alloc_id(), vec![Arc::new(g)]); + let d = symbol_doc(art, |_| {}); + assert_eq!(text(&plot(&d, &opts(&d))), "IN;PU;SP0;"); +} + +/// Inline graphics in type are left out with a warning. +#[test] +fn inline_graphics_in_type_are_left_out_with_a_warning() { + let d = doc_with(|d| { + let style = CharStyle { size: 30.0, fill: Paint::solid(Color::BLACK), ..CharStyle::default() }; + let mut t = TextObject::point(Point::new(10.0, 60.0), "O", style.clone()); + t.runs.push(vectorcraft_doc::TextRun::inline(vectorcraft_doc::InlineArt::new("mark"), style)); + vec![Node::new(d.alloc_id(), NodeKind::Text(Box::new(t)))] + }); + let out = plot(&d, &opts(&d)); + assert!(out.warnings.iter().any(|w| w == INLINE_GRAPHICS), "{:?}", out.warnings); +} + +/// A gradient's pen is the average of its stops' colors. +#[test] +fn a_gradient_takes_the_average_of_its_stops() { + let mut g = vectorcraft_color::GradientPaint::new(Default::default()); + g.gradient.stops[0].color = Color::rgb8(255, 0, 0); + g.gradient.stops[1].color = Color::rgb8(0, 0, 255); + let d = + doc_with(|d| vec![Node::path(d.alloc_id(), rect(10.0, 10.0, 60.0, 40.0), Appearance::basic(Paint::Gradient(Box::new(g)), Paint::None, 1.0))]); + assert_eq!(plot(&d, &opts(&d)).pens, [[128, 0, 128]]); +} + +/// An object or group at 0% opacity shows nothing, and a fill or stroke at 0% opacity gives a +/// path no color: here only the blue fill's outline is drawn. +#[test] +fn art_at_no_opacity_is_left_out() { + let (red, green, blue) = (Color::rgb8(255, 0, 0), Color::rgb8(0, 255, 0), Color::rgb8(0, 0, 255)); + let d = doc_with(|d| { + let mut faded = stroked(d, rect(10.0, 10.0, 20.0, 20.0), red); + faded.opacity = 0.0; + let inner = stroked(d, line((30.0, 10.0), (40.0, 10.0)), green); + let mut group = Node::group(d.alloc_id(), vec![Arc::new(inner)]); + group.opacity = 0.0; + let mut clear_fill = filled(d, rect(10.0, 30.0, 20.0, 40.0), green); + let mut fill_and_clear_stroke = + Node::path(d.alloc_id(), rect(50.0, 10.0, 60.0, 20.0), Appearance::basic(Paint::solid(blue), Paint::solid(red), 1.0)); + for item in clear_fill.appearance.items.iter_mut().chain(fill_and_clear_stroke.appearance.items.iter_mut()) { + match item { + AppearanceItem::Fill(f) if f.paint == Paint::solid(green) => f.opacity = 0.0, + AppearanceItem::Stroke(s) => s.opacity = 0.0, + _ => {} + } + } + vec![faded, group, clear_fill, fill_and_clear_stroke] + }); + let out = plot(&d, &opts(&d)); + assert_eq!(out.pens, [[0, 0, 255]]); + assert_eq!(text(&out).matches("PD").count(), 1, "{}", text(&out)); +} + +/// A pattern's pen is the color of its first visible solid fill: a hidden tile object, one at 0% +/// opacity and a fill at 0% opacity are skipped. +#[test] +fn a_pattern_takes_the_color_of_its_first_visible_fill() { + let mut d = doc_with(|_| vec![]); + let mut hidden = filled(&mut d, rect(0.0, 0.0, 5.0, 5.0), Color::rgb8(255, 0, 0)); + hidden.visible = false; + let mut faded = filled(&mut d, rect(0.0, 5.0, 5.0, 10.0), Color::rgb8(0, 255, 0)); + faded.opacity = 0.0; + let mut clear_fill = filled(&mut d, rect(5.0, 5.0, 10.0, 10.0), Color::rgb8(255, 255, 0)); + for item in &mut clear_fill.appearance.items { + if let AppearanceItem::Fill(f) = item { + f.opacity = 0.0; + } + } + let shown = filled(&mut d, rect(5.0, 0.0, 10.0, 5.0), Color::rgb8(0, 0, 255)); + let art = [hidden, faded, clear_fill, shown].map(Arc::new).to_vec(); + d.patterns.push(vectorcraft_doc::PatternDef::new("tiles", art)); + let path = Node::path( + d.alloc_id(), + rect(10.0, 10.0, 50.0, 50.0), + Appearance::basic(Paint::Pattern { pattern: "tiles".into(), xf: Default::default() }, Paint::None, 1.0), + ); + let layer = d.layers[0].id; + d.insert(Some(layer), usize::MAX, path).unwrap(); + assert_eq!(plot(&d, &opts(&d)).pens, [[0, 0, 255]]); +} + +#[test] +fn art_is_cut_at_the_artboard_and_by_clipping_masks() { + let d = doc_with(|d| { + let across = stroked(d, line((-50.0, 50.0), (250.0, 50.0)), Color::BLACK); + let clip = Node::path(d.alloc_id(), rect(20.0, 20.0, 40.0, 40.0), Appearance::default()); + let clipped = stroked(d, line((0.0, 30.0), (200.0, 30.0)), Color::BLACK); + let mut group = Node::group(d.alloc_id(), vec![Arc::new(clip), Arc::new(clipped)]); + if let NodeKind::Group { clip, .. } = &mut group.kind { + *clip = true; + } + vec![across, group] + }); + let t = text(&plot(&d, &opts(&d))); + assert_eq!(t, "IN;PU;SP1;PU0,706;PD2822,706;PU282,988;PD564,988;PU;SP0;"); +} + +#[test] +fn type_is_drawn_as_its_outlines() { + let d = doc_with(|d| { + let style = CharStyle { size: 30.0, fill: Paint::solid(Color::BLACK), ..CharStyle::default() }; + vec![Node::new(d.alloc_id(), NodeKind::Text(Box::new(TextObject::point(Point::new(10.0, 60.0), "Ol", style))))] + }); + let out = plot(&d, &opts(&d)); + assert!(out.warnings.iter().any(|w| w == TEXT_OUTLINES), "{:?}", out.warnings); + // A pen-up move to each contour (the O's two and the l's one), and the two around the pen. + let t = text(&out); + assert!(t.matches("PU").count() >= 5, "{t}"); +} + +#[test] +fn an_empty_or_zero_length_plot_has_no_moves() { + let empty = Document::new(200.0, 100.0); + assert_eq!(text(&plot(&empty, &opts(&empty))), "IN;PU;SP0;"); + let d = + doc_with(|d| vec![stroked(d, line((10.0, 10.0), (10.0, 10.0)), Color::BLACK), stroked(d, line((10.0, 10.0), (10.01, 10.0)), Color::BLACK)]); + assert_eq!(text(&plot(&d, &opts(&d))), "IN;PU;SP0;"); + let bad = HpglOptions { region: Rect::new(0.0, 0.0, 0.0, 10.0), ..HpglOptions::default() }; + assert_eq!(export(&d, &bad).err().as_deref(), Some("the export region is empty")); + let nan = HpglOptions { region: Rect::new(0.0, 0.0, f64::NAN, 10.0), ..HpglOptions::default() }; + assert!(export(&d, &nan).is_err()); +} + +/// A tolerance outside its range and a pen table of more than 255 pens are errors, not changed. +#[test] +fn bad_options_are_errors() { + let d = three(); + for tolerance in [0.0, 0.009, 10.01, f64::NAN, f64::INFINITY] { + let o = HpglOptions { tolerance, ..opts(&d) }; + assert_eq!(export(&d, &o).err().as_deref(), Some("the curve tolerance must be from 0.01 to 10 points"), "{tolerance}"); + } + for tolerance in [0.01, 10.0] { + assert!(export(&d, &HpglOptions { tolerance, ..opts(&d) }).is_ok(), "{tolerance}"); + } + let o = HpglOptions { pens: vec![[0, 0, 0]; MAX_PENS + 1], ..opts(&d) }; + assert_eq!(export(&d, &o).err().as_deref(), Some("the pen table holds more than 255 pens")); + assert!(export(&d, &HpglOptions { pens: vec![[0, 0, 0]; MAX_PENS], ..opts(&d) }).is_ok()); +} + +#[test] +fn art_past_the_plotter_range_is_cut_off() { + let d = doc_with(|d| vec![stroked(d, line((0.0, 50.0), (1e9, 50.0)), Color::BLACK)]); + let out = plot(&d, &HpglOptions { region: Rect::new(0.0, 0.0, 1e9, 100.0), ..HpglOptions::default() }); + assert!(out.warnings.iter().any(|w| w == OUT_OF_RANGE), "{:?}", out.warnings); + assert_eq!(text(&out), format!("IN;PU;SP1;PU0,706;PD{MAX_COORD},706;PU;SP0;")); + // Art past the range but off the region asked for would be cut off anyway: no warning. + let d = doc_with(|d| vec![stroked(d, line((-1e9, 50.0), (10.0, 50.0)), Color::BLACK)]); + let out = plot(&d, &HpglOptions { region: Rect::new(0.0, 0.0, 1e9, 100.0), ..HpglOptions::default() }); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + assert_eq!(text(&out), "IN;PU;SP1;PU0,706;PD141,706;PU;SP0;"); +} + +/// HP-GL past 16-bit coordinates is written as it is, with a warning; HP-GL/2 gets none. +#[test] +fn hpgl_past_16_bit_coordinates_warns() { + let region = Rect::new(-2400.0, 0.0, 2400.0, 100.0); + // Past 32,767 from the bottom-left corner, within the range from the center. + let d = doc_with(|d| vec![stroked(d, line((-2000.0, 50.0), (2000.0, 50.0)), Color::BLACK)]); + let out = plot(&d, &HpglOptions { region, ..HpglOptions::default() }); + assert_eq!(out.warnings, [PAST_CLASSIC_RANGE]); + assert_eq!(text(&out), "IN;PU;SP1;PU5644,706;PD62089,706;PU;SP0;"); + let out = plot(&d, &HpglOptions { region, origin: Origin::Center, ..HpglOptions::default() }); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + assert_eq!(text(&out), "IN;PU;SP1;PU-28222,0;PD28222,0;PU;SP0;"); + // Past −32,768 and 32,767 from the center. + let d = doc_with(|d| vec![stroked(d, line((-2400.0, 50.0), (2400.0, 50.0)), Color::BLACK)]); + let out = plot(&d, &HpglOptions { region, origin: Origin::Center, ..HpglOptions::default() }); + assert_eq!(out.warnings, [PAST_CLASSIC_RANGE]); + assert_eq!(text(&out), "IN;PU;SP1;PU-33867,0;PD33867,0;PU;SP0;"); + let out = plot(&d, &HpglOptions { region, origin: Origin::Center, version: Version::Hpgl2, ..HpglOptions::default() }); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); +} + +#[test] +fn a_plot_stops_at_its_point_budget() { + let d = doc_with(|d| (0..MAX_POINTS / 4).map(|i| stroked(d, rect(1.0, 1.0, 2.0 + (i % 50) as f64, 3.0), Color::BLACK)).collect()); + let out = plot(&d, &opts(&d)); + assert!(out.warnings.iter().any(|w| w == TOO_MANY_POINTS), "{:?}", out.warnings); + assert!(text(&out).matches("PU").count() <= MAX_POINTS / 5 + 3); +} + +/// The points a plain plot moves through. +fn moves(t: &str) -> usize { + t.split_terminator(';') + .filter(|i| i.starts_with("PU") || i.starts_with("PD")) + .map(|i| i[2..].split(',').filter(|v| !v.is_empty()).count() / 2) + .sum() +} + +#[test] +fn one_path_longer_than_the_budget_is_cut_at_it() { + let d = doc_with(|d| { + let mut bp = BezPath::new(); + bp.move_to((1.0, 1.0)); + for i in 0..MAX_POINTS + 10 { + bp.line_to((if i % 2 == 0 { 2.0 } else { 1.0 }, 1.0 + (i % 50) as f64)); + } + vec![stroked(d, PathData::from_bezpath(&bp), Color::BLACK)] + }); + let out = plot(&d, &opts(&d)); + assert!(out.warnings.iter().any(|w| w == TOO_MANY_POINTS), "{:?}", out.warnings); + let n = moves(&text(&out)); + assert!(n > 2 && n <= MAX_POINTS, "{n}"); +} + +/// A path whose flattening stops at the budget while its moves so far lie off the artboard: the +/// rest, over the artboard, is left out with a warning. +#[test] +fn a_path_cut_short_by_the_budget_warns() { + let d = doc_with(|d| { + let mut bp = BezPath::new(); + bp.move_to((-50.0, 10.0)); + for i in 0..MAX_POINTS * 4 + 10 { + bp.line_to((if i % 2 == 0 { -40.0 } else { -50.0 }, 10.0)); + } + bp.line_to((50.0, 50.0)); + bp.line_to((60.0, 50.0)); + vec![stroked(d, PathData::from_bezpath(&bp), Color::BLACK)] + }); + let out = plot(&d, &opts(&d)); + assert!(out.warnings.iter().any(|w| w == TOO_MANY_POINTS), "{:?}", out.warnings); +} + +/// A filled path cut short by the budget is not closed: the move from where it stopped back to its +/// start is not on its outline. Only its first move, along y = 50 off the artboard's left edge, +/// is drawn. +#[test] +fn a_filled_path_cut_short_stays_open() { + let d = doc_with(|d| { + let mut bp = BezPath::new(); + bp.move_to((10.0, 50.0)); + bp.line_to((-40.0, 50.0)); + for i in 0..MAX_POINTS * 4 + 10 { + bp.line_to((if i % 2 == 0 { -40.0 } else { -50.0 }, 10.0)); + } + vec![filled(d, PathData::from_bezpath(&bp), Color::BLACK)] + }); + let out = plot(&d, &opts(&d)); + assert!(out.warnings.iter().any(|w| w == TOO_MANY_POINTS), "{:?}", out.warnings); + assert_eq!(text(&out), "IN;PU;SP1;PU141,706;PD0,706;PU;SP0;"); +} + +/// A blend's steps that its bent spine turns onto the region plotted are drawn, although its keys +/// and spine lie off it. +#[test] +fn blend_steps_a_spine_turns_onto_the_region_are_drawn() { + let d = doc_with(|d| { + let keys = + vec![stroked(d, line((-400.0, -200.0), (200.0, -200.0)), Color::BLACK), stroked(d, line((-560.0, -60.0), (40.0, -60.0)), Color::BLACK)]; + let mut spine = BezPath::new(); + spine.move_to((-100.0, -200.0)); + spine.quad_to((-100.0, -60.0), (-260.0, -60.0)); + let spec = vectorcraft_doc::BlendSpec { + spacing: vectorcraft_doc::BlendSpacing::Steps(20), + spine: Some(PathData::from_bezpath(&spine)), + orientation: vectorcraft_doc::BlendOrientation::AlignToPath, + ..Default::default() + }; + vec![Node::new(d.alloc_id(), NodeKind::Blend { children: keys.into_iter().map(Arc::new).collect(), spec: Box::new(spec) })] + }); + // The keys and spine lie above y = -55; the steps turned along the spine cross this area. + let region = Rect::new(-300.0, 0.0, -200.0, 50.0); + let t = text(&plot(&d, &HpglOptions { region, ..HpglOptions::default() })); + assert!(t.contains("PD"), "{t}"); +} + +/// A closed path that starts on the artboard, leaves it and comes back is one line, with no +/// pen lift where it started. +#[test] +fn a_closed_path_cut_at_the_artboard_is_one_line() { + let d = doc_with(|d| { + let mut bp = BezPath::new(); + bp.move_to((150.0, 10.0)); + bp.line_to((250.0, 10.0)); + bp.line_to((250.0, 50.0)); + bp.line_to((150.0, 50.0)); + bp.close_path(); + vec![stroked(d, PathData::from_bezpath(&bp), Color::BLACK)] + }); + let t = text(&plot(&d, &opts(&d))); + assert_eq!(t, "IN;PU;SP1;PU2822,706;PD2117,706,2117,1270,2822,1270;PU;SP0;"); +} + +/// A clipping path that paints is drawn once: where its fill paints (before the art it clips), +/// or where its stroke paints (after it). +#[test] +fn a_clipping_path_is_drawn_where_it_paints() { + let clip_doc = |fill: Paint, stroke: Paint| { + doc_with(|d| { + let clip = Node::path(d.alloc_id(), rect(20.0, 20.0, 40.0, 40.0), Appearance::basic(fill, stroke, 1.0)); + let clipped = stroked(d, line((0.0, 30.0), (200.0, 30.0)), Color::BLACK); + let mut group = Node::group(d.alloc_id(), vec![Arc::new(clip), Arc::new(clipped)]); + if let NodeKind::Group { clip, .. } = &mut group.kind { + *clip = true; + } + vec![group] + }) + }; + let red = Paint::solid(Color::rgb8(255, 0, 0)); + let filled = clip_doc(red.clone(), Paint::None); + assert_eq!(plot(&filled, &opts(&filled)).pens, [[255, 0, 0], [0, 0, 0]]); + let stroked = clip_doc(Paint::None, red.clone()); + assert_eq!(plot(&stroked, &opts(&stroked)).pens, [[0, 0, 0], [255, 0, 0]]); + let both = clip_doc(Paint::solid(Color::rgb8(0, 0, 255)), red); + let out = plot(&both, &opts(&both)); + assert_eq!(out.pens, [[0, 0, 0], [255, 0, 0]], "drawn once, in its stroke's color"); + // Two pen changes, a move to each of the two paths, and the last pen up. + assert_eq!(text(&out).matches("PU").count(), 5, "{}", text(&out)); + // A stroke at 0% opacity isn't drawn: the clipping path is drawn in its fill, below. + let faded = doc_with(|d| { + let mut clip = Node::path( + d.alloc_id(), + rect(20.0, 20.0, 40.0, 40.0), + Appearance::basic(Paint::solid(Color::rgb8(0, 0, 255)), Paint::solid(Color::rgb8(255, 0, 0)), 1.0), + ); + for item in &mut clip.appearance.items { + if let AppearanceItem::Stroke(s) = item { + s.opacity = 0.0; + } + } + let clipped = Node::path(d.alloc_id(), line((0.0, 30.0), (200.0, 30.0)), Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0)); + let mut group = Node::group(d.alloc_id(), vec![Arc::new(clip), Arc::new(clipped)]); + if let NodeKind::Group { clip, .. } = &mut group.kind { + *clip = true; + } + vec![group] + }); + assert_eq!(plot(&faded, &opts(&faded)).pens, [[0, 0, 255], [0, 0, 0]]); + // An open clipping path with a fill and a stroke is drawn closed, as other filled paths are. + let mut open = BezPath::new(); + open.move_to((20.0, 20.0)); + open.line_to((40.0, 20.0)); + open.line_to((40.0, 40.0)); + let open = PathData::from_bezpath(&open); + let open_doc = doc_with(|d| { + let clip = Node::path(d.alloc_id(), open, Appearance::basic(Paint::solid(Color::rgb8(0, 0, 255)), Paint::solid(Color::rgb8(255, 0, 0)), 1.0)); + let clipped = Node::path(d.alloc_id(), line((0.0, 30.0), (200.0, 30.0)), Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0)); + let mut group = Node::group(d.alloc_id(), vec![Arc::new(clip), Arc::new(clipped)]); + if let NodeKind::Group { clip, .. } = &mut group.kind { + *clip = true; + } + vec![group] + }); + let t = text(&plot(&open_doc, &opts(&open_doc))); + assert!(t.ends_with("SP2;PU282,1129;PD564,1129,564,847,282,1129;PU;SP0;"), "{t}"); +} + +/// A symbol `art` and an instance of it at its place. +fn symbol_doc(art: Node, instance: impl FnOnce(&mut Node)) -> Document { + let mut d = doc_with(|d| { + let mut n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "s".into(), xf: Affine::IDENTITY }); + instance(&mut n); + vec![n] + }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "s".into(), art: Arc::new(art) }); + d +} + +/// Symbols nested more than 8 deep are left out with a warning. +#[test] +fn symbols_nested_too_deep_are_left_out_with_a_warning() { + let mut d = doc_with(|d| vec![Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "s9".into(), xf: Affine::IDENTITY })]); + let art = stroked(&mut d, rect(10.0, 10.0, 60.0, 40.0), Color::BLACK); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "s0".into(), art: Arc::new(art) }); + for i in 1..10 { + let inner = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: format!("s{}", i - 1), xf: Affine::IDENTITY }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: format!("s{i}"), art: Arc::new(inner) }); + } + let out = plot(&d, &opts(&d)); + assert!(out.warnings.iter().any(|w| w == TOO_DEEP), "{:?}", out.warnings); + assert_eq!(text(&out), "IN;PU;SP0;"); +} + +/// A symbol instance stained by its fill draws in the stained color. +#[test] +fn a_stained_symbol_instance_takes_its_stain() { + let mut d = Document::new(200.0, 100.0); + let art = stroked(&mut d, rect(10.0, 10.0, 60.0, 40.0), Color::BLACK); + let d = symbol_doc(art, |n| n.appearance = Appearance::basic(Paint::solid(Color::rgb8(255, 0, 0)), Paint::None, 1.0).into()); + assert_eq!(plot(&d, &opts(&d)).pens, [[255, 0, 0]]); +} + +/// The geometry effects in a symbol's art apply: a line moved 30 pt right by a Transform effect. +#[test] +fn a_symbol_draws_its_art_with_its_effects() { + let mut d = Document::new(200.0, 100.0); + let mut art = stroked(&mut d, line((10.0, 10.0), (20.0, 10.0)), Color::BLACK); + art.appearance.effects.push(vectorcraft_doc::Effect { + id: "distort.transform".into(), + params: serde_json::json!({"moveH": 30.0}), + visible: true, + }); + let d = symbol_doc(art, |_| {}); + assert_eq!(text(&plot(&d, &opts(&d))), "IN;PU;SP1;PU564,1270;PD706,1270;PU;SP0;"); +} + +/// Art an effect moves onto the artboard from off it is drawn, for an instance on its own and +/// one in a group: the bounds that skip art off the artboard don't measure symbol effects. +#[test] +fn symbol_art_an_effect_moves_onto_the_artboard_is_drawn() { + let mut d = Document::new(200.0, 100.0); + let mut art = stroked(&mut d, line((-30.0, 10.0), (-20.0, 10.0)), Color::BLACK); + art.appearance.effects.push(vectorcraft_doc::Effect { + id: "distort.transform".into(), + params: serde_json::json!({"moveH": 40.0}), + visible: true, + }); + let alone = symbol_doc(art.clone(), |_| {}); + assert_eq!(text(&plot(&alone, &opts(&alone))), "IN;PU;SP1;PU141,1270;PD282,1270;PU;SP0;"); + let mut grouped = doc_with(|d| { + let n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "s".into(), xf: Affine::IDENTITY }); + vec![Node::group(d.alloc_id(), vec![Arc::new(n)])] + }); + grouped.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "s".into(), art: Arc::new(art.clone()) }); + assert_eq!(text(&plot(&grouped, &opts(&grouped))), "IN;PU;SP1;PU141,1270;PD282,1270;PU;SP0;"); + // Other art off the artboard is still skipped: a blend there doesn't spend the live art's + // limit (1,000 objects in tests) before the blend on the artboard. + let mut d = doc_with(|d| { + let off = + vec![stroked(d, line((-500.0, 10.0), (-500.0, 20.0)), Color::BLACK), stroked(d, line((-400.0, 10.0), (-400.0, 20.0)), Color::BLACK)]; + let on = vec![stroked(d, line((10.0, 10.0), (10.0, 20.0)), Color::BLACK), stroked(d, line((30.0, 10.0), (30.0, 20.0)), Color::BLACK)]; + vec![blend_of(d, off, 1_200), blend_of(d, on, 1)] + }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "unused".into(), art: Arc::new(art) }); + let out = plot(&d, &opts(&d)); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + assert_eq!(text(&out).matches("PD").count(), 3, "{}", text(&out)); +} + +/// A rectangle with `per_side` straight moves along each side. +fn fine_rect(x0: f64, y0: f64, x1: f64, y1: f64, per_side: u32) -> PathData { + let corners = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]; + let mut bp = BezPath::new(); + bp.move_to(corners[0]); + for (k, a) in corners.iter().enumerate() { + let b = corners[(k + 1) % 4]; + for i in 1..=per_side { + let t = f64::from(i) / f64::from(per_side); + bp.line_to((a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t)); + } + } + bp.close_path(); + PathData::from_bezpath(&bp) +} + +/// Nested clipping masks of 6,000 points each pass the 10,000 points masks may hold together +/// in tests: the inner one is left out with a warning, and the line is cut by the outer one only. +#[test] +fn masks_past_their_point_budget_are_left_out() { + let d = doc_with(|d| { + let clip_group = |d: &mut Document, mask: PathData, art: Node| { + let mask = Node::path(d.alloc_id(), mask, Appearance::basic(Paint::None, Paint::None, 1.0)); + let mut group = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(art)]); + if let NodeKind::Group { clip, .. } = &mut group.kind { + *clip = true; + } + group + }; + let across = Node::path(d.alloc_id(), line((0.0, 50.0), (200.0, 50.0)), Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0)); + let inner = clip_group(d, fine_rect(50.0, 30.0, 150.0, 70.0, 1500), across); + vec![clip_group(d, fine_rect(10.0, 10.0, 190.0, 90.0, 1500), inner)] + }); + let out = plot(&d, &opts(&d)); + assert!(out.warnings.iter().any(|w| w == MASK_POINTS), "{:?}", out.warnings); + assert_eq!(text(&out), "IN;PU;SP1;PU141,706;PD2681,706;PU;SP0;"); +} + +/// A line through the 500 teeth of a comb-shaped mask crosses its edges about 1,000 times, and +/// each piece between crossings is tested against all 2,002 edges: that spends the clipping +/// budget, so the line is drawn whole with a warning. +#[test] +fn a_mask_crossed_many_times_spends_the_clipping_budget() { + let d = doc_with(|d| { + let mut pts = vec![]; + for i in 0..500 { + let x = f64::from(i) * 0.4; + pts.extend([(x, 20.0), (x + 0.2, 20.0), (x + 0.2, 50.0), (x + 0.4, 50.0)]); + } + pts.extend([(200.0, 80.0), (0.0, 80.0)]); + let mut bp = BezPath::new(); + bp.move_to(pts[0]); + pts[1..].iter().for_each(|&p| bp.line_to(p)); + bp.close_path(); + let comb = Node::path(d.alloc_id(), PathData::from_bezpath(&bp), Appearance::basic(Paint::None, Paint::None, 1.0)); + let clipped = stroked(d, line((0.5, 35.0), (199.5, 35.0)), Color::BLACK); + let mut group = Node::group(d.alloc_id(), vec![Arc::new(comb), Arc::new(clipped)]); + if let NodeKind::Group { clip, .. } = &mut group.kind { + *clip = true; + } + vec![group] + }); + let out = plot(&d, &opts(&d)); + assert!(out.warnings.iter().any(|w| w == CLIP_WORK), "{:?}", out.warnings); + assert_eq!(text(&out).matches("PD").count(), 1, "{}", text(&out)); +} + +#[test] +fn more_colors_than_pens_share_the_nearest_pen() { + let d = doc_with(|d| (0..300).map(|i| stroked(d, rect(1.0, 1.0, 5.0, 5.0), Color::rgb8((i % 256) as u8, (i / 256) as u8, 7))).collect()); + let out = plot(&d, &opts(&d)); + assert_eq!(out.pens.len(), MAX_PENS); + assert!(out.warnings.iter().any(|w| w == MANY_COLORS), "{:?}", out.warnings); +} + +#[test] +fn sorting_draws_the_nearest_path_next() { + let d = doc_with(|d| { + vec![ + stroked(d, line((150.0, 90.0), (150.0, 80.0)), Color::BLACK), + stroked(d, line((10.0, 80.0), (10.0, 90.0)), Color::BLACK), + stroked(d, line((80.0, 90.0), (80.0, 80.0)), Color::BLACK), + ] + }); + let unsorted = text(&plot(&d, &opts(&d))); + assert_eq!(unsorted, "IN;PU;SP1;PU2117,141;PD2117,282;PU141,282;PD141,141;PU1129,141;PD1129,282;PU;SP0;"); + // From the origin: the left line drawn backwards from its lower end, then the middle and the + // right one from the end the pen is nearest. + let sorted = text(&plot(&d, &HpglOptions { sort: true, ..opts(&d) })); + assert_eq!(sorted, "IN;PU;SP1;PU141,141;PD141,282;PU1129,282;PD1129,141;PU2117,141;PD2117,282;PU;SP0;"); +} + +/// A closed path is as near as its nearest point, and starts there. +#[test] +fn sorting_measures_a_closed_path_by_its_nearest_point() { + let d = doc_with(|d| vec![stroked(d, rect(40.0, 60.0, 50.0, 70.0), Color::BLACK), stroked(d, rect(10.0, 10.0, 190.0, 90.0), Color::BLACK)]); + let t = text(&plot(&d, &HpglOptions { sort: true, ..opts(&d) })); + // The large square's bottom-left corner is nearer the origin than any point of the small one. + assert_eq!(t, "IN;PU;SP1;PU141,141;PD141,1270,2681,1270,2681,141,141,141;PU564,423;PD564,564,706,564,706,423,564,423;PU;SP0;"); +} + +#[test] +fn sorting_stops_at_its_budget_and_keeps_every_path() { + let d = doc_with(|d| (0..600).map(|i| stroked(d, line((1.0 + (i % 100) as f64, 10.0), (1.0 + (i % 100) as f64, 20.0)), Color::BLACK)).collect()); + let out = plot(&d, &HpglOptions { sort: true, ..opts(&d) }); + assert_eq!(out.setting_notes, [UNSORTED]); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + assert_eq!(text(&out).matches("PD").count(), 600); +} + +/// `x` points in plotter units. +fn plu(x: f64) -> i64 { + (x * 1016.0 / 72.0).round() as i64 +} + +/// The left edge of each path a plain HP-GL plot draws, in drawing order (plotter units). +fn lefts(out: &HpglOutput) -> Vec { + let mut lefts: Vec = vec![]; + for i in text(out).split_terminator(';') { + let xs = i.get(2..).unwrap_or_default().split(',').step_by(2).filter_map(|x| x.parse::().ok()); + match i.get(..2) { + Some("PU") => lefts.extend(xs.min()), + Some("PD") => { + if let (Some(l), Some(x)) = (lefts.last_mut(), xs.min()) { + *l = (*l).min(x); + } + } + _ => {} + } + } + lefts +} + +/// A letter O made as one path: its outline, then its counter. +#[test] +fn inside_first_cuts_a_letters_counter_before_its_outline() { + let d = doc_with(|d| { + let mut bp = rect(10.0, 10.0, 60.0, 90.0).to_bezpath(); + bp.extend(shapes::ellipse(Rect::new(25.0, 30.0, 45.0, 70.0)).to_bezpath()); + vec![filled(d, PathData::from_bezpath(&bp), Color::BLACK)] + }); + assert_eq!(lefts(&plot(&d, &opts(&d))), [plu(10.0), plu(25.0)]); + assert_eq!(lefts(&plot(&d, &HpglOptions { inside_first: true, ..opts(&d) })), [plu(25.0), plu(10.0)]); +} + +/// A part drawn before its two holes: the holes are cut first, nearest first with `sort`. +#[test] +fn a_part_with_two_holes_is_cut_holes_first() { + let d = doc_with(|d| { + vec![ + stroked(d, rect(10.0, 10.0, 190.0, 90.0), Color::BLACK), + stroked(d, shapes::ellipse(Rect::new(160.0, 40.0, 180.0, 60.0)), Color::BLACK), + stroked(d, shapes::ellipse(Rect::new(20.0, 40.0, 40.0, 60.0)), Color::BLACK), + ] + }); + let (part, right, left) = (plu(10.0), plu(160.0), plu(20.0)); + assert_eq!(lefts(&plot(&d, &opts(&d))), [part, right, left]); + assert_eq!(lefts(&plot(&d, &HpglOptions { inside_first: true, ..opts(&d) })), [right, left, part]); + // Sorting alone starts at the part's corner, nearest the origin; inside first, the nearest + // hole comes first, then the other, then the part. + assert_eq!(lefts(&plot(&d, &HpglOptions { sort: true, ..opts(&d) })), [part, left, right]); + let both = plot(&d, &HpglOptions { sort: true, inside_first: true, ..opts(&d) }); + assert_eq!(lefts(&both), [left, right, part]); + assert!(both.warnings.is_empty(), "{:?}", both.warnings); +} + +/// Rings inside rings are cut innermost first, and a ring with nothing inside it keeps its place +/// in paint order. +#[test] +fn nested_rings_are_cut_innermost_first() { + let d = doc_with(|d| { + vec![ + stroked(d, rect(120.0, 10.0, 190.0, 90.0), Color::BLACK), + stroked(d, rect(10.0, 10.0, 100.0, 90.0), Color::BLACK), + stroked(d, rect(20.0, 20.0, 90.0, 80.0), Color::BLACK), + stroked(d, rect(30.0, 30.0, 80.0, 70.0), Color::BLACK), + ] + }); + let out = plot(&d, &HpglOptions { inside_first: true, ..opts(&d) }); + assert_eq!(lefts(&out), [plu(120.0), plu(30.0), plu(20.0), plu(10.0)]); +} + +/// Each pen's paths are ordered among themselves: a red square inside a black part is drawn with +/// the red pen, after the black part. +#[test] +fn inside_first_orders_each_pens_paths() { + let d = doc_with(|d| { + vec![ + stroked(d, rect(10.0, 10.0, 190.0, 90.0), Color::BLACK), + stroked(d, rect(20.0, 20.0, 40.0, 40.0), Color::rgb8(255, 0, 0)), + stroked(d, rect(50.0, 20.0, 70.0, 40.0), Color::BLACK), + ] + }); + let out = plot(&d, &HpglOptions { inside_first: true, ..opts(&d) }); + assert_eq!(lefts(&out), [plu(50.0), plu(10.0), plu(20.0)]); +} + +/// Finding which of 100 nested rings lie inside which is past the budget: they are drawn in +/// paint order, with a note on the option. +#[test] +fn inside_first_past_its_budget_draws_in_paint_order() { + let d = doc_with(|d| (0..100).map(|i| stroked(d, rect(1.0 + 0.4 * f64::from(i), 10.0, 199.0, 90.0), Color::BLACK)).collect()); + let out = plot(&d, &HpglOptions { inside_first: true, ..opts(&d) }); + assert_eq!(out.setting_notes, [UNNESTED]); + let l = lefts(&out); + assert_eq!(l.len(), 100); + assert!(l.windows(2).all(|w| w[0] <= w[1]), "{l:?}"); + // With `sort` too, the budget is spent before sorting starts: paint order, with both notes. + let out = plot(&d, &HpglOptions { sort: true, inside_first: true, ..opts(&d) }); + assert_eq!(out.setting_notes, [UNNESTED, UNSORTED]); + assert_eq!(lefts(&out), l); +} + +/// Sorting 600 lines inside two rings runs out of work: every path is drawn, the inner ring and +/// then the outer one last. +#[test] +fn inside_first_past_its_sorting_budget_keeps_the_rings_last() { + let d = doc_with(|d| { + let mut v = vec![stroked(d, rect(0.5, 5.0, 150.0, 30.0), Color::BLACK), stroked(d, rect(0.7, 7.0, 140.0, 25.0), Color::BLACK)]; + v.extend((0..600).map(|i| stroked(d, line((1.0 + (i % 100) as f64, 10.0), (1.0 + (i % 100) as f64, 20.0)), Color::BLACK))); + v + }); + let out = plot(&d, &HpglOptions { sort: true, inside_first: true, ..opts(&d) }); + assert_eq!(out.setting_notes, [UNSORTED_INSIDE]); + let l = lefts(&out); + assert_eq!(l.len(), 602); + assert_eq!(l.get(600..), Some(&[plu(0.7), plu(0.5)][..])); +} + +/// Without `sort`, 1,000 lines inside a ring are drawn in paint order and the ring after them, +/// within the budget. +#[test] +fn inside_first_alone_keeps_paint_order_for_many_paths() { + let d = doc_with(|d| { + let mut v = vec![stroked(d, rect(0.5, 5.0, 199.0, 30.0), Color::BLACK)]; + v.extend((0..1000).map(|i| stroked(d, line((1.0 + 0.19 * f64::from(i), 10.0), (1.0 + 0.19 * f64::from(i), 20.0)), Color::BLACK))); + v + }); + let out = plot(&d, &HpglOptions { inside_first: true, ..opts(&d) }); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + let l = lefts(&out); + assert_eq!(l.len(), 1001); + assert_eq!(l.last(), Some(&plu(0.5))); + assert!(l.get(..1000).is_some_and(|l| l.windows(2).all(|w| w[0] < w[1])), "{l:?}"); +} + +#[test] +fn art_wholly_past_the_plotter_range_is_cut_off_with_a_warning() { + let d = doc_with(|d| vec![stroked(d, line((7e8, 50.0), (7e8 + 10.0, 50.0)), Color::BLACK)]); + let out = plot(&d, &HpglOptions { region: Rect::new(0.0, 0.0, 1e9, 100.0), ..HpglOptions::default() }); + assert!(out.warnings.iter().any(|w| w == OUT_OF_RANGE), "{:?}", out.warnings); + assert_eq!(text(&out), "IN;PU;SP0;"); +} + +/// The reference guide's example of an encoded number: 10,525 is written as the bytes 121, 71 +/// and 196 (https://support.hp.com/sg-en/document/c01121263). +#[test] +fn encoded_numbers_follow_the_reference_guide() { + let mut out = vec![]; + pe_number(&mut out, 10_525); + assert_eq!(out, [121, 71, 196]); + out.clear(); + pe_number(&mut out, -1); + pe_number(&mut out, 0); + // The sign in the low bit: -1 is 3. + assert_eq!(out, [194, 191]); +} + +#[test] +fn hpgl2_writes_the_palette_and_encoded_polylines() { + let out = plot(&three(), &HpglOptions { version: Version::Hpgl2, ..opts(&three()) }); + let b = &out.bytes; + assert!(b.starts_with(b"IN;NP4;PC1,0,0,0;PC2,255,0,0;PC3,0,0,255;PU;SP1;PE<="), "{:?}", String::from_utf8_lossy(b)); + assert!(b.ends_with(b";PU;SP0;")); + assert_eq!(b.windows(4).filter(|w| w == b";PE<").count(), 3, "one encoded polyline per pen"); + // Encoded moves take fewer bytes than the same moves written as text. + let plain = plot(&three(), &opts(&three())); + assert!(b.len() < plain.bytes.len(), "{} against {}", b.len(), plain.bytes.len()); +} + +/// A move longer than 8,388,607 units is written absolute (`=`), so every number stays in the +/// range: here from about −5,000,000 to +5,000,000 units around a centered origin. +#[test] +fn hpgl2_writes_a_move_past_the_range_absolute() { + let d = doc_with(|d| { + vec![ + stroked(d, line((-354_000.0, 50.0), (-353_990.0, 50.0)), Color::BLACK), + stroked(d, line((353_990.0, 50.0), (354_000.0, 50.0)), Color::BLACK), + ] + }); + let o = HpglOptions { + version: Version::Hpgl2, + origin: Origin::Center, + region: Rect::new(-400_000.0, 0.0, 400_000.0, 100.0), + ..HpglOptions::default() + }; + let out = plot(&d, &o); + assert_eq!(out.bytes.iter().filter(|b| **b == b'=').count(), 2, "{:?}", String::from_utf8_lossy(&out.bytes)); + let back = super::super::import(&out.bytes).unwrap(); + let mut xs = vec![]; + back.document.walk(|n| { + if let Some(p) = n.path_data() { + xs.extend(p.to_bezpath().elements().iter().filter_map(|e| if let PathEl::MoveTo(p) = e { Some(p.x) } else { None })); + } + }); + assert_eq!(xs.len(), 2); + assert!((xs[1] - xs[0] - 707_990.0).abs() < 0.2, "{xs:?}"); +} + +/// The points of every path `doc` holds, in paint order. +fn polylines(doc: &Document) -> Vec<(Vec, Option)> { + let mut out = vec![]; + doc.walk(|n| { + if let NodeKind::Path { path, .. } = &n.kind { + let bp = path.to_bezpath(); + let pts = bp.elements().iter().filter_map(|e| match e { + PathEl::MoveTo(p) | PathEl::LineTo(p) => Some(*p), + _ => None, + }); + let stroke = n.appearance.items.iter().find_map(|i| if let AppearanceItem::Stroke(s) = i { Some(s.paint.clone()) } else { None }); + out.push((pts.collect(), stroke)); + } + }); + out +} + +/// Each version's plot read back: the same lines, within the tolerance and half a plotter unit, +/// and with HP-GL/2 the same colors. +#[test] +fn plots_read_back_as_the_same_lines() { + let d = three(); + for version in Version::ALL { + let out = plot(&d, &HpglOptions { version, ..opts(&d) }); + let back = super::super::import(&out.bytes).unwrap(); + assert!(back.warnings.is_empty(), "{:?}", back.warnings); + let lines = polylines(&back.document); + assert_eq!(lines.len(), 3, "{version:?}"); + // The reader's artboard is round what the art paints: line the two up by the square. + let shift = lines[0].0[0] - Point::new(10.0, 10.0); + // Two roundings to whole plotter units (1/1016 in) apart at most. + let near = |p: Point, q: Point| (p - shift).distance(q) <= 0.11; + let square = [(10.0, 10.0), (60.0, 10.0), (60.0, 40.0), (10.0, 40.0), (10.0, 10.0)].map(Point::from); + assert!(lines[0].0.iter().zip(square).all(|(p, q)| near(*p, q)) && lines[0].0.len() == 5, "{:?}", lines[0].0); + assert!(near(lines[1].0[0], Point::new(70.0, 20.0)) && near(lines[1].0[1], Point::new(150.0, 80.0)), "{:?}", lines[1].0); + // The ellipse's every point lies on it, within the tolerance and the rounding. + let ellipse = kurbo::Ellipse::new((100.0, 50.0), (30.0, 20.0), 0.0); + for p in &lines[2].0 { + let q = p.to_vec2() - shift - kurbo::Vec2::new(100.0, 50.0); + let r = (q.x / 30.0).hypot(q.y / 20.0); + assert!((r - 1.0).abs() * 20.0 <= DEFAULT_TOLERANCE + 0.1, "{p:?} off the ellipse"); + } + assert!(lines[2].0.len() > 16 && ellipse.area() > 0.0); + if version == Version::Hpgl2 { + let colors: Vec> = lines.iter().map(|l| l.1.clone()).collect(); + assert_eq!( + colors, + [Paint::solid(Color::rgb8(0, 0, 0)), Paint::solid(Color::rgb8(255, 0, 0)), Paint::solid(Color::rgb8(0, 0, 255))].map(Some) + ); + } + } +} diff --git a/crates/cad/src/lib.rs b/crates/cad/src/lib.rs index 6035211600..1443829806 100644 --- a/crates/cad/src/lib.rs +++ b/crates/cad/src/lib.rs @@ -1,4 +1,5 @@ -//! CAD interchange: a hand-written ASCII DXF writer (versions R12 to 2018) and reader. +//! CAD interchange: a hand-written ASCII DXF writer (versions R12 to 2018) and reader, and an +//! HP-GL/2 plot file reader and writer. //! //! [`export`] writes the visible art of a document into one DXF drawing: each layer becomes a DXF //! layer (hidden ones switched off, locked ones locked, non-printing ones not plotted), paths @@ -11,13 +12,16 @@ //! clipping) is approximated or left out, and each such loss comes back as a warning. //! //! [`import()`] reads an ASCII DXF drawing (any version) into a document: see [`import`]. +//! [`hpgl::import`] reads an HP-GL plotter file, and [`hpgl::export`] writes one: see [`hpgl`]. //! //! - `aci`: the 256-colour index palette and the nearest index of a colour. //! - `writer`: group codes, handles and the file's sections, tables and objects. //! - `scene`: the document walk that turns objects into entities. //! - `import`: the reader, entities to art, blocks to symbols. +//! - `hpgl`: the HP-GL reader, the pen's moves to paths, and the writer, paths to pen moves. mod aci; +pub mod hpgl; pub mod import; mod scene; mod writer; @@ -277,6 +281,10 @@ pub struct DxfOptions { pub scale_lineweights: bool, pub colors: ColorDepth, pub raster: RasterFormat, + /// Placed images are written as IMAGE entities with their files (else left out, undecoded). + pub include_images: bool, + /// Filled areas get a solid HATCH after their outlines (else the outlines alone). + pub include_hatches: bool, pub preserve: Preserve, /// Alter Paths for Appearance: a stroke a CAD line can't draw (one [`Preserve::Appearance`] /// outlines, one wider than the widest lineweight, or any stroke in R13 and R14, which have @@ -299,6 +307,8 @@ impl Default for DxfOptions { scale_lineweights: false, colors: ColorDepth::default(), raster: RasterFormat::default(), + include_images: true, + include_hatches: true, preserve: Preserve::default(), alter_paths: false, outline_text: false, @@ -318,7 +328,8 @@ pub enum DxfPreset { /// 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. + /// and placed images and fill hatches left out (fills are their outlines), with PNG as the + /// format images take when they are put back in. Cnc, } @@ -356,6 +367,8 @@ impl DxfPreset { scale_lineweights: false, colors: ColorDepth::Aci256, raster: RasterFormat::Png, + include_images: false, + include_hatches: false, preserve: Preserve::Editability, alter_paths: false, outline_text: true, @@ -373,6 +386,8 @@ impl DxfPreset { && o.scale_lineweights == c.scale_lineweights && o.colors == c.colors && o.raster == c.raster + && o.include_images == c.include_images + && o.include_hatches == c.include_hatches && o.preserve == c.preserve && o.alter_paths == c.alter_paths && o.outline_text == c.outline_text; @@ -395,6 +410,9 @@ pub struct DxfOutput { pub images: Vec, /// What was approximated or left out. pub warnings: Vec, + /// What was left out because an option turns it off (Include Placed Images or Include Fill + /// Hatches off). + pub setting_notes: Vec, } /// The smallest and largest `scale` (drawing units per unit). diff --git a/crates/cad/src/scene.rs b/crates/cad/src/scene.rs index 3faf94423f..4860e4989a 100644 --- a/crates/cad/src/scene.rs +++ b/crates/cad/src/scene.rs @@ -1,5 +1,6 @@ //! The document walk: each visible object becomes DXF entities on its layer's DXF layer, in paint -//! order. Fills are their outlines then solid hatches (the outlines alone in R12), strokes +//! order. Fills are their outlines then solid hatches (the outlines alone in R12 or with +//! hatches left out), placed images are linked image files unless left out, strokes //! polylines (with bulges for circular arcs) and cubic splines with a lineweight and dashes, or //! filled outlines where the look needs them. @@ -28,6 +29,8 @@ const NO_TRUE_COLOR: &str = "true colour needs DXF 2004 or later: colours are wr const NO_TRANSPARENCY: &str = "transparency needs DXF 2004 or later: transparent objects are written opaque"; const NO_FILLS: &str = "DXF R12 has no fills: filled areas are written as their outlines"; const NO_IMAGES: &str = "DXF R12 has no images: placed images are left out"; +const IMAGES_OFF: &str = "placed images are left out (Include Placed Images is off)"; +const HATCHES_OFF: &str = "fill hatches are left out: filled areas are written as their outlines (Include Fill Hatches is off)"; const WIDE_LINES: &str = "lines wider than 2.11 mm (the widest lineweight) are written at 2.11 mm: Alter Paths for Appearance writes their true width"; const STROKE_EXTRAS: &str = "stroke alignment, width profiles, arrowheads and brushes are left out (Maximize Editability writes strokes as lines)"; @@ -339,6 +342,32 @@ fn subpaths(bp: &BezPath) -> Vec { out } +/// `bp` with each open subpath that can enclose an area closed, as a fill closes it: two or more +/// segments, or one curve. A single straight segment stays open. +fn closed_fill(bp: &BezPath) -> BezPath { + let mut out = BezPath::new(); + let (mut segs, mut curved) = (0usize, false); + let close = |out: &mut BezPath, segs: usize, curved: bool| { + if segs >= 2 || (segs == 1 && curved) { + out.close_path(); + } + }; + for el in bp.elements() { + match *el { + PathEl::MoveTo(_) => { + close(&mut out, segs, curved); + (segs, curved) = (0, false); + } + PathEl::ClosePath => (segs, curved) = (0, false), + PathEl::LineTo(_) => segs += 1, + PathEl::QuadTo(..) | PathEl::CurveTo(..) => (segs, curved) = (segs + 1, true), + } + out.push(*el); + } + close(&mut out, segs, curved); + out +} + /// The most pixels of an image written (it is held decoded, as RGBA and encoded at once). const MAX_IMAGE_PIXELS: u64 = 64 << 20; @@ -491,6 +520,8 @@ pub(crate) struct Scene<'a> { /// Image keys → index into `images` (`None`: left out). by_key: HashMap>, warnings: Vec, + /// What was left out because an option asked for it ([`DxfOutput::setting_notes`]). + setting_notes: Vec, brushes: Option>, extents: Option<[f64; 4]>, /// The opacity of the containers around the current object. @@ -525,6 +556,7 @@ impl<'a> Scene<'a> { files: vec![], by_key: HashMap::new(), warnings: vec![], + setting_notes: vec![], brushes: None, extents: None, opacity: 1.0, @@ -559,15 +591,24 @@ impl<'a> Scene<'a> { metric: matches!(self.o.unit, Unit::Millimeters | Unit::Centimeters | Unit::Meters), next: self.next, }; - DxfOutput { bytes: drawing.write().into_bytes(), images: self.files, warnings: self.warnings } + DxfOutput { bytes: drawing.write().into_bytes(), images: self.files, warnings: self.warnings, setting_notes: self.setting_notes } } + /// Note `w`, once, about something of the document that the drawing leaves out or that reaches + /// it changed. A note about an option goes to [`Self::note_setting`]. fn warn(&mut self, w: &str) { if !self.warnings.iter().any(|x| x == w) { self.warnings.push(w.to_string()); } } + /// Note `w`, once, about something left out because an option turns it off. + fn note_setting(&mut self, w: &str) { + if !self.setting_notes.iter().any(|x| x == w) { + self.setting_notes.push(w.to_string()); + } + } + fn handle(&mut self) -> Handle { let h = Handle(self.next); self.next = self.next.saturating_add(1); @@ -631,7 +672,7 @@ impl<'a> Scene<'a> { self.shape(n, &bp, *rule); } NodeKind::Text(t) => self.text(n, t), - NodeKind::Image(im) => self.image(im), + NodeKind::Image(im) => self.image(&self.doc.shown_image(n, im)), NodeKind::SymbolInstance { symbol, xf } => { let doc = self.doc; if self.symbol_nodes >= vectorcraft_doc::MAX_SYMBOL_NODES { @@ -878,13 +919,13 @@ impl<'a> Scene<'a> { Some(vectorcraft_brush::stroke_pieces(doc, b, bp, st)) } - /// A filled area as its outlines followed by a solid hatch (R12: the outlines alone). Laser - /// and cutter software reads the outlines and skips hatches. `clean`: the path has no + /// A filled area as its outlines followed by a solid hatch (R12, or with hatches left out: the + /// outlines alone). Laser and cutter software reads the outlines and skips hatches. `clean`: the path has no /// overlaps, so the hatch's even-odd rule reads it as it is. fn area(&mut self, bp: &BezPath, rule: FillRule, style: &EntityStyle, clean: bool) { if !self.o.version.handles() { self.warn(NO_FILLS); - self.lines(bp, style, 0.0); + self.lines(&closed_fill(bp), style, 0.0); return; } let several = bp.elements().iter().filter(|e| matches!(e, PathEl::MoveTo(_))).count() > 1; @@ -893,11 +934,17 @@ impl<'a> Scene<'a> { .flatten() .map(|p| p.to_bezpath()); let outline = normalized.as_ref().unwrap_or(bp); + // A fill with no loop of three points or more encloses no area: no outline and no hatch. let loops: Vec> = polygons(outline).into_iter().filter(|p| p.len() >= 3).collect(); if loops.is_empty() { return; } - self.lines(outline, style, 0.0); + // The outlines close as the fill does, so an open path's fill keeps its closing edge. + self.lines(&closed_fill(outline), style, 0.0); + if !self.o.include_hatches { + self.note_setting(HATCHES_OFF); + return; + } let h = self.handle(); let layer = self.layer.clone(); self.e.entity("HATCH", h, fixed::MODEL_RECORD, &layer, style, "AcDbHatch"); @@ -1285,6 +1332,10 @@ impl<'a> Scene<'a> { self.warn(NO_IMAGES); return; } + if !self.o.include_images { + self.note_setting(IMAGES_OFF); + return; + } let Some(i) = self.image_def(im) else { return }; let Some((dw, dh)) = self.images.get(i).map(|d| (f64::from(d.size.0), f64::from(d.size.1))) else { return }; let (w, h) = (f64::from(im.width.max(1)), f64::from(im.height.max(1))); diff --git a/crates/cad/src/tests.rs b/crates/cad/src/tests.rs index 90e4cbc2c6..96c037a4a7 100644 --- a/crates/cad/src/tests.rs +++ b/crates/cad/src/tests.rs @@ -843,10 +843,156 @@ fn the_cnc_preset_writes_version_2000_in_millimeters_with_type_as_paths_and_stro 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 { include_images: true, ..o.clone() }), DxfPreset::Custom); + assert_eq!(DxfPreset::of(&DxfOptions { include_hatches: true, ..o.clone() }), DxfPreset::Custom); assert_eq!(DxfPreset::of(&DxfOptions::default()), DxfPreset::Custom); assert_eq!(DxfPreset::from_id(" CNC "), Some(DxfPreset::Cnc)); } +/// A 4 × 2 px PNG placed at (10, 20) under key `raster-1`, and before it in paint order +/// `fill`'s rectangle. +fn image_and_fill_doc(fill: Paint) -> Document { + let mut png = vec![]; + image::RgbaImage::from_pixel(4, 2, image::Rgba([0, 0, 255, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let mut d = doc_with(|d| { + let im = ImageObject { + key: "raster-1".into(), + width: 4, + height: 2, + xf: Affine::translate((10.0, 20.0)) * Affine::scale(5.0), + link: None, + placement: Default::default(), + pixels: None, + }; + vec![ + path(d, shapes::rectangle(Rect::new(50.0, 10.0, 150.0, 60.0)), fill, Paint::None, 0.0), + Node::new(d.alloc_id(), NodeKind::Image(Box::new(im))), + ] + }); + d.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None }); + d +} + +const IMAGES_OFF: &str = "placed images are left out (Include Placed Images is off)"; +const HATCHES_OFF: &str = "fill hatches are left out: filled areas are written as their outlines (Include Fill Hatches is off)"; + +#[test] +fn fills_without_hatches_keep_their_outlines() { + let d = shapes_doc(); + let out = export(&d, &DxfOptions { include_hatches: false, ..opts(&d) }).unwrap(); + assert_eq!(kinds(&out), ["LWPOLYLINE", "LWPOLYLINE", "CIRCLE"], "the fill's outline, the stroke, the circle"); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + assert_eq!(out.setting_notes, [HATCHES_OFF]); + let e = entities(&out); + assert_eq!((get(&e[0], 70), get(&e[0], 370)), (Some("1"), None), "the closed outline, without a lineweight"); + // Hatches stay by default, with no note. + let on = export(&d, &opts(&d)).unwrap(); + assert!(kinds(&on).iter().any(|k| k == "HATCH") && on.setting_notes.is_empty()); + // The outlines are the ones written beside hatches, also for overlapping subpaths, which are + // merged first; a fill with no area (a flat rectangle, a diagonal line) writes nothing either way. + let compound = doc_with(|d| { + let mut bp = shapes::rectangle(Rect::new(10.0, 10.0, 60.0, 60.0)).to_bezpath(); + bp.extend(shapes::rectangle(Rect::new(40.0, 40.0, 90.0, 90.0)).to_bezpath().elements().iter().copied()); + let p = PathData::from_bezpath(&bp); + vec![ + path(d, p, Paint::solid(Color::BLACK), Paint::None, 0.0), + path(d, shapes::rectangle(Rect::new(10.0, 70.0, 90.0, 70.0)), Paint::solid(Color::BLACK), Paint::None, 0.0), + path(d, shapes::line(Point::new(100.0, 10.0), Point::new(150.0, 60.0)), Paint::solid(Color::BLACK), Paint::None, 0.0), + ] + }); + let without_hatches = |o: &DxfOutput| { + let mut e = entities(o); + e.retain(|x| kind(x) != "HATCH"); + e.into_iter().map(|x| x.into_iter().filter(|p| p.0 != 5).collect::()).collect::>() + }; + let (c_on, c_off) = + (export(&compound, &opts(&compound)).unwrap(), export(&compound, &DxfOptions { include_hatches: false, ..opts(&compound) }).unwrap()); + assert_eq!(kinds(&c_on), ["LWPOLYLINE", "HATCH"], "one merged outline"); + assert_eq!(without_hatches(&c_off), without_hatches(&c_on)); + assert_eq!(without_hatches(&out), without_hatches(&on)); + // Strokes outlined for their look are areas too: their outlines stay. + let altered = + export(&d, &DxfOptions { include_hatches: false, alter_paths: true, preserve: Preserve::Editability, version: DxfVersion::R14, ..opts(&d) }) + .unwrap(); + assert!(!kinds(&altered).iter().any(|k| k == "HATCH") && !kinds(&altered).is_empty(), "{:?}", kinds(&altered)); + // Nothing filled: no note. + let lines = doc_with(|d| vec![path(d, shapes::ellipse(Rect::new(120.0, 20.0, 180.0, 80.0)), Paint::None, Paint::solid(Color::BLACK), 1.0)]); + let none = export(&lines, &DxfOptions { include_hatches: false, ..opts(&lines) }).unwrap(); + assert!(none.warnings.is_empty() && none.setting_notes.is_empty()); + // R12 has no hatches anyway: the same outlines, and its own note alone. + let r12 = |include_hatches| export(&d, &DxfOptions { version: DxfVersion::R12, include_hatches, ..opts(&d) }).unwrap(); + let (off, on) = (r12(false), r12(true)); + assert_eq!(off.bytes, on.bytes); + assert_eq!(off.warnings, on.warnings); + assert!(off.setting_notes.is_empty()); +} + +#[test] +fn an_open_path_s_fill_outline_keeps_its_closing_edge() { + let mut bp = vectorcraft_geom::BezPath::new(); + bp.move_to((10.0, 10.0)); + bp.line_to((90.0, 10.0)); + bp.line_to((50.0, 80.0)); + let open = PathData::from_bezpath(&bp); + let d = doc_with(|d| vec![path(d, open.clone(), Paint::solid(Color::BLACK), Paint::solid(Color::BLACK), 1.0)]); + let closed = |e: &Pairs| get(e, 70).and_then(|v| v.trim().parse::().ok()).is_some_and(|v| v & 1 == 1); + for include_hatches in [false, true] { + let out = export(&d, &DxfOptions { include_hatches, ..opts(&d) }).unwrap(); + let e: Vec = entities(&out).into_iter().filter(|x| kind(x) == "LWPOLYLINE").collect(); + assert_eq!(e.len(), 2, "the fill's outline and the stroke: {:?}", kinds(&out)); + assert!(closed(&e[0]), "the fill's outline closes as the fill does (hatches {include_hatches})"); + assert!(!closed(&e[1]), "the stroke stays open (hatches {include_hatches})"); + } + // R12 writes the outline alone, closed too. + let fill_only = doc_with(|d| vec![path(d, open.clone(), Paint::solid(Color::BLACK), Paint::None, 0.0)]); + let r12 = export(&fill_only, &DxfOptions { version: DxfVersion::R12, ..opts(&fill_only) }).unwrap(); + let e = entities(&r12); + assert_eq!(kind(&e[0]), "POLYLINE", "{:?}", kinds(&r12)); + assert!(closed(&e[0]), "R12's outline closes as the fill does"); +} + +#[test] +fn images_can_be_left_out_with_their_files() { + let d = image_and_fill_doc(Paint::None); + let out = export(&d, &DxfOptions { include_images: false, ..opts(&d) }).unwrap(); + assert!(entities(&out).is_empty() && out.images.is_empty(), "{:?}", kinds(&out)); + let p = pairs(&out.bytes); + assert!(!section(&p, "OBJECTS").iter().any(|o| matches!(kind(o), "IMAGEDEF" | "IMAGEDEF_REACTOR" | "RASTERVARIABLES"))); + assert!(!section(&p, "CLASSES").iter().any(|o| get(o, 1) == Some("IMAGE"))); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + assert_eq!(out.setting_notes, [IMAGES_OFF]); + // An image that can't be decoded is not read when images are left out. + let mut broken = d.clone(); + broken.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(b"not a png".to_vec()), proxy: None }); + let left_out = export(&broken, &DxfOptions { include_images: false, ..opts(&broken) }).unwrap(); + assert!(left_out.warnings.is_empty(), "{:?}", left_out.warnings); + assert_eq!(left_out.setting_notes, [IMAGES_OFF]); + assert!(export(&broken, &opts(&broken)).unwrap().warnings.iter().any(|w| w.contains("couldn't be decoded"))); + // R12 has no images anyway: its own note alone. + let r12 = export(&d, &DxfOptions { version: DxfVersion::R12, include_images: false, ..opts(&d) }).unwrap(); + assert!(r12.warnings.iter().any(|w| w.contains("no images")) && r12.setting_notes.is_empty()); +} + +#[test] +fn images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both() { + let d = image_and_fill_doc(Paint::solid(Color::rgb(1.0, 0.0, 0.0))); + let run = |o: DxfOptions| export(&d, &DxfOptions { region: d.artboards[0].rect, ..o }).unwrap(); + let both = run(DxfOptions::default()); + assert_eq!(kinds(&both), ["LWPOLYLINE", "HATCH", "IMAGE"]); + assert_eq!(both.images.len(), 1); + let no_images = run(DxfOptions { include_images: false, ..DxfOptions::default() }); + assert_eq!((kinds(&no_images), no_images.images.len()), (vec!["LWPOLYLINE".to_string(), "HATCH".into()], 0)); + let no_hatches = run(DxfOptions { include_hatches: false, ..DxfOptions::default() }); + assert_eq!((kinds(&no_hatches), no_hatches.images.len()), (vec!["LWPOLYLINE".to_string(), "IMAGE".into()], 1)); + // CNC / CAM: the cutting path alone, with no image file and both notes. + let cnc = run(DxfPreset::Cnc.options()); + assert_eq!(kinds(&cnc), ["LWPOLYLINE"]); + assert!(cnc.images.is_empty()); + assert!(cnc.setting_notes.iter().any(|w| w == IMAGES_OFF) && cnc.setting_notes.iter().any(|w| w == HATCHES_OFF), "{:?}", cnc.setting_notes); + let custom = DxfPreset::Custom.options(); + assert!(custom.include_images && custom.include_hatches, "Custom keeps both"); +} + #[test] fn layers_become_dxf_layers() { let mut d = shapes_doc(); diff --git a/crates/color/src/cms.rs b/crates/color/src/cms.rs index f2a705857e..c5e5bc5bea 100644 --- a/crates/color/src/cms.rs +++ b/crates/color/src/cms.rs @@ -6,8 +6,9 @@ //! * **CMYK spaces:** [`GENERIC_CMYK`] is our own documented parametric press model //! ([`generic`]); [`DEVICE_CMYK`] is the old profile-free formula (kept for exact legacy numbers); //! any CMYK `.icc` the user loads goes through `moxcms` (LUT-based profiles). -//! * The **active settings** (Edit → Color Settings) are process-wide; [`crate::Color::to_rgb`] -//! uses them. Code that needs deterministic numbers builds its own [`Cms`] with [`Cms::new`]. +//! * The **active settings** are process-wide: the working settings (Edit → Color Settings), with +//! the profiles [`use_document_profiles`] last put in place of the working spaces; +//! [`crate::Color::to_rgb`] uses them. Code that needs deterministic numbers builds its own [`Cms`] with [`Cms::new`]. pub mod generic; pub mod icc; @@ -320,6 +321,9 @@ pub struct Cms { settings: ColorSettings, rgb: RgbSpace, cmyk: CmykSpace, + /// The working settings, when a document's assigned profiles take the place of their spaces + /// ([`use_document_profiles`]): a [`ProofTarget::WorkingCmyk`] proof simulates their CMYK space. + working: Option>, } impl std::fmt::Debug for Cms { @@ -330,7 +334,7 @@ impl std::fmt::Debug for Cms { impl Default for Cms { fn default() -> Self { - Self { settings: ColorSettings::default(), rgb: RgbSpace::Srgb, cmyk: CmykSpace::Generic(generic()) } + Self { settings: ColorSettings::default(), rgb: RgbSpace::Srgb, cmyk: CmykSpace::Generic(generic()), working: None } } } @@ -338,7 +342,7 @@ impl Cms { /// Profiles named by a legacy name are stored under their current name. pub fn new(settings: &ColorSettings) -> Result { let settings = ColorSettings { rgb: canonical_name(&settings.rgb).into(), cmyk: canonical_name(&settings.cmyk).into(), ..settings.clone() }; - Ok(Self { rgb: rgb_space(&settings.rgb)?, cmyk: cmyk_space(&settings.cmyk)?, settings }) + Ok(Self { rgb: rgb_space(&settings.rgb)?, cmyk: cmyk_space(&settings.cmyk)?, settings, working: None }) } pub fn settings(&self) -> &ColorSettings { &self.settings @@ -527,7 +531,7 @@ impl Cms { } } - /// Gamut warning: can this colour be printed in the working CMYK space? + /// Gamut warning: can this color be printed in this context's CMYK space? pub fn out_of_gamut(&self, c: &Color) -> bool { self.gamut_error(c) > GAMUT_THRESHOLD } @@ -542,8 +546,9 @@ impl Cms { ProofTarget::Deuteranopia => simulate_cvd(srgb, &DEUTERANOPIA), ProofTarget::Tritanopia => TRITANOPIA.simulate(srgb), ProofTarget::WorkingCmyk => { - let cmyk = self.srgb_to_cmyk(srgb, proof.intent); - self.cmyk_to_srgb(cmyk, proof.simulate_paper) + let working = self.working_cms(); + let cmyk = working.srgb_to_cmyk(srgb, proof.intent); + working.cmyk_to_srgb(cmyk, proof.simulate_paper) } ProofTarget::Cmyk(name) => match cmyk_space(name) { Ok(sp) => { @@ -555,20 +560,29 @@ impl Cms { } } - /// Display sRGB of CMYK inks in the proof's CMYK space (the working space for RGB targets). + /// Display sRGB of CMYK inks in the proof's CMYK space (this context's CMYK space for RGB + /// targets). pub fn proof_cmyk_to_srgb(&self, cmyk: [f32; 4], proof: &ProofSetup) -> [f32; 3] { match &proof.target { ProofTarget::Cmyk(name) => match cmyk_space(name) { Ok(sp) => Self::cmyk_to_srgb_in(&sp, cmyk, proof.simulate_paper, self.settings.bpc), Err(_) => self.cmyk_to_srgb(cmyk, proof.simulate_paper), }, + ProofTarget::WorkingCmyk => self.working_cms().cmyk_to_srgb(cmyk, proof.simulate_paper), _ => self.cmyk_to_srgb(cmyk, proof.simulate_paper), } } + /// The context of the working settings: the one [`use_document_profiles`] put a document's + /// profiles in place of, else this one. + fn working_cms(&self) -> &Cms { + self.working.as_deref().unwrap_or(self) + } + /// A cached 3-D lookup table implementing [`Cms::proof_srgb`] for 8-bit pixels. pub fn proof_lut(&self, proof: &ProofSetup) -> Arc { - let key = format!("{:?}|{:?}|{:?}|{}", self.settings, proof.target, proof.intent, proof.simulate_paper); + let working = self.working.as_ref().map(|w| &w.settings); + let key = format!("{:?}|{working:?}|{:?}|{:?}|{}", self.settings, proof.target, proof.intent, proof.simulate_paper); let mut cache = PROOF_CACHE.lock().unwrap_or_else(|e| e.into_inner()); if let Some((_, l)) = cache.iter().find(|(k, _)| *k == key) { return l.clone(); @@ -890,10 +904,12 @@ impl CmykLut { // ---------- the active (process-wide) settings ---------- static ACTIVE: RwLock>> = RwLock::new(None); +static WORKING: RwLock>> = RwLock::new(None); static RGB_IS_SRGB: AtomicBool = AtomicBool::new(true); static CMYK_IS_DEVICE: AtomicBool = AtomicBool::new(false); -/// The active colour-management context (Edit → Color Settings). +/// The active color-management context: the working settings, with the profiles +/// [`use_document_profiles`] last put in place of the working spaces. pub fn active() -> Arc { if let Some(c) = ACTIVE.read().unwrap_or_else(|e| e.into_inner()).as_ref() { return c.clone(); @@ -906,13 +922,62 @@ pub fn active_settings() -> ColorSettings { active().settings.clone() } -/// Replace the active settings (fails, leaving them unchanged, if a profile is unknown). +/// The color-management context of Edit → Color Settings (the working spaces, intent and black +/// point compensation), as [`set_active`] last set them, whatever profiles a document is assigned. +pub fn working() -> Arc { + if let Some(c) = WORKING.read().unwrap_or_else(|e| e.into_inner()).as_ref() { + return c.clone(); + } + let mut w = WORKING.write().unwrap_or_else(|e| e.into_inner()); + w.get_or_insert_with(|| Arc::new(Cms::default())).clone() +} + +/// The settings of [`working`]. +pub fn working_settings() -> ColorSettings { + working().settings.clone() +} + +/// Replace the working settings (Edit → Color Settings) and make them the active settings (fails, +/// leaving both unchanged, if a profile is unknown). pub fn set_active(settings: &ColorSettings) -> Result<(), CmsError> { - let cms = Cms::new(settings)?; + let cms = Arc::new(Cms::new(settings)?); + *WORKING.write().unwrap_or_else(|e| e.into_inner()) = Some(cms.clone()); + install(cms); + Ok(()) +} + +/// Make the working settings the active settings, with the profiles a document is assigned +/// (`None`: none) in place of the working spaces. An assigned profile that is not available, or +/// is not of its model, leaves the working space. The working settings stay as they are. True when +/// the active settings changed. +pub fn use_document_profiles(rgb: Option<&str>, cmyk: Option<&str>) -> bool { + let working = working(); + let mut st = working.settings.clone(); + if let Some(p) = rgb.and_then(profile).filter(|p| p.kind == ProfileKind::Rgb) { + st.rgb = p.name; + } + if let Some(p) = cmyk.and_then(profile).filter(|p| p.kind == ProfileKind::Cmyk) { + st.cmyk = p.name; + } + if st == active().settings { + return false; + } + if st == working.settings { + install(working); + return true; + } + // The working settings were checked when they were set; a working profile removed since then + // leaves the active settings as they are. + let Ok(mut cms) = Cms::new(&st) else { return false }; + cms.working = Some(working); + install(Arc::new(cms)); + true +} + +fn install(cms: Arc) { RGB_IS_SRGB.store(cms.rgb_is_srgb(), Ordering::Relaxed); CMYK_IS_DEVICE.store(matches!(cms.cmyk, CmykSpace::Device), Ordering::Relaxed); - *ACTIVE.write().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(cms)); - Ok(()) + *ACTIVE.write().unwrap_or_else(|e| e.into_inner()) = Some(cms); } /// Fast path for [`Color::to_rgb`]: RGB colours need no conversion while the working space is sRGB. diff --git a/crates/color/src/gradient.rs b/crates/color/src/gradient.rs index 18aa1bd189..54cb50c197 100644 --- a/crates/color/src/gradient.rs +++ b/crates/color/src/gradient.rs @@ -8,6 +8,9 @@ use serde::{Deserialize, Serialize}; use crate::Color; use crate::freeform::Freeform; +mod spread; +pub use spread::{MAX_SPREAD_LEVEL, MAX_SPREAD_RUNS, MAX_SPREAD_STOPS, Padded}; + #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum GradientKind { #[default] @@ -19,13 +22,18 @@ pub enum GradientKind { /// the page from the vector, with a seam where the last stop meets the first. A negative /// `aspect` mirrors the sweep (see [`GradientGeom::transform`]). Conic, + /// Diamond gradients: the stops run from the center (`start`) out to a square whose + /// half-diagonal is the vector (a diamond when the vector is level), stretched across the + /// vector by `aspect` (see [`GradientGeom::diamond_frame`]). + Diamond, } impl GradientKind { /// Every kind, in the order the Gradient panel lists them. - pub const ALL: [GradientKind; 4] = [GradientKind::Linear, GradientKind::Radial, GradientKind::Conic, GradientKind::Freeform]; - /// Parse a kind name (`linear`, `radial`, `conic`, `freeform`; any case). `angle` and - /// `conical` also mean conic. + pub const ALL: [GradientKind; 5] = + [GradientKind::Linear, GradientKind::Radial, GradientKind::Conic, GradientKind::Diamond, GradientKind::Freeform]; + /// Parse a kind name (`linear`, `radial`, `conic`, `diamond`, `freeform`; any case). `angle` + /// and `conical` also mean conic. pub fn parse(s: &str) -> Option { if s.eq_ignore_ascii_case("angle") || s.eq_ignore_ascii_case("conical") { return Some(GradientKind::Conic); @@ -38,12 +46,13 @@ impl GradientKind { GradientKind::Radial => "Radial", GradientKind::Freeform => "Freeform", GradientKind::Conic => "Conic", + GradientKind::Diamond => "Diamond", } } - /// Is it placed by a center (`start`) and an extent ellipse (radial and conic), rather than - /// by a line? + /// Is it placed by a center (`start`) and an extent around it (radial, conic and diamond), + /// rather than by a line? pub fn is_centered(self) -> bool { - matches!(self, GradientKind::Radial | GradientKind::Conic) + matches!(self, GradientKind::Radial | GradientKind::Conic | GradientKind::Diamond) } } @@ -56,24 +65,62 @@ pub enum GradientMethod { /// Mixed in a perceptual colour space (OKLab), so the steps look even to the eye: blue to /// yellow passes through a light blue-grey rather than a dull mid grey. Perceptual, + /// Mixed around the hue wheel, clockwise as the color wheels draw it: the hue angle falls + /// from each stop to the next (red, magenta, blue, cyan, green, yellow, red), and saturation + /// and brightness change evenly ([`hue_mix`]). + HueClockwise, + /// Mixed around the hue wheel the other way: the hue angle rises from each stop to the next + /// (red, yellow, green, cyan, blue, magenta, red). + HueCounterclockwise, } impl GradientMethod { - /// Parse a method name (`classic`, `perceptual`; any case). + /// Every method, in the order the Gradient panel lists them. + pub const ALL: [GradientMethod; 4] = [Self::Classic, Self::Perceptual, Self::HueClockwise, Self::HueCounterclockwise]; + /// Parse a method name (`classic`, `perceptual`, `hue-clockwise`, `hue-counterclockwise`; + /// any case, and the hyphen may be a space or an underscore, or left out). Any other text, + /// one with a separator elsewhere included, is `None`. pub fn parse(s: &str) -> Option { - [Self::Classic, Self::Perceptual].into_iter().find(|m| m.label().eq_ignore_ascii_case(s)) + let name = s.to_ascii_lowercase(); + Self::ALL.into_iter().find(|m| ["-", " ", "_", ""].iter().any(|sep| m.id().replace('-', sep) == name)) } pub fn label(self) -> &'static str { match self { Self::Classic => "Classic", Self::Perceptual => "Perceptual", + Self::HueClockwise => "Hue Clockwise", + Self::HueCounterclockwise => "Hue Counterclockwise", + } + } + /// The method's name in command params (`classic`, `perceptual`, `hue-clockwise`, + /// `hue-counterclockwise`). + pub fn id(self) -> &'static str { + match self { + Self::Classic => "classic", + Self::Perceptual => "perceptual", + Self::HueClockwise => "hue-clockwise", + Self::HueCounterclockwise => "hue-counterclockwise", } } pub fn is_classic(&self) -> bool { *self == Self::Classic } - /// `a` and `b` mixed at `t` (0..1): in display RGB (Classic), or in OKLab (Perceptual: an - /// RGB colour between the two). + /// Does it mix around the hue wheel (Hue Clockwise or Hue Counterclockwise)? The colors + /// between two stops then are not mixes of the stops' inks. + pub fn is_hue(&self) -> bool { + matches!(self, Self::HueClockwise | Self::HueCounterclockwise) + } + /// The method that mixes `b` to `a` through the colors this one mixes `a` to `b` through: a + /// hue method turned the other way, Classic and Perceptual as they are. + pub fn mirrored(self) -> Self { + match self { + Self::HueClockwise => Self::HueCounterclockwise, + Self::HueCounterclockwise => Self::HueClockwise, + m => m, + } + } + /// `a` and `b` mixed at `t` (0..1): in display RGB (Classic), in OKLab (Perceptual: an + /// RGB colour between the two), or around the hue wheel ([`hue_mix`]: an RGB colour). pub fn mix(self, a: &Color, b: &Color, t: f32) -> Color { match self { Self::Classic => Color::lerp(a, b, t), @@ -84,10 +131,144 @@ impl GradientMethod { let c = |v: f64| if v.is_finite() { v.clamp(0.0, 1.0) as f32 } else { 0.0 }; Color::rgb(c(r), c(g), c(bl)) } + Self::HueClockwise => hue_mix(a, b, t, false), + Self::HueCounterclockwise => hue_mix(a, b, t, true), } } } +/// The brightness (0..1) at or below which a color is black for [`hue_mix`], and the spread +/// between its largest and smallest RGB numbers (saturation × brightness) at or below which it +/// has no hue of its own: under half a color level. +const NO_HUE: f32 = 0.4 / 255.0; + +/// The hue difference (degrees) that moves an RGB number by half a color level in a color whose +/// largest and smallest RGB numbers are 1 apart; a color with a smaller spread takes +/// proportionally more degrees. [`hue_mix`] counts two hues closer than this as one hue. +const SAME_HUE: f32 = 60.0 * 0.5 / 255.0; + +/// `a` and `b` mixed at `t` (0..1) around the hue wheel, as display RGB: hue (degrees), +/// saturation and brightness each change evenly from `a`'s to `b`'s. The hue angle only rises +/// (`rising`) or only falls, by the fixed-direction rules of +/// , and two equal hues stay where they are. +/// Two hues that differ by less than half a color level ([`SAME_HUE`]) count as equal and take the +/// short way, so a color and a tint or shade of it, whose computed hues differ by rounding, do +/// not turn the whole wheel. A color whose RGB numbers are less than half a color level apart +/// ([`NO_HUE`]) has no hue and takes the other color's; black has no saturation either and takes +/// the other color's too. Two colors without a hue mix as grays. A `t` that is not a number +/// gives `a`. +pub fn hue_mix(a: &Color, b: &Color, t: f32, rising: bool) -> Color { + let t = if t.is_nan() { 0.0 } else { t.clamp(0.0, 1.0) }; + let ([mut h0, mut s0, v0], [mut h1, mut s1, v1]) = (a.to_hsb(), b.to_hsb()); + let (black0, black1) = (v0 <= NO_HUE, v1 <= NO_HUE); + // The spread between each color's own largest and smallest RGB numbers. + let (spread0, spread1) = (s0 * v0, s1 * v1); + // Black takes the other color's saturation, so it darkens that color rather than graying it. + if black0 && !black1 { + s0 = s1; + } else if black1 && !black0 { + s1 = s0; + } + let (gray0, gray1) = (black0 || spread0 <= NO_HUE, black1 || spread1 <= NO_HUE); + match (gray0, gray1) { + (true, _) => h0 = h1, + (false, true) => h1 = h0, + (false, false) => { + // The short way from the first hue to the second, -180..180. + let short = (h1 - h0 + 180.0).rem_euclid(360.0) - 180.0; + h1 = if short.abs() * spread0.min(spread1) <= SAME_HUE { + h0 + short + } else if rising { + h0 + short.rem_euclid(360.0) + } else { + h0 + short.rem_euclid(360.0) - 360.0 + }; + } + } + let at = |p: f32, q: f32| p + (q - p) * t; + let (h, s, v) = (at(h0, h1), at(s0, s1), at(v0, v1)); + if !(h.is_finite() && s.is_finite() && v.is_finite()) { + return Color::rgb(0.0, 0.0, 0.0); + } + Color::from_hsb(h.rem_euclid(360.0), s.clamp(0.0, 1.0), v.clamp(0.0, 1.0)) +} + +/// What a linear, radial, conic or diamond gradient paints past the ends of its stops (the +/// Gradient panel's Spread). With Repeat and Reflect, the stops run [`Gradient::repeats`] times +/// along the vector (around the circle, for a conic), and keep going past both of its ends. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize)] +pub enum GradientSpread { + /// The first and last stops' colors carry on past the ends, as gradients always did. + #[default] + Pad, + /// The stops start again at each end. + Repeat, + /// The stops run back the other way at each end, so every other run is mirrored. + Reflect, +} + +impl GradientSpread { + /// Every spread, in the order the Gradient panel lists them. + pub const ALL: [GradientSpread; 3] = [GradientSpread::Pad, GradientSpread::Repeat, GradientSpread::Reflect]; + /// Parse a spread name (`pad`, `repeat`, `reflect`; any case). + pub fn parse(s: &str) -> Option { + Self::ALL.into_iter().find(|m| m.label().eq_ignore_ascii_case(s)) + } + pub fn label(self) -> &'static str { + match self { + Self::Pad => "Pad", + Self::Repeat => "Repeat", + Self::Reflect => "Reflect", + } + } + pub fn is_pad(&self) -> bool { + *self == Self::Pad + } +} + +impl<'de> Deserialize<'de> for GradientSpread { + /// A spread name; a file's unknown name or other value reads as Pad. + fn deserialize>(d: D) -> Result { + #[derive(Deserialize)] + #[serde(untagged)] + enum Raw { + Name(String), + Other(serde::de::IgnoredAny), + } + Ok(match Raw::deserialize(d)? { + Raw::Name(s) => Self::parse(&s).unwrap_or_default(), + Raw::Other(_) => Self::Pad, + }) + } +} + +/// Most times a gradient's stops run along its vector ([`Gradient::repeats`]): VectorCraft's own +/// limit. +pub const MAX_REPEATS: u32 = 100; + +fn one_repeat() -> u32 { + 1 +} + +fn is_one_repeat(n: &u32) -> bool { + *n == 1 +} + +/// A file's repeat count: a number, rounded and kept within 1 to [`MAX_REPEATS`]; anything else +/// reads as 1. +fn lenient_repeats<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + #[derive(Deserialize)] + #[serde(untagged)] + enum Raw { + Number(f64), + Other(serde::de::IgnoredAny), + } + Ok(match Raw::deserialize(d)? { + Raw::Number(n) if n.is_finite() => n.round().clamp(1.0, f64::from(MAX_REPEATS)) as u32, + _ => 1, + }) +} + /// How far (display RGB, 0..1) the straight line between a Perceptual gradient's neighbouring /// expanded stops may stray from the perceptual mix: under half a colour level. const PERCEPTUAL_TOLERANCE: f32 = 0.4 / 255.0; @@ -107,10 +288,11 @@ const MAX_INK_TINTS: usize = 4096; const INK_MIX_STEPS: u32 = 64; /// The mix positions (0..1, after `v0`, before `v1`) between which display RGB mixed linearly -/// stays within [`PERCEPTUAL_TOLERANCE`] of the perceptual mix of `a` and `b`: the span halved -/// where a straight line strays, at most [`PERCEPTUAL_DEPTH`] times, in order. -fn perceptual_steps(a: &Color, b: &Color, (v0, v1): (f32, f32), depth: u32, out: &mut Vec) { - let at = |v: f32| GradientMethod::Perceptual.mix(a, b, v).to_rgb(); +/// stays within [`PERCEPTUAL_TOLERANCE`] of `method`'s mix of `a` and `b` (Perceptual, or around +/// the hue wheel): the span halved where a straight line strays, at most [`PERCEPTUAL_DEPTH`] +/// times, in order. +fn perceptual_steps(method: GradientMethod, a: &Color, b: &Color, (v0, v1): (f32, f32), depth: u32, out: &mut Vec) { + let at = |v: f32| method.mix(a, b, v).to_rgb(); let (c0, c1) = (at(v0), at(v1)); let stray = [0.25, 0.5, 0.75] .into_iter() @@ -121,19 +303,20 @@ fn perceptual_steps(a: &Color, b: &Color, (v0, v1): (f32, f32), depth: u32, out: .fold(0.0, f32::max); if depth < PERCEPTUAL_DEPTH && stray > PERCEPTUAL_TOLERANCE { let m = (v0 + v1) / 2.0; - perceptual_steps(a, b, (v0, m), depth + 1, out); + perceptual_steps(method, a, b, (v0, m), depth + 1, out); out.push(m); - perceptual_steps(a, b, (m, v1), depth + 1, out); + perceptual_steps(method, a, b, (m, v1), depth + 1, out); } } -/// The mix positions (`v`, 0..1) of the stops a Perceptual gradient's curve has between stops `a` -/// and `b`, in order: [`perceptual_steps`] on either side of the midpoint, and the midpoint (½). -fn perceptual_mixes(a: &GradientStop, b: &GradientStop) -> Vec { +/// The mix positions (`v`, 0..1) of the stops the curve of a gradient mixed by `method` +/// (Perceptual, or around the hue wheel) has between stops `a` and `b`, in order: +/// [`perceptual_steps`] on either side of the midpoint, and the midpoint (½). +fn perceptual_mixes(method: GradientMethod, a: &GradientStop, b: &GradientStop) -> Vec { let mut vs = Vec::new(); - perceptual_steps(&a.color, &b.color, (0.0, 0.5), 1, &mut vs); + perceptual_steps(method, &a.color, &b.color, (0.0, 0.5), 1, &mut vs); vs.push(0.5); - perceptual_steps(&a.color, &b.color, (0.5, 1.0), 1, &mut vs); + perceptual_steps(method, &a.color, &b.color, (0.5, 1.0), 1, &mut vs); vs } @@ -253,6 +436,15 @@ pub struct Gradient { /// How the colours between the stops are mixed (Classic unless set; written only when not). #[serde(default, skip_serializing_if = "GradientMethod::is_classic")] pub method: GradientMethod, + /// What it paints past the ends of its stops (Pad unless set; written only when not). A + /// freeform gradient has no ends and ignores it. + #[serde(default, skip_serializing_if = "GradientSpread::is_pad")] + pub spread: GradientSpread, + /// How many times the stops run along the vector with Repeat and Reflect, 1 to + /// [`MAX_REPEATS`] (use [`Self::repeat_count`]: a value set in code may be out of range); Pad + /// ignores it. Written only when it is not 1. + #[serde(default = "one_repeat", skip_serializing_if = "is_one_repeat", deserialize_with = "lenient_repeats")] + pub repeats: u32, } impl Default for Gradient { @@ -265,7 +457,55 @@ impl Default for Gradient { impl Gradient { /// A gradient of `kind` through `stops`, with the default options. pub fn new(kind: GradientKind, stops: Vec) -> Self { - Self { kind, stops, dither: false, method: GradientMethod::Classic } + Self { kind, stops, dither: false, method: GradientMethod::Classic, spread: GradientSpread::Pad, repeats: 1 } + } + /// [`Self::repeats`] kept within 1 to [`MAX_REPEATS`]. + pub fn repeat_count(&self) -> u32 { + self.repeats.clamp(1, MAX_REPEATS) + } + /// Does it paint something other than its end colors past the ends of its stops, or run its + /// stops more than once: a linear, radial, conic or diamond gradient that repeats or reflects? + pub fn is_spread(&self) -> bool { + !self.spread.is_pad() && self.kind != GradientKind::Freeform + } + /// The spread and count as the gradient paints them: Pad and 1 for one that pads (whatever + /// count it keeps) and for a freeform one, else its spread and [`Self::repeat_count`]. Equal + /// for two gradients whose spreads paint alike. + pub fn painted_spread(&self) -> (GradientSpread, u32) { + if self.is_spread() { (self.spread, self.repeat_count()) } else { (GradientSpread::Pad, 1) } + } + /// The position (0..1) along the stops that gradient parameter `t` (0 at the start of the + /// vector, 1 at its end; [`GradientGeom::param_at`]) samples: `t` itself with Pad (the stops + /// clamp it), else `t` × [`Self::repeat_count`] wrapped back into 0..1, every other run + /// mirrored with Reflect. A `t` that is not finite is returned as it is. + pub fn spread_param(&self, t: f64) -> f64 { + self.spreader()(t) + } + /// How many wedges a conic gradient is written as ([`GradientGeom::conic_wedges`]) where + /// `per_turn` would do for stops that run once around: that many for each time the stops run + /// around, at most [`MAX_CONIC_WEDGES`]. Sample each wedge at [`Self::spread_param`] of its + /// turn. + pub fn conic_wedge_count(&self, per_turn: usize) -> usize { + let runs = if self.is_spread() { self.repeat_count() as usize } else { 1 }; + per_turn.saturating_mul(runs).clamp(1, MAX_CONIC_WEDGES) + } + /// [`Self::spread_param`] as a function that holds no borrow of the gradient. + pub fn spreader(&self) -> impl Fn(f64) -> f64 + Copy + use<> { + let spread = if self.is_spread() { self.spread } else { GradientSpread::Pad }; + let n = f64::from(self.repeat_count()); + move |t: f64| { + if !t.is_finite() { + return t; + } + match spread { + GradientSpread::Pad => t, + GradientSpread::Repeat => (t * n).rem_euclid(1.0), + GradientSpread::Reflect => { + let w = (t * n).rem_euclid(2.0); + if w > 1.0 { 2.0 - w } else { w } + } + } + } } /// Colour and opacity at `t` (honours midpoints and the method). pub fn sample(&self, t: f32) -> (Color, f32) { @@ -370,10 +610,11 @@ impl Gradient { }; (t, c, o, Some(s.midpoint), None) }); - // Perceptual: stops along the mix (`v`) where a straight line would stray from it, the - // midpoint (v = ½) among them, placed through the midpoint as [`Self::sample`] maps them. + // Perceptual and the hue methods: stops along the mix (`v`) where a straight line would + // stray from it, the midpoint (v = ½) among them, placed through the midpoint as + // [`Self::sample`] maps them. let perceptual = next.filter(|_| !self.method.is_classic()).map(|n| { - perceptual_mixes(s, n).into_iter().map(move |v| { + perceptual_mixes(self.method, s, n).into_iter().map(move |v| { let mid = v == 0.5; let t = curve_offset(s, n, v); let o = s.opacity + (n.opacity - s.opacity) * v; @@ -429,11 +670,12 @@ impl Gradient { /// position itself when the two colors' lightness differs by less than /// [`MIN_INK_LIGHTNESS_SPAN`], or when the display RGB mix's lightness turns back somewhere /// on the way from one color's lightness to the other's (checked at [`INK_MIX_STEPS`] even - /// steps), as from red to blue. `None` for a Classic gradient, and when the curve has more - /// than [`MAX_INK_TINTS`] stops ([`Self::fits_ink_tints`]). + /// steps), as from red to blue. `None` for a Classic gradient, for one mixed around the hue + /// wheel (its colors between two stops are not mixes of the stops' inks), and when the curve + /// has more than [`MAX_INK_TINTS`] stops ([`Self::fits_ink_tints`]). pub fn ink_mixes(&self) -> Option> { use crate::libraries::srgb_to_oklab; - if self.method.is_classic() || !self.fits_ink_tints() { + if self.method != GradientMethod::Perceptual || !self.fits_ink_tints() { return None; } let lightness = |c: &Color| srgb_to_oklab(c.to_rgb())[0]; @@ -450,7 +692,7 @@ impl Gradient { .collect::>() .windows(2) .all(|w| (w[1] - w[0]) * (l1 - l0) >= 0.0); - for v in perceptual_mixes(s, n) { + for v in perceptual_mixes(self.method, s, n) { let weight = if by_position { v } else { @@ -508,8 +750,10 @@ impl Gradient { Some(Ramp { stops }) } /// The same ramp the other way round: the stops in reverse order at mirrored offsets, each - /// segment's midpoint mirrored with it. + /// segment's midpoint mirrored with it, and a hue method turned the other way (red to blue + /// through magenta, reversed, is blue to red through magenta). pub fn reverse(&mut self) { + self.method = self.method.mirrored(); self.stops.reverse(); for i in 0..self.stops.len() { // A midpoint belongs to the segment after its stop: reversed, stop i's segment is the @@ -524,6 +768,13 @@ impl Gradient { pub fn sort(&mut self) { self.stops.sort_by(|a, b| a.offset.total_cmp(&b.offset)); } + /// The gradient's colors as a Classic gradient: its curve's stops ([`Self::expanded_stops`]) as + /// stops of their own, mixed in display RGB, within [`PERCEPTUAL_TOLERANCE`] of it. The stops + /// keep no swatch links, tints or process plates. + pub fn as_classic_curve(&self) -> Gradient { + let stops = self.expanded().map(|(t, color, opacity, _)| GradientStop { opacity, ..GradientStop::new(t, color) }).collect(); + Gradient { kind: self.kind, stops, dither: self.dither, method: GradientMethod::Classic, spread: self.spread, repeats: self.repeats } + } /// The part of the gradient from `from` to `to` (0..1, either way round) as a linear gradient /// of its own running 0 → 1: the same colours (midpoints become stops, as in /// [`Self::expanded_stops`]). One colour throughout when `from == to`. @@ -538,10 +789,18 @@ impl Gradient { GradientStop { opacity, ..GradientStop::new(offset, color) } }; let d = to - from; - let mut stops = vec![stop(0.0, from)]; + let expanded = self.expanded_stops(); + // Where stops share the offset `from` (a sharp step, as where the runs of a repeating + // gradient meet), the piece starts with the color after the step; sampling gives the one + // before it. + let first = match expanded.iter().rev().find(|(t, ..)| *t == from) { + Some(&(_, color, opacity)) if d > 1e-6 => GradientStop { opacity, ..GradientStop::new(0.0, color) }, + _ => stop(0.0, from), + }; + let mut stops = vec![first]; if d > 1e-6 { stops.extend( - self.expanded_stops() + expanded .into_iter() .filter(|(t, ..)| *t > from && *t < to) .map(|(t, color, opacity)| GradientStop { opacity, ..GradientStop::new((t - from) / d, color) }), @@ -668,13 +927,22 @@ fn one64() -> f64 { impl GradientGeom { /// Default placement for a bounding box: linear spans the box through the centre at `angle_deg`, /// radial and conic are centered with radius = half the larger dimension and their vector at - /// `angle_deg`. + /// `angle_deg`, and diamond is centered with its vector at `angle_deg`, its square's edge + /// running through the box's farthest corner (at 0 or 90 degrees, through all four). pub fn fit(kind: GradientKind, b: Rect, angle_deg: f64) -> Self { let c = b.center(); let a = angle_deg.to_radians(); let d = Vec2::new(a.cos(), -a.sin()); match kind { GradientKind::Radial | GradientKind::Conic => Self { start: c, end: c + d * (b.width().max(b.height()) / 2.0), aspect: 1.0, focal: None }, + GradientKind::Diamond => { + // The square through the box's farthest corner: the largest reach along the vector + // plus across it, at one corner. + let (w, h) = (b.width() / 2.0, b.height() / 2.0); + let level = |x: f64, y: f64| (x * d.x + y * d.y).abs() + (y * d.x - x * d.y).abs(); + let half = level(w, h).max(level(w, -h)); + Self { start: c, end: c + d * half, aspect: 1.0, focal: None } + } _ => { // Project the box corners onto the direction to cover the whole box. let half = (b.width() * d.x.abs() + b.height() * d.y.abs()) / 2.0; @@ -694,6 +962,10 @@ impl GradientGeom { /// other way: exact for moves, rotations, uniform scales and mirrors, and the nearest frame /// that keeps the seam under a shear or a non-uniform scale. A conic whose vector has no /// length, or whose aspect is 0, still has the sign of its aspect flipped by a mirror. + /// Diamond gradients keep their vector (a corner of the square) the same way, with the size + /// of the mapped extent across it as their aspect: exact for moves, rotations, scales along or + /// across the vector and mirrors, and the nearest square stretched across its vector under a + /// shear or another scale. pub fn transform(&mut self, a: Affine, kind: GradientKind) { // The focal point is a point like any other. self.focal = self.focal.map(|f| a * f); @@ -724,6 +996,14 @@ impl GradientGeom { }; return; } + if kind == GradientKind::Diamond { + let (lu, lw) = (lin(u), lin(perp(u) * self.aspect)); + self.start = start; + self.end = start + lu; + let aspect = (lw.dot(perp(lu)) / lu.hypot2()).abs(); + self.aspect = if lu.hypot2() > 1e-18 && aspect.is_finite() { aspect } else { 1.0 }; + return; + } if kind != GradientKind::Radial { let far = a * self.end; let nrm = perp(lin(perp(u))); @@ -768,6 +1048,8 @@ impl GradientGeom { /// measured from the focal point (each level is the ellipse scaled about the line from the /// focal point to the centre). For conic gradients it is the turn from the vector in /// [`Self::conic_frame`], clockwise on the page (counterclockwise when mirrored), in 0..=1. + /// For diamond gradients it is the size of the square through `p`, as a fraction of the one + /// [`Self::diamond_frame`] gives (1 everywhere for a diamond without a frame). pub fn param_at(&self, kind: GradientKind, p: Point) -> f64 { if kind == GradientKind::Conic { let q = (self.conic_frame().inverse() * p).to_vec2(); @@ -775,6 +1057,13 @@ impl GradientGeom { let t = if t < 0.0 { t + 1.0 } else { t }; return if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 }; } + if kind == GradientKind::Diamond { + // Without a frame the square has no inside: every point is past its edge. + let Some(m) = self.diamond_frame() else { return 1.0 }; + let q = (m.inverse() * p).to_vec2(); + let t = q.x.abs() + q.y.abs(); + return if t.is_nan() { 1.0 } else { t }; + } let u = self.end - self.start; if u.hypot2() < 1e-18 { return 0.0; @@ -835,32 +1124,52 @@ impl GradientGeom { pub fn conic_wedges(&self, b: Rect, n: usize, overlap: bool) -> Vec<(Vec, f64)> { let n = n.clamp(1, MAX_CONIC_WEDGES); let frame = self.conic_frame(); - let to_unit = frame.inverse(); - let corners = [b.origin(), Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1)]; - let reach = corners.iter().map(|&c| (to_unit * c).to_vec2().hypot()).fold(0.0f64, f64::max).max(1e-6); - let reach = if reach.is_finite() { reach * 1.01 } else { 1.0 }; - // Arc points at most ARC of a turn apart, at a radius where their chords stay outside - // `reach`. - const ARC: f64 = 1.0 / 32.0; - let r = reach / (std::f64::consts::PI * ARC).cos(); - let at = |turn: f64| { - let a = turn * std::f64::consts::TAU; - frame * Point::new(r * a.cos(), r * a.sin()) - }; - let center = frame * Point::ORIGIN; + let r = fan_radius(frame, b); (0..n) .map(|k| { let from = k as f64 / n as f64; let to = if overlap { 1.0 } else { (k + 1) as f64 / n as f64 }; - let steps = ((to - from) / ARC).ceil().max(1.0) as usize; - let mut pts = Vec::with_capacity(steps + 2); - pts.push(center); - pts.extend((0..=steps).map(|i| at(from + (to - from) * i as f64 / steps as f64))); - (pts, (k as f64 + 0.5) / n as f64) + (fan(frame, r, from, to), (k as f64 + 0.5) / n as f64) }) .collect() } + /// The frame a diamond gradient is drawn in: its [`Self::unit_frame`], which maps the square + /// with corners (±1, 0) and (0, ±1) onto the diamond (its first corner at the end of the + /// vector). `None` when the square is flat or not finite (a vector without length, an aspect + /// of 0, or a file's out-of-range numbers): such a diamond has no inside, and every point + /// takes its last stop. + pub fn diamond_frame(&self) -> Option { + self.unit_frame().filter(|m| m.is_finite() && m.determinant().abs() > 1e-18) + } + + /// A diamond gradient as four linear gradients, one for each quadrant of its + /// [`Self::diamond_frame`], for formats without diamond gradients: each quadrant's outline (the + /// center, then an arc that reaches past every corner of `b`) and the linear gradient that + /// equals the diamond there (its stops run across the square's edge in that quadrant), in the + /// order they are drawn. Each of the first three runs on past its last edge under the next, + /// and the first also back past its first edge under the last, so every edge drawn lies on + /// the quadrant before it and no hairline of what lies below shows between them; where they + /// overlap, translucent stops would add up, so the stops must be opaque. `None` for a diamond + /// without a frame. + pub fn diamond_quadrants(&self, b: Rect) -> Option<[(Vec, GradientGeom); 4]> { + let frame = self.diamond_frame()?; + let r = fan_radius(frame, b); + Some(std::array::from_fn(|k| { + let first = k as f64 / 4.0; + let (from, to) = match k { + 0 => (-0.125, 0.375), + 3 => (0.75, 1.0), + _ => (first, first + 0.375), + }; + // The quadrant's corner of the square, halfway along whose edge t is 1/2. + let (sx, sy) = [(1.0, 1.0), (-1.0, 1.0), (-1.0, -1.0), (1.0, -1.0)][k]; + let mut geom = GradientGeom { start: Point::ORIGIN, end: Point::new(sx / 2.0, sy / 2.0), aspect: 1.0, focal: None }; + geom.transform(frame, GradientKind::Linear); + (fan(frame, r, from, to), geom) + })) + } + /// The map that squashes a radial gradient's circle (centre `start`, radius the vector's /// length) into its extent ellipse: by `aspect` across the vector, about the centre. pub fn radial_squash(&self) -> Affine { @@ -898,6 +1207,35 @@ impl GradientGeom { self.set_focal(Some(m * q)); } } + /// The placement whose level `t` is this one's level `k`·`t` (`k` > 0), for a linear, radial or + /// diamond gradient: the vector `k` times as long from the same start, and for an off-center + /// radial the extent ellipse scaled `k` times about the focal point, which stays. A conic keeps + /// its placement (its level is a turn). + pub fn levels_scaled(&self, kind: GradientKind, k: f64) -> GradientGeom { + if kind == GradientKind::Conic || !(k.is_finite() && k > 0.0) { + return *self; + } + let u = self.end - self.start; + let mut out = *self; + if kind == GradientKind::Radial + && let (Some(f), Some(frame)) = (self.focal, self.unit_frame()) + { + // Level t of an off-center radial is the extent ellipse scaled by t about the line + // from the focal point to the center: the new center sits on that line, `k` times as + // far from the focal point. + let f = (frame.inverse() * f).to_vec2(); + out.start = frame * (f * (1.0 - k)).to_point(); + } + out.end = out.start + u * k; + out + } + + /// The placement over which one run of the stops of a gradient that repeats `n` times along + /// its vector lies ([`Self::levels_scaled`] by 1/`n`). + pub fn period(&self, kind: GradientKind, n: u32) -> GradientGeom { + self.levels_scaled(kind, 1.0 / f64::from(n.max(1))) + } + pub fn angle_deg(&self) -> f64 { let v = self.end - self.start; (-v.y).atan2(v.x).to_degrees() @@ -907,6 +1245,34 @@ impl GradientGeom { } } +/// Arc points of [`fan`] are at most this much of a turn apart. +const FAN_ARC: f64 = 1.0 / 32.0; + +/// The radius of the unit circle of `frame` at which the chords of [`fan`]'s arcs stay outside +/// every corner of `b`. +fn fan_radius(frame: Affine, b: Rect) -> f64 { + let to_unit = frame.inverse(); + let corners = [b.origin(), Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1)]; + let reach = corners.iter().map(|&c| (to_unit * c).to_vec2().hypot()).fold(0.0f64, f64::max).max(1e-6); + let reach = if reach.is_finite() { reach * 1.01 } else { 1.0 }; + reach / (std::f64::consts::PI * FAN_ARC).cos() +} + +/// The sector of `frame`'s unit circle, scaled to radius `r`, from turn `from` to turn `to` +/// (counted from the frame's x axis toward its y axis) as an outline: the center, then points on +/// the arc at most [`FAN_ARC`] of a turn apart. +fn fan(frame: Affine, r: f64, from: f64, to: f64) -> Vec { + let at = |turn: f64| { + let a = turn * std::f64::consts::TAU; + frame * Point::new(r * a.cos(), r * a.sin()) + }; + let steps = ((to - from) / FAN_ARC).ceil().max(1.0) as usize; + let mut pts = Vec::with_capacity(steps + 2); + pts.push(frame * Point::ORIGIN); + pts.extend((0..=steps).map(|i| at(from + (to - from) * i as f64 / steps as f64))); + pts +} + /// `p` moved from box `from` to box `to`, keeping its position relative to the box (along a side /// `from` has no extent on, its offset from the centre). fn rebase_point(p: Point, from: Rect, to: Rect) -> Point { @@ -1004,12 +1370,13 @@ impl GradientPaint { } /// Is this gradient drawn as pixels rather than as a vector gradient when it paints a fill /// (`fill`) or a stroke (SVG and PDF draw such gradients as images): a freeform gradient, a - /// dithered fill (dither applies to fills only), or a Perceptual one (its colours don't mix - /// linearly between the stops, as SVG's and PDF's gradients do)? + /// dithered fill (dither applies to fills only), or a Perceptual one or one mixed around the + /// hue wheel (its colours don't mix linearly between the stops, as SVG's and PDF's gradients + /// do)? pub fn draws_as_pixels(&self, fill: bool) -> bool { self.gradient.kind == GradientKind::Freeform || (fill && self.gradient.dither) || !self.gradient.method.is_classic() } - /// A linear, radial or conic gradient placed on box `bounds` as a `cols` × `rows` grid of + /// A linear, radial, conic or diamond gradient placed on box `bounds` as a `cols` × `rows` grid of /// unpremultiplied RGBA8 pixels over `area`, row by row, each sampled at its centre (colours /// as `rgb` gives them, mixed as the renderer mixes them: [`Ramp`]). Dithered and painting a /// fill (`fill`; dither applies to fills only), each colour channel of pixel (column, row) gets @@ -1040,7 +1407,7 @@ impl GradientPaint { ) -> impl Iterator + use<> { self.grid(Ramp::new(&self.gradient, rgb), bounds, area, cols, rows, cells, fill, false) } - /// [`Self::pixels`] of a linear, radial or conic gradient whose stops are all CMYK, as C, M, Y, K + /// [`Self::pixels`] of a linear, radial, conic or diamond gradient whose stops are all CMYK, as C, M, Y, K /// and opacity levels mixed from the stops' inks; `None` when a stop is in another model, /// there are no stops, or a Perceptual curve has too many stops for [`Gradient::ink_mixes`]. /// Dither's noise adds no ink where the ramp has none. @@ -1064,12 +1431,13 @@ impl GradientPaint { inks: bool, ) -> impl Iterator + use { let (kind, geom, dither) = (self.gradient.kind, self.resolve(bounds), fill && self.gradient.dither); + let spread = self.gradient.spreader(); let (cw, ch) = (area.width() / f64::from(cols.max(1)), area.height() / f64::from(rows.max(1))); let (x0, y0) = (area.x0, area.y0); let [across, down] = cells.map(|r| u32::from(r.start)..u32::from(r.end)); down.flat_map(move |j| across.clone().map(move |i| (i, j))).map(move |(i, j)| { let p = Point::new(x0 + (f64::from(i) + 0.5) * cw, y0 + (f64::from(j) + 0.5) * ch); - let c = ramp.at(geom.param_at(kind, p) as f32); + let c = ramp.at(spread(geom.param_at(kind, p)) as f32); std::array::from_fn(|k| { if k + 1 == N { return (c[k].clamp(0.0, 1.0) * 255.0).round() as u8; diff --git a/crates/color/src/gradient/spread.rs b/crates/color/src/gradient/spread.rs new file mode 100644 index 0000000000..fa111586ba --- /dev/null +++ b/crates/color/src/gradient/spread.rs @@ -0,0 +1,390 @@ +//! A repeating or reflecting gradient as one that pads, for formats whose gradients only pad +//! past their ends: the stops repeated (every other run mirrored, for Reflect) as many times as +//! the painted area needs, and the vector stretched over those runs. + +use kurbo::{Point, Rect, Vec2}; + +use super::{Gradient, GradientGeom, GradientKind, GradientMethod, GradientSpread, GradientStop}; +use crate::Color; + +/// Most runs of the stops [`Gradient::padded_over`] writes. +pub const MAX_SPREAD_RUNS: usize = 256; + +/// Most stops [`Gradient::padded_over`] writes, all runs together. +pub const MAX_SPREAD_STOPS: usize = 16384; + +/// The farthest level from its center a radial or diamond gradient's runs are written out to by +/// [`Gradient::padded_over`] (its stops' offsets, single-precision fractions of it, stay apart), +/// nearer for stops closer together than a run ([`MIN_OFFSET_GAP`]). +pub const MAX_SPREAD_LEVEL: f64 = 65536.0; + +/// The least difference between two stops' offsets [`Gradient::padded_over`] writes as +/// different: sixteen times single precision's step just below 1. +const MIN_OFFSET_GAP: f64 = 1e-6; + +/// A repeating or reflecting gradient written as one that pads ([`Gradient::padded_over`]). +#[derive(Clone, Debug, PartialEq)] +pub struct Padded { + /// The gradient with its stops repeated, padding past its ends. + pub gradient: Gradient, + /// Where those runs lie. + pub geom: GradientGeom, + /// Where along `geom` (0 to 1) the first run written starts: 0 for a linear gradient, the + /// first run's level over the last one's outer level for a radial or diamond one. + pub first: f64, + /// How many runs are written, evenly spaced from [`Self::first`] to 1. + pub runs: usize, + /// The area needed more runs than [`MAX_SPREAD_RUNS`] (or more than half the stops allowed, + /// two to a run), or runs past [`MAX_SPREAD_LEVEL`]: the gradient pads past the runs written. + pub capped: bool, +} + +impl Gradient { + /// A linear, radial or diamond gradient that repeats or reflects, placed at `geom`, as a + /// gradient that pads and paints `area` the same way: its stops repeated, each run's + /// placement [`GradientGeom::period`] of `geom`, as many runs as the area reaches (a radial or + /// diamond from its first level, 0, the first stop's color inside the area's innermost run). + /// `None` for a gradient that pads, a conic or + /// freeform one, one without stops, and a placement whose levels at the corners are not + /// finite. + pub fn padded_over(&self, geom: &GradientGeom, area: Rect) -> Option { + self.padded_within(geom, area, MAX_SPREAD_STOPS) + } + + /// [`Self::padded_over`] with at most `max_stops` stops (and at least one run). When the runs + /// written need more stops than that, each run leaves out the stops that change its colors + /// least ([`fit_run`]), so every run is still written. + pub fn padded_within(&self, geom: &GradientGeom, area: Rect, max_stops: usize) -> Option { + let kind = self.kind; + if !self.is_spread() || matches!(kind, GradientKind::Conic | GradientKind::Freeform) || self.stops.is_empty() { + return None; + } + if self.mirrors_a_hue_turn() { + return self.as_classic_curve().padded_within(geom, area, max_stops); + } + let period = geom.period(kind, self.repeat_count()); + let corners = [Point::new(area.x0, area.y0), Point::new(area.x1, area.y0), Point::new(area.x1, area.y1), Point::new(area.x0, area.y1)]; + let ts = corners.map(|p| period.param_at(kind, p)); + if ts.iter().any(|t| !t.is_finite()) { + return None; + } + let centered = kind.is_centered(); + // The level's range over the area. A linear gradient's extremes lie at corners. Radial and + // diamond levels are nested convex rings from level 0: the largest at a corner, the + // smallest 0 when the area holds the rings' center, else on its edge. + let lo = if centered { inner_level(&period, kind, area).floor() } else { ts.iter().copied().fold(f64::INFINITY, f64::min).floor() }; + let hi = ts.iter().copied().fold(f64::NEG_INFINITY, f64::max).ceil().max(lo + 1.0); + let budget = max_stops.min(MAX_SPREAD_STOPS); + let most = MAX_SPREAD_RUNS.min(budget / 2).max(1); + let capped = hi - lo > most as f64; + // Capped, the runs kept are the area's innermost ones (radial and diamond), or (linear) + // those around the vector's start where the area reaches it, else the area's runs nearest + // to it. + let lo = match capped { + true if !centered => (-((most / 2) as f64)).clamp(lo, hi - most as f64), + _ => lo, + }; + let n = (hi - lo).min(most as f64).max(1.0); + let one = fit_run(whole_run(&self.stops), budget / n as usize, self.method); + // A radial or diamond writes its runs among the levels from 0, which its stops' offsets + // (single-precision fractions of the outermost level) tell apart only so far out, the + // nearer the closer its stops lie: past that, the runs end there and the gradient pads. + let gap = one.windows(2).map(|w| f64::from(w[1].offset - w[0].offset)).filter(|d| *d > 0.0).fold(1.0, f64::min); + // A whole level, so the runs keep their places (and Reflect its mirrored ones). + let farthest = MAX_SPREAD_LEVEL.min(gap / MIN_OFFSET_GAP).floor().max(n); + let far = centered && lo + n > farthest; + let (lo, capped) = if far { ((farthest - n).max(0.0), true) } else { (lo, capped) }; + // `lo` is a whole number, possibly past what an integer holds: its parity in floating point. + let first_odd = lo.rem_euclid(2.0) >= 1.0; + let (stops, geom) = if centered { + // The levels from 0, the runs from level `lo` (the first stop's color inside it). + (self.runs(&one, first_odd, lo, n as usize, lo + n), period.levels_scaled(kind, lo + n)) + } else { + let u = period.end - period.start; + ( + self.runs(&one, first_odd, 0.0, n as usize, n), + GradientGeom { start: period.start + u * lo, end: period.start + u * (lo + n), ..period }, + ) + }; + let gradient = Gradient { stops, spread: GradientSpread::Pad, repeats: 1, ..self.clone() }; + let first = if centered { lo / (lo + n) } else { 0.0 }; + Some(Padded { gradient, geom, first, runs: n as usize, capped }) + } + + /// The gradient as it runs from the start of its vector (0) to its end (1), as one that + /// pads: a gradient that repeats or reflects with its stops repeated [`Self::repeat_count`] + /// times between 0 and 1 (every other run mirrored, for Reflect), for what only shows that + /// stretch (a gradient along or across a stroke, a swatch's preview). Others as they are. + pub fn unrolled(&self) -> std::borrow::Cow<'_, Gradient> { + self.unrolled_within(MAX_SPREAD_STOPS) + } + + /// [`Self::unrolled`] with at most `max_stops` stops: every run, each run without the stops + /// that change its colors least ([`fit_run`]) when the runs need more stops than that. Only with + /// fewer than two stops for each run do the runs past those that fit pad with the last one. + pub fn unrolled_within(&self, max_stops: usize) -> std::borrow::Cow<'_, Gradient> { + use std::borrow::Cow; + if !self.is_spread() { + return Cow::Borrowed(self); + } + // Without stops there is nothing to repeat: it pads all the same. + if self.stops.is_empty() { + return Cow::Owned(Gradient { spread: GradientSpread::Pad, repeats: 1, ..self.clone() }); + } + if self.mirrors_a_hue_turn() { + return Cow::Owned(self.as_classic_curve().unrolled_within(max_stops).into_owned()); + } + let n = self.repeat_count() as usize; + let budget = max_stops.min(MAX_SPREAD_STOPS); + let kept = n.min(budget / 2).max(1); + let one = fit_run(whole_run(&self.stops), budget / kept, self.method); + let stops = self.runs(&one, false, 0.0, kept, n as f64); + Cow::Owned(Gradient { stops, spread: GradientSpread::Pad, repeats: 1, ..self.clone() }) + } + + /// The gradient as [`Self::unrolled`] gives it with at most `max_stops` stops (at least two): + /// a gradient that repeats or reflects as [`Self::unrolled_within`] gives it, and one that + /// pads with more stops than that without the stops that change its colors least + /// ([`fit_run`]). Others as they are. + pub fn fitted(&self, max_stops: usize) -> std::borrow::Cow<'_, Gradient> { + use std::borrow::Cow; + if self.is_spread() { + return self.unrolled_within(max_stops); + } + if self.stops.len() <= max_stops.max(2) { + return Cow::Borrowed(self); + } + Cow::Owned(Gradient { stops: fit_run(whole_run(&self.stops), max_stops, self.method), ..self.clone() }) + } + + /// One cycle of a gradient that repeats or reflects, which repeated end to end paints it, as + /// a gradient that pads: one run of the stops (Repeat), or a run and its mirror (Reflect), + /// between 0 and 1, and how many runs that is (1 or 2). `None` for a gradient that pads and + /// one without stops. + pub fn cycle(&self) -> Option<(Gradient, u32)> { + if !self.is_spread() || self.stops.is_empty() { + return None; + } + if self.mirrors_a_hue_turn() { + return self.as_classic_curve().cycle(); + } + let one = whole_run(&self.stops); + let runs = if self.spread == GradientSpread::Reflect { 2 } else { 1 }; + let stops = self.runs(&one, false, 0.0, runs, runs as f64); + Some((Gradient { stops, spread: GradientSpread::Pad, repeats: 1, ..self.clone() }, runs as u32)) + } + + /// Does the gradient reflect while mixing around the hue wheel? A mirrored run of its stops + /// would turn the wheel the other way, and one gradient has one method, so its runs are + /// written from its curve's stops ([`Self::as_classic_curve`]), which mirror as they are. + fn mirrors_a_hue_turn(&self) -> bool { + self.method.is_hue() && self.spread == GradientSpread::Reflect + } + + /// `n` runs of `one` (one run of the stops, [`whole_run`]) on a line of `of` runs from 0 to 1, + /// the first of them `start` runs along it and an odd-numbered run when `first_odd` (with + /// Reflect, the odd-numbered runs are mirrored). + fn runs(&self, one: &[GradientStop], first_odd: bool, start: f64, n: usize, of: f64) -> Vec { + let mirrored_run = (self.spread == GradientSpread::Reflect).then(|| mirror(one)); + let mut stops = Vec::with_capacity(one.len() * n); + for j in 0..n { + let run = match &mirrored_run { + Some(m) if (j % 2 == 1) != first_odd => m.as_slice(), + _ => one, + }; + stops.extend(run.iter().map(|s| GradientStop { offset: ((start + j as f64 + f64::from(s.offset)) / of) as f32, ..s.clone() })); + } + stops + } +} + +/// The smallest level of radial or diamond gradient `geom` over `area`, less a run (for rounding): +/// 0 when the area holds the rings' center (a radial's focal point, a diamond's center), else the +/// smallest along its sides, worked out in the gradient's unit frame from the sides' ends rather +/// than from samples along them, so a long side does not hide a run near it. 0 for a placement +/// without a frame. +fn inner_level(geom: &GradientGeom, kind: GradientKind, area: Rect) -> f64 { + let center = if kind == GradientKind::Radial { geom.focal_point() } else { geom.start }; + if area.contains(center) { + return 0.0; + } + let frame = if kind == GradientKind::Diamond { geom.diamond_frame() } else { geom.unit_frame() }; + let Some(to_unit) = frame.map(|m| m.inverse()) else { return 0.0 }; + let focal = geom.focal.filter(|_| kind == GradientKind::Radial).map(|f| (to_unit * f).to_vec2()); + let corners = [Point::new(area.x0, area.y0), Point::new(area.x1, area.y0), Point::new(area.x1, area.y1), Point::new(area.x0, area.y1)] + .map(|p| (to_unit * p).to_vec2()); + let mut least = f64::INFINITY; + for (&a, &b) in corners.iter().zip(corners.iter().cycle().skip(1)) { + let side = if kind == GradientKind::Diamond { diamond_least(a, b) } else { radial_least(a, b, focal) }; + least = least.min(side); + } + if least.is_finite() { (least - 1.0).max(0.0) } else { 0.0 } +} + +/// The smallest diamond level, |x| + |y| in its unit frame, on the segment from `a` to `b`: the +/// level is linear between the points where the segment crosses an axis, so the smallest is at +/// an end or at one of those crossings. +fn diamond_least(a: Vec2, b: Vec2) -> f64 { + let d = b - a; + let crossings = [(d.x != 0.0).then(|| -a.x / d.x), (d.y != 0.0).then(|| -a.y / d.y)]; + [Some(0.0), Some(1.0), crossings[0], crossings[1]] + .into_iter() + .flatten() + .filter(|u| (0.0..=1.0).contains(u)) + .map(|u| { + let p = a + d * u; + p.x.abs() + p.y.abs() + }) + .fold(f64::INFINITY, f64::min) +} + +/// Halvings at most in [`radial_least`]: enough to bring any finite span below a quarter level. +const RADIAL_HALVINGS: usize = 1100; + +/// The smallest radial level on the segment from `a` to `b` in the unit frame, at most a quarter +/// level under it: the distance to the center for a centered radial. An off-center radial's level +/// `t` is the circle of radius `t` about `f`(1 − `t`), `f` its focal point; the segment's distance +/// from that center less `t` falls as `t` grows (the center moves |`f`| < 1 per level), and the +/// smallest level is where it reaches 0, found by halving. 0 for a focal point not inside the +/// extent ellipse. +fn radial_least(a: Vec2, b: Vec2, focal: Option) -> f64 { + let Some(f) = focal else { return distance_to_segment(a, b, Vec2::ZERO) }; + let reach = f.hypot(); + if reach.is_nan() || reach >= 1.0 { + return 0.0; + } + let past = |t: f64| distance_to_segment(a, b, f * (1.0 - t)) <= t; + // At this level the circle reaches the segment's nearest point to the ellipse's center. + let mut hi = (distance_to_segment(a, b, Vec2::ZERO) / (1.0 - reach)).max(1.0); + let mut lo = 0.0; + if !hi.is_finite() || past(lo) { + return 0.0; + } + for _ in 0..RADIAL_HALVINGS { + let mid = lo + (hi - lo) / 2.0; + if hi - lo <= 0.25 || mid <= lo || mid >= hi { + break; + } + if past(mid) { hi = mid } else { lo = mid } + } + lo +} + +/// How far `c` is from the segment from `a` to `b`. +fn distance_to_segment(a: Vec2, b: Vec2, c: Vec2) -> f64 { + let d = b - a; + let along = (c - a).dot(d) / d.hypot2(); + let u = if along.is_finite() { along.clamp(0.0, 1.0) } else { 0.0 }; + (a + d * u - c).hypot() +} + +/// The stops of one run, from offset 0 to 1: the end colors held out to the ends. +fn whole_run(stops: &[GradientStop]) -> Vec { + let mut out = stops.to_vec(); + if let Some(first) = out.first().filter(|s| s.offset > 0.0).cloned() { + out.insert(0, GradientStop { offset: 0.0, ..first }); + } + if let Some(last) = out.last_mut() { + // The last stop's midpoint leads nowhere; the copy at 1 takes over. + if last.offset < 1.0 { + let end = GradientStop { offset: 1.0, ..last.clone() }; + out.push(end); + } + } + out +} + +/// `one` (a run of a gradient's stops, [`whole_run`]) with at most `budget` stops (at least two): +/// as it is when it fits, else without the stops that change its colors least, left out one at a +/// time. Leaving out a stop costs how far its color lies from the one that mixing the stops still +/// on either side of it by `method` gives there, and how far its CMYK inks, opacity, tint or +/// process plates lie from the line between theirs (a whole unit when its swatch link or color +/// model differs from either of theirs, and a whole unit more when its midpoint or the one before +/// it is off center), so the ends, sharp steps, ink changes and shaped spans stay. A stop whose +/// next stop was left out gets its midpoint centered. The work is the stops times their logarithm. +fn fit_run(one: Vec, budget: usize, method: GradientMethod) -> Vec { + use std::cmp::Reverse; + use std::collections::BinaryHeap; + let budget = budget.max(2); + let n = one.len(); + if n <= budget { + return one; + } + let mix = |x: &Color, y: &Color, v: f32| match method { + GradientMethod::Classic => x.lerp_keep_model(y, v), + m => m.mix(x, y, v), + }; + let cost = |a: &GradientStop, s: &GradientStop, b: &GradientStop| -> u32 { + let span = b.offset - a.offset; + let u = if span > 0.0 { ((s.offset - a.offset) / span).clamp(0.0, 1.0) } else { 0.0 }; + // Left out, the span from `a` to `b` has a centered midpoint, so it mixes them by `u`. + let (want, cs) = (mix(&a.color, &b.color, u).to_rgb(), s.color.to_rgb()); + let color = (0..3).map(|k| (want[k] - cs[k]).abs()).fold(0.0, f32::max); + let opacity = (a.opacity + (b.opacity - a.opacity) * u - s.opacity).abs(); + // Process inks, which colors that look alike can print differently: off their line, or a + // change of color model. + let process = match (&a.color, &s.color, &b.color) { + (Color::Cmyk { c: c0, m: m0, y: y0, k: k0 }, Color::Cmyk { c, m, y, k }, Color::Cmyk { c: c1, m: m1, y: y1, k: k1 }) => { + [(c0, c, c1), (m0, m, m1), (y0, y, y1), (k0, k, k1)].iter().map(|(p, q, r)| (*p + (*r - *p) * u - *q).abs()).fold(0.0, f32::max) + } + _ if a.color.model() == s.color.model() && s.color.model() == b.color.model() => 0.0, + _ => 1.0, + }; + let color = color.max(process); + // Separations: a change of swatch link, or of tint or process plates off their line. + let ink = if s.swatch != a.swatch || s.swatch != b.swatch { + 1.0 + } else { + let tint = (a.tint + (b.tint - a.tint) * u - s.tint).abs(); + let plates = match (a.plates, s.plates, b.plates) { + (None, None, None) => 0.0, + (Some(pa), Some(ps), Some(pb)) => (0..4).map(|k| (pa[k] + (pb[k] - pa[k]) * u - ps[k]).abs()).fold(0.0, f32::max), + _ => 1.0, + }; + tint.max(plates) + }; + // Leaving it out merges two spans, and an off-center midpoint shapes one of them. + let shaped = if [a.midpoint, s.midpoint].iter().any(|m| (m - 0.5).abs() > 1e-3) { 1.0 } else { 0.0 }; + // Non-negative, so the bits order as the numbers do (NaN counts as 0). + (color.max(opacity).max(ink) + shaped).max(0.0).to_bits() + }; + // The stops still kept on either side of each stop, and each stop's latest cost entry. + let mut prev: Vec = (0..n).map(|i| i.saturating_sub(1)).collect(); + let mut next: Vec = (1..=n).collect(); + let mut gone = vec![false; n]; + let mut version = vec![0u32; n]; + let mut heap: BinaryHeap> = (1..n - 1).map(|i| Reverse((cost(&one[i - 1], &one[i], &one[i + 1]), i, 0))).collect(); + let mut left = n; + while left > budget { + let Some(Reverse((_, i, v))) = heap.pop() else { break }; + if gone[i] || v != version[i] { + continue; + } + gone[i] = true; + left -= 1; + let (a, b) = (prev[i], next[i]); + next[a] = b; + prev[b] = a; + for j in [a, b] { + if j != 0 && j != n - 1 { + version[j] += 1; + heap.push(Reverse((cost(&one[prev[j]], &one[j], &one[next[j]]), j, version[j]))); + } + } + } + one.into_iter() + .enumerate() + .filter(|(i, _)| !gone[*i]) + .map(|(i, s)| if next[i] == i + 1 { s } else { GradientStop { midpoint: 0.5, ..s } }) + .collect() +} + +/// A run mirrored: the stops in reverse, each midpoint measured from the other side. +fn mirror(run: &[GradientStop]) -> Vec { + let mut g = Gradient::new(GradientKind::Linear, run.to_vec()); + g.reverse(); + g.stops +} + +#[cfg(test)] +mod tests; diff --git a/crates/color/src/gradient/spread/tests.rs b/crates/color/src/gradient/spread/tests.rs new file mode 100644 index 0000000000..ab088293da --- /dev/null +++ b/crates/color/src/gradient/spread/tests.rs @@ -0,0 +1,520 @@ +use kurbo::Vec2; + +use super::*; +use crate::gradient::{GradientPaint, MAX_REPEATS}; +use crate::{Color, GradientMethod}; + +fn spread(kind: GradientKind, spread: GradientSpread, repeats: u32) -> Gradient { + Gradient { spread, repeats, ..Gradient::new(kind, Gradient::default().stops) } +} + +fn black_white() -> Vec { + let mut a = GradientStop::new(0.0, Color::BLACK); + a.midpoint = 0.3; + vec![a, GradientStop::new(1.0, Color::WHITE)] +} + +fn close(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-9 +} + +/// Repeat wraps the parameter, `repeats` times along the vector and on past both ends; Reflect +/// runs every other run backwards; Pad leaves it to the stops to clamp; a freeform gradient has +/// no ends to spread past. +#[test] +fn spread_maps_the_parameter_to_a_place_along_the_stops() { + let repeat = spread(GradientKind::Linear, GradientSpread::Repeat, 3); + for (t, want) in [(0.0, 0.0), (0.1, 0.3), (0.5, 0.5), (1.0 / 3.0 + 0.1, 0.3), (1.1, 0.3), (-0.1, 0.7)] { + assert!(close(repeat.spread_param(t), want), "repeat {t}: {}", repeat.spread_param(t)); + } + let reflect = spread(GradientKind::Radial, GradientSpread::Reflect, 3); + for (t, want) in [(0.0, 0.0), (0.1, 0.3), (1.0 / 3.0 + 0.1, 0.7), (2.0 / 3.0 + 0.1, 0.3), (1.0, 1.0), (-0.1, 0.3)] { + assert!(close(reflect.spread_param(t), want), "reflect {t}: {}", reflect.spread_param(t)); + } + let pad = spread(GradientKind::Linear, GradientSpread::Pad, 3); + assert_eq!((pad.spread_param(1.7), pad.spread_param(-0.2)), (1.7, -0.2)); + let free = spread(GradientKind::Freeform, GradientSpread::Repeat, 3); + assert_eq!(free.spread_param(0.7), 0.7); + assert!(!free.is_spread() && !pad.is_spread() && repeat.is_spread()); + assert!(repeat.spread_param(f64::NAN).is_nan()); + // A count out of range (set in code) counts as the nearest one in range. + assert_eq!(spread(GradientKind::Linear, GradientSpread::Repeat, 0).repeat_count(), 1); + assert_eq!(spread(GradientKind::Linear, GradientSpread::Repeat, 5000).repeat_count(), MAX_REPEATS); +} + +/// The native format writes the spread and count only when they are not Pad and 1, reads a file +/// without them as Pad and 1, and reads an unknown spread or a count out of range as the nearest +/// one it can hold. +#[test] +fn the_file_keeps_the_spread_and_reads_bad_values_leniently() { + let plain = serde_json::to_value(Gradient::default()).unwrap(); + assert!(plain.get("spread").is_none() && plain.get("repeats").is_none(), "{plain}"); + let g = spread(GradientKind::Conic, GradientSpread::Reflect, 4); + let v = serde_json::to_value(&g).unwrap(); + assert_eq!((v["spread"].as_str(), v["repeats"].as_u64()), (Some("Reflect"), Some(4))); + assert_eq!(serde_json::from_value::(v).unwrap(), g); + let read = |spread: serde_json::Value, repeats: serde_json::Value| { + let mut v = serde_json::to_value(Gradient::default()).unwrap(); + v["spread"] = spread; + v["repeats"] = repeats; + let g: Gradient = serde_json::from_value(v).unwrap(); + (g.spread, g.repeats) + }; + assert_eq!(read("Repeat".into(), 3.4.into()), (GradientSpread::Repeat, 3)); + assert_eq!(read("Spiral".into(), (-5).into()), (GradientSpread::Pad, 1)); + assert_eq!(read(7.into(), 1e12.into()), (GradientSpread::Pad, MAX_REPEATS)); + assert_eq!(read(serde_json::Value::Null, "many".into()), (GradientSpread::Pad, 1)); + let missing: Gradient = serde_json::from_value(serde_json::json!({"kind": "Linear", "stops": []})).unwrap(); + assert_eq!((missing.spread, missing.repeats), (GradientSpread::Pad, 1)); +} + +/// One run's placement: a level of the period is the gradient's level times the count, for +/// linear, diamond and off-center radial gradients; a conic keeps its placement. +#[test] +fn a_period_holds_one_run_of_the_stops() { + let p = Point::new(72.0, 61.0); + let linear = GradientGeom { start: Point::new(10.0, 20.0), end: Point::new(60.0, 40.0), aspect: 1.0, focal: None }; + let radial = GradientGeom { start: Point::new(50.0, 50.0), end: Point::new(60.0, 50.0), aspect: 0.6, focal: Some(Point::new(55.0, 52.0)) }; + let diamond = GradientGeom { end: Point::new(58.0, 56.0), focal: None, ..radial }; + for (kind, geom) in [(GradientKind::Linear, linear), (GradientKind::Radial, radial), (GradientKind::Diamond, diamond)] { + let period = geom.period(kind, 4); + assert!(close(period.param_at(kind, p), 4.0 * geom.param_at(kind, p)), "{kind:?}"); + assert_eq!(period.focal, geom.focal, "{kind:?}"); + } + assert_eq!(radial.period(GradientKind::Conic, 4), radial); + assert_eq!(linear.period(GradientKind::Linear, 0), linear, "a count of 0 counts as 1"); +} + +/// The stops repeated over the area: as many runs as its corners reach, each in place. +#[test] +fn a_linear_gradient_pads_with_its_stops_repeated_over_the_area() { + let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(20.0, 0.0), aspect: 1.0, focal: None }; + let g = Gradient { spread: GradientSpread::Repeat, repeats: 2, ..Gradient::new(GradientKind::Linear, black_white()) }; + let p = g.padded_over(&geom, Rect::new(-5.0, 0.0, 25.0, 10.0)).unwrap(); + assert!(!p.capped); + // Runs of 10 from -10 to 30: four of them. + assert_eq!((p.geom.start, p.geom.end), (Point::new(-10.0, 0.0), Point::new(30.0, 0.0))); + let offsets: Vec = p.gradient.stops.iter().map(|s| s.offset).collect(); + assert_eq!(offsets, [0.0, 0.25, 0.25, 0.5, 0.5, 0.75, 0.75, 1.0]); + assert!(p.gradient.stops.iter().step_by(2).all(|s| s.color == Color::BLACK && (s.midpoint - 0.3).abs() < 1e-6)); + assert_eq!((p.gradient.spread, p.gradient.repeats), (GradientSpread::Pad, 1)); + // Every point gets the color the gradient gives it. + for x in [-4.0, 1.0, 7.5, 13.0, 24.0] { + let q = Point::new(x, 5.0); + let want = g.sample(g.spread_param(geom.param_at(GradientKind::Linear, q)) as f32).0; + let got = p.gradient.sample(p.geom.param_at(GradientKind::Linear, q) as f32).0; + assert!(want.to_rgb().iter().zip(got.to_rgb()).all(|(a, b)| (a - b).abs() < 1e-4), "{x}: {want:?} vs {got:?}"); + } +} + +#[test] +fn reflect_mirrors_every_other_run_and_its_midpoints() { + let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(10.0, 0.0), aspect: 1.0, focal: None }; + let g = Gradient { spread: GradientSpread::Reflect, ..Gradient::new(GradientKind::Linear, black_white()) }; + let p = g.padded_over(&geom, Rect::new(0.0, 0.0, 20.0, 10.0)).unwrap(); + let colors: Vec = p.gradient.stops.iter().map(|s| s.color).collect(); + assert_eq!(colors, [Color::BLACK, Color::WHITE, Color::WHITE, Color::BLACK]); + // Black → white with the midpoint at 0.3 mirrors to white → black with it at 0.7. + assert!((p.gradient.stops[2].midpoint - 0.7).abs() < 1e-6, "{:?}", p.gradient.stops); +} + +/// A gradient mixed around the hue wheel that reflects: a mirrored run turns the wheel back the +/// way it came, so every point keeps its color when the runs are written out as a gradient that +/// pads, unrolled along the vector, or as one cycle, with a repeating one's too. +#[test] +fn reflected_and_repeated_hue_turns_keep_every_color() { + let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(10.0, 0.0), aspect: 1.0, focal: None }; + let stops = || { + let mut red = GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)); + red.midpoint = 0.3; + vec![red, GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))] + }; + let near = |a: Color, b: Color, what: &str| { + assert!(a.to_rgb().iter().zip(b.to_rgb()).all(|(x, y)| (x - y).abs() < 1.0 / 255.0), "{what}: {a:?} vs {b:?}"); + }; + for method in [GradientMethod::HueClockwise, GradientMethod::HueCounterclockwise] { + for spread in [GradientSpread::Reflect, GradientSpread::Repeat] { + let g = Gradient { method, spread, repeats: 2, ..Gradient::new(GradientKind::Linear, stops()) }; + let p = g.padded_over(&geom, Rect::new(-10.0, 0.0, 20.0, 10.0)).unwrap(); + assert_eq!((p.gradient.spread, p.gradient.repeats), (GradientSpread::Pad, 1)); + for k in 0..300 { + let q = Point::new(-10.0 + f64::from(k) * 0.1 + 0.013, 5.0); + let want = g.sample(g.spread_param(geom.param_at(GradientKind::Linear, q)) as f32).0; + let got = p.gradient.sample(p.geom.param_at(GradientKind::Linear, q) as f32).0; + near(want, got, &format!("{method:?} {spread:?} padded at {}", q.x)); + } + let unrolled = g.unrolled(); + let (cycle, runs) = g.cycle().unwrap(); + for k in 0..=200 { + let t = (k as f32 + 0.37) / 201.0; + let want = g.sample(g.spread_param(f64::from(t)) as f32).0; + near(want, unrolled.sample(t).0, &format!("{method:?} {spread:?} unrolled at {t}")); + // One cycle covers `runs` of the two runs between 0 and 1. + let along = t * runs as f32 / 2.0; + let want = g.sample(g.spread_param(f64::from(along)) as f32).0; + near(want, cycle.sample(t).0, &format!("{method:?} {spread:?} cycle at {t}")); + } + } + } +} + +#[test] +fn stops_inside_a_run_hold_their_colors_to_its_ends() { + let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(10.0, 0.0), aspect: 1.0, focal: None }; + let stops = vec![GradientStop::new(0.25, Color::BLACK), GradientStop::new(0.75, Color::WHITE)]; + let g = Gradient { spread: GradientSpread::Repeat, ..Gradient::new(GradientKind::Linear, stops) }; + let p = g.padded_over(&geom, Rect::new(0.0, 0.0, 20.0, 10.0)).unwrap(); + let offsets: Vec = p.gradient.stops.iter().map(|s| s.offset).collect(); + assert_eq!(offsets, [0.0, 0.125, 0.375, 0.5, 0.5, 0.625, 0.875, 1.0]); +} + +/// An off-center radial grows about its focal point, a diamond about its center; every point +/// keeps its color. +#[test] +fn radial_and_diamond_gradients_pad_in_rings_from_their_first_level() { + let c = Point::new(50.0, 50.0); + let radial = GradientGeom { start: c, end: Point::new(60.0, 50.0), aspect: 1.0, focal: Some(Point::new(55.0, 50.0)) }; + let diamond = GradientGeom { focal: None, ..radial }; + for (kind, geom) in [(GradientKind::Radial, radial), (GradientKind::Diamond, diamond)] { + let g = Gradient { spread: GradientSpread::Reflect, repeats: 2, ..Gradient::new(kind, black_white()) }; + let p = g.padded_over(&geom, Rect::new(0.0, 0.0, 100.0, 100.0)).unwrap(); + assert!(p.gradient.stops.len() / 2 >= 10, "{kind:?}: {}", p.gradient.stops.len()); + assert_eq!(p.geom.focal, geom.focal); + for q in [Point::new(72.0, 61.0), Point::new(10.0, 95.0), Point::new(52.0, 49.0)] { + let want = g.sample(g.spread_param(geom.param_at(kind, q)) as f32).0.to_rgb(); + let got = p.gradient.sample(p.geom.param_at(kind, q) as f32).0.to_rgb(); + assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 1e-4), "{kind:?} {q:?}: {want:?} vs {got:?}"); + } + } +} + +/// A run of the stops far too short for the area is written with at most so many runs, and pads +/// past them; a gradient of many stops is written with every run the area needs, each run +/// without the stops that change its colors least, within so many stops; a conic, a padding +/// gradient and one without stops have nothing to pad. +#[test] +fn far_repeats_are_capped_and_many_stops_are_sampled() { + let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(0.01, 0.0), aspect: 1.0, focal: None }; + let g = Gradient { spread: GradientSpread::Repeat, repeats: MAX_REPEATS, ..Gradient::new(GradientKind::Linear, black_white()) }; + let p = g.padded_over(&geom, Rect::new(0.0, 0.0, 100.0, 1.0)).unwrap(); + assert!(p.capped); + assert_eq!(p.gradient.stops.len(), 2 * MAX_SPREAD_RUNS); + let many: Vec = (0..=4000).map(|i| GradientStop::new(i as f32 / 4000.0, Color::gray(i as f32 / 4000.0))).collect(); + let g = Gradient { spread: GradientSpread::Reflect, repeats: 50, ..Gradient::new(GradientKind::Linear, many) }; + let wide = GradientGeom { end: Point::new(100.0, 0.0), ..geom }; + let p = g.padded_over(&wide, Rect::new(0.0, 0.0, 100.0, 1.0)).unwrap(); + assert!(!p.capped && p.runs == 50 && p.gradient.stops.len() <= MAX_SPREAD_STOPS, "{} {}", p.runs, p.gradient.stops.len()); + for x in [0.7, 33.3, 66.1, 99.5] { + let q = Point::new(x, 0.5); + let want = g.sample(g.spread_param(wide.param_at(GradientKind::Linear, q)) as f32).0.to_rgb(); + let got = p.gradient.sample(p.geom.param_at(GradientKind::Linear, q) as f32).0.to_rgb(); + assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 2e-3), "{x}: {want:?} vs {got:?}"); + } + assert!(g.unrolled().stops.len() <= MAX_SPREAD_STOPS); + assert!(p.gradient.padded_over(&p.geom, Rect::new(0.0, 0.0, 1.0, 1.0)).is_none(), "it pads"); + assert!(spread(GradientKind::Conic, GradientSpread::Repeat, 3).padded_over(&wide, Rect::new(0.0, 0.0, 1.0, 1.0)).is_none()); + let empty = Gradient { spread: GradientSpread::Repeat, ..Gradient::new(GradientKind::Linear, vec![]) }; + assert!(empty.padded_over(&wide, Rect::new(0.0, 0.0, 1.0, 1.0)).is_none()); +} + +/// The runs written are the ones the area shows: a radial or diamond centered a thousand runs +/// from the area writes the hundred it crosses, not the first 256 from the center; a linear +/// gradient over an area of 1,100 runs far before its start, capped, keeps the runs nearest it. +/// Every point checked gets the color the gradient gives it. +#[test] +fn the_runs_written_cover_a_distant_area() { + let centered = GradientGeom { start: Point::new(0.0, 50.0), end: Point::new(1.0, 50.0), aspect: 1.0, focal: None }; + let before = GradientGeom { start: Point::new(5000.0, 0.0), end: Point::new(5001.0, 0.0), aspect: 1.0, focal: None }; + for (kind, geom, area) in [ + (GradientKind::Radial, centered, Rect::new(1000.0, 0.0, 1100.0, 100.0)), + (GradientKind::Diamond, centered, Rect::new(1000.0, 0.0, 1100.0, 100.0)), + (GradientKind::Linear, before, Rect::new(0.0, 0.0, 1100.0, 100.0)), + ] { + let g = Gradient { spread: GradientSpread::Reflect, repeats: 1, ..Gradient::new(kind, black_white()) }; + let p = g.padded_over(&geom, area).unwrap(); + assert_eq!(p.capped, kind == GradientKind::Linear, "{kind:?}"); + assert!(p.gradient.stops.len() <= MAX_SPREAD_STOPS); + for q in [Point::new(1000.5, 0.5), Point::new(1050.25, 50.0), Point::new(1099.5, 99.5), Point::new(1010.75, 90.0)] { + let want = g.sample(g.spread_param(geom.param_at(kind, q)) as f32).0.to_rgb(); + let got = p.gradient.sample(p.geom.param_at(kind, q) as f32).0.to_rgb(); + assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 2e-3), "{kind:?} {q:?}: {want:?} vs {got:?}"); + } + } +} + +/// A tiny radial centered just outside the area, beside a side between any evenly spaced +/// samples of it: the runs written start from the area's true innermost level. +#[test] +fn the_innermost_level_is_found_between_samples() { + let c = Point::new(-0.0005, 7.8125); + let geom = GradientGeom { start: c, end: c + Vec2::new(0.001, 0.0), aspect: 1.0, focal: None }; + let g = Gradient { spread: GradientSpread::Reflect, repeats: 1, ..Gradient::new(GradientKind::Radial, black_white()) }; + let p = g.padded_over(&geom, Rect::new(0.0, 0.0, 1000.0, 1000.0)).unwrap(); + for q in [Point::new(0.05, 7.8125), Point::new(0.1, 7.9)] { + let want = g.sample(g.spread_param(geom.param_at(GradientKind::Radial, q)) as f32).0.to_rgb(); + let got = p.gradient.sample(p.geom.param_at(GradientKind::Radial, q) as f32).0.to_rgb(); + assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 2e-3), "{q:?}: {want:?} vs {got:?}"); + } +} + +/// An area four billion units wide whose long side passes 50 runs from a tiny radial or diamond's +/// center: the runs written start from that side's true innermost level, so the runs beside it +/// keep their colors. +#[test] +fn the_innermost_level_is_found_along_a_very_long_side() { + let area = Rect::new(-1.3e9, 0.0, 2.9e9, 1.0); + for x in [0.3, 12345.678, -7777.25, 98765.4321] { + let c = Point::new(x, -0.00005); + let run = GradientGeom { start: c, end: c + Vec2::new(1e-6, 0.0), aspect: 1.0, focal: None }; + let off_center = GradientGeom { focal: Some(c + Vec2::new(0.5e-6, 0.0)), ..run }; + for (kind, geom) in [(GradientKind::Diamond, run), (GradientKind::Radial, run), (GradientKind::Radial, off_center)] { + let g = Gradient { spread: GradientSpread::Reflect, repeats: 1, ..Gradient::new(kind, black_white()) }; + let p = g.padded_over(&geom, area).unwrap(); + assert!(p.capped, "{kind:?}"); + for q in [Point::new(x, 1e-5), Point::new(x + 2e-5, 2e-5), Point::new(x - 1e-5, 0.0001)] { + let level = geom.param_at(kind, q); + assert!((40.0..200.0).contains(&level), "{kind:?} {q:?}: level {level}"); + let want = g.sample(g.spread_param(level) as f32).0.to_rgb(); + let got = p.gradient.sample(p.geom.param_at(kind, q) as f32).0.to_rgb(); + assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 2e-3), "{kind:?} {q:?}: {want:?} vs {got:?}"); + } + } + } +} + +/// Runs a billion levels from a radial's center are past what the stops' offsets can tell apart: +/// the gradient is written capped, its stops still apart and in order. +#[test] +fn runs_too_far_from_the_center_are_capped() { + let c = Point::new(0.0, 0.0); + let geom = GradientGeom { start: c, end: c + Vec2::new(1e-6, 0.0), aspect: 1.0, focal: None }; + let g = Gradient { spread: GradientSpread::Reflect, repeats: 1, ..Gradient::new(GradientKind::Radial, black_white()) }; + let p = g.padded_over(&geom, Rect::new(1000.0, 0.0, 1000.0001, 0.0001)).unwrap(); + assert!(p.capped); + assert!(p.gradient.stops.windows(2).all(|w| w[0].offset <= w[1].offset), "in order"); + let distinct = p.gradient.stops.windows(2).filter(|w| w[1].offset > w[0].offset).count(); + assert!(distinct * 2 + 2 >= p.gradient.stops.len(), "the runs stay apart: {distinct} of {}", p.gradient.stops.len()); +} + +/// A run of 1,000 close stops is written only as far out as their offsets stay apart: around +/// level 50,000 it is capped, every stop written apart from the next. +#[test] +fn close_stops_are_written_only_where_they_stay_apart() { + let many: Vec = (0..=1000).map(|i| GradientStop::new(i as f32 / 1000.0, Color::gray(i as f32 / 1000.0))).collect(); + let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(0.001, 0.0), aspect: 1.0, focal: None }; + let g = Gradient { spread: GradientSpread::Repeat, repeats: 1, ..Gradient::new(GradientKind::Diamond, many) }; + let p = g.padded_over(&geom, Rect::new(50.0, 0.0, 50.002, 0.002)).unwrap(); + assert!(p.capped); + // Only where one run meets the next do two stops share an offset. + let runs = p.gradient.stops.len() / 1001; + let shared = p.gradient.stops.windows(2).filter(|w| w[1].offset <= w[0].offset).count(); + assert!(shared < runs, "{shared} stops share an offset in {runs} runs"); + // Stops 0.0001234 of a run apart are written out to level 123, on whole runs: an area within + // it gets the gradient's colors, Reflect's mirrored runs included. + let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(0.0001234, Color::gray(0.5)), GradientStop::new(1.0, Color::WHITE)]; + let g = Gradient { spread: GradientSpread::Reflect, repeats: 1, ..Gradient::new(GradientKind::Diamond, stops) }; + let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(1.0, 0.0), aspect: 1.0, focal: None }; + let p = g.padded_over(&geom, Rect::new(121.0, 0.0, 123.9, 0.2)).unwrap(); + assert!(p.capped, "past level 123 it pads"); + for x in [121.3, 121.9, 122.5] { + let q = Point::new(x, 0.1); + let want = g.sample(g.spread_param(geom.param_at(GradientKind::Diamond, q)) as f32).0.to_rgb(); + let got = p.gradient.sample(p.geom.param_at(GradientKind::Diamond, q) as f32).0.to_rgb(); + assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 2e-3), "{x}: {want:?} vs {got:?}"); + } +} + +/// A piece of a gradient that starts where two runs meet (a gradient along a stroke, sliced at a +/// corner there) starts with the new run's first color, not the old run's last. +#[test] +fn a_piece_starting_at_a_sharp_step_takes_the_color_after_it() { + let g = Gradient { spread: GradientSpread::Repeat, repeats: 2, ..Gradient::new(GradientKind::Linear, Gradient::default().stops) }; + let piece = g.unrolled().span(0.5, 1.0); + assert_eq!(piece.stops.first().map(|s| s.color), Some(Color::WHITE), "{:?}", piece.stops); + assert_eq!(piece.stops.last().map(|s| s.color), Some(Color::BLACK)); + let before = g.unrolled().span(0.0, 0.5); + assert_eq!((before.stops[0].color, before.stops.last().unwrap().color), (Color::WHITE, Color::BLACK)); +} + +/// An area very far past a very short reflecting vector (a file's numbers) is padded without the +/// run count overflowing. +#[test] +fn a_far_area_pads_without_overflowing() { + let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(1e-300, 0.0), aspect: 1.0, focal: None }; + let g = Gradient { spread: GradientSpread::Reflect, repeats: MAX_REPEATS, ..Gradient::new(GradientKind::Linear, black_white()) }; + let p = g.padded_over(&geom, Rect::new(1e3, 0.0, 2e3, 1.0)); + assert!(p.is_none_or(|p| p.gradient.stops.len() <= MAX_SPREAD_STOPS)); + // Runs of 1e-8: the area's levels lie past 1e19, more than an integer holds. + let geom = GradientGeom { end: Point::new(1e-6, 0.0), ..geom }; + let p = g.padded_over(&geom, Rect::new(1e11, 0.0, 1e11 + 1.0, 1.0)).unwrap(); + assert!(p.capped && p.gradient.stops.len() <= MAX_SPREAD_STOPS, "{} {} {:?}", p.capped, p.gradient.stops.len(), p.geom); +} + +/// Unrolled, the stops run `repeats` times between 0 and 1 (every other run mirrored with +/// Reflect); one cycle is a run, or a run and its mirror. +#[test] +fn unrolled_and_cycle_stops() { + let g = Gradient { spread: GradientSpread::Reflect, repeats: 3, ..Gradient::new(GradientKind::Linear, black_white()) }; + let u = g.unrolled(); + let offsets: Vec = u.stops.iter().map(|s| (s.offset * 3.0).round()).collect(); + assert_eq!(offsets, [0.0, 1.0, 1.0, 2.0, 2.0, 3.0]); + let colors: Vec = u.stops.iter().map(|s| s.color).collect(); + assert_eq!(colors, [Color::BLACK, Color::WHITE, Color::WHITE, Color::BLACK, Color::BLACK, Color::WHITE]); + for t in [0.05, 0.4, 0.71, 0.99] { + let (a, b) = (g.sample(g.spread_param(t) as f32).0.to_rgb(), u.sample(t as f32).0.to_rgb()); + assert!(a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-4), "{t}"); + } + let (cycle, runs) = g.cycle().unwrap(); + assert_eq!((runs, cycle.stops.len()), (2, 4)); + let repeat = Gradient { spread: GradientSpread::Repeat, ..g.clone() }; + assert_eq!(repeat.cycle().unwrap().1, 1); + assert!(Gradient::default().cycle().is_none()); + assert!(matches!(Gradient::default().unrolled(), std::borrow::Cow::Borrowed(_))); +} + +/// A gradient of more stops than [`MAX_SPREAD_STOPS`] allows for all its runs keeps every run +/// when unrolled, each run without the stops that change its colors least: its last run ends on +/// its last color instead of the rest padding with it. +#[test] +fn unrolled_many_stops_keep_every_run() { + let stops: Vec = (0..200).map(|i| GradientStop::new(i as f32 / 199.0, Color::gray(i as f32 / 199.0))).collect(); + let g = Gradient { spread: GradientSpread::Repeat, repeats: MAX_REPEATS, ..Gradient::new(GradientKind::Linear, stops) }; + let u = g.unrolled(); + assert!(u.stops.len() <= MAX_SPREAD_STOPS, "{}", u.stops.len()); + for t in [0.005, 0.5051, 0.9149, 0.9951] { + let want = g.sample(g.spread_param(t) as f32).0.to_rgb(); + let got = u.sample(t as f32).0.to_rgb(); + assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 2e-3), "{t}: {want:?} vs {got:?}"); + } + // A padding gradient fitted to fewer stops keeps its ends. + let pad = Gradient::new(GradientKind::Linear, g.stops.clone()); + let fitted = pad.fitted(16); + assert_eq!(fitted.stops.len(), 16); + for (stop, want) in [(&fitted.stops[0], Color::gray(0.0)), (&fitted.stops[15], Color::gray(1.0))] { + assert!(stop.color.to_rgb().iter().zip(want.to_rgb()).all(|(a, b)| (a - b).abs() < 1e-5), "{:?}", stop.color); + } + assert!(matches!(pad.fitted(500), std::borrow::Cow::Borrowed(_))); +} + +/// One run of more stops than the limit (255 inside it, and a copy of each end color at 0 and 1) +/// is written within the limit, every run the area needs included. +#[test] +fn a_run_over_the_stop_limit_is_written_within_it() { + let stops: Vec = (1..=255).map(|i| GradientStop::new(i as f32 / 256.0, Color::gray(i as f32 / 256.0))).collect(); + let g = Gradient { spread: GradientSpread::Repeat, repeats: 2, ..Gradient::new(GradientKind::Linear, stops) }; + let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(20.0, 0.0), aspect: 1.0, focal: None }; + let p = g.padded_within(&geom, Rect::new(0.0, 0.0, 20.0, 1.0), 256).unwrap(); + assert!(!p.capped && p.runs == 2 && p.gradient.stops.len() <= 256, "{} {} {}", p.capped, p.runs, p.gradient.stops.len()); + assert!(g.unrolled_within(256).stops.len() <= 256); +} + +/// Fitting a run to fewer stops keeps a narrow band between two sharp steps, a stop linked to a +/// swatch, and each kept stop's link and tint, where sampling at evenly spaced places would lose +/// them. +#[test] +fn fitting_keeps_sharp_steps_and_swatch_links() { + let mut stops: Vec = (0..300).map(|i| GradientStop::new(i as f32 / 299.0, Color::gray(i as f32 / 299.0))).collect(); + let red = Color::rgb(1.0, 0.0, 0.0); + // A band of red from 0.5003 to 0.5013, with a sharp step at each side. + for (offset, color) in [(0.5003, None), (0.5003, Some(red)), (0.5013, Some(red)), (0.5013, None)] { + let gray = Color::gray(offset); + stops.push(GradientStop::new(offset, color.unwrap_or(gray))); + } + let spot = GradientStop { swatch: Some("Ink".into()), tint: 0.4, ..GradientStop::new(0.25, Color::gray(0.25)) }; + stops.push(spot.clone()); + // Three stops of one ink that look alike but print at different tints. + for (offset, tint) in [(0.8, 0.2), (0.81, 0.9), (0.82, 0.2)] { + stops.push(GradientStop { swatch: Some("Ink2".into()), tint, ..GradientStop::new(offset, Color::gray(offset)) }); + } + // A span shaped by an off-center midpoint. + if let Some(s) = stops.iter_mut().find(|s| (s.offset - 0.6).abs() < 2e-3) { + s.midpoint = 0.13; + } + stops.sort_by(|a, b| a.offset.total_cmp(&b.offset)); + let g = Gradient::new(GradientKind::Linear, stops); + let fitted = g.fitted(32); + assert!(fitted.stops.len() <= 32, "{}", fitted.stops.len()); + let red_at = |t: f32| fitted.sample(t).0.to_rgb(); + assert_eq!(red_at(0.5008), [1.0, 0.0, 0.0], "the band stays"); + assert!(red_at(0.499)[1] > 0.4 && red_at(0.503)[1] > 0.4, "the band stays narrow"); + assert!(fitted.stops.iter().any(|s| s.swatch.as_deref() == Some("Ink") && s.tint == 0.4 && s.offset == 0.25), "{:?}", fitted.stops); + assert!(fitted.stops.iter().any(|s| s.swatch.as_deref() == Some("Ink2") && s.tint == 0.9), "the tint change stays"); + assert!(fitted.stops.iter().any(|s| s.midpoint == 0.13), "the shaped span stays"); + // Of a stop that changes only its ink's tint and one that the colors' line nearly gives, the + // first stays. (The stop before an ink starts stays as well: leaving it out would blend the + // ink in sooner.) + let ink = |offset: f32, tint: f32| GradientStop { swatch: Some("Ink2".into()), tint, ..GradientStop::new(offset, Color::gray(0.5)) }; + let few = vec![ + GradientStop::new(0.0, Color::gray(0.0)), + GradientStop::new(0.2, Color::gray(0.17)), + GradientStop::new(0.3, Color::gray(0.3)), + ink(0.4, 0.2), + ink(0.5, 0.9), + ink(0.6, 0.2), + GradientStop::new(1.0, Color::gray(1.0)), + ]; + let fitted = Gradient::new(GradientKind::Linear, few).fitted(6).into_owned(); + let offsets: Vec = fitted.stops.iter().map(|s| s.offset).collect(); + assert_eq!(offsets, [0.0, 0.3, 0.4, 0.5, 0.6, 1.0]); + // A Perceptual gradient leaves out the stop its own mixing gives, not the one the RGB line + // gives. + let (blue, yellow, gray) = (Color::rgb(0.0, 0.0, 1.0), Color::rgb(1.0, 1.0, 0.0), Color::rgb(0.5, 0.5, 0.5)); + let on_curve = GradientMethod::Perceptual.mix(&gray, &yellow, 0.5); + let stops = vec![GradientStop::new(0.0, blue), GradientStop::new(0.5, gray), GradientStop::new(0.75, on_curve), GradientStop::new(1.0, yellow)]; + let perceptual = Gradient { method: GradientMethod::Perceptual, ..Gradient::new(GradientKind::Linear, stops) }; + let fitted = perceptual.fitted(3).into_owned(); + let offsets: Vec = fitted.stops.iter().map(|s| s.offset).collect(); + assert_eq!(offsets, [0.0, 0.5, 1.0]); + // A black of other inks between blacks that look the same prints differently: it stays. + let k = |offset: f32| GradientStop::new(offset, Color::Cmyk { c: 1.0, m: 1.0, y: 1.0, k: 1.0 }); + let rich = GradientStop::new(0.5, Color::Cmyk { c: 0.6, m: 0.4, y: 0.4, k: 1.0 }); + let blacks = vec![k(0.0), k(0.4), rich, k(0.6), k(1.0)]; + let fitted = Gradient::new(GradientKind::Linear, blacks).fitted(3).into_owned(); + let offsets: Vec = fitted.stops.iter().map(|s| s.offset).collect(); + assert_eq!(offsets, [0.0, 0.5, 1.0]); + let spread = Gradient { spread: GradientSpread::Repeat, repeats: 4, ..g.clone() }; + let u = spread.unrolled_within(128); + assert_eq!(u.stops.iter().filter(|s| s.swatch.as_deref() == Some("Ink")).count(), 4, "one linked stop a run"); +} + +/// Pixels (what the canvas draws a diamond, dithered or Perceptual gradient as, and what SVG and +/// PDF write as images) repeat with the stops, for each kind. +#[test] +fn pixels_repeat_and_reflect_for_every_kind() { + let b = Rect::new(0.0, 0.0, 40.0, 40.0); + let c = Point::new(20.0, 20.0); + for kind in [GradientKind::Linear, GradientKind::Radial, GradientKind::Conic, GradientKind::Diamond] { + for sp in [GradientSpread::Repeat, GradientSpread::Reflect] { + for method in [GradientMethod::Classic, GradientMethod::Perceptual] { + let mut g = GradientPaint::new(Gradient { spread: sp, repeats: 3, method, ..Gradient::new(kind, Gradient::default().stops) }); + let geom = if kind == GradientKind::Linear { + GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(40.0, 10.0), aspect: 1.0, focal: None } + } else { + GradientGeom { start: c, end: c + Vec2::new(18.0, 4.0), aspect: 0.8, focal: None } + }; + g.geom = Some(geom); + let px: Vec<[u8; 4]> = g.pixels(b, b, 40, 40, false, &Color::to_rgb).collect(); + for (i, got) in px.iter().enumerate().step_by(37) { + let p = Point::new((i % 40) as f64 + 0.5, (i / 40) as f64 + 0.5); + let t = g.gradient.spread_param(geom.param_at(kind, p)); + // Not where Repeat jumps from the last stop back to the first. + if sp == GradientSpread::Repeat && !(0.03..0.97).contains(&t) { + continue; + } + let want = g.gradient.sample(t as f32).0.to_rgba8(1.0); + assert!(got[0].abs_diff(want[0]) <= 2, "{kind:?} {sp:?} {method:?} {p:?}: {got:?} vs {want:?}"); + } + } + } + } +} + +/// A conic gradient's wedges: as many for each time the stops run around as for one turn, at most +/// so many. +#[test] +fn conic_wedges_count_each_run() { + let g = spread(GradientKind::Conic, GradientSpread::Repeat, 4); + assert_eq!(g.conic_wedge_count(360), 1440); + assert_eq!(spread(GradientKind::Conic, GradientSpread::Pad, 4).conic_wedge_count(360), 360); + assert_eq!(spread(GradientKind::Conic, GradientSpread::Reflect, MAX_REPEATS).conic_wedge_count(360), crate::gradient::MAX_CONIC_WEDGES); +} diff --git a/crates/color/src/gradient/tests.rs b/crates/color/src/gradient/tests.rs index c8d0a4bb64..cd25753a05 100644 --- a/crates/color/src/gradient/tests.rs +++ b/crates/color/src/gradient/tests.rs @@ -514,6 +514,283 @@ fn perceptual_gradients_draw_as_pixels() { } } +fn two_stops(a: Color, b: Color, method: GradientMethod) -> Gradient { + let mut g = Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, a), GradientStop::new(1.0, b)]); + g.method = method; + g +} + +/// The hue methods mix around the hue wheel in one direction: Hue Counterclockwise raises the +/// hue angle from each stop to the next and Hue Clockwise lowers it, by the fixed-direction rules +/// of (the angles below are that +/// section's own examples), with saturation and brightness changing evenly. +#[test] +fn hue_methods_turn_one_way_around_the_wheel() { + let (red, blue) = (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0)); + let rising = two_stops(red, blue, GradientMethod::HueCounterclockwise); + assert_eq!(rising.sample(0.0).0.to_hex(), "#ff0000"); + assert_eq!(rising.sample(0.25).0.to_hex(), "#ffff00", "60°"); + assert_eq!(rising.sample(0.5).0.to_hex(), "#00ff00", "120°"); + assert_eq!(rising.sample(1.0).0.to_hex(), "#0000ff"); + let falling = two_stops(red, blue, GradientMethod::HueClockwise); + assert_eq!(falling.sample(0.0).0.to_hex(), "#ff0000"); + assert_eq!(falling.sample(0.5).0.to_hex(), "#ff00ff", "300°"); + assert_eq!(falling.sample(1.0).0.to_hex(), "#0000ff"); + assert_eq!(two_stops(red, blue, GradientMethod::Classic).sample(0.5).0.to_rgb(), [0.5, 0.0, 0.5], "classic: the RGB mix"); + // 30° to 190° and to 230°: halfway is 110° and 130° rising, 290° and 310° falling. + for (to, up, down) in [(190.0, 110.0, 290.0), (230.0, 130.0, 310.0)] { + let (a, b) = (Color::from_hsb(30.0, 0.5, 0.8), Color::from_hsb(to, 0.9, 0.4)); + for (method, want) in [(GradientMethod::HueCounterclockwise, up), (GradientMethod::HueClockwise, down)] { + let [h, s, v] = method.mix(&a, &b, 0.5).to_hsb(); + assert!((h - want).abs() < 0.05, "{method:?} to {to}: hue {h}, not {want}"); + assert!((s - 0.7).abs() < 1e-3 && (v - 0.6).abs() < 1e-3, "{method:?}: saturation {s}, brightness {v}"); + } + } + // The other way round, each method takes the arc the other took. + let back = two_stops(blue, red, GradientMethod::HueClockwise); + assert_eq!(back.sample(0.5).0.to_hex(), "#00ff00"); + // A position that is not a number gives the first color. + assert_eq!(hue_mix(&red, &blue, f32::NAN, true).to_hex(), "#ff0000"); +} + +/// A color without a hue does not turn the wheel: a gray takes the hue of the stop it mixes +/// with, black its saturation too, two grays mix as grays, and two stops of one hue keep that +/// hue, whichever way the method turns. +#[test] +fn hue_methods_keep_the_hue_where_a_stop_has_none() { + let red = Color::rgb(1.0, 0.0, 0.0); + let close = |c: Color, want: [f32; 3], what: &str| { + let got = c.to_rgb(); + assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() < 1e-3), "{what}: {got:?}, not {want:?}"); + }; + let green = Color::rgb(0.0, 1.0, 0.0); + for method in [GradientMethod::HueClockwise, GradientMethod::HueCounterclockwise] { + close(method.mix(&Color::WHITE, &green, 0.5), [0.5, 1.0, 0.5], "white to green: a light green"); + close(method.mix(&green, &Color::WHITE, 0.5), [0.5, 1.0, 0.5], "green to white: a light green"); + close(method.mix(&Color::rgb(0.5, 0.5, 0.5), &green, 0.5), [0.375, 0.75, 0.375], "gray to green"); + close(method.mix(&Color::BLACK, &green, 0.5), [0.0, 0.5, 0.0], "black to green: a dark green, not a gray green"); + close(method.mix(&green, &Color::BLACK, 0.25), [0.0, 0.75, 0.0], "green to black"); + close(method.mix(&Color::BLACK, &Color::WHITE, 0.5), [0.5, 0.5, 0.5], "black to white: gray"); + close(method.mix(&Color::BLACK, &Color::BLACK, 0.5), [0.0, 0.0, 0.0], "black to black"); + let dark = Color::rgb(0.5, 0.0, 0.0); + close(method.mix(&red, &dark, 0.5), [0.75, 0.0, 0.0], "one hue: a red between the two"); + close(method.mix(&red, &red, 0.5), [1.0, 0.0, 0.0], "one color stays"); + // One hue with saturation and brightness both changing: the hue stays, and the color is + // the even mix of saturation and brightness, which is not Classic's RGB mix. + let pink = Color::rgb(1.0, 0.8, 0.8); + close(method.mix(&dark, &pink, 0.5), [0.75, 0.3, 0.3], "dark red to pink"); + assert!((Color::lerp(&dark, &pink, 0.5).to_rgb()[1] - 0.4).abs() < 1e-3, "classic differs"); + // A color whose RGB numbers are under half a color level apart has no hue of its own: a + // near gray leaning blue takes green's hue rather than turning from blue. + let near_gray = Color::rgb(0.5, 0.5, 0.5 + 0.3 / 255.0); + let [h, _, _] = method.mix(&near_gray, &green, 0.5).to_hsb(); + assert!((h - 120.0).abs() < 0.5, "{method:?}: near gray to green passes hue {h}"); + // One a whole color level apart has its hue (240°) and turns from it. + let bluish = Color::rgb(128.0 / 255.0, 128.0 / 255.0, 129.0 / 255.0); + let [h, _, _] = method.mix(&bluish, &green, 0.5).to_hsb(); + let want = if method == GradientMethod::HueClockwise { 180.0 } else { 0.0 }; + assert!(((h - want + 180.0).rem_euclid(360.0) - 180.0).abs() < 0.5, "{method:?}: bluish gray to green passes hue {h}, not {want}"); + } +} + +/// Hues that differ only by rounding are one hue: a color and a tint or shade of it, whose +/// computed hue angles differ in their last digits, mix without turning the wheel, with either +/// method, and a stop added to a ramp leaves the ramp's colors as they were. Hues a whole color +/// level apart still turn. +#[test] +fn hue_methods_take_hues_within_half_a_color_level_as_one() { + let level = |n: u8| f32::from(n) / 255.0; + let rgb8 = |r: u8, g: u8, b: u8| Color::rgb(level(r), level(g), level(b)); + let methods = [GradientMethod::HueClockwise, GradientMethod::HueCounterclockwise]; + // Colors against their 50% tint toward white and a shade at 40% brightness. At least one + // pair's computed hues differ, or the test checks nothing. + let colors = [rgb8(60, 253, 230), rgb8(241, 194, 107), rgb8(68, 32, 130), rgb8(13, 200, 77), rgb8(250, 3, 201), rgb8(90, 91, 200)]; + let mut uneven = 0; + for c in colors { + let [h, s, v] = c.to_hsb(); + let tint = Color::lerp(&c, &Color::WHITE, 0.5); + let shade = Color::from_hsb(h, s, v * 0.4); + for other in [tint, shade] { + let [h1, _, _] = other.to_hsb(); + assert!((h1 - h).abs() < 0.01, "{c:?} and {other:?} are one hue: {h} and {h1}"); + uneven += usize::from(h1 != h); + for method in methods { + for (a, b) in [(c, other), (other, c)] { + for k in 0..=20 { + let [hm, _, _] = method.mix(&a, &b, k as f32 / 20.0).to_hsb(); + let off = (hm - h + 180.0).rem_euclid(360.0) - 180.0; + assert!(off.abs() < 0.5, "{method:?} {a:?} → {b:?} at {k}/20: hue {hm}, not {h}"); + } + } + } + } + } + assert!(uneven > 0, "no pair's hues differ by rounding"); + // Across 0°: 359.99° and 0.01° are one hue too. + for method in methods { + let [h, _, _] = method.mix(&Color::from_hsb(359.99, 1.0, 1.0), &Color::from_hsb(0.01, 1.0, 1.0), 0.5).to_hsb(); + assert!(!(1.0..=359.0).contains(&h), "{method:?} across 0°: {h}"); + } + // A stop added to a ramp samples the ramp's color there, and the ramp keeps its colors: + // white to red, a color to its tint, and a turn from red to blue. + let ramps = [ + (Color::WHITE, rgb8(255, 0, 0)), + (rgb8(60, 253, 230), Color::lerp(&rgb8(60, 253, 230), &Color::WHITE, 0.5)), + (rgb8(255, 0, 0), rgb8(0, 0, 255)), + ]; + for method in methods { + for (a, b) in ramps { + let g = two_stops(a, b, method); + for at in [0.21, 0.5, 0.83] { + let (stops, i) = insert_stop(&g, at); + assert_eq!((stops.len(), i), (3, 1)); + let with = Gradient { stops, ..g.clone() }; + for k in 0..=200 { + let t = k as f32 / 200.0; + let (was, now) = (g.sample(t).0.to_rgb(), with.sample(t).0.to_rgb()); + let off = was.iter().zip(now).map(|(x, y)| (x - y).abs()).fold(0.0, f32::max); + assert!(off < 1.0 / 255.0, "{method:?} {a:?} → {b:?}, a stop at {at}: {was:?} became {now:?} at {t}"); + } + } + } + } + // One color level of hue is a hue of its own: red to a red one level toward yellow turns + // nearly the whole wheel one way and stays put the other. + let (red, next) = (rgb8(255, 0, 0), rgb8(255, 1, 0)); + let [h, _, _] = GradientMethod::HueClockwise.mix(&red, &next, 0.5).to_hsb(); + assert!((h - 180.0).abs() < 1.0, "the long way: {h}"); + let [h, _, _] = GradientMethod::HueCounterclockwise.mix(&red, &next, 0.5).to_hsb(); + assert!(h < 1.0, "the short way: {h}"); +} + +/// Renderers mix linearly between stops: a hue segment becomes stops on its way around the +/// wheel, close enough that the linear ramp between them stays within half a color level of it, +/// through the midpoint and with the opacity changing evenly. +#[test] +fn hue_segments_expand_into_stops_on_the_curve() { + let pairs = [ + (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0)), + (Color::rgb(1.0, 0.0, 0.0), Color::rgb(1.0, 0.02, 0.0)), + (Color::from_hsb(30.0, 0.5, 0.8), Color::from_hsb(190.0, 0.9, 0.4)), + (Color::cmyk(0.0, 0.9, 0.9, 0.0), Color::WHITE), + (Color::BLACK, Color::rgb(0.0, 1.0, 0.0)), + ]; + for method in [GradientMethod::HueClockwise, GradientMethod::HueCounterclockwise] { + for (a, b) in pairs { + let mut g = two_stops(a, b, method); + g.stops[0].midpoint = 0.3; + g.stops[1].opacity = 0.5; + let ex: Vec<_> = g.expanded().collect(); + assert!((3..=600).contains(&ex.len()), "{method:?} {a:?} → {b:?}: {} stops", ex.len()); + assert!(ex.windows(2).all(|w| w[0].0 < w[1].0), "in order"); + assert!(ex.iter().any(|s| s.3 == Some(0.3) && (s.0 - 0.3).abs() < 1e-6), "a stop stands for the midpoint"); + let ramp = Ramp::new(&g, &Color::to_rgb); + for k in 0..=4000 { + let t = k as f32 / 4000.0; + let (c, o) = g.sample(t); + let [r, gr, bl] = c.to_rgb(); + let off = [r, gr, bl, o].iter().zip(ramp.at(t)).map(|(x, y)| (x - y).abs()).fold(0.0, f32::max); + assert!(off < 0.5 / 255.0, "{method:?} {a:?} → {b:?} at {t}: {off}"); + } + assert_eq!(g.sample_keep_model(0.4), g.sample(0.4), "one mix"); + } + } +} + +/// Reversing a gradient gives the same ramp the other way round: a hue method turns the other +/// way with the stops, so every color keeps its place mirrored, and reversing twice gives the +/// gradient back. Classic and Perceptual keep their method. A backward span and the curve as a +/// Classic gradient hold the same colors. +#[test] +fn reversing_a_hue_gradient_keeps_its_colors_mirrored() { + let near = |a: Color, b: Color, what: &str| { + assert!(a.to_rgb().iter().zip(b.to_rgb()).all(|(x, y)| (x - y).abs() < 1.0 / 255.0), "{what}: {a:?} vs {b:?}"); + }; + for (method, other) in + [(GradientMethod::HueClockwise, GradientMethod::HueCounterclockwise), (GradientMethod::HueCounterclockwise, GradientMethod::HueClockwise)] + { + let mut g = Gradient::new( + GradientKind::Linear, + vec![ + GradientStop { midpoint: 0.3, ..GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)) }, + GradientStop { opacity: 0.5, ..GradientStop::new(0.6, Color::rgb(0.0, 0.0, 1.0)) }, + GradientStop::new(1.0, Color::rgb(0.9, 0.8, 0.1)), + ], + ); + g.method = method; + let mut back = g.clone(); + back.reverse(); + assert_eq!(back.method, other); + let (span, curve) = (g.span(1.0, 0.0), g.as_classic_curve()); + assert!(span.method.is_classic() && curve.method.is_classic()); + assert!(curve.stops.len() > g.stops.len() && curve.stops.iter().all(|s| s.swatch.is_none() && s.midpoint == 0.5)); + for k in 0..=400 { + let t = k as f32 / 400.0; + let (want, opacity) = g.sample(1.0 - t); + near(want, back.sample(t).0, &format!("{method:?} reversed at {t}")); + assert!((opacity - back.sample(t).1).abs() < 1e-4, "{method:?} opacity at {t}"); + near(want, span.sample(t).0, &format!("{method:?} backward span at {t}")); + near(g.sample(t).0, curve.sample(t).0, &format!("{method:?} curve at {t}")); + } + back.reverse(); + assert_eq!(back.method, method); + assert_eq!(back.stops.len(), g.stops.len()); + } + for method in [GradientMethod::Classic, GradientMethod::Perceptual] { + assert_eq!(method.mirrored(), method); + let mut g = blue_yellow(method); + g.reverse(); + assert_eq!(g.method, method); + } +} + +/// The hue methods are written by name, read back, and parsed from their param names; their +/// gradients draw as pixels in SVG and PDF, and are not mixes of the stops' inks. +#[test] +fn hue_methods_save_parse_and_draw_as_pixels() { + for (method, name, id) in [ + (GradientMethod::HueClockwise, "HueClockwise", "hue-clockwise"), + (GradientMethod::HueCounterclockwise, "HueCounterclockwise", "hue-counterclockwise"), + ] { + let g = two_stops(Color::cmyk(0.0, 1.0, 1.0, 0.0), Color::cmyk(1.0, 1.0, 0.0, 0.0), method); + let v = serde_json::to_value(&g).unwrap(); + assert_eq!(v["method"], name); + assert_eq!(serde_json::from_value::(v).unwrap(), g); + assert_eq!(method.id(), id); + for written in [id.to_string(), id.to_uppercase(), id.replace('-', " "), id.replace('-', "_"), name.to_string(), method.label().to_string()] { + assert_eq!(GradientMethod::parse(&written), Some(method), "{written}"); + } + assert!(method.is_hue() && !method.is_classic()); + let paint = GradientPaint::new(g.clone()); + assert!(paint.draws_as_pixels(true) && paint.draws_as_pixels(false)); + assert!(g.ink_mixes().is_none(), "not mixes of the stops' inks"); + assert!( + paint.ink_pixels(Rect::new(0.0, 0.0, 10.0, 10.0), Rect::new(0.0, 0.0, 10.0, 10.0), 4, 4, true).is_none(), + "an RGB image, not an ink image" + ); + } + assert!(!GradientMethod::Perceptual.is_hue() && !GradientMethod::Classic.is_hue()); + for (id, method) in [("classic", GradientMethod::Classic), ("perceptual", GradientMethod::Perceptual)] { + assert_eq!(method.id(), id); + assert_eq!(GradientMethod::parse(id), Some(method)); + } + for bad in [ + "hue", + "clockwise", + "hue-", + "", + "hue clockwise wise", + "c-l-a-s-s-i-c", + "per ceptual", + "hue--clockwise", + "hue-clock_wise", + " classic", + "hue- clockwise", + ] { + assert_eq!(GradientMethod::parse(bad), None, "{bad}"); + } +} + /// A Perceptual gradient of an ink's tints as tints: its stops keep their tints, and each tint on /// the curve has the lightness of the color mixed there, so the tints between the stops are not /// a straight line. @@ -880,3 +1157,177 @@ fn conic_pixels_follow_the_sweep() { let many = GradientPaint { gradient: Gradient::new(GradientKind::Conic, many), ..g }; assert_eq!(many.pixels(b, b, 4, 4, true, &Color::to_rgb).count(), 16); } + +/// A diamond placed at `center` with its vector `dx` long to the right and aspect `aspect`. +fn diamond_at(center: Point, dx: f64, aspect: f64) -> GradientGeom { + GradientGeom { start: center, end: center + Vec2::new(dx, 0.0), aspect, focal: None } +} + +#[test] +fn a_diamond_runs_from_its_center_out_to_a_square_with_a_corner_at_the_end_of_its_vector() { + let g = diamond_at(Point::new(100.0, 100.0), 50.0, 1.0); + let t = |x: f64, y: f64| g.param_at(GradientKind::Diamond, Point::new(x, y)); + assert!(t(100.0, 100.0).abs() < 1e-12); + // The square's corners: at the end of the vector and a quarter turn on from it each way. + for (x, y) in [(150.0, 100.0), (100.0, 150.0), (50.0, 100.0), (100.0, 50.0)] { + assert!((t(x, y) - 1.0).abs() < 1e-12, "({x}, {y})"); + } + // Halfway along an edge, and halfway out along a diagonal (the middle of the edge's half size). + assert!((t(125.0, 125.0) - 1.0).abs() < 1e-12); + assert!((t(112.5, 87.5) - 0.5).abs() < 1e-12); + // Past the square: more than 1 (the last stop pads on). + assert!((t(200.0, 200.0) - 4.0).abs() < 1e-12); + // The aspect stretches the square across the vector into a rhombus. + let tall = diamond_at(Point::new(100.0, 100.0), 50.0, 2.0); + assert!((tall.param_at(GradientKind::Diamond, Point::new(100.0, 200.0)) - 1.0).abs() < 1e-12); + assert!((tall.param_at(GradientKind::Diamond, Point::new(150.0, 100.0)) - 1.0).abs() < 1e-12); + // Turned: the corner follows the vector. + let turned = GradientGeom { end: Point::new(130.0, 140.0), ..g }; + assert!((turned.param_at(GradientKind::Diamond, Point::new(130.0, 140.0)) - 1.0).abs() < 1e-12); + assert!((turned.param_at(GradientKind::Diamond, Point::new(115.0, 120.0)) - 0.5).abs() < 1e-12); +} + +#[test] +fn diamond_kind_names_and_fit() { + for s in ["diamond", "Diamond", "DIAMOND"] { + assert_eq!(GradientKind::parse(s), Some(GradientKind::Diamond), "{s}"); + } + assert_eq!(GradientKind::Diamond.label(), "Diamond"); + assert!(GradientKind::Diamond.is_centered()); + assert!(GradientKind::ALL.contains(&GradientKind::Diamond)); + // Level: the square's edges pass through the box's corners, so it covers the box exactly. + let b = Rect::new(0.0, 0.0, 200.0, 100.0); + let fit = GradientGeom::fit(GradientKind::Diamond, b, 0.0); + assert_eq!(fit.start, Point::new(100.0, 50.0)); + assert!(fit.end.distance(Point::new(250.0, 50.0)) < 1e-9, "{fit:?}"); + for c in [Point::new(0.0, 0.0), Point::new(200.0, 0.0), Point::new(200.0, 100.0), Point::new(0.0, 100.0)] { + assert!((fit.param_at(GradientKind::Diamond, c) - 1.0).abs() < 1e-9, "{c:?}"); + } + // At any angle the square covers the box and runs through its farthest corner, on a square + // box too. + for b in [b, Rect::new(0.0, 0.0, 100.0, 100.0)] { + for angle in [30.0, 45.0, 90.0, -120.0] { + let fit = GradientGeom::fit(GradientKind::Diamond, b, angle); + let levels = [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1)] + .map(|c| fit.param_at(GradientKind::Diamond, c)); + assert!(levels.iter().all(|&t| t <= 1.0 + 1e-9), "{angle}: {levels:?}"); + assert!(levels.iter().any(|&t| (t - 1.0).abs() < 1e-9), "{angle}: {levels:?}"); + } + } +} + +#[test] +fn a_diamond_follows_moves_turns_scales_and_mirrors() { + let c = Point::new(10.0, 20.0); + let g0 = diamond_at(c, 30.0, 0.5); + let probes = [c + Vec2::new(5.0, 7.0), c + Vec2::new(-9.0, 2.0), c + Vec2::new(3.0, -11.0), c + Vec2::new(-20.0, -4.0)]; + for a in [ + Affine::rotate(0.7), + Affine::scale(2.5), + Affine::translate((4.0, -9.0)) * Affine::rotate(-2.0), + Affine::FLIP_X, + Affine::FLIP_Y * Affine::rotate(1.1), + // Along and across the vector. + Affine::scale_non_uniform(2.0, 0.5), + Affine::scale_non_uniform(-3.0, 0.25), + ] { + let mut g = g0; + g.transform(a, GradientKind::Diamond); + assert!(g.start.distance(a * c) < 1e-9, "{a:?}"); + // A mirror changes nothing a diamond shows: its aspect stays a size. + assert!(g.aspect > 0.0, "{a:?}: {g:?}"); + for p in probes { + let (want, got) = (g0.param_at(GradientKind::Diamond, p), g.param_at(GradientKind::Diamond, a * p)); + assert!((want - got).abs() < 1e-9, "{a:?} at {p:?}: {want} vs {got}"); + } + } + // Under a shear the corner stays where the vector maps. + let shear = Affine::new([1.0, 0.0, 0.6, 1.0, 0.0, 0.0]); + let mut g = g0; + g.transform(shear, GradientKind::Diamond); + assert!((g.param_at(GradientKind::Diamond, shear * (c + Vec2::new(30.0, 0.0))) - 1.0).abs() < 1e-9, "{g:?}"); + // Out-of-range numbers: a finite aspect after any transform. + for bad in [diamond_at(c, 30.0, f64::NAN), diamond_at(c, f64::INFINITY, 1.0), diamond_at(c, 0.0, 1.0)] { + let mut g = bad; + g.transform(Affine::rotate(0.4), GradientKind::Diamond); + assert!(g.aspect.is_finite(), "{g:?}"); + } +} + +/// A diamond without a frame (no vector, a flat or a not-finite extent) has no inside: every +/// point is past its edge and takes the last stop. Points that aren't numbers do too. +#[test] +fn a_diamond_with_no_extent_or_bad_numbers_is_its_last_stop() { + let c = Point::new(50.0, 50.0); + for g in [ + diamond_at(c, 0.0, 1.0), + diamond_at(c, 30.0, 0.0), + diamond_at(c, 30.0, f64::NAN), + diamond_at(c, f64::INFINITY, 1.0), + GradientGeom { start: Point::new(f64::NAN, 0.0), ..diamond_at(c, 30.0, 1.0) }, + ] { + assert!(g.diamond_frame().is_none(), "{g:?}"); + assert!(g.diamond_quadrants(Rect::new(0.0, 0.0, 100.0, 100.0)).is_none(), "{g:?}"); + assert_eq!(g.param_at(GradientKind::Diamond, Point::new(60.0, 40.0)), 1.0, "{g:?}"); + } + let g = diamond_at(c, 30.0, 1.0); + assert_eq!(g.param_at(GradientKind::Diamond, Point::new(f64::NAN, 1.0)), 1.0); + assert!(g.param_at(GradientKind::Diamond, Point::new(f64::INFINITY, 1.0)) >= 1.0); +} + +/// The four linear gradients a format without diamond gradients gets, drawn in order, equal the +/// diamond everywhere, and each edge drawn lies on the quadrant drawn before it. +#[test] +fn diamond_quadrants_are_linear_gradients_that_equal_the_diamond() { + let b = Rect::new(0.0, 0.0, 200.0, 100.0); + let probes: Vec = (0..=20).flat_map(|i| (0..=10).map(move |j| Point::new(i as f64 * 10.0 + 0.3, j as f64 * 10.0 + 0.7))).collect(); + // Squashed and turned, stretched twice as tall as wide, and stretched by a shear. + let mut turned = diamond_at(Point::new(60.0, 40.0), 30.0, 0.5); + turned.transform(Affine::rotate_about(0.4, Point::new(60.0, 40.0)), GradientKind::Diamond); + let mut sheared = diamond_at(Point::new(90.0, 50.0), 25.0, 1.0); + sheared.transform(Affine::new([2.0, 0.0, 0.7, 1.0, -60.0, 0.0]), GradientKind::Diamond); + for g in [turned, diamond_at(Point::new(100.0, 50.0), 20.0, 2.0), sheared] { + let quadrants = g.diamond_quadrants(b).expect("a frame"); + for p in &probes { + // The last quadrant drawn that holds the point paints it. + let Some((_, linear)) = quadrants.iter().rev().find(|(poly, _)| inside(poly, *p)) else { panic!("{p:?} is in no quadrant") }; + let (want, got) = (g.param_at(GradientKind::Diamond, *p), linear.param_at(GradientKind::Linear, *p)); + assert!((want - got).abs() < 1e-9, "{g:?} at {p:?}: {want} vs {got}"); + } + } + let g = turned; + let quadrants = g.diamond_quadrants(b).expect("a frame"); + // Next to each edge of a quadrant drawn later, on either side, the quadrant drawn before it + // lies underneath (the first quadrant's edges are covered by the second and the last). + let frame = g.diamond_frame().expect("a frame"); + for (unit, under) in [ + // The second quadrant's first edge, on the first. + (Point::new(0.01, 0.5), 0), + (Point::new(-0.01, 0.5), 0), + // The third's, on the second. + (Point::new(-0.5, 0.01), 1), + (Point::new(-0.5, -0.01), 1), + // The last's two, on the third and on the first. + (Point::new(-0.01, -0.5), 2), + (Point::new(0.01, -0.5), 2), + (Point::new(0.5, -0.01), 0), + (Point::new(0.5, 0.01), 0), + ] { + assert!(inside(&quadrants[under].0, frame * unit), "{unit:?} lies on quadrant {under}"); + } +} + +/// A diamond's pixels (what SVG and PDF draw a dithered or Perceptual one as, and what the canvas +/// draws) follow the squares. +#[test] +fn diamond_pixels_follow_the_squares() { + let b = Rect::new(0.0, 0.0, 5.0, 5.0); + let mut g = GradientPaint::new(Gradient::new(GradientKind::Diamond, Gradient::default().stops)); + g.geom = Some(diamond_at(Point::new(2.5, 2.5), 2.5, 1.0)); + let px: Vec<[u8; 4]> = g.pixels(b, b, 5, 5, false, &Color::to_rgb).collect(); + // White at the center, black in the corners, and the same on each side of it. + assert!(px[2 * 5 + 2][0] > 200 && px[0][0] < 10 && px[24][0] < 10, "{px:?}"); + assert_eq!(px[2 * 5 + 1], px[2 * 5 + 3]); + assert_eq!(px[5 + 2], px[3 * 5 + 2]); + assert_eq!(px[2 * 5 + 1], px[5 + 2]); +} diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs index 03e7dc10e7..3afca8063c 100644 --- a/crates/color/src/lib.rs +++ b/crates/color/src/lib.rs @@ -16,7 +16,7 @@ pub mod swatch; pub use blend::BlendMode; pub use freeform::{Freeform, FreeformMode, FreeformPoint}; -pub use gradient::{Gradient, GradientGeom, GradientKind, GradientMethod, GradientPaint, GradientStop}; +pub use gradient::{Gradient, GradientGeom, GradientKind, GradientMethod, GradientPaint, GradientSpread, GradientStop}; pub use libraries::SwatchLibrary; pub use swatch::{Swatch, SwatchGroup, default_swatches}; @@ -102,12 +102,13 @@ impl Color { pub fn to_lab(&self) -> cms::Lab { cms::active().lab(self) } - /// Colour-managed CMYK in the working CMYK space with `intent` (see [`Color::to_cmyk`] for the - /// profile-free formula). + /// Color-managed CMYK in the active CMYK space (the front document's assigned CMYK profile, else + /// the working CMYK space) with `intent` (see [`Color::to_cmyk`] for the profile-free formula). pub fn to_cmyk_managed(&self, intent: cms::Intent) -> [f32; 4] { cms::active().to_cmyk(self, intent) } - /// Gamut warning: true when this colour can't be reproduced in the working CMYK space. + /// Gamut warning: true when this color can't be reproduced in the active CMYK space (the front + /// document's assigned CMYK profile, else the working CMYK space). pub fn out_of_gamut(&self) -> bool { cms::active().out_of_gamut(self) } diff --git a/crates/color/src/libraries.rs b/crates/color/src/libraries.rs index e96760d5c5..5fc952a061 100644 --- a/crates/color/src/libraries.rs +++ b/crates/color/src/libraries.rs @@ -9,7 +9,7 @@ use std::sync::{Arc, OnceLock}; use serde::{Deserialize, Serialize}; -use crate::{Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint, Swatch, SwatchGroup}; +use crate::{Color, Gradient, GradientKind, GradientMethod, GradientPaint, GradientStop, Paint, Swatch, SwatchGroup}; /// A library: its name, its ungrouped swatches and its colour groups. #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] @@ -72,6 +72,8 @@ pub const GRADIENT_LIBRARIES: &[BuiltinLibrary] = &[ lib!("spectrum-gradients", "Spectrum Gradients", spectrum_gradients), lib!("sky-gradients", "Sky Gradients", sky_gradients), lib!("neutral-gradients", "Neutral Gradients", neutral_gradients), + lib!("organic-fades", "Organic Fades", organic_fades), + lib!("holographic", "Holographic", holographic), lib!("duotone-gradients", "Duotone Gradients", duotone_gradients), lib!("radial-glows", "Radial Glows", radial_glows), ]; @@ -179,6 +181,14 @@ pub(crate) fn gradient(name: &str, kind: GradientKind, stops: &[(f32, Color, f32 Swatch { name: name.into(), paint: Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(kind, stops)))), global: false, spot: false } } +/// A gradient swatch mixed by `method` through `stops` of (offset, color, opacity, midpoint). +fn gradient_with(name: &str, kind: GradientKind, method: GradientMethod, stops: &[(f32, Color, f32, f32)]) -> Swatch { + let stops = + stops.iter().map(|&(offset, color, opacity, midpoint)| GradientStop { opacity, midpoint, ..GradientStop::new(offset, color) }).collect(); + let gradient = Gradient { method, ..Gradient::new(kind, stops) }; + Swatch { name: name.into(), paint: Paint::Gradient(Box::new(GradientPaint::new(gradient))), global: false, spot: false } +} + /// `n` steps of OKLCH lightness from `l0` to `l1`, chroma `c(t)` and hue `h(t)` (`t` in 0..=1), /// named "`name` 1"… fn ramp(name: &str, n: usize, (l0, l1): (f64, f64), c: impl Fn(f64) -> f64, h: impl Fn(f64) -> f64) -> SwatchGroup { @@ -387,6 +397,197 @@ fn radial_glows() -> (Vec, Vec) { (s, vec![]) } +/// A stop of [`organic_fades`]: offset, OKLCH `(l, c, h°)`, opacity and midpoint. +type FadeStop = (f32, (f64, f64, f64), f32, f32); + +/// Soft fades through a few unevenly spaced stops with off-center midpoints, mixed perceptually, +/// that thin out to transparent: at the end of the linear ones and at the edge of the radial ones. +fn organic_fades() -> (Vec, Vec) { + use GradientKind::{Linear, Radial}; + let fades: [(&str, GradientKind, &[FadeStop]); 15] = [ + ( + "Mist", + Linear, + &[ + (0.0, (0.94, 0.012, 240.0), 1.0, 0.38), + (0.35, (0.86, 0.03, 235.0), 0.85, 0.62), + (0.7, (0.8, 0.035, 230.0), 0.4, 0.45), + (1.0, (0.78, 0.035, 230.0), 0.0, 0.5), + ], + ), + ( + "Petal", + Linear, + &[ + (0.0, (0.82, 0.09, 350.0), 1.0, 0.42), + (0.28, (0.88, 0.07, 10.0), 0.9, 0.66), + (0.64, (0.93, 0.04, 30.0), 0.45, 0.35), + (1.0, (0.95, 0.03, 40.0), 0.0, 0.5), + ], + ), + ("Fern", Linear, &[(0.0, (0.52, 0.1, 145.0), 1.0, 0.6), (0.4, (0.68, 0.11, 135.0), 0.75, 0.4), (1.0, (0.85, 0.08, 120.0), 0.0, 0.5)]), + ( + "Smoke", + Linear, + &[ + (0.0, (0.35, 0.01, 260.0), 1.0, 0.3), + (0.22, (0.48, 0.012, 255.0), 0.8, 0.58), + (0.58, (0.62, 0.01, 250.0), 0.35, 0.7), + (1.0, (0.72, 0.008, 250.0), 0.0, 0.5), + ], + ), + ( + "Honey", + Linear, + &[ + (0.0, (0.72, 0.15, 70.0), 1.0, 0.55), + (0.3, (0.8, 0.14, 80.0), 0.9, 0.35), + (0.75, (0.9, 0.09, 90.0), 0.3, 0.6), + (1.0, (0.95, 0.05, 95.0), 0.0, 0.5), + ], + ), + ("Seafoam", Linear, &[(0.0, (0.7, 0.09, 175.0), 1.0, 0.45), (0.45, (0.84, 0.07, 170.0), 0.6, 0.65), (1.0, (0.95, 0.03, 165.0), 0.0, 0.5)]), + ( + "Lavender", + Linear, + &[ + (0.0, (0.62, 0.12, 300.0), 1.0, 0.36), + (0.3, (0.72, 0.1, 295.0), 0.85, 0.55), + (0.55, (0.82, 0.07, 290.0), 0.5, 0.68), + (0.82, (0.9, 0.04, 285.0), 0.15, 0.4), + (1.0, (0.93, 0.03, 285.0), 0.0, 0.5), + ], + ), + ("Driftwood", Linear, &[(0.0, (0.55, 0.04, 60.0), 1.0, 0.64), (0.38, (0.68, 0.035, 70.0), 0.7, 0.42), (1.0, (0.84, 0.025, 80.0), 0.0, 0.5)]), + ( + "Ink Wash", + Linear, + &[ + (0.0, (0.25, 0.05, 265.0), 1.0, 0.28), + (0.18, (0.35, 0.06, 262.0), 0.9, 0.6), + (0.5, (0.5, 0.05, 258.0), 0.45, 0.72), + (1.0, (0.65, 0.04, 255.0), 0.0, 0.5), + ], + ), + ( + "Tide", + Linear, + &[ + (0.0, (0.45, 0.1, 230.0), 1.0, 0.4), + (0.26, (0.6, 0.1, 215.0), 0.8, 0.62), + (0.72, (0.76, 0.08, 200.0), 0.35, 0.44), + (1.0, (0.88, 0.05, 195.0), 0.0, 0.5), + ], + ), + ( + "Bloom", + Radial, + &[ + (0.0, (0.92, 0.05, 40.0), 1.0, 0.4), + (0.22, (0.8, 0.12, 20.0), 0.95, 0.6), + (0.6, (0.7, 0.14, 355.0), 0.4, 0.35), + (1.0, (0.66, 0.13, 345.0), 0.0, 0.5), + ], + ), + ("Dew", Radial, &[(0.0, (0.97, 0.01, 200.0), 1.0, 0.3), (0.3, (0.88, 0.05, 195.0), 0.7, 0.58), (1.0, (0.8, 0.06, 190.0), 0.0, 0.5)]), + ( + "Pollen", + Radial, + &[ + (0.0, (0.96, 0.08, 100.0), 1.0, 0.45), + (0.18, (0.9, 0.15, 95.0), 1.0, 0.65), + (0.55, (0.82, 0.16, 85.0), 0.5, 0.4), + (1.0, (0.76, 0.15, 75.0), 0.0, 0.5), + ], + ), + // A ring: clear at the center, then a band that fades out to the edge. + ( + "Halo", + Radial, + &[ + (0.0, (0.98, 0.005, 90.0), 0.0, 0.6), + (0.42, (0.95, 0.02, 85.0), 0.0, 0.35), + (0.62, (0.92, 0.04, 80.0), 1.0, 0.55), + (1.0, (0.88, 0.05, 75.0), 0.0, 0.5), + ], + ), + ( + "Lichen", + Radial, + &[ + (0.0, (0.8, 0.07, 120.0), 1.0, 0.58), + (0.35, (0.7, 0.08, 130.0), 0.75, 0.4), + (0.74, (0.6, 0.07, 140.0), 0.25, 0.62), + (1.0, (0.55, 0.06, 145.0), 0.0, 0.5), + ], + ), + ]; + let s = fades + .iter() + .map(|&(name, kind, stops)| { + let stops: Vec<(f32, Color, f32, f32)> = stops.iter().map(|&(at, (l, c, h), opacity, mid)| (at, oklch(l, c, h), opacity, mid)).collect(); + gradient_with(name, kind, GradientMethod::Perceptual, &stops) + }) + .collect(); + (s, vec![]) +} + +/// The stops of a [`holographic`] look: offset, opacity and midpoint toward the next stop. +type Bands = [(f32, f32, f32)]; + +/// Foil: six opaque linear bands, a narrow bright one among them, with off-center midpoints. +const FOIL: &Bands = &[(0.0, 1.0, 0.37), (0.13, 1.0, 0.64), (0.34, 1.0, 0.28), (0.48, 1.0, 0.68), (0.71, 1.0, 0.42), (1.0, 1.0, 0.5)]; + +/// Glow: five radial rings from a bright center out to a clear edge. +const GLOW: &Bands = &[(0.0, 0.95, 0.4), (0.12, 1.0, 0.58), (0.31, 0.72, 0.34), (0.58, 0.3, 0.62), (1.0, 0.0, 0.5)]; + +/// A [`holographic`] look: name, kind, stops and the OKLCH color of each stop in order. +type Look = (&'static str, GradientKind, &'static Bands, Anchors); + +/// Iridescent looks mixed perceptually: linear foils of narrow pastel and pearl bands, and radial +/// glows that fade out to a clear edge. Each color is one stop of [`FOIL`] or [`GLOW`] in order. +fn holographic() -> (Vec, Vec) { + use GradientKind::{Linear, Radial}; + // Pale pearl, pastel and deep-violet OKLCH `(l, c, h°)` anchors. + const PEARL: (f64, f64, f64) = (0.97, 0.01, 90.0); + const SILVER: (f64, f64, f64) = (0.86, 0.015, 255.0); + const BLUSH: (f64, f64, f64) = (0.82, 0.055, 340.0); + const VIOLET: (f64, f64, f64) = (0.72, 0.1, 310.0); + const BLUE: (f64, f64, f64) = (0.73, 0.09, 255.0); + const CYAN: (f64, f64, f64) = (0.79, 0.09, 210.0); + const MINT: (f64, f64, f64) = (0.82, 0.08, 165.0); + const LIME: (f64, f64, f64) = (0.86, 0.085, 125.0); + const GOLD: (f64, f64, f64) = (0.89, 0.08, 85.0); + const AMBER: (f64, f64, f64) = (0.82, 0.1, 55.0); + const CORAL: (f64, f64, f64) = (0.78, 0.09, 25.0); + const DEEP_VIOLET: (f64, f64, f64) = (0.42, 0.04, 275.0); + let looks: [Look; 14] = [ + ("Prism Veil", Linear, FOIL, &[SILVER, BLUSH, PEARL, CYAN, VIOLET, SILVER]), + ("Opal Ribbon", Linear, FOIL, &[PEARL, MINT, BLUSH, PEARL, BLUE, SILVER]), + ("Pearl Flash", Linear, FOIL, &[SILVER, VIOLET, PEARL, GOLD, CYAN, PEARL]), + ("Aurora Foil", Linear, FOIL, &[BLUE, MINT, PEARL, BLUSH, CYAN, SILVER]), + ("Iris Sheen", Linear, FOIL, &[BLUSH, VIOLET, PEARL, CYAN, MINT, SILVER]), + ("Frost Spectrum", Linear, FOIL, &[CYAN, BLUE, PEARL, MINT, BLUSH, SILVER]), + ("Silver Tide", Linear, FOIL, &[SILVER, CYAN, PEARL, VIOLET, BLUE, SILVER]), + ("Rose Quartz Gleam", Radial, GLOW, &[PEARL, BLUSH, CORAL, VIOLET, BLUSH]), + ("Moonstone Shift", Radial, GLOW, &[PEARL, CYAN, MINT, BLUE, SILVER]), + ("Violet Edge", Radial, GLOW, &[PEARL, VIOLET, BLUSH, BLUE, DEEP_VIOLET]), + ("Mint Halo", Radial, GLOW, &[PEARL, MINT, CYAN, LIME, MINT]), + ("Amber Corona", Radial, GLOW, &[PEARL, GOLD, AMBER, CORAL, AMBER]), + ("Polar Glint", Radial, GLOW, &[PEARL, CYAN, BLUE, VIOLET, BLUE]), + ("Pastel Orbit", Radial, GLOW, &[PEARL, BLUSH, MINT, CYAN, VIOLET]), + ]; + let s = looks + .iter() + .map(|&(name, kind, bands, colors)| { + let stops: Vec<(f32, Color, f32, f32)> = + bands.iter().zip(colors).map(|(&(at, opacity, mid), &(l, c, h))| (at, oklch(l, c, h), opacity, mid)).collect(); + gradient_with(name, kind, GradientMethod::Perceptual, &stops) + }) + .collect(); + (s, vec![]) +} + /// The sequential scales of [`perceptual`]: name and anchors of rising lightness. const SEQUENTIAL: [(&str, Anchors); 5] = [ ("Ember", &[(0.22, 0.10, 300.0), (0.55, 0.18, 30.0), (0.93, 0.15, 100.0)]), @@ -532,6 +733,99 @@ mod tests { let st = &g.gradient.stops; assert!(st.len() >= 2 && st.windows(2).all(|w| w[0].offset <= w[1].offset), "{}", s.name); assert!(st.iter().all(|s| (0.0..=1.0).contains(&s.offset) && (0.0..=1.0).contains(&s.opacity))); + assert!(st.iter().all(|s| (0.01..=0.99).contains(&s.midpoint)), "{}: a midpoint out of range", s.name); + } + } + } + } + + #[test] + fn organic_fades_are_perceptual_multi_stop_fades_to_transparent() { + let lib = builtin_library("organic-fades").unwrap(); + assert_eq!(GRADIENT_LIBRARIES.iter().map(|b| b.name).position(|n| n == "Organic Fades"), Some(3), "after Neutral Gradients"); + assert!(lib.groups.is_empty() && (12..=16).contains(&lib.len()), "{} swatches", lib.len()); + let radial = lib.iter().filter(|s| matches!(&s.paint, Paint::Gradient(g) if g.gradient.kind == GradientKind::Radial)).count(); + assert!(radial >= 3 && radial * 2 <= lib.len(), "{radial} radial of {}", lib.len()); + for s in lib.iter() { + let Paint::Gradient(g) = &s.paint else { panic!("{} is a gradient", s.name) }; + let (g, n) = (&g.gradient, &s.name); + assert_eq!(g.method, GradientMethod::Perceptual, "{n}"); + assert!((3..=5).contains(&g.stops.len()), "{n}: {} stops", g.stops.len()); + assert!(g.stops.windows(2).all(|w| w[0].offset < w[1].offset), "{n}: rising offsets"); + assert_eq!((g.stops[0].offset, g.stops[g.stops.len() - 1].offset), (0.0, 1.0), "{n}"); + // Unevenly spaced: some gap differs from an even step. + let even = 1.0 / (g.stops.len() - 1) as f32; + assert!(g.stops.windows(2).any(|w| (w[1].offset - w[0].offset - even).abs() > 0.02), "{n}: uneven stops"); + // Every segment's midpoint is off center and within the Gradient panel's 13 to 87%. + let segments = &g.stops[..g.stops.len() - 1]; + assert!(segments.iter().all(|st| (st.midpoint - 0.5).abs() > 0.02 && (0.13..=0.87).contains(&st.midpoint)), "{n}: midpoints"); + // Fully opaque somewhere, and clear at the end (the edge of a radial one). + assert!(g.stops.iter().any(|st| st.opacity == 1.0), "{n}: an opaque stop"); + assert_eq!(g.stops[g.stops.len() - 1].opacity, 0.0, "{n}: clear at the end"); + } + } + + #[test] + fn holographic_holds_seven_opaque_foils_and_seven_glows_to_a_clear_edge() { + let lib = builtin_library("holographic").unwrap(); + let order: Vec<&str> = GRADIENT_LIBRARIES.iter().map(|b| b.name).collect(); + assert_eq!(order.iter().position(|n| *n == "Holographic"), Some(4), "after Organic Fades: {order:?}"); + assert!(lib.groups.is_empty()); + assert_eq!(lib.len(), 14); + // No name another built-in gradient has, in any case. + let mut others = std::collections::HashSet::new(); + for other in builtins().filter(|b| b.id != "holographic").map(|b| builtin_library(b.id).unwrap()) { + others.extend(other.iter().filter(|s| matches!(s.paint, Paint::Gradient(_))).map(|s| s.name.to_lowercase())); + } + assert!(lib.iter().all(|s| !others.contains(&s.name.to_lowercase())), "a name another library has"); + let (mut foils, mut glows) = (0, 0); + for s in lib.iter() { + let Paint::Gradient(g) = &s.paint else { panic!("{} is a gradient", s.name) }; + let (g, n) = (&g.gradient, &s.name); + assert_eq!(g.method, GradientMethod::Perceptual, "{n}"); + let bands = match &g.kind { + GradientKind::Linear => { + foils += 1; + FOIL + } + GradientKind::Radial => { + glows += 1; + GLOW + } + kind => panic!("{n}: {kind:?}"), + }; + // Every stop takes its band's offset, opacity and midpoint, and none is dropped. + let shape: Vec<(f32, f32, f32)> = g.stops.iter().map(|st| (st.offset, st.opacity, st.midpoint)).collect(); + assert_eq!(shape, bands, "{n}"); + assert!(g.stops.iter().all(|st| matches!(st.color, Color::Rgb { .. })), "{n}"); + } + assert_eq!((foils, glows), (7, 7)); + // Foils are opaque; a glow is clear at the edge. + assert!(FOIL.iter().all(|&(_, opacity, _)| opacity == 1.0)); + assert_eq!(GLOW.last().map(|b| b.1), Some(0.0)); + // Every segment's midpoint is off center and within the Gradient panel's 13 to 87%. + for bands in [FOIL, GLOW] { + assert!(bands[..bands.len() - 1].iter().all(|&(_, _, m)| (m - 0.5).abs() > 0.02 && (0.13..=0.87).contains(&m))); + assert!(bands.windows(2).all(|w| w[0].0 < w[1].0) && bands[0].0 == 0.0 && bands[bands.len() - 1].0 == 1.0); + } + // Sampled colors: Prism Veil's bright band is the pearl anchor, and Violet Edge ends in deep violet. + let stop = |name: &str, i: usize| match &lib.swatch(name).unwrap().paint { + Paint::Gradient(g) => g.gradient.stops[i].color, + _ => panic!("{name} is a gradient"), + }; + assert_eq!(stop("Prism Veil", 2), oklch(0.97, 0.01, 90.0)); + assert_eq!(stop("Violet Edge", 4), oklch(0.42, 0.04, 275.0)); + let [l, ..] = to_oklab(&stop("Violet Edge", 4)); + assert!(l < 0.5 && to_oklab(&stop("Prism Veil", 2))[0] > 0.95, "{l}"); + } + + #[test] + fn the_other_libraries_keep_classic_mixing_and_centered_midpoints() { + for b in builtins().filter(|b| !["organic-fades", "holographic"].contains(&b.id)) { + for s in builtin_library(b.id).unwrap().iter() { + if let Paint::Gradient(g) = &s.paint { + assert_eq!(g.gradient.method, GradientMethod::Classic, "{}", s.name); + assert!(g.gradient.stops.iter().all(|st| st.midpoint == 0.5), "{}", s.name); } } } diff --git a/crates/color/src/palette_io.rs b/crates/color/src/palette_io.rs index 6be0f2abf5..996c963c11 100644 --- a/crates/color/src/palette_io.rs +++ b/crates/color/src/palette_io.rs @@ -196,8 +196,10 @@ fn write_css(lib: &SwatchLibrary, keep: impl Fn(&&Swatch) -> bool) -> String { let at = if mirrored { 1.0 - s.offset } else { s.offset }; format!("{} {}%", css_color(&s.color, s.opacity), at * 100.0) }; + // Stops that repeat or reflect run that many times across the box. + let unrolled = g.gradient.unrolled(); let stops: Vec = - if mirrored { g.gradient.stops.iter().rev().map(stop).collect() } else { g.gradient.stops.iter().map(stop).collect() }; + if mirrored { unrolled.stops.iter().rev().map(stop).collect() } else { unrolled.stops.iter().map(stop).collect() }; match g.gradient.kind { GradientKind::Radial => format!("radial-gradient(circle, {})", stops.join(", ")), // CSS sweeps clockwise from straight up; the angle is counted counterclockwise @@ -205,6 +207,23 @@ fn write_css(lib: &SwatchLibrary, keep: impl Fn(&&Swatch) -> bool) -> String { GradientKind::Conic => { format!("conic-gradient(from {}deg, {})", (90.0 - g.angle).rem_euclid(360.0).round(), stops.join(", ")) } + // CSS has no diamond gradient: four layers, each a quarter of the box with + // the stops running from the center out to its corner at a diagonal angle, + // make the diamond its fit gives a box of any shape: the level at a point + // is its distance from the center along both axes over the box's + // half-width plus half-height + // (https://www.w3.org/TR/css-images-3/#linear-gradients). Turned by an angle + // that is not a multiple of 90 degrees, its corners leave the box's axes, + // and a circle stands in for it, as for a radial swatch. + GradientKind::Diamond if (1e-9..90.0 - 1e-9).contains(&g.angle.rem_euclid(90.0)) => { + format!("radial-gradient(circle, {})", stops.join(", ")) + } + GradientKind::Diamond => { + let stops = stops.join(", "); + [("top left", 315), ("top right", 45), ("bottom right", 135), ("bottom left", 225)] + .map(|(corner, deg)| format!("linear-gradient({deg}deg, {stops}) {corner} / 50% 50% no-repeat")) + .join(", ") + } _ => format!("linear-gradient({}deg, {})", (90.0 - g.angle).rem_euclid(360.0).round(), stops.join(", ")), } } diff --git a/crates/color/src/palette_io/tests.rs b/crates/color/src/palette_io/tests.rs index 9ee07cb623..f3de69baf9 100644 --- a/crates/color/src/palette_io/tests.rs +++ b/crates/color/src/palette_io/tests.rs @@ -186,6 +186,55 @@ fn css_writes_conic_gradient_swatches() { assert!(text.contains("--back: conic-gradient(from 0deg, #000000 0%, #ffffff 80%);"), "{text}"); } +/// A diamond gradient swatch (CSS has none) is four layered linear gradients, one a quarter of the +/// box running from the center out to its corner, for the `background` shorthand. +#[test] +fn css_writes_diamond_gradient_swatches_as_four_corner_layers() { + let lib = SwatchLibrary { + name: "x".into(), + swatches: vec![Swatch { + name: "Gem".into(), + paint: Paint::Gradient(Box::new(GradientPaint::new(Gradient { kind: GradientKind::Diamond, ..Gradient::default() }))), + global: false, + spot: false, + }], + groups: vec![], + }; + let text = written(&lib, PaletteFormat::Css); + // Diagonal angles, not `to `: on a box that isn't square, `to ` would turn + // each layer's lines to run through the quarter's other two corners. + let layer = |corner: &str, deg: u32| format!("linear-gradient({deg}deg, #ffffff 0%, #000000 100%) {corner} / 50% 50% no-repeat"); + let want = + format!("--gem: {}, {}, {}, {};", layer("top left", 315), layer("top right", 45), layer("bottom right", 135), layer("bottom left", 225)); + assert!(text.contains(&want), "{text}"); + // CSS's gradient line for a diagonal angle on a quarter box w × h is (w + h) / √2 long and + // starts at the quarter's corner at the box's center: the level at a point x, y from the + // center is (|x| + |y|) / (w + h), the level the diamond fitted to the whole box has there. + let (w, h) = (100.0f64, 50.0f64); + let length = (w + h) / std::f64::consts::SQRT_2; + let fit = crate::GradientGeom::fit(GradientKind::Diamond, kurbo::Rect::new(-w, -h, w, h), 0.0); + for (x, y) in [(0.0, -50.0), (-100.0, 0.0), (-30.0, -20.0), (-100.0, -50.0)] { + // The top-left quarter's layer runs toward (-1, -1). + let css = (-x - y) / std::f64::consts::SQRT_2 / length; + let model = fit.param_at(GradientKind::Diamond, kurbo::Point::new(x, y)); + assert!((css - model).abs() < 1e-9, "({x}, {y}): {css} vs {model}"); + } + // Turned a quarter or a half turn, it is the same diamond; turned 30 degrees, a circle stands + // in for it. + let turned = |angle: f64| { + let mut gp = GradientPaint::new(Gradient { kind: GradientKind::Diamond, ..Gradient::default() }); + gp.angle = angle; + let lib = SwatchLibrary { + name: "x".into(), + swatches: vec![Swatch { name: "Gem".into(), paint: Paint::Gradient(Box::new(gp)), global: false, spot: false }], + groups: vec![], + }; + written(&lib, PaletteFormat::Css) + }; + assert!(turned(90.0).contains(&want) && turned(-180.0).contains(&want), "{}", turned(90.0)); + assert!(turned(30.0).contains("--gem: radial-gradient(circle, #ffffff 0%, #000000 100%);"), "{}", turned(30.0)); +} + #[test] fn css_preserves_fractional_gradient_stop_positions() { for kind in [GradientKind::Linear, GradientKind::Radial] { @@ -212,6 +261,29 @@ fn css_preserves_fractional_gradient_stop_positions() { } } +/// A gradient swatch that repeats or reflects has its stops written that many times across the +/// box, every other run backwards for Reflect. +#[test] +fn css_writes_spread_gradient_swatches_with_their_stops_repeated() { + for (spread, want) in [ + (crate::GradientSpread::Repeat, "#ffffff 0%, #000000 50%, #ffffff 50%, #000000 100%"), + (crate::GradientSpread::Reflect, "#ffffff 0%, #000000 50%, #000000 50%, #ffffff 100%"), + ] { + let lib = SwatchLibrary { + name: "x".into(), + swatches: vec![Swatch { + name: "Bands".into(), + paint: Paint::Gradient(Box::new(GradientPaint::new(Gradient { spread, repeats: 2, ..Gradient::default() }))), + global: false, + spot: false, + }], + groups: vec![], + }; + let text = written(&lib, PaletteFormat::Css); + assert!(text.contains(&format!("--bands: linear-gradient(90deg, {want});")), "{spread:?}: {text}"); + } +} + #[test] fn holds_counts_the_swatches_each_format_writes() { // `sample()` holds the spot color Ink, the linear gradient Fade, the pattern Tiles and two solid colors in a group. diff --git a/crates/color/src/recolor.rs b/crates/color/src/recolor.rs index 5117f16a36..05c386e405 100644 --- a/crates/color/src/recolor.rs +++ b/crates/color/src/recolor.rs @@ -485,6 +485,194 @@ pub fn cluster(colors: &[Color], weights: &[f32], n: usize) -> Vec> { rows } +/// The distinct colors [`theme_palette`] clusters, at most. +const THEME_CANDIDATES: usize = 4096; + +/// The color palette of the weighted colors `samples` (color, weight), for Recolor Artwork's Color +/// Theme Picker: at most `n` colors. The same color given twice counts once with both weights, +/// and past [`THEME_CANDIDATES`] distinct colors, colors close in Lab merge into the heaviest of +/// them first. +/// The colors are grouped as [`cluster`] groups them, each group shows its heaviest color (a color +/// of `samples`, in its own model; on a tie the one given first), and the heaviest group comes +/// first (on a tie the group whose first color was given first). Samples without a positive, +/// finite weight are left out, so no samples give no colors. +pub fn theme_palette(samples: &[(Color, f32)], n: usize) -> Vec { + let mut index: std::collections::HashMap = std::collections::HashMap::new(); + let mut colors: Vec = vec![]; + let mut weights: Vec = vec![]; + for (c, w) in samples { + if !(w.is_finite() && *w > 0.0) { + continue; + } + let i = *index.entry(ColorKey::of(c)).or_insert_with(|| { + colors.push(*c); + weights.push(0.0); + colors.len() - 1 + }); + weights[i] += w; + } + if colors.is_empty() || n == 0 { + return vec![]; + } + // At most THEME_CANDIDATES colors are clustered: past that, colors in the same cube of Lab + // space merge into the heaviest of them, the cubes doubling in size until few enough remain. + if colors.len() > THEME_CANDIDATES { + let labs: Vec<[f32; 3]> = colors + .iter() + .map(|c| { + let l = c.to_lab(); + [l.l, l.a, l.b] + }) + .collect(); + let mut side = 2.0f32; + loop { + let mut cube: std::collections::HashMap<[i32; 3], usize> = std::collections::HashMap::new(); + let (mut top, mut sum): (Vec, Vec) = (vec![], vec![]); + for (i, lab) in labs.iter().enumerate() { + let k = lab.map(|v| (v / side).floor() as i32); + match cube.get(&k) { + Some(&j) => { + sum[j] += weights[i]; + if weights[i] > weights[top[j]] { + top[j] = i; + } + } + None => { + cube.insert(k, top.len()); + top.push(i); + sum.push(weights[i]); + } + } + } + if top.len() <= THEME_CANDIDATES { + colors = top.iter().map(|&i| colors[i]).collect(); + weights = sum; + break; + } + side *= 2.0; + } + } + let mut groups: Vec<(f32, usize, Color)> = cluster(&colors, &weights, n) + .into_iter() + .filter_map(|g| { + let total: f32 = g.iter().map(|&i| weights[i]).sum(); + let top = g.iter().copied().fold(None::, |best, i| match best { + Some(b) if weights[b] >= weights[i] => Some(b), + _ => Some(i), + })?; + Some((total, *g.first()?, colors[top])) + }) + .collect(); + groups.sort_by(|a, b| b.0.total_cmp(&a.0).then(a.1.cmp(&b.1))); + groups.into_iter().map(|g| g.2).collect() +} + +/// Colors that [`weigh`] moves from one row to another as one: a color they are shown by, how +/// often the art uses them and the row they are in. A fixed unit (such as the color a row is +/// shown by) stays in its row. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct WeighUnit { + pub color: Color, + pub uses: f64, + pub row: usize, + pub fixed: bool, +} + +/// The unit-by-row comparisons one [`weigh`] makes, at most. +const WEIGH_WORK: usize = 50_000_000; + +/// The uses of `u` that count: a positive finite number, else 0. +fn unit_uses(u: &WeighUnit) -> f64 { + if u.uses.is_finite() && u.uses > 0.0 { u.uses } else { 0.0 } +} + +/// Each row's share of the uses of `units`, in percent (0 for every row when nothing is used). +/// Units whose row is past `rows`, or whose uses are not a positive finite number, count nothing. +pub fn row_shares(units: &[WeighUnit], rows: usize) -> Vec { + let mut sums = vec![0.0; rows]; + for u in units { + if let Some(s) = sums.get_mut(u.row) { + *s += unit_uses(u); + } + } + let total: f64 = sums.iter().sum(); + if total <= 0.0 { + return vec![0.0; rows]; + } + sums.iter().map(|s| s / total * 100.0).collect() +} + +/// For Recolor Artwork's Prominent Colors (our own rule): the row each of `units` goes to so that +/// each row's share of the uses comes as near its share of `weights` as whole units allow. One +/// unit moves at a time, while a move brings the rows' shares nearer their weights (the sum of +/// every row's distance from its weight falls); of those moves, the one taken is the unit nearest +/// in Lab (CIEDE2000) to the color of the row it goes to (`anchors`), compared with the row it +/// leaves; on a tie, the move that brings the shares nearest. Fixed units, units in a row past +/// `anchors` and units used no times stay where they are. Weights that are negative or not finite +/// count as 0; when no weight is positive, every unit stays. The moves stop after +/// [`WEIGH_WORK`] comparisons of a unit with a row, and when the movable units times the rows pass +/// it, every unit stays. +pub fn weigh(units: &[WeighUnit], anchors: &[Color], weights: &[f64]) -> Vec { + let mut row: Vec = units.iter().map(|u| u.row).collect(); + let n = anchors.len(); + let given = |r: usize| weights.get(r).copied().filter(|x| x.is_finite() && *x > 0.0).unwrap_or(0.0); + // Scaled by the largest weight first, so the sum stays finite. + let top = (0..n).map(given).fold(0.0, f64::max); + let w = |r: usize| if top > 0.0 { given(r) / top } else { 0.0 }; + let sum_w: f64 = (0..n).map(w).sum(); + let movable: Vec = (0..units.len()).filter(|&i| !units[i].fixed && units[i].row < n && unit_uses(&units[i]) > 0.0).collect(); + let per_pass = movable.len().saturating_mul(n); + if sum_w <= 0.0 || n < 2 || movable.is_empty() || per_pass > WEIGH_WORK { + return row; + } + let mut sums = vec![0.0; n]; + for u in units.iter().filter(|u| u.row < n) { + sums[u.row] += unit_uses(u); + } + let total: f64 = sums.iter().sum(); + let target: Vec = (0..n).map(|r| w(r) / sum_w * total).collect(); + let anchor_labs: Vec = anchors.iter().map(|c| c.to_lab()).collect(); + // Each movable unit's distance to each row's color. + let dist: Vec> = movable + .iter() + .map(|&i| { + let l = units[i].color.to_lab(); + anchor_labs.iter().map(|a| delta_e2000(*a, l)).collect() + }) + .collect(); + // A move must bring the shares nearer by more than rounding. + let eps = total * 1e-9; + for _ in 0..WEIGH_WORK / per_pass { + let mut best: Option<(f32, f64, usize, usize)> = None; + for (m, &i) in movable.iter().enumerate() { + let (a, x) = (row[i], unit_uses(&units[i])); + let before_a = (sums[a] - target[a]).abs(); + let after_a = (sums[a] - x - target[a]).abs(); + for b in (0..n).filter(|&b| b != a) { + let gain = before_a + (sums[b] - target[b]).abs() - after_a - (sums[b] + x - target[b]).abs(); + if gain <= eps { + continue; + } + let cost = dist[m][b] - dist[m][a]; + let better = match best { + None => true, + Some((c, g, ..)) => cost < c || (cost == c && gain > g), + }; + if better { + best = Some((cost, gain, m, b)); + } + } + } + let Some((_, _, m, b)) = best else { break }; + let i = movable[m]; + let x = unit_uses(&units[i]); + sums[row[i]] -= x; + sums[b] += x; + row[i] = b; + } + row +} + /// A set of colours to snap to (Limit to Library), with their Lab values cached. #[derive(Clone, Debug, Default)] pub struct Palette(Vec<(Color, Lab)>); @@ -691,6 +879,39 @@ mod tests { assert!(cluster(&[], &[], 3).is_empty()); } + /// The Color Theme Picker's palette: similar colors merge, each group shows its heaviest + /// color in its own model, and the heaviest group comes first. + #[test] + fn theme_palette_takes_the_heaviest_color_of_each_group_heaviest_first() { + let red = Color::rgb(1.0, 0.0, 0.0); + let pink = Color::rgb(1.0, 0.2, 0.2); + let blue = Color::cmyk(1.0, 0.8, 0.0, 0.0); + let navy = Color::cmyk(1.0, 0.9, 0.0, 0.3); + let samples = [(pink, 1.0), (blue, 2.0), (red, 3.0), (navy, 2.5), (red, 0.5)]; + // Blue and navy weigh 4.5, and so do red (3 + 0.5, its two samples add up) and pink. + assert_eq!(theme_palette(&samples, 2), vec![red, navy], "a tie: the group given first"); + let samples = [(pink, 1.0), (blue, 2.0), (red, 3.0), (navy, 1.0)]; + assert_eq!(theme_palette(&samples, 2), vec![red, blue], "heaviest group first, its heaviest color"); + assert_eq!(theme_palette(&samples, 9).len(), 4, "never more colors than given"); + assert_eq!(theme_palette(&samples, 1), vec![red]); + assert!(theme_palette(&samples, 0).is_empty()); + assert!(theme_palette(&[(red, 0.0), (blue, f32::NAN), (pink, -1.0)], 3).is_empty(), "no weight, no colors"); + assert!(theme_palette(&[], 3).is_empty()); + } + + /// Past 4,096 distinct colors, close colors merge before clustering: the palette still keeps + /// a heavy color apart from thousands of light ones. + #[test] + fn theme_palette_merges_close_colors_past_its_candidate_limit() { + let mut samples: Vec<(Color, f32)> = (0..20_000).map(|i| (Color::rgb(0.0, 0.0, 0.3 + 0.7 * i as f32 / 20_000.0), 0.001)).collect(); + samples.extend((0..20_000).map(|i| (Color::rgb(1.0, 0.8 * i as f32 / 20_000.0, 0.0), 0.0001))); + samples.push((Color::rgb(0.0, 1.0, 0.0), 50.0)); + let p = theme_palette(&samples, 3); + assert_eq!(p.len(), 3); + assert_eq!(p[0], Color::rgb(0.0, 1.0, 0.0), "the heavy green first, exactly as given"); + assert!(p[1].to_hsb()[0] > 180.0 && p[2].to_hsb()[0] < 90.0, "then the blues, then the reds and oranges: {p:?}"); + } + #[test] fn hue_shift_with_own_model_puts_every_colour_of_the_row_in_the_new_model() { let to = Color::cmyk(0.0, 1.0, 1.0, 0.0); @@ -796,4 +1017,55 @@ mod tests { assert!(matches!(Rng::new(3).saturation_brightness(Color::lab(50.0, 40.0, 20.0)), Color::Lab { .. })); assert_eq!(Rng::new(3).saturation_brightness(Color::gray(0.4)).to_hsb()[1], 0.0, "greys stay grey"); } + + fn unit(color: Color, uses: f64, row: usize, fixed: bool) -> WeighUnit { + WeighUnit { color, uses, row, fixed } + } + + #[test] + fn row_shares_are_percent_of_the_uses() { + let units = [unit(Color::rgb(1.0, 0.0, 0.0), 3.0, 0, true), unit(Color::rgb(0.0, 0.0, 1.0), 1.0, 1, true), unit(Color::WHITE, 5.0, 4, false)]; + assert_eq!(row_shares(&units, 2), vec![75.0, 25.0]); + assert_eq!(row_shares(&[], 2), vec![0.0, 0.0]); + assert_eq!(row_shares(&[unit(Color::WHITE, f64::NAN, 0, false)], 1), vec![0.0]); + } + + #[test] + fn weigh_moves_the_nearest_colors_toward_the_weights() { + let (red, blue) = (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0)); + let units = [ + unit(red, 1.0, 0, true), + unit(Color::rgb(0.9, 0.1, 0.3), 1.0, 0, false), + unit(Color::rgb(0.5, 0.0, 0.8), 1.0, 0, false), + unit(blue, 1.0, 1, true), + ]; + // Equal weights: the reddish purple, nearer blue than the red-pink is, moves. + assert_eq!(weigh(&units, &[red, blue], &[1.0, 1.0]), vec![0, 0, 1, 1]); + // Most of the weight on blue: both movable colors go, the row's own color stays. + assert_eq!(weigh(&units, &[red, blue], &[0.0, 1.0]), vec![0, 1, 1, 1]); + // Weights already met, or none positive: nothing moves. + assert_eq!(weigh(&units, &[red, blue], &[3.0, 1.0]), vec![0, 0, 0, 1]); + assert_eq!(weigh(&units, &[red, blue], &[0.0, f64::NAN]), vec![0, 0, 0, 1]); + assert_eq!(weigh(&units, &[red, blue], &[1e308, 1e308]), vec![0, 0, 1, 1], "huge weights act as equal ones"); + assert_eq!(weigh(&units, &[red], &[1.0]), vec![0, 0, 0, 1], "a row past the anchors keeps its units"); + } + + #[test] + fn weigh_takes_whole_units_and_stops_when_no_move_helps() { + let (red, blue) = (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0)); + // A heavy unit: moving it would overshoot by more than staying misses. + let units = [unit(red, 1.0, 0, true), unit(Color::rgb(0.8, 0.0, 0.2), 10.0, 0, false), unit(blue, 10.0, 1, true)]; + assert_eq!(weigh(&units, &[red, blue], &[1.0, 1.4]), vec![0, 0, 1]); + assert_eq!(weigh(&units, &[red, blue], &[1.0, 20.0]), vec![0, 1, 1]); + // Many units: the result still follows the weights. + let many: Vec = (0..400).map(|i| unit(Color::rgb(i as f32 / 400.0, 0.2, 1.0 - i as f32 / 400.0), 1.0, 0, i == 0)).collect(); + let rows = weigh(&many, &[Color::rgb(0.0, 0.2, 1.0), Color::rgb(1.0, 0.2, 0.0)], &[1.0, 3.0]); + assert_eq!(rows.iter().filter(|r| **r == 1).count(), 300); + assert!(rows[399] == 1 && rows[1] == 0, "the reddest colors go to the red row"); + // Past the work limit (8,000 units by 7,000 rows) nothing moves. + let units: Vec = (0..8_000).map(|i| unit(Color::WHITE, 1.0, 0, i == 0)).collect(); + let anchors = vec![Color::BLACK; 7_000]; + let weights = vec![1.0; 7_000]; + assert!(weigh(&units, &anchors, &weights).iter().all(|r| *r == 0)); + } } diff --git a/crates/doc/src/appearance.rs b/crates/doc/src/appearance.rs index c057aeb231..ba0f5fc013 100644 --- a/crates/doc/src/appearance.rs +++ b/crates/doc/src/appearance.rs @@ -10,7 +10,7 @@ mod stroke_style; pub use layers::{Effect, FillLayer, StrokeGradientMode, StrokeLayer, stroke_paint_bounds}; pub use profile::{AngleProfile, PressureProfile, ProfilePreset, SavedProfile, WidthProfile}; -pub use stroke_style::{ArrowAlign, Arrowhead, Dash, LineCap, LineJoin, StrokeAlign}; +pub use stroke_style::{ArrowAlign, Arrowhead, CustomArrowhead, Dash, LineCap, LineJoin, StrokeAlign}; /// One entry of the appearance stack. // A stroke takes 328 bytes and a fill 104; an appearance holds a few of each. @@ -444,7 +444,8 @@ impl Appearance { } } /// Map placed gradients through a warp, given its local affine approximation at a point (taken - /// at each gradient's center: the start of a radial or conic, the middle of a linear vector). + /// at each gradient's center: the start of a radial, conic or diamond, the middle of a linear + /// vector). /// Freeform points each follow the warp at their own position. pub fn warp_gradients(&mut self, near: &dyn Fn(vectorcraft_geom::Point) -> vectorcraft_geom::Affine) { for g in self.gradients_mut() { diff --git a/crates/doc/src/appearance/layers.rs b/crates/doc/src/appearance/layers.rs index 923275999b..f8a58758d8 100644 --- a/crates/doc/src/appearance/layers.rs +++ b/crates/doc/src/appearance/layers.rs @@ -193,8 +193,10 @@ impl StrokeLayer { /// How far the start (`end == false`) or end arrowhead can reach from its end point (0 /// without one): the head's diagonal, or with [`ArrowAlign::Extend`] its length, plus the cap. pub fn head_reach(&self, end: bool) -> f64 { - let head = if end { self.end_arrow } else { self.start_arrow }; - head.map_or(0.0, |k| k.reach() * self.arrow_weight(end) + self.width / 2.0) + let head = if end { &self.end_arrow } else { &self.start_arrow }; + // A custom head can paint in front of its tip, which Extend puts past the end point. + let reach = |k: &Arrowhead| if self.arrow_align == ArrowAlign::Extend { k.reach().max(k.length()) } else { k.reach() }; + head.as_ref().map_or(0.0, |k| reach(k) * self.arrow_weight(end) + self.width / 2.0) } /// How far the arrowheads can reach from the path's end points (0 without heads). pub fn arrow_reach(&self) -> f64 { diff --git a/crates/doc/src/appearance/profile.rs b/crates/doc/src/appearance/profile.rs index 0887961730..3d89615016 100644 --- a/crates/doc/src/appearance/profile.rs +++ b/crates/doc/src/appearance/profile.rs @@ -26,11 +26,16 @@ impl WidthProfile { pub fn at(&self, t: f64) -> (f64, f64) { Self::at_points(&self.points, t) } - /// [`Self::at`] of a profile's points (a preset's or a saved profile's). Each side runs through - /// its points on a monotone cubic curve (Fritsch–Carlson): it flows through a width point - /// without a kink, turns flat at a point wider or narrower than both neighbours, and never - /// goes past either point of the span it is in (#5714). Points on one straight line stay on - /// it. A step (two points at one position, [`Self::around`]) ends the curve on each side of it. + /// [`Self::at`] of a profile's points (a preset's or a saved profile's). + /// + /// Each side runs through its points on a cubic Hermite curve, its slope at each one the + /// weighted harmonic mean of the secants either side (Fritsch–Carlson). That is C1 continuous + /// and monotone between points, so it never overshoots them, a point eases into its neighbours + /// instead of making a corner, and moving one reshapes the curve as far as its neighbours' + /// neighbours (their slopes depend on it). The ends of a run use the one-sided PCHIP slope + /// from its first two secants, or the secant when it has only two points, so a two-point + /// profile stays a straight taper and the lens is a parabola. Two points at one `t` are still + /// a step: each run either side ends independently at it. pub fn at_points(p: &[(f64, f64, f64)], t: f64) -> (f64, f64) { if p.is_empty() { return (1.0, 1.0); @@ -71,9 +76,10 @@ impl WidthProfile { // Two swells between narrow necks. ProfilePreset { id: "wave", label: "Wave", points: &[(0.0, 0.3, 0.3), (0.25, 1.0, 1.0), (0.5, 0.3, 0.3), (0.75, 1.0, 1.0), (1.0, 0.3, 0.3)] }, ]; - /// The widest the stroke gets, as a multiple of its weight, 1 for a profile without points. Each - /// side stays between the widths of the two points of each span ([`Self::at_points`]), but the - /// two sides needn't peak together, so a span counts its wider left and its wider right. + /// The widest the stroke gets, as a multiple of its weight, 1 for a profile without points. + /// Each side's smooth curve stays between the widths of the two points of each span + /// ([`Self::at_points`]), but the two sides needn't peak together, so a span counts its wider + /// left and its wider right. pub fn widest(&self) -> f64 { let p = &self.points; if p.is_empty() { @@ -196,6 +202,13 @@ impl AngleProfile { if v.is_finite() { vectorcraft_geom::normalize_deg(v) } else { 0.0 } } + /// The angle at `t` (0..1) as [`Self::at`] reads it, but in the samples' own running degrees, + /// so the whole turns the curve makes along the stroke are kept; 0 without any samples. + pub fn unwrapped_at(&self, t: f64) -> f64 { + let v = interpolated(&self.points, t).unwrap_or(0.0); + if v.is_finite() { v } else { 0.0 } + } + /// A profile from (position, degrees) samples in order along the stroke: non-finite ones are /// dropped, each sample is joined to the one before it the shorter way round, and the curve is /// simplified to within 1° and kept to [`PressureProfile::MAX_POINTS`]. `None` without a sample. @@ -249,11 +262,27 @@ impl AngleProfile { /// How close two width points' positions are to make a step ([`WidthProfile::around`]). const STEP: f64 = 1e-7; +/// The one-sided three-point PCHIP slope at the start of a run, from the first two secants. +/// A sign change caps the slope, and a slope that turns back on the first secant is flattened. +/// Runs of only two points use their secant instead (see [`tangent`]). +fn end_slope(h0: f64, h1: f64, d0: f64, d1: f64) -> f64 { + let m = ((2.0 * h0 + h1) * d0 - h0 * d1) / (h0 + h1); + if !m.is_finite() || m * d0 <= 0.0 { + return 0.0; + } + if d0 * d1 < 0.0 { + return if d0 > 0.0 { m.min(3.0 * d0) } else { m.max(3.0 * d0) }; + } + m +} + /// The slope of one side (`v` reads it from a point) of width profile `p` at its point `j`, in /// width per unit of position: Fritsch–Carlson's choice for a monotone cubic curve. It is 0 where -/// the point is wider or narrower than both neighbours, the weighted harmonic mean of the slopes -/// of the spans on either side elsewhere (never more than three times either, so no span -/// overshoots its points), and the span's own slope at an end of the profile or beside a step. +/// the point is wider or narrower than both neighbours, and the weighted harmonic mean of the +/// slopes of the spans on either side elsewhere (never more than three times either, so no span +/// overshoots its points). The ends of a run take the one-sided three-point PCHIP slope, or their +/// secant when the run has only two points; a step ends the run on each side, so the points either +/// side of it do not see across it. fn tangent(p: &[(f64, f64, f64)], j: usize, v: fn(&(f64, f64, f64)) -> f64) -> f64 { let Some(q) = p.get(j) else { return 0.0 }; let before = j.checked_sub(1).and_then(|k| p.get(k)).filter(|a| q.0 - a.0 > STEP); @@ -268,8 +297,18 @@ fn tangent(p: &[(f64, f64, f64)], j: usize, v: fn(&(f64, f64, f64)) -> f64) -> f let (h0, h1) = (q.0 - a.0, b.0 - q.0); 3.0 * (h0 + h1) / ((2.0 * h1 + h0) / d0 + (h1 + 2.0 * h0) / d1) } - (Some(a), None) => slope(a, q), - (None, Some(b)) => slope(q, b), + // The end of a run: its previous two points set a one-sided three-point slope, or its + // secant when the run has only two points (the point before `a` is on the other side of a + // step, or does not exist). + (Some(a), None) => { + let Some(prev) = j.checked_sub(2).and_then(|k| p.get(k)).filter(|z| a.0 - z.0 > STEP) else { return slope(a, q) }; + end_slope(q.0 - a.0, a.0 - prev.0, slope(a, q), slope(prev, a)) + } + // The start of a run, symmetrically. + (None, Some(b)) => { + let Some(next) = p.get(j + 2).filter(|z| z.0 - b.0 > STEP) else { return slope(q, b) }; + end_slope(b.0 - q.0, next.0 - b.0, slope(q, b), slope(b, next)) + } (None, None) => 0.0, } } @@ -424,12 +463,12 @@ mod tests { #[test] fn widths_run_smoothly_through_width_points() { // A swell in the middle: flat at its widest, and a quarter of the way along above the - // straight ramp from 1 to 3 (2). + // straight ramp from 1 to 3 (2) because the end eases out of the first point. let swell = WidthProfile { points: vec![(0.0, 1.0, 1.0), (0.5, 3.0, 2.0), (1.0, 1.0, 1.0)] }; let (before, after) = slopes(&swell, 0.5); assert!(before.abs() < 1e-4 && after.abs() < 1e-4, "{before} {after}"); let (l, r) = swell.at(0.25); - assert!((l - 2.25).abs() < 1e-12 && (r - 1.625).abs() < 1e-12, "{l} {r}"); + assert!((l - 2.5).abs() < 1e-12 && (r - 1.75).abs() < 1e-12, "{l} {r}"); // Rising on both sides of a point: the slope is the same either side of it. let rise = WidthProfile { points: vec![(0.0, 0.0, 0.0), (0.3, 1.0, 1.0), (1.0, 4.0, 4.0)] }; let (before, after) = slopes(&rise, 0.3); diff --git a/crates/doc/src/appearance/stroke_style.rs b/crates/doc/src/appearance/stroke_style.rs index 46a0c30c33..18b226c676 100644 --- a/crates/doc/src/appearance/stroke_style.rs +++ b/crates/doc/src/appearance/stroke_style.rs @@ -1,3 +1,7 @@ +use std::sync::Arc; + +use vectorcraft_geom::{PathData, Rect}; + use super::{Deserialize, Serialize}; #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] @@ -53,8 +57,74 @@ impl Dash { /// (the open arrow's arms are cut square a little behind the box). const HEAD_REACH: f64 = 4.6; +/// An arrowhead the user drew (Stroke panel menu › Edit Arrowheads…), carried with its art so a +/// document that uses it draws it wherever it opens. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(from = "CustomArrowheadData")] +pub struct CustomArrowhead { + /// The name the arrowhead menus show (the symbol's name in the arrowheads file). + pub name: String, + /// The filled outline (non-zero rule) in head units: x from the tip (0) back along the line, y + /// across it, positive to the right of the direction the head points. A head is 4 units wide, + /// as the built-in heads are, and a unit is the head's weight. + pub path: PathData, +} + +#[derive(Deserialize)] +struct CustomArrowheadData { + name: String, + #[serde(default)] + path: PathData, +} + +impl From for CustomArrowhead { + fn from(d: CustomArrowheadData) -> Self { + CustomArrowhead::new(d.name, d.path) + } +} + +impl CustomArrowhead { + /// The most anchors a custom head's outline may have, and the most subpaths. + pub const MAX_ANCHORS: usize = 4096; + /// How far from the tip a custom head's outline may reach, in head units. + pub const MAX_UNITS: f64 = 64.0; + + /// Head `name` with outline `path` (in head units). An outline with more than + /// [`Self::MAX_ANCHORS`] anchors or subpaths, a point that is not finite, or a point farther + /// than [`Self::MAX_UNITS`] from the tip is dropped: the head then draws nothing. + pub fn new(name: String, path: PathData) -> Self { + let path = if Self::fits(&path) { path } else { PathData::default() }; + CustomArrowhead { name, path } + } + /// Whether outline `path` has at most [`Self::MAX_ANCHORS`] anchors and as many subpaths, with + /// finite points within [`Self::MAX_UNITS`] only. + pub fn fits(path: &PathData) -> bool { + let anchors = path.subpaths.iter().map(|s| s.anchors.len()).sum::(); + let near = |p: vectorcraft_geom::Point| p.x.is_finite() && p.y.is_finite() && p.x.abs() <= Self::MAX_UNITS && p.y.abs() <= Self::MAX_UNITS; + anchors <= Self::MAX_ANCHORS + && path.subpaths.len() <= Self::MAX_ANCHORS + && path.subpaths.iter().flat_map(|s| &s.anchors).all(|a| near(a.p) && near(a.h_in) && near(a.h_out)) + } + fn bounds(&self) -> Option { + self.path.control_bounds() + } + /// How far any part of the head can be from its tip, in head units. + pub fn reach(&self) -> f64 { + self.bounds().map_or(0.0, |b| b.x0.hypot(b.y0).max(b.x1.hypot(b.y0)).max(b.x0.hypot(b.y1)).max(b.x1.hypot(b.y1))) + } + /// How far the head spreads either side of its line, in head units. + pub fn half_width(&self) -> f64 { + self.bounds().map_or(0.0, |b| b.y0.abs().max(b.y1.abs())) + } + /// Where the stroke ends under the head, in head units back from the tip: halfway along the + /// head's length. + pub fn stop(&self) -> f64 { + self.bounds().map_or(0.0, |b| b.x1.max(0.0) / 2.0) + } +} + /// An arrowhead shape. Saved by variant name: new shapes are appended, never renamed or reordered. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Arrowhead { Triangle, TriangleOpen, @@ -102,6 +172,8 @@ pub enum Arrowhead { /// more) meeting at right angles in a sharp tip, cut square at their ends. Twice as wide as /// the other heads. LineArrow, + /// A head the user drew, with its art. + Custom(Arc), } impl Arrowhead { @@ -151,23 +223,43 @@ impl Arrowhead { ]; /// How far any part of the head can be from its tip, in units of its weight. - pub fn reach(self) -> f64 { + pub fn reach(&self) -> f64 { match self { // Its farthest corners are 4 + ½√2 back and 4 − ½√2 out. Arrowhead::LineArrow => 5.75, + Arrowhead::Custom(c) => c.reach(), _ => HEAD_REACH, } } /// How far the head spreads either side of its line, in units of its weight. - pub fn half_width(self) -> f64 { + pub fn half_width(&self) -> f64 { match self { Arrowhead::LineArrow => 4.0, + Arrowhead::Custom(c) => c.half_width(), _ => 2.0, } } + /// How far past its end point a head placed with [`ArrowAlign::Extend`] can paint, in units of + /// its weight: the built-in heads' length, or a custom head's reach past its tip, which sits + /// [`CustomArrowhead::stop`] past the end point. + pub fn length(&self) -> f64 { + match self { + Arrowhead::Custom(c) => c.stop() + c.reach(), + _ => 4.0, + } + } - /// The name the arrowhead menus show. - pub fn label(self) -> &'static str { + /// The name the arrowhead menus show: [`Self::label`], or a custom head's own name. + pub fn name(&self) -> &str { + match self { + Arrowhead::Custom(c) => &c.name, + _ => self.label(), + } + } + + /// The name the arrowhead menus show for a built-in head ("Custom" for a custom one, whose + /// own name is [`Self::name`]). + pub fn label(&self) -> &'static str { match self { Arrowhead::Triangle => "Triangle", Arrowhead::TriangleOpen => "Triangle (open)", @@ -210,6 +302,7 @@ impl Arrowhead { Arrowhead::TriangleBar => "Triangle to Bar", Arrowhead::Oval => "Oval", Arrowhead::LineArrow => "Line Arrow", + Arrowhead::Custom(_) => "Custom", } } } diff --git a/crates/doc/src/appearance/tests.rs b/crates/doc/src/appearance/tests.rs index 0a1b3e1a5d..22e5659051 100644 --- a/crates/doc/src/appearance/tests.rs +++ b/crates/doc/src/appearance/tests.rs @@ -197,12 +197,85 @@ fn strokes_without_pressure_round_trip_unchanged() { fn profile_interp() { let p = WidthProfile::lens(); assert_eq!(p.at(0.5), (1.0, 1.0)); - // Half way up the lens the width curves above the straight ramp (0.5), flattening into its - // widest point (#5714). - assert_eq!(p.at(0.25), (0.625, 0.625)); + // The lens is a parabola between its ends, so a quarter of the way along is 0.75: above the + // 0.5 a straight taper would give. + assert_eq!(p.at(0.25), (0.75, 0.75)); assert_eq!(p.at(2.0), (0.0, 0.0)); } +/// The width runs smoothly between points: it passes through them, has one slope either side +/// of one, and never overshoots the widths its points set. +#[test] +fn profile_is_smooth_between_points() { + let p = [(0.0, 1.0, 2.0), (0.5, 0.2, 2.0), (1.0, 1.0, 2.0)]; + assert!((WidthProfile::at_points(&p, 0.5).0 - 0.2).abs() < 1e-12); + let slope = |t: f64| (WidthProfile::at_points(&p, t + 1e-6).0 - WidthProfile::at_points(&p, t - 1e-6).0) / 2e-6; + // A local minimum at the middle point is flat there, so the two sides agree. + assert!(slope(0.5).abs() < 1e-3, "{}", slope(0.5)); + for k in 0..=100 { + let w = WidthProfile::at_points(&p, k as f64 / 100.0).0; + assert!((0.2..=1.0).contains(&w), "{w} at {k}"); + } + // The side with no points of its own stays flat. + for k in 0..=100 { + assert!((WidthProfile::at_points(&p, k as f64 / 100.0).1 - 2.0).abs() < 1e-12); + } +} + +/// A run with only two points takes its secant as both end slopes, so it stays a straight +/// taper on each side instead of becoming a smoothstep. +#[test] +fn profile_two_point_runs_are_linear() { + let p = [(0.0, 0.0, 1.0), (1.0, 1.0, 0.0)]; + for k in 0..=100 { + let t = k as f64 / 100.0; + let (l, r) = WidthProfile::at_points(&p, t); + assert!((l - t).abs() < 1e-12, "left {l} at {t}"); + assert!((r - (1.0 - t)).abs() < 1e-12, "right {r} at {t}"); + } +} + +/// The lens's one-sided end slopes make it a parabola: at a quarter of the way it is 0.75, +/// above the 0.5 a straight line between its points would give. +#[test] +fn profile_lens_is_convex() { + let p = WidthProfile::lens(); + assert!((p.at(0.25).0 - 0.75).abs() < 1e-12); + assert!((p.at(0.75).0 - 0.75).abs() < 1e-12); + for k in 1..25 { + let t = k as f64 / 100.0; + assert!(p.at(t).0 > 2.0 * t, "{} at {t}", p.at(t).0); + assert!(p.at(1.0 - t).0 > 2.0 * t, "{} at {}", p.at(1.0 - t).0, 1.0 - t); + } +} + +/// A step still steps, and the smooth runs either side meet it flat. +#[test] +fn profile_steps_stay_steps() { + let p = [(0.0, 1.0, 1.0), (0.5, 1.0, 1.0), (0.5, 2.0, 2.0), (1.0, 2.0, 2.0)]; + assert_eq!(WidthProfile::at_points(&p, 0.5), (1.0, 1.0)); + assert_eq!(WidthProfile::at_points(&p, 0.5 + 1e-6), (2.0, 2.0)); + assert_eq!(WidthProfile::at_points(&p, 0.5 - 1e-6), (1.0, 1.0)); + assert_eq!(WidthProfile::at_points(&p, 0.25), (1.0, 1.0)); + assert_eq!(WidthProfile::at_points(&p, 0.75), (2.0, 2.0)); +} + +/// Moving a point only reshapes the segments beside it (local influence), not the whole path. +#[test] +fn profile_points_only_affect_the_curve_around_them() { + // A monotone run, so no neighbouring slope is held flat by a local extremum. + let a = [(0.0, 0.0, 0.0), (0.25, 0.3, 0.3), (0.5, 0.5, 0.5), (0.75, 0.7, 0.7), (1.0, 1.0, 1.0)]; + let mut b = a; + b[3] = (0.75, 0.9, 0.9); + // Moving p[3] changes the slopes at p[2] and p[3], so p[1] and p[4] also shape the + // curve: nothing before p[1] may move. + for k in 0..=24 { + let t = k as f64 / 100.0; + assert_eq!(WidthProfile::at_points(&a, t), WidthProfile::at_points(&b, t), "at {t}"); + } + assert_ne!(WidthProfile::at_points(&a, 0.3), WidthProfile::at_points(&b, 0.3)); +} + #[test] fn profile_presets_round_trip_their_ids() { for p in WidthProfile::PRESETS { @@ -264,13 +337,65 @@ fn arrowhead_names_are_stable_and_every_one_is_listed_once() { ]; for name in SAVED { let a: Arrowhead = serde_json::from_value(serde_json::json!(name)).unwrap(); - assert_eq!(serde_json::to_value(a).unwrap(), name); + assert_eq!(serde_json::to_value(&a).unwrap(), name); assert_eq!(Arrowhead::ALL.iter().filter(|x| **x == a).count(), 1, "{name} in the menu once"); } let labels: std::collections::HashSet<&str> = Arrowhead::ALL.iter().map(|a| a.label()).collect(); assert_eq!(labels.len(), Arrowhead::ALL.len(), "labels are distinct"); } +/// A custom head: a triangle from its tip back 3 units, 2 units right and 1 left of its line. +fn custom_head() -> Arrowhead { + use vectorcraft_geom::{PathData, Point, SubPath}; + let path = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(3.0, 2.0), Point::new(3.0, -1.0)], true)); + Arrowhead::Custom(std::sync::Arc::new(CustomArrowhead::new("Wedge".into(), path))) +} + +#[test] +fn custom_arrowheads_carry_their_art_and_measure_it() { + let head = custom_head(); + assert_eq!((head.name(), head.label()), ("Wedge", "Custom")); + assert_eq!(head.reach(), 3.0f64.hypot(2.0)); + assert_eq!(head.half_width(), 2.0); + let Arrowhead::Custom(c) = &head else { panic!("custom") }; + assert_eq!(c.stop(), 1.5, "the line stops halfway along the head"); + // Saved with the stroke, art and all, beside the built-in heads' names. + let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 2.0); + (st.start_arrow, st.end_arrow) = (Some(Arrowhead::Triangle), Some(head.clone())); + let json = serde_json::to_value(&st).unwrap(); + assert_eq!(json["start_arrow"], "Triangle"); + assert_eq!(json["end_arrow"]["Custom"]["name"], "Wedge"); + let back: StrokeLayer = serde_json::from_value(json).unwrap(); + assert_eq!(back, st); + // Extended, the tip sits the stop past the end point; on it, only the reach counts. + assert_eq!(head.length(), 1.5 + head.reach()); + assert_eq!(st.head_reach(true), head.length() * 2.0 + 1.0); + st.arrow_align = ArrowAlign::Tip; + assert_eq!(st.head_reach(true), head.reach() * 2.0 + 1.0); +} + +#[test] +fn custom_arrowheads_out_of_bounds_draw_nothing() { + let Arrowhead::Custom(c) = custom_head() else { panic!("custom") }; + let mut path = c.path.clone(); + path.subpaths[0].anchors[1] = vectorcraft_geom::Anchor::corner(vectorcraft_geom::Point::new(1e9, 0.0)); + // A file can hold what `new` drops: reading it drops it too. + let json = serde_json::to_value(CustomArrowhead { name: "Wedge".into(), path }).unwrap(); + let far: CustomArrowhead = serde_json::from_value(json).unwrap(); + assert_eq!((far.name.as_str(), far.path.subpaths.len()), ("Wedge", 0)); + assert_eq!((far.reach(), far.half_width(), far.stop()), (0.0, 0.0, 0.0)); + let anchors = vec![vectorcraft_geom::Anchor::corner(vectorcraft_geom::Point::new(1.0, 0.0)); CustomArrowhead::MAX_ANCHORS + 1]; + let many = CustomArrowhead::new("Many".into(), vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::new(anchors, true))); + assert!(many.path.subpaths.is_empty(), "too many anchors"); + // Empty subpaths add no anchors, and still count. + let mut hollow = c.path.clone(); + hollow.subpaths.extend(std::iter::repeat_n(vectorcraft_geom::SubPath::new(vec![], false), CustomArrowhead::MAX_ANCHORS)); + assert!(!CustomArrowhead::fits(&hollow), "too many subpaths"); + let json = serde_json::to_value(CustomArrowhead { name: "Hollow".into(), path: hollow }).unwrap(); + let hollow: CustomArrowhead = serde_json::from_value(json).unwrap(); + assert!(hollow.path.subpaths.is_empty(), "too many subpaths, read back"); +} + #[test] fn arrow_align_defaults_to_extend_and_round_trips() { let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 2.0); diff --git a/crates/doc/src/blend.rs b/crates/doc/src/blend.rs index d6b7eda2c5..d170bd606f 100644 --- a/crates/doc/src/blend.rs +++ b/crates/doc/src/blend.rs @@ -5,7 +5,8 @@ //! winding and to the start points that keep them from twisting, or to the anchors the Blend //! tool clicked. //! - **Paint**: colours, gradients (stops resampled to a common set when their counts differ), -//! opacity, stroke weight, dashes, miter limit and width profiles interpolate; what can't +//! opacity, stroke weight, dashes, miter limit, width profiles and the pen pressure, tilt, +//! bearing and rotation that brushes read interpolate; what can't //! (caps, joins, brushes, fonts, symbols, text content) switches halfway. //! - **Groups** pair their children in stacking order; the children one group has more of grow //! out of the other group's centre. Compound paths stay compound paths. @@ -22,7 +23,7 @@ use vectorcraft_color::{Color, Gradient, GradientPaint, GradientStop, Paint}; use vectorcraft_geom::kurbo::{ParamCurve, ParamCurveArclen, ParamCurveDeriv}; use vectorcraft_geom::{Affine, Anchor, BezPath, FillRule, PathData, Point, Rect, SubPath, Vec2}; -use crate::appearance::{Appearance, AppearanceItem, Dash, StrokeLayer, WidthProfile}; +use crate::appearance::{AngleProfile, Appearance, AppearanceItem, Dash, PressureProfile, StrokeLayer, WidthProfile}; use crate::live::{BlendOrientation, BlendSpacing, BlendSpec}; use crate::node::{Node, NodeId, NodeKind}; use crate::text::TextObject; @@ -152,6 +153,11 @@ fn lerp_gradient(a: &GradientPaint, b: &GradientPaint, t: f32) -> Option usize { a.checked_div(x).map_or(0, |q| q * b) } -/// Interpolate width profiles (none is uniform) at every position either has a width point. +/// Interpolate width profiles (none is uniform) at every position either has a width point, +/// keeping their discontinuous points (a position where either steps gives two points). fn lerp_profile(x: Option<&WidthProfile>, y: Option<&WidthProfile>, t: f64) -> Option { if x.is_none() && y.is_none() { return None; @@ -239,20 +246,135 @@ fn lerp_profile(x: Option<&WidthProfile>, y: Option<&WidthProfile>, t: f64) -> O let (x, y) = (x.unwrap_or(&uniform), y.unwrap_or(&uniform)); let mut at: Vec = x.points.iter().chain(&y.points).map(|p| p.0).filter(|p| p.is_finite()).collect(); at.sort_by(f64::total_cmp); - at.dedup_by(|a, b| (*a - *b).abs() < 1e-6); - let points = at - .into_iter() - .map(|p| { - let ((l1, r1), (l2, r2)) = (x.at(p), y.at(p)); - (p, lerp_f64(l1, l2, t), lerp_f64(r1, r2, t)) - }) - .collect(); + // Within the distance `around` reads a discontinuous point at, so a point near one keeps it. + at.dedup_by(|a, b| (*a - *b).abs() <= 1e-7); + // Each profile is a smooth curve through its own points: samples between the positions keep + // both curves' shapes where the other profile's points and steps change the tangents. Two + // profiles with points at the same positions need none (so a preset on both keys stays it). + let same_positions = x.points.len() == y.points.len() && x.points.iter().zip(&y.points).all(|(p, q)| (p.0 - q.0).abs() <= 1e-7); + let per_span = if same_positions { 1 } else { (4096 / at.len().max(1)).clamp(1, 8) }; + let mut points = Vec::with_capacity(at.len() * per_span + 2); + let mix = |p: f64, (l1, r1): (f64, f64), (l2, r2): (f64, f64)| (p, lerp_f64(l1, l2, t), lerp_f64(r1, r2, t)); + for (k, &p) in at.iter().enumerate() { + let ((xb, xa), (yb, ya)) = (x.around(p), y.around(p)); + points.push(mix(p, xb, yb)); + // A discontinuous point ends the curve on each side even where both widths match. + if steps_at(x, p) || steps_at(y, p) { + points.push(mix(p, xa, ya)); + } + if let Some(&q) = at.get(k + 1) { + for j in 1..per_span { + let f = p + (q - p) * j as f64 / per_span as f64; + points.push(mix(f, x.at(f), y.at(f))); + } + } + } Some(WidthProfile { points }) } -/// Interpolate a stroke's paint, weight, opacity, miter limit, dashes, arrowhead scale and width -/// profile into `o` (a copy of the nearer stroke, so caps, joins, alignment, arrowheads and -/// brushes switch halfway). +/// Whether width profile `w` has a discontinuous point at `p` (two points there, within `1e-7`, +/// as [`WidthProfile::around`] reads them). +fn steps_at(w: &WidthProfile, p: f64) -> bool { + let i = w.points.partition_point(|q| q.0 < p - 1e-7); + w.points.get(i..).unwrap_or_default().iter().take_while(|q| q.0 <= p + 1e-7).count() > 1 +} + +/// The positions along the stroke where either of two pen recordings has a sample, in order. +fn sample_positions(x: Option<&[(f64, f64)]>, y: Option<&[(f64, f64)]>) -> Vec { + let mut at: Vec = x.unwrap_or_default().iter().chain(y.unwrap_or_default()).map(|p| p.0).filter(|p| p.is_finite()).collect(); + at.sort_by(f64::total_cmp); + // Within the distance `step_after` reads a step at, so a sample near a step keeps the step. + at.dedup_by(|a, b| (*a - *b).abs() <= 1e-9); + if at.is_empty() { + at = vec![0.0, 1.0]; + } + at +} + +/// The value pen recording `p` steps to at position `f`, where two or more of its samples share +/// that position (reading at `f` gives the first of them); None where it doesn't step. +fn step_after(p: Option<&[(f64, f64)]>, f: f64) -> Option { + let p = p?; + let i = p.partition_point(|q| q.0 < f - 1e-9); + let j = p.partition_point(|q| q.0 <= f + 1e-9).checked_sub(1)?; + (j > i && (p.get(i)?.0 - f).abs() <= 1e-9).then(|| p.get(j).map(|q| q.1)).flatten() +} + +/// Two pen recordings read at every position either has a sample, as (position, x's value, y's +/// value): `read_x` and `read_y` read them, and `clean` makes a stepped sample's value one they +/// would read. A position where either steps gives two, before and after the step. +fn paired_samples( + x: Option<&[(f64, f64)]>, + y: Option<&[(f64, f64)]>, + read_x: impl Fn(f64) -> f64, + read_y: impl Fn(f64) -> f64, + clean: impl Fn(f64) -> f64, +) -> Vec<(f64, f64, f64)> { + let mut out = Vec::new(); + for f in sample_positions(x, y) { + let (a, b) = (read_x(f), read_y(f)); + out.push((f, a, b)); + let (sa, sb) = (step_after(x, f), step_after(y, f)); + if sa.is_some() || sb.is_some() { + out.push((f, sa.map_or(a, &clean), sb.map_or(b, &clean))); + } + } + out +} + +/// Interpolate pen pressure or tilt recordings at every position either has a sample, keeping +/// their steps. A stroke without one reads as [`PressureProfile::MID`], as brushes read it; None +/// when neither has one. +fn lerp_pressure(x: Option<&PressureProfile>, y: Option<&PressureProfile>, t: f64) -> Option { + if x.is_none() && y.is_none() { + return None; + } + let read = |p: Option<&PressureProfile>, f: f64| p.map_or(PressureProfile::MID, |p| p.at(f)); + let clean = |v: f64| if v.is_finite() { v.clamp(0.0, 1.0) } else { PressureProfile::MID }; + let samples = paired_samples(x.map(|p| p.points.as_slice()), y.map(|p| p.points.as_slice()), |f| read(x, f), |f| read(y, f), clean); + PressureProfile::from_samples(samples.into_iter().map(|(f, a, b)| (f, lerp_f64(a, b, t)))) +} + +/// Interpolate pen angle recordings (bearing or barrel rotation) at every position either has a +/// sample: the steps turn from one key's angle to the other's the shorter way round at the +/// stroke's start, and keep the whole turns each recording makes along the stroke. A stroke +/// without one reads as 0°, as brushes read it; None when neither has one. +fn lerp_angle(x: Option<&AngleProfile>, y: Option<&AngleProfile>, t: f64) -> Option { + if x.is_none() && y.is_none() { + return None; + } + let read = |p: Option<&AngleProfile>, f: f64| p.map_or(0.0, |p| p.unwrapped_at(f)); + let clean = |v: f64| if v.is_finite() { v } else { 0.0 }; + let pairs = paired_samples(x.map(|p| p.points.as_slice()), y.map(|p| p.points.as_slice()), |f| read(x, f), |f| read(y, f), clean); + // Whole turns that bring the two angles within half a turn of each other at the first position. + let d0 = pairs.first().map_or(0.0, |&(_, a, b)| b - a); + let turns = vectorcraft_geom::normalize_deg(d0) - d0; + let value = |a: f64, b: f64| a + (b - a + turns) * t; + // Both curves are straight between two positions; samples are added where the steps turn + // through 90° or more between them, since `AngleProfile::from_samples` joins neighbours the + // shorter way round. A document's recordings can be long, so the added samples are limited. + let mut budget = 4 * PressureProfile::MAX_POINTS; + let mut samples = Vec::with_capacity(pairs.len()); + let mut prev: Option<(f64, f64)> = None; + for (f, a, b) in pairs { + let v = value(a, b); + if let Some((pf, pv)) = prev.filter(|p| f - p.0 > 1e-9) { + let parts = ((v - pv).abs() / 90.0).ceil().min((budget + 1) as f64) as usize; + for k in 1..parts { + let g = pf + (f - pf) * k as f64 / parts as f64; + samples.push((g, value(read(x, g), read(y, g)))); + } + budget -= parts.saturating_sub(1).min(budget); + } + samples.push((f, v)); + prev = Some((f, v)); + } + AngleProfile::from_samples(samples) +} + +/// Interpolate a stroke's paint, weight, opacity, miter limit, dashes, arrowhead scale, width +/// profile and the pen pressure, tilt, bearing and rotation its brush reads into `o` (a copy of +/// the nearer stroke, so caps, joins, alignment, arrowheads and brushes switch halfway). fn lerp_stroke(o: &mut StrokeLayer, x: &StrokeLayer, y: &StrokeLayer, t: f64) { let tf = t as f32; o.paint = lerp_paint(&x.paint, &y.paint, tf); @@ -262,6 +384,10 @@ fn lerp_stroke(o: &mut StrokeLayer, x: &StrokeLayer, y: &StrokeLayer, t: f64) { o.dash = lerp_dash(x.dash.as_ref(), y.dash.as_ref(), t); o.arrow_scale = (lerp_f64(x.arrow_scale.0, y.arrow_scale.0, t), lerp_f64(x.arrow_scale.1, y.arrow_scale.1, t)); o.profile = lerp_profile(x.profile.as_ref(), y.profile.as_ref(), t); + o.pressure = lerp_pressure(x.pressure.as_ref(), y.pressure.as_ref(), t); + o.tilt = lerp_pressure(x.tilt.as_ref(), y.tilt.as_ref(), t); + o.bearing = lerp_angle(x.bearing.as_ref(), y.bearing.as_ref(), t); + o.rotation = lerp_angle(x.rotation.as_ref(), y.rotation.as_ref(), t); } /// Interpolate appearance stacks: item by item when their structure matches, else the top fill @@ -385,6 +511,161 @@ fn reverse_closed(sp: &mut SubPath) { sp.anchors.rotate_right(1); } +/// How a key's subpaths were turned for its blend, so that its stroke's profiles, pen +/// recordings and arrowheads turn with it: position `u` along the turned subpath is position +/// `start + u` (`start - u` when `reversed`) along the key's own, wrapping round a closed one. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +struct Orient { + start: f64, + reversed: bool, + closed: bool, +} + +impl Orient { + fn of(sp: &SubPath) -> Self { + Self { closed: sp.closed, ..Self::default() } + } + + /// The subpath now starts at the fraction `f` of its length. + fn rotate(&mut self, f: f64) { + self.start += if self.reversed { -f } else { f }; + } + + /// The subpath now runs the other way. + fn reverse(&mut self) { + self.start += if self.reversed { -1.0 } else { 1.0 }; + self.reversed = !self.reversed; + } + + /// As [`start_at`] turns `sp` (call it before). + fn start_at(&mut self, sp: &SubPath, i: usize) { + let n = sp.anchors.len(); + if i >= n { + return; + } + if sp.closed { + self.rotate(arc_fraction(sp, i)); + } else if i + 1 == n && n > 1 { + self.reverse(); + } + } + + /// Where a closed subpath now starts, as a fraction of its length; 0 for an open one. + fn seam(&self) -> f64 { + let s = if self.closed { self.start.rem_euclid(1.0) } else { 0.0 }; + if s > 1e-9 && s < 1.0 - 1e-9 { s } else { 0.0 } + } + + fn is_identity(&self) -> bool { + !self.reversed && self.seam() == 0.0 + } + + /// Whether two subpaths were turned alike, so one stroke along both turns the same way. + fn same_turn(&self, o: &Self) -> bool { + self.reversed == o.reversed && (self.seam() - o.seam()).abs() < 1e-9 + } +} + +/// How far along `sp` its anchor `i` sits, as a fraction of its length. +fn arc_fraction(sp: &SubPath, i: usize) -> f64 { + let pos = sp.anchor_arc_positions(); + match (pos.get(i), pos.last()) { + (Some(&at), Some(&total)) if total.is_finite() && total > 1e-12 => (at / total).clamp(0.0, 1.0), + _ => 0.0, + } +} + +/// Samples (position, value) along a key's subpath, read along the subpath turned as `o` says. +/// A closed subpath starting elsewhere starts the samples there too: the ones before it move +/// past the seam (`wrap` applied), which keeps any step the seam makes, and a value between +/// samples is read with `at`. A reversed subpath then reads them backwards (`flip` applied). +fn reoriented(points: &[(f64, V)], o: Orient, at: impl Fn(f64) -> V, wrap: impl Fn(V) -> V, flip: impl Fn(V) -> V) -> Vec<(f64, V)> { + let s = o.seam(); + let mut out = points.to_vec(); + if s > 0.0 + && let (Some(&(_, first)), Some(&(_, last))) = (points.first(), points.last()) + { + let i = points.partition_point(|q| q.0 < s - 1e-9); + let j = points.partition_point(|q| q.0 <= s + 1e-9).max(i); + let (before, after) = match points.get(i..j) { + Some([p, .., q]) => (p.1, q.1), + Some([p]) => (p.1, p.1), + _ => (at(s), at(s)), + }; + out = Vec::with_capacity(points.len() + 4); + out.push((0.0, after)); + out.extend(points.get(j..).unwrap_or_default().iter().map(|&(t, v)| (t - s, v))); + out.push((1.0 - s, last)); + out.push((1.0 - s, wrap(first))); + out.extend(points.get(..i).unwrap_or_default().iter().map(|&(t, v)| (t + 1.0 - s, wrap(v)))); + out.push((1.0, wrap(before))); + } + if o.reversed { + out = out.into_iter().rev().map(|(t, v)| (1.0 - t, flip(v))).collect(); + } + out +} + +/// A key's stroke read along its subpath turned as `o` says: its width profile (whose sides swap +/// when reversed), pen pressure, tilt, bearing and rotation, and on a reversed open path its +/// arrowheads. +fn reorient_stroke(s: &mut StrokeLayer, o: Orient) { + if o.is_identity() { + return; + } + let same = |v: f64| v; + if let Some(p) = &mut s.profile { + let mut pts: Vec<(f64, (f64, f64))> = p.points.iter().map(|&(t, l, r)| (t, (l, r))).collect(); + // A width profile is a smooth curve through its points: where the new start splits a span, + // samples of that span keep its curve once its ends become ends of the profile. + let seam = o.seam(); + let i = p.points.partition_point(|q| q.0 < seam); + if seam > 0.0 + && let (Some(a), Some(b)) = (i.checked_sub(1).and_then(|j| p.points.get(j)), p.points.get(i)) + && seam - a.0 > 1e-9 + && b.0 - seam > 1e-9 + { + const SAMPLES: usize = 32; + let (a, b) = (a.0, b.0); + let extra: Vec<(f64, (f64, f64))> = + (1..SAMPLES).map(|k| a + (b - a) * k as f64 / SAMPLES as f64).filter(|f| (f - seam).abs() > 1e-9).map(|f| (f, p.at(f))).collect(); + pts.splice(i..i, extra); + } + let out = reoriented(&pts, o, |f| p.at(f), |v| v, |(l, r)| (r, l)); + p.points = out.into_iter().map(|(t, (l, r))| (t, l, r)).collect(); + } + for p in [&mut s.pressure, &mut s.tilt].into_iter().flatten() { + let out = reoriented(&p.points, o, |f| p.at(f), same, same); + p.points = out; + } + for p in [&mut s.bearing, &mut s.rotation].into_iter().flatten() { + // The samples moved past the seam carry the whole turns the recording makes along the + // stroke, so the angle does not jump by them there. + let turns = match (p.points.first(), p.points.last()) { + (Some(a), Some(b)) if (b.1 - a.1).is_finite() => ((b.1 - a.1) / 360.0).round() * 360.0, + _ => 0.0, + }; + let out = reoriented(&p.points, o, |f| p.unwrapped_at(f), |v| v + turns, same); + p.points = out; + } + if o.reversed && !o.closed { + std::mem::swap(&mut s.start_arrow, &mut s.end_arrow); + s.arrow_scale = (s.arrow_scale.1, s.arrow_scale.0); + } +} + +/// `n` with every stroke read along its subpaths turned as `o` says. +fn reorient_strokes(n: &mut Node, o: Orient) { + if o.is_identity() { + return; + } + for it in n.appearance.items.iter_mut() { + if let AppearanceItem::Stroke(s) = it { + reorient_stroke(s, o); + } + } +} + /// Anchor positions of a subpath relative to its box, scaled to unit size. fn normalised(sp: &SubPath) -> Vec { let pts = sp.anchors.iter().map(|a| a.p); @@ -422,6 +703,8 @@ fn best_rotation(a: &SubPath, b: &SubPath) -> usize { pub struct PathPair { a: Vec, b: Vec, + /// How each path's subpaths were turned, where all of them turned alike (else unturned). + orient: (Orient, Orient), } impl PathPair { @@ -433,6 +716,7 @@ impl PathPair { let cb = b.bounds().map(|r| r.center()).unwrap_or_default(); let degenerate = |like: &SubPath, c: Point| SubPath::new(vec![Anchor::corner(c); like.anchors.len().max(1)], like.closed); let (mut va, mut vb) = (Vec::with_capacity(n), Vec::with_capacity(n)); + let mut orient = (Orient::default(), Orient::default()); for i in 0..n { let (mut sa, mut sb) = match (a.subpaths.get(i), b.subpaths.get(i)) { (Some(x), Some(y)) => (x.clone(), y.clone()), @@ -440,17 +724,21 @@ impl PathPair { (None, Some(y)) => (degenerate(y, ca), y.clone()), (None, None) => continue, }; + let (mut oa, mut ob) = (Orient::of(&sa), Orient::of(&sb)); let explicit = i == 0 && (starts.0.is_some() || starts.1.is_some()); if explicit { if let Some(s) = starts.0 { + oa.start_at(&sa, s); start_at(&mut sa, s); } if let Some(s) = starts.1 { + ob.start_at(&sb, s); start_at(&mut sb, s); } } let closed = sa.closed && sb.closed && sa.anchors.len() > 2 && sb.anchors.len() > 2; if closed && (sa.area() * sb.area()) < 0.0 { + ob.reverse(); reverse_closed(&mut sb); } let m = sa.anchors.len().max(sb.anchors.len()); @@ -458,12 +746,26 @@ impl PathPair { grow(&mut sb, m); if closed && !explicit { let r = best_rotation(&sa, &sb); + if r != 0 { + ob.rotate(arc_fraction(&sb, r)); + } sb.anchors.rotate_left(r); } + // One stroke runs along every subpath of a key, each reading it by its own length, so + // it turns only when all of the key's subpaths turned alike. + if i == 0 { + orient = (oa, ob); + } + if i < a.subpaths.len() && !orient.0.same_turn(&oa) { + orient.0 = Orient::default(); + } + if i < b.subpaths.len() && !orient.1.same_turn(&ob) { + orient.1 = Orient::default(); + } va.push(sa); vb.push(sb); } - Self { a: va, b: vb } + Self { a: va, b: vb, orient } } /// The path at `t` (0 = `a`, 1 = `b`). @@ -578,7 +880,12 @@ impl Lerp { _ => Shape::Other, }, }; - Self { a: a.clone(), b: b.clone(), shape } + let (mut a, mut b) = (a.clone(), b.clone()); + if let Shape::Path { pair, .. } = &shape { + reorient_strokes(&mut a, pair.orient.0); + reorient_strokes(&mut b, pair.orient.1); + } + Self { a, b, shape } } /// The object at `t` (0 = `a`, 1 = `b`), with id 0. @@ -1019,27 +1326,39 @@ impl Spine { let s = if s.is_finite() { s.clamp(0.0, self.length()) } else { 0.0 }; let sp = &self.subpath; let n = sp.segment_count(); - let mut start = 0.0; - for i in 0..n { - let c = sp.segment(i); - let end = self.anchor_length(i + 1).unwrap_or(self.length()); - if s <= end || i + 1 == n { - let local_s = (s - start).max(0.0) / (end - start).max(1e-12) * c.arclen(1e-9); - let t = c.inv_arclen(local_s, 1e-9).clamp(0.0, 1.0); - let e = c.eval(t); - let tv = c.deriv().eval(t).to_vec2(); - // Where a handle sits on its anchor the derivative vanishes there: take the - // direction between points a little before and after instead. - let tv = if tv.hypot2() < 1e-24 { c.eval((t + 1e-3).min(1.0)) - c.eval((t - 1e-3).max(0.0)) } else { tv }; - return (Point::new(e.x, e.y), tv.y.atan2(tv.x)); - } - start = end; + if n == 0 { + return (self.pts.first().copied().unwrap_or_default(), 0.0); } - // Only a spine without segments gets here: the loop returns at the last one. - (self.pts.first().copied().unwrap_or_default(), 0.0) + let i = segment_at(&self.anchors, n, s, || {}); + let c = sp.segment(i); + let start = if i == 0 { 0.0 } else { self.anchor_length(i).unwrap_or(0.0) }; + let end = self.anchor_length(i + 1).unwrap_or(self.length()); + let local_s = (s - start).max(0.0) / (end - start).max(1e-12) * c.arclen(1e-9); + let t = c.inv_arclen(local_s, 1e-9).clamp(0.0, 1.0); + let e = c.eval(t); + let tv = c.deriv().eval(t).to_vec2(); + // Where a handle sits on its anchor the derivative vanishes there: take the + // direction between points a little before and after instead. + let tv = if tv.hypot2() < 1e-24 { c.eval((t + 1e-3).min(1.0)) - c.eval((t - 1e-3).max(0.0)) } else { tv }; + (Point::new(e.x, e.y), tv.y.atan2(tv.x)) } } +/// The segment of a spine with `n` segments (`n > 0`) that holds arc length `s`: the first one whose +/// end is at or past `s`, or the last one when none is. `anchors` holds the arc length at each +/// anchor, so segment `i` ends at `anchors[i + 1]`, and the last segment of a closed spine, which has +/// no entry for its end, ends at the spine's length. The lengths never decrease (each is a sum of +/// distances that are not negative, at most `+inf` and never NaN), so a binary search finds the +/// segment in about `log2(n)` comparisons. `probe` is called once for each comparison. +fn segment_at(anchors: &[f64], n: usize, s: f64, mut probe: impl FnMut()) -> usize { + let ends = anchors.get(1..n.min(anchors.len())).unwrap_or_default(); + ends.partition_point(|&end| { + probe(); + end < s + }) + .min(n.saturating_sub(1)) +} + /// The anchor of the first subpath each key sits on, when they are all valid for `n` anchors. fn pinned(spec: &BlendSpec, keys: usize, n: usize) -> Option> { (spec.key_anchors.len() == keys && keys >= 2 && spec.key_anchors.iter().all(|a| (*a as usize) < n)) @@ -1051,17 +1370,59 @@ fn pinned(spec: &BlendSpec, keys: usize, n: usize) -> Option> { /// - a pinned spine (`key_anchors`): the stored spine's first subpath with each key's anchor (and /// its handles) moved onto the key's centre, so moving a key moves its end of the spine; /// - a spine from Replace Spine: its first subpath, `None` for the anchors (the keys spread -/// evenly along it by arc length). +/// evenly along it by arc length) while the keys sit there; once one is moved off, pinned as +/// above at the anchors where they were spread. +/// +/// `None` for a blend made without a spine ([`BlendSpec::no_spine`]). pub fn blend_spine(keys: &[Arc], spec: &BlendSpec) -> Option<(PathData, Option>)> { + if spec.no_spine { + return None; + } + layout_spine(keys, spec) +} + +/// The line the steps of a blend of `keys` are placed along: [`blend_spine`]'s path for a blend +/// with a spine, and the straight lines between the key centers, in key order, for a blend made +/// without one ([`BlendSpec::no_spine`]). For a blend without a spine the line places the steps +/// only; it is not a spine and is not drawn as one. `None` with fewer than two keys. +pub fn blend_layout_line(keys: &[Arc], spec: &BlendSpec) -> Option { + layout_spine(keys, spec).map(|(path, _)| path) +} + +/// The spine `spec` stores, unless the blend was made without one. +fn stored_spine(spec: &BlendSpec) -> Option<&PathData> { + spec.spine.as_ref().filter(|_| !spec.no_spine) +} + +/// [`blend_spine`] for placing the steps: a blend made without a spine still places them on the +/// straight lines between its key centers. +fn layout_spine(keys: &[Arc], spec: &BlendSpec) -> Option<(PathData, Option>)> { if keys.len() < 2 { return None; } - let Some(stored) = &spec.spine else { + let Some(stored) = stored_spine(spec) else { let centers: Vec = keys.iter().map(|k| center_of(k)).collect(); return Some((PathData::single(SubPath::polyline(¢ers, false)), Some((0..keys.len()).collect()))); }; let mut first = stored.subpaths.first()?.clone(); - let Some(ka) = pinned(spec, keys.len(), first.anchors.len()) else { return Some((PathData::single(first), None)) }; + let Some(ka) = pinned(spec, keys.len(), first.anchors.len()) else { + let mut path = PathData::single(first); + // A key moved off where Replace Spine spread it takes its point of the spine along, as + // on a pinned spine; otherwise the steps would put it back on the spine (#6809). + if Spine::new(&path).is_none_or(|sp| keys_spread_along(keys, &sp)) { + return Some((path, None)); + } + let Some(mut ka) = spread_anchors(&mut path, keys.len()) else { return Some((path, None)) }; + let mut first = path.subpaths.into_iter().next()?; + open_at_start(&mut first, &mut ka); + for (k, &ai) in keys.iter().zip(&ka) { + if let Some(a) = first.anchors.get_mut(ai) { + let d = center_of(k) - a.p; + a.translate(d); + } + } + return Some((PathData::single(first), Some(ka))); + }; for (k, &ai) in keys.iter().zip(&ka) { let c = center_of(k); if let Some(a) = first.anchors.get_mut(ai) { @@ -1075,21 +1436,62 @@ pub fn blend_spine(keys: &[Arc], spec: &BlendSpec) -> Option<(PathData, Op /// [`blend_spine`] with every key on an anchor: a spine from Replace Spine gets anchors where its /// keys sit (by arc length), so editing it keeps them in place. pub fn pin_spine(keys: &[Arc], spec: &BlendSpec) -> Option<(PathData, Vec)> { - let (mut path, anchors) = blend_spine(keys, spec)?; - if let Some(a) = anchors { - return Some((path, a)); + // A spine from Replace Spine is pinned as stored, even with a key moved off it (where + // [`blend_spine`] moves that key's point along): the layout is the same. + if keys.len() >= 2 + && let Some(first) = stored_spine(spec).and_then(|s| s.subpaths.first()) + && pinned(spec, keys.len(), first.anchors.len()).is_none() + { + let mut path = PathData::single(first.clone()); + let mut out = spread_anchors(&mut path, keys.len())?; + // A closed spine's end keys get points of their own, so that once pinned each still + // moves only its own end. + let mut sp = path.subpaths.into_iter().next()?; + open_at_start(&mut sp, &mut out); + return Some((PathData::single(sp), out)); } + let (path, anchors) = blend_spine(keys, spec)?; + Some((path, anchors?)) +} + +/// Do `keys` sit where a spine from Replace Spine spreads them: evenly along `spine` by arc length +/// (within a hundredth of a point, as [`anchor_at_length`] matches anchors)? +fn keys_spread_along(keys: &[Arc], spine: &Spine) -> bool { let k = keys.len(); - let total = Spine::new(&path)?.length(); + keys.iter().enumerate().all(|(i, key)| { + let f = if k > 1 { i as f64 / (k - 1) as f64 } else { 0.0 }; + center_of(key).distance(spine.at(f).0) < 0.01 + }) +} + +/// Open closed spine `sp` at its first anchor when the last key sits there with the first (as +/// [`spread_anchors`] puts them): a copy of that anchor at the end takes the closing segment and +/// the last key, so the two end keys move their ends of the spine apart. +fn open_at_start(sp: &mut SubPath, ka: &mut [usize]) { + let Some(&start) = sp.anchors.first() else { return }; + if !sp.closed || ka.len() < 2 { + return; + } + if let Some(last) = ka.last_mut().filter(|a| **a == 0) { + *last = sp.anchors.len(); + sp.anchors.push(start); + sp.closed = false; + } +} + +/// The anchors of `path`'s first subpath that `k` keys spread evenly along it by arc length sit +/// on, splitting segments where none is. +fn spread_anchors(path: &mut PathData, k: usize) -> Option> { + let total = Spine::new(path)?.length(); let closed = path.subpaths.first().is_some_and(|s| s.closed); let mut out = vec![0usize]; for i in 1..k.saturating_sub(1) { let s = total * i as f64 / (k - 1) as f64; - out.push(anchor_at_length(&mut path, s)?); + out.push(anchor_at_length(path, s)?); } let last = path.subpaths.first().map_or(0, |sp| if closed { 0 } else { sp.anchors.len().saturating_sub(1) }); out.push(last); - Some((path, out)) + Some(out) } /// The anchor of the first subpath at arc length `s`: an existing one within a hundredth of a @@ -1127,10 +1529,10 @@ impl Rail { /// `None` when nothing moves: no stored spine and the steps keep the page's orientation. fn new(keys: &[Arc], spec: &BlendSpec) -> Option { let rotate = spec.orientation == BlendOrientation::AlignToPath; - if spec.spine.is_none() && !rotate { + if stored_spine(spec).is_none() && !rotate { return None; } - let (path, anchors) = blend_spine(keys, spec)?; + let (path, anchors) = layout_spine(keys, spec)?; let spine = Spine::new(&path)?; let total = spine.length(); let k = keys.len(); @@ -1192,10 +1594,10 @@ impl Rail { /// spine it is moved to, and so does its own centre, which it turns about. `None` when nothing /// moves. pub(crate) fn rail_reach(keys: &[Arc], spec: &BlendSpec, symbols: Option<&crate::SymbolBoxes>) -> Option { - if spec.spine.is_none() && spec.orientation != BlendOrientation::AlignToPath { + if stored_spine(spec).is_none() && spec.orientation != BlendOrientation::AlignToPath { return None; } - let spine = blend_spine(keys, spec)?.0.bounds()?; + let spine = layout_spine(keys, spec)?.0.bounds()?; let radius = keys .iter() .filter_map(|k| { @@ -1404,7 +1806,9 @@ pub fn blend_expand(keys: &[Arc], spec: &BlendSpec) -> Vec { for j in 1..=n { // Even position of the step, then where the easing puts its shape and its colours. let u = j as f64 / (n + 1) as f64; - let (t, tc) = (if rail.is_some() { spec.ease.apply(u) } else { u }, spec.color_position(u)); + // Easing needs a spine: a blend made without one keeps its steps evenly spaced. + let eased = rail.is_some() && spec.eases_along_spine(); + let (t, tc) = (if eased { spec.ease.apply(u) } else { u }, spec.color_position(u)); let mut s = lerp.at_eased(t, tc); if let Some(r) = &rail { r.place(&mut s, i, t); @@ -1418,6 +1822,7 @@ pub fn blend_expand(keys: &[Arc], spec: &BlendSpec) -> Vec { #[cfg(test)] mod tests { use super::*; + use crate::appearance::Arrowhead; use vectorcraft_geom::{Rect, shapes}; #[test] @@ -1455,6 +1860,28 @@ mod tests { assert_eq!(moved.subpaths[0].anchors[2].p, Point::new(305.0, 5.0)); } + #[test] + fn a_blend_without_a_spine_has_a_layout_line_through_its_key_centers() { + let at = + |x: f64, y: f64| Arc::new(Node::path(NodeId(1), shapes::rectangle(Rect::new(x - 5.0, y - 5.0, x + 5.0, y + 5.0)), Appearance::default())); + let line_of = |path: &PathData| path.subpaths.iter().flat_map(|s| s.anchors.iter().map(|a| a.p)).collect::>(); + // A stored spine is ignored once the blend is made without one. + let stored = PathData::single(SubPath::polyline(&[Point::new(0.0, 50.0), Point::new(300.0, 50.0)], false)); + let spec = BlendSpec { no_spine: true, spine: Some(stored), ..Default::default() }; + for keys in [vec![at(10.0, 20.0), at(110.0, 20.0)], vec![at(10.0, 20.0), at(110.0, 20.0), at(110.0, 220.0), at(-40.0, 0.0)]] { + assert!(blend_spine(&keys, &spec).is_none(), "still no spine"); + let line = blend_layout_line(&keys, &spec).unwrap(); + assert_eq!(line.subpaths.len(), 1); + assert!(!line.subpaths[0].closed); + let centers: Vec = keys.iter().map(|k| center_of(k)).collect(); + assert_eq!(line_of(&line), centers, "in key order"); + } + // With a spine, the layout line is the spine. + let keys = vec![key(0.0), key(100.0), key(300.0)]; + assert_eq!(blend_layout_line(&keys, &BlendSpec::default()), blend_spine(&keys, &BlendSpec::default()).map(|(p, _)| p)); + assert!(blend_layout_line(&keys[..1], &spec).is_none(), "one key"); + } + #[test] fn steps_follow_a_bent_spine() { let keys = vec![key(0.0), key(100.0)]; @@ -1506,6 +1933,76 @@ mod tests { assert!(end.is_finite(), "{end}"); } + /// [`Spine::at_length`] by walking the segments from the first, as a reference for the search. + fn walked_at_length(sp: &Spine, s: f64) -> (Point, f64) { + let s = if s.is_finite() { s.clamp(0.0, sp.length()) } else { 0.0 }; + let n = sp.subpath.segment_count(); + let mut start = 0.0; + for i in 0..n { + let c = sp.subpath.segment(i); + let end = sp.anchor_length(i + 1).unwrap_or(sp.length()); + if s <= end || i + 1 == n { + let local_s = (s - start).max(0.0) / (end - start).max(1e-12) * c.arclen(1e-9); + let t = c.inv_arclen(local_s, 1e-9).clamp(0.0, 1.0); + let e = c.eval(t); + let tv = c.deriv().eval(t).to_vec2(); + let tv = if tv.hypot2() < 1e-24 { c.eval((t + 1e-3).min(1.0)) - c.eval((t - 1e-3).max(0.0)) } else { tv }; + return (Point::new(e.x, e.y), tv.y.atan2(tv.x)); + } + start = end; + } + panic!("a spine without segments") + } + + /// The search picks the same segment as walking them in order, so points and tangents stay the + /// same: on open and closed spines, one segment, curves, and zero-length segments whose anchors + /// share an arc length; at every anchor, between anchors, at both ends, past them, and for + /// values that are not finite. + #[test] + fn spine_lookup_matches_walking_the_segments() { + let p = Point::new; + let bow = SubPath::new( + vec![Anchor::smooth(p(0.0, 0.0), p(50.0, 50.0)), Anchor::smooth(p(100.0, 0.0), p(150.0, -50.0)), Anchor::corner(p(200.0, 0.0))], + false, + ); + let spines = [ + SubPath::polyline(&[p(0.0, 0.0), p(10.0, 0.0), p(10.0, 0.0), p(10.0, 0.0), p(30.0, 5.0), p(30.0, 5.0)], false), + SubPath::polyline(&[p(0.0, 0.0), p(0.0, 0.0), p(40.0, 0.0), p(40.0, 30.0)], true), + SubPath::polyline(&[p(0.0, 0.0), p(40.0, 0.0), p(40.0, 30.0), p(0.0, 0.0)], true), + SubPath::polyline(&[p(0.0, 0.0), p(25.0, 25.0)], false), + SubPath::polyline(&[p(0.0, 0.0), p(25.0, 25.0)], true), + bow.clone(), + SubPath { closed: true, ..bow }, + ]; + for sub in spines { + let sp = Spine::new(&PathData::single(sub)).unwrap(); + let len = sp.length(); + let mut lengths = vec![0.0, len, -1.0, len + 1.0, -len, f64::NAN, f64::INFINITY, f64::NEG_INFINITY, f64::MAX, f64::MIN]; + lengths.extend(sp.anchors.iter().flat_map(|&a| [a, a - 1e-9, a + 1e-9])); + lengths.extend((0..=400).map(|k| len * k as f64 / 400.0)); + for s in lengths { + assert_eq!(sp.at_length(s), walked_at_length(&sp, s), "s = {s} on {:?}", sp.anchors); + } + } + } + + /// Finding the segment for an arc length on a spine of thousands of segments takes a few + /// comparisons, not one for each segment before it. + #[test] + fn spine_lookup_compares_a_few_segment_ends() { + let pts: Vec = (0..=4096).map(|i| Point::new(i as f64, if i % 2 == 0 { 0.0 } else { 1.0 })).collect(); + let sp = Spine::new(&PathData::single(SubPath::polyline(&pts, false))).unwrap(); + let n = sp.subpath.segment_count(); + assert_eq!(n, 4096); + for s in [sp.length() - 0.5, sp.length(), sp.length() / 2.0, 0.25] { + let mut compared = 0; + let i = segment_at(&sp.anchors, n, s, || compared += 1); + assert!(compared <= 13, "{compared} comparisons at {s}"); + assert_eq!(sp.at_length(s), walked_at_length(&sp, s)); + assert!(sp.anchors[i] <= s && (i + 1 == n || s <= sp.anchors[i + 1]), "segment {i} at {s}"); + } + } + #[test] fn easing_keeps_the_ends_and_stays_monotone() { use crate::live::{BlendEase, BlendEaseType as K}; @@ -1579,6 +2076,25 @@ mod tests { assert!(pair.at(0.5).bounds().unwrap().height() < 1e-6, "the clicked anchors pair up"); } + /// A blend between two gradients that repeat steps the count; one between a gradient that + /// pads and one that repeats switches halfway, as the method does. + #[test] + fn blend_between_repeating_gradients_steps_the_count() { + use vectorcraft_color::GradientSpread; + let spread = |spread, repeats| Paint::Gradient(Box::new(GradientPaint::new(Gradient { spread, repeats, ..Gradient::default() }))); + let at = |a: &Paint, b: &Paint, t: f32| match lerp_paint(a, b, t) { + Paint::Gradient(g) => (g.gradient.spread, g.gradient.repeat_count()), + p => panic!("a gradient, not {p:?}"), + }; + let (two, twenty) = (spread(GradientSpread::Repeat, 2), spread(GradientSpread::Repeat, 20)); + assert_eq!(at(&two, &twenty, 0.25), (GradientSpread::Repeat, 7)); + assert_eq!(at(&two, &twenty, 0.5), (GradientSpread::Repeat, 11)); + assert_eq!(at(&two, &twenty, 1.0), (GradientSpread::Repeat, 20)); + let pad = spread(GradientSpread::Pad, 1); + assert_eq!(at(&pad, &twenty, 0.25), (GradientSpread::Pad, 1)); + assert_eq!(at(&pad, &twenty, 0.75), (GradientSpread::Repeat, 20)); + } + #[test] fn blend_between_tints_of_one_swatch_keeps_the_link() { let tinted = |tint: f32| Paint::Solid { color: Color::cmyk(1.0, 0.7, 0.0, 0.4).tinted(tint), swatch: Some("Spot".into()), tint }; @@ -1654,6 +2170,146 @@ mod tests { assert_eq!(p.at(0.5), (1.0, 1.0)); } + #[test] + fn pen_pressure_tilt_and_angles_interpolate_for_brushes() { + let stroked = |pressure: Option, tilt: Option, bearing: Option| { + let mut ap = Appearance::default(); + ap.set_stroke(Paint::solid(Color::BLACK)); + if let Some(s) = ap.stroke_mut() { + s.brush = Some("Pressure Round".into()); + s.pressure = pressure.map(|p| PressureProfile { points: vec![(0.0, p), (1.0, p)] }); + s.tilt = tilt.map(|p| PressureProfile { points: vec![(0.0, p), (1.0, p)] }); + s.bearing = bearing.map(|a| AngleProfile { points: vec![(0.0, a), (1.0, a)] }); + } + ap + }; + let at = |ap: &Appearance, f: f64| { + let s = ap.stroke().cloned().unwrap_or_else(|| panic!("a stroke")); + let read = |p: Option<&PressureProfile>| p.map_or(PressureProfile::MID, |p| p.at(f)); + (read(s.pressure.as_ref()), read(s.tilt.as_ref()), s.bearing.as_ref().map_or(0.0, |p| p.at(f))) + }; + let (light, heavy) = (stroked(Some(0.0), Some(0.2), Some(170.0)), stroked(Some(1.0), Some(0.6), Some(-170.0))); + let (p, tilt, bearing) = at(&lerp_appearance(&light, &heavy, 0.25), 0.5); + assert!((p - 0.25).abs() < 1e-9 && (tilt - 0.3).abs() < 1e-9, "a quarter of the way: {p} {tilt}"); + assert!((bearing - 175.0).abs() < 1e-9, "the angle turns the shorter way round, through 180°: {bearing}"); + assert!((at(&lerp_appearance(&light, &heavy, 0.5), 0.5).2.abs() - 180.0).abs() < 1e-9); + // A stroke drawn without a recording reads as half pressure, half tilt and 0°. + let plain = stroked(None, None, None); + let (p, tilt, bearing) = at(&lerp_appearance(&heavy, &plain, 0.5), 0.0); + assert!((p - 0.75).abs() < 1e-9 && (tilt - 0.55).abs() < 1e-9 && (bearing + 85.0).abs() < 1e-9, "{p} {tilt} {bearing}"); + // Profiles that vary along the stroke interpolate at each position. + let mut ramp = stroked(None, None, None); + if let Some(s) = ramp.stroke_mut() { + s.pressure = Some(PressureProfile { points: vec![(0.0, 0.0), (1.0, 1.0)] }); + } + let mid = lerp_appearance(&ramp, &heavy, 0.5); + assert!((at(&mid, 0.0).0 - 0.5).abs() < 1e-9 && (at(&mid, 0.5).0 - 0.75).abs() < 1e-9, "{:?}", mid.stroke().map(|s| &s.pressure)); + // A step in a recording (two samples at one position) stays a step. + let mut stepped = stroked(None, None, None); + if let Some(s) = stepped.stroke_mut() { + s.pressure = Some(PressureProfile { points: vec![(0.0, 0.0), (0.5, 0.0), (0.5, 1.0), (1.0, 1.0)] }); + } + let mid = lerp_appearance(&stepped, &stepped, 0.5); + assert!(at(&mid, 0.25).0.abs() < 1e-9 && (at(&mid, 0.75).0 - 1.0).abs() < 1e-9, "{:?}", mid.stroke().map(|s| &s.pressure)); + // A whole turn recorded along a stroke stays a whole turn in the steps. + let mut turning = stroked(None, None, None); + if let Some(s) = turning.stroke_mut() { + s.rotation = Some(AngleProfile { points: vec![(0.0, 0.0), (1.0, 360.0)] }); + } + let rot = |ap: &Appearance, f: f64| ap.stroke().and_then(|s| s.rotation.as_ref()).map_or(0.0, |p| p.at(f)); + let same = lerp_appearance(&turning, &turning, 0.5); + assert!((rot(&same, 0.25) - 90.0).abs() < 1e-9 && (rot(&same, 0.5).abs() - 180.0).abs() < 1e-9, "{:?}", same.stroke().map(|s| &s.rotation)); + let half = lerp_appearance(&turning, &plain, 0.5); + assert!((rot(&half, 0.5) - 90.0).abs() < 1e-9 && (rot(&half, 1.0).abs() - 180.0).abs() < 1e-9, "{:?}", half.stroke().map(|s| &s.rotation)); + // Neither key has a recording: the steps have none either. + let none = lerp_appearance(&plain, &plain, 0.5); + let s = none.stroke().cloned().unwrap_or_else(|| panic!("a stroke")); + assert!(s.pressure.is_none() && s.tilt.is_none() && s.bearing.is_none() && s.rotation.is_none()); + } + + #[test] + fn a_point_near_the_other_keys_step_keeps_the_step() { + let flat = PressureProfile { points: vec![(0.0, 0.0), (0.4999995, 0.0), (1.0, 0.0)] }; + let stepped = PressureProfile { points: vec![(0.0, 0.0), (0.5, 0.0), (0.5, 1.0), (1.0, 1.0)] }; + let p = lerp_pressure(Some(&flat), Some(&stepped), 1.0).unwrap_or_default(); + assert!((p.at(0.75) - 1.0).abs() < 1e-9, "{p:?}"); + let narrow = WidthProfile { points: vec![(0.0, 1.0, 1.0), (0.4999995, 1.0, 1.0), (1.0, 1.0, 1.0)] }; + let stepped = WidthProfile { points: vec![(0.0, 1.0, 1.0), (0.5, 1.0, 1.0), (0.5, 0.0, 0.0), (1.0, 0.0, 0.0)] }; + let w = lerp_profile(Some(&narrow), Some(&stepped), 1.0).unwrap_or_default(); + assert!(w.at(0.75).0.abs() < 1e-9, "{w:?}"); + // The other key's step doesn't reshape a smooth profile's curve. + let early = WidthProfile { points: vec![(0.0, 1.0, 1.0), (0.25, 1.0, 1.0), (0.25, 0.5, 0.5), (1.0, 0.5, 0.5)] }; + let w = lerp_profile(Some(&WidthProfile::lens()), Some(&early), 0.0).unwrap_or_default(); + for u in [0.1, 0.125, 0.2, 0.3, 0.4] { + let (got, want) = (w.at(u).0, WidthProfile::lens().at(u).0); + assert!((got - want).abs() < 5e-3, "at {u}: {got} for {want}: {w:?}"); + } + let lens = WidthProfile::lens(); + assert_eq!(lerp_profile(Some(&lens), Some(&lens), 0.5).and_then(|p| p.preset_id()), Some("lens")); + } + + #[test] + fn stroke_profiles_turn_with_a_key_path_started_elsewhere() { + let keyed = |path: PathData, edit: &dyn Fn(&mut StrokeLayer)| { + let mut ap = Appearance::default(); + ap.set_stroke(Paint::solid(Color::BLACK)); + if let Some(s) = ap.stroke_mut() { + edit(s); + } + Node::path(NodeId(1), path, ap) + }; + let stroke = |n: &Node| n.appearance.stroke().cloned().unwrap_or_else(|| panic!("a stroke")); + let pressure = |s: &StrokeLayer, f: f64| s.pressure.as_ref().map_or(PressureProfile::MID, |p| p.at(f)); + // An open key clicked at its last anchor runs the other way, and so do its pressure, its + // width profile (whose sides swap) and its arrowheads. + let line = |x: f64| PathData::single(SubPath::polyline(&[Point::new(x, 0.0), Point::new(x + 10.0, 0.0)], false)); + let light = keyed(line(0.0), &|s| s.pressure = Some(PressureProfile { points: vec![(0.0, 0.0), (1.0, 0.0)] })); + let ramp = keyed(line(100.0), &|s| { + s.pressure = Some(PressureProfile { points: vec![(0.0, 1.0), (1.0, 0.0)] }); + s.profile = Some(WidthProfile { points: vec![(0.0, 1.0, 0.0), (1.0, 0.0, 0.0)] }); + s.start_arrow = Some(Arrowhead::Triangle); + s.arrow_scale = (200.0, 100.0); + }); + let blend = Lerp::new(&light, &ramp, (None, Some(1))); + let s = stroke(&blend.at(0.25)); + assert!(pressure(&s, 0.0).abs() < 1e-9 && (pressure(&s, 1.0) - 0.25).abs() < 1e-9, "{:?}", s.pressure); + let s = stroke(&blend.at(1.0)); + assert_eq!(s.profile.as_ref().map(|p| p.at(1.0)), Some((0.0, 1.0)), "{:?}", s.profile); + assert_eq!((s.start_arrow, s.end_arrow, s.arrow_scale), (None, Some(Arrowhead::Triangle), (100.0, 200.0))); + // A key whose other subpaths keep their direction keeps its one stroke as it is. + let two = |x: f64| { + let sub = |y: f64| SubPath::polyline(&[Point::new(x, y), Point::new(x + 10.0, y)], false); + PathData::new(vec![sub(0.0), sub(20.0)]) + }; + let ramps = keyed(two(100.0), &|s| s.pressure = Some(PressureProfile { points: vec![(0.0, 1.0), (1.0, 0.0)] })); + let s = stroke(&Lerp::new(&keyed(two(0.0), &|_| {}), &ramps, (None, Some(1))).at(1.0)); + assert!((pressure(&s, 0.0) - 1.0).abs() < 1e-9, "{:?}", s.pressure); + // A closed key started half way round starts its recordings there too, keeping the step + // where its own start was and the whole turn its rotation makes. + let square = |x: f64| shapes::rectangle(Rect::new(x, 0.0, x + 10.0, 10.0)); + let plain = keyed(square(0.0), &|_| {}); + let turning = keyed(square(100.0), &|s| { + s.pressure = Some(PressureProfile { points: vec![(0.0, 0.0), (1.0, 1.0)] }); + s.rotation = Some(AngleProfile { points: vec![(0.0, 0.0), (1.0, 360.0)] }); + s.profile = Some(WidthProfile { points: vec![(0.0, 1.0, 1.0), (1.0, 0.0, 0.0)] }); + }); + let blend = Lerp::new(&plain, &turning, (Some(0), Some(2))); + let s = stroke(&blend.at(1.0)); + assert!((pressure(&s, 0.25) - 0.75).abs() < 1e-9 && (pressure(&s, 0.75) - 0.25).abs() < 1e-9, "{:?}", s.pressure); + let width = s.profile.as_ref().map_or((1.0, 1.0), |p| p.at(0.75)); + assert!((width.0 - 0.75).abs() < 1e-6 && (width.1 - 0.75).abs() < 1e-6, "the width steps where the key started: {:?}", s.profile); + // A width curve split by the new start keeps its shape. + let lensed = keyed(square(100.0), &|s| s.profile = Some(WidthProfile::lens())); + let s = stroke(&Lerp::new(&plain, &lensed, (Some(0), Some(1))).at(1.0)); + for u in [0.05, 0.125, 0.2, 0.6, 0.7, 0.74, 0.76, 0.8, 0.875, 0.95] { + let (got, want) = (s.profile.as_ref().map_or(1.0, |p| p.at(u).0), WidthProfile::lens().at((u + 0.25) % 1.0).0); + assert!((got - want).abs() < 2e-3, "at {u}: {got} for {want}: {:?}", s.profile); + } + let rot = |t: f64, f: f64| stroke(&blend.at(t)).rotation.as_ref().map_or(0.0, |p| p.unwrapped_at(f)); + assert!((vectorcraft_geom::normalize_deg(rot(1.0, 0.25)) + 90.0).abs() < 1e-6, "{:?}", s.rotation); + assert!((rot(0.5, 0.499) - rot(0.5, 0.501)).abs() < 1.0, "no jump where the key started: {:?}", stroke(&blend.at(0.5)).rotation); + } + #[test] fn odd_dash_blends_to_solid_with_closed_gaps() { let d = lerp_dash(Some(&Dash { pattern: vec![2.0, 3.0, 4.0], ..Default::default() }), None, 1.0).unwrap(); diff --git a/crates/doc/src/canvas_range.rs b/crates/doc/src/canvas_range.rs index e4f267a8b6..491b79f158 100644 --- a/crates/doc/src/canvas_range.rs +++ b/crates/doc/src/canvas_range.rs @@ -15,7 +15,8 @@ pub struct BeyondCanvas { /// Objects removed whole (a layer or group keeps its children within the canvas). pub objects: usize, pub artboards: usize, - /// Guides beyond the canvas, and the artboard guides of the artboards removed. + /// Guides beyond the canvas, the artboard guides of the artboards removed, and the layer + /// guides of the layers removed. pub guides: usize, /// The ruler origin was beyond the canvas and is back at the origin. pub ruler_origin: bool, @@ -100,11 +101,20 @@ fn layers_in(n: &Node, layers: &mut Vec) { } } +/// How many ruler guides the layers in `n` hold, if it is a layer or group. +fn guides_in(n: &Node) -> usize { + match clipping(n) { + None => 0, + Some(_) => n.children().into_iter().flatten().map(|c| if c.is_ruler_guide() { 1 } else { guides_in(c) }).sum(), + } +} + /// Remove the objects in `node` that reach beyond the canvas: a layer or group keeps those of its /// objects within it, unless its clipping path reaches beyond (see [`clips_beyond`]); anything /// else goes whole. Only containers holding such an object are copied. Recursion follows the -/// nesting, which [`Document::limit_depth`] bounds. The layers removed are added to `layers`. -fn drop_children_beyond(node: &mut Arc, dropped: &mut usize, layers: &mut Vec) { +/// nesting, which [`Document::limit_depth`] bounds. The layers removed are added to `layers`, and +/// the ruler guides they held to `guides`. +fn drop_children_beyond(node: &mut Arc, dropped: &mut usize, layers: &mut Vec, guides: &mut usize) { if !node.children().is_some_and(|c| c.iter().any(|c| reaches_beyond(c))) { return; } @@ -114,10 +124,11 @@ fn drop_children_beyond(node: &mut Arc, dropped: &mut usize, layers: &mut return true; } if clipping(c).is_some() && !clips_beyond(c) { - drop_children_beyond(c, dropped, layers); + drop_children_beyond(c, dropped, layers, guides); return true; } layers_in(c, layers); + *guides += guides_in(c); *dropped += 1; false }); @@ -159,13 +170,14 @@ impl Document { for c in children.iter() { layers_in(c, &mut layers); } - // The layer's own ruler guides stay; only its art goes. + // The layer's own ruler guides stay; only its art goes, with its sublayers' guides. gone.objects += children.iter().filter(|c| !c.is_ruler_guide()).count(); + gone.guides += children.iter().filter(|c| !c.is_ruler_guide()).map(|c| guides_in(c)).sum::(); children.retain(|c| c.is_ruler_guide()); *clip = false; } } else { - drop_children_beyond(layer, &mut gone.objects, &mut layers); + drop_children_beyond(layer, &mut gone.objects, &mut layers, &mut gone.guides); } } if gone.objects > 0 { @@ -184,7 +196,7 @@ impl Document { let guides = self.saved_guides.len(); self.saved_guides .retain(|g| in_range(g.pos) && g.artboard.is_none_or(|a| !removed.contains(&a)) && g.layer.is_none_or(|l| !layers.contains(&l))); - gone.guides = guides - self.saved_guides.len(); + gone.guides += guides - self.saved_guides.len(); let out = |n: &Node| match n.kind { NodeKind::RulerGuide { pos, artboard, .. } => !in_range(pos) || artboard.is_some_and(|a| removed.contains(&a)), _ => false, @@ -324,6 +336,21 @@ mod tests { let layer = d2.layers[0].id.0; assert_eq!(d2.drop_beyond_canvas().objects, 1); assert_eq!(ids(&d2), [layer, 10]); + // The guides of a sublayer emptied out of a top-level layer go with it, counted. + let probe = Document::new(1.0, 1.0); + let sub = sublayer(&probe, 40, vec![rect(41, 0.0)], false); + let mut d3 = doc(vec![rect(10, 1e17), sub]); + if let NodeKind::Layer { clip, .. } = &mut Arc::make_mut(&mut d3.layers[0]).kind { + *clip = true; + } + d3.saved_guides = + vec![Guide { layer: Some(NodeId(40)), ..Guide::new(false, 5.0) }, Guide { layer: Some(d3.layers[0].id), ..Guide::new(true, 5.0) }]; + let mut nodes = d3.clone(); + assert_eq!(nodes.guides_into_nodes(), 2); + let gone = d3.drop_beyond_canvas(); + assert_eq!((gone.objects, gone.guides), (2, 1), "the clipping path, the sublayer and its guide; the layer's own guide stays"); + assert_eq!(nodes.drop_beyond_canvas(), gone); + assert_eq!(nodes.ruler_guides().len(), 1); assert_eq!(d.drop_beyond_canvas(), BeyondCanvas::default()); } @@ -353,8 +380,13 @@ mod tests { ]; d.variables.bindings.insert(NodeId(11), ["v".to_string()].into()); d.variables.bindings.insert(NodeId(10), ["w".to_string()].into()); + // The same guides as nodes, as a document has them once read. + let mut nodes = d.clone(); + assert_eq!(nodes.guides_into_nodes(), 2); let gone = d.drop_beyond_canvas(); assert_eq!((gone.objects, gone.guides), (2, 1), "the far rectangle, the clipping sublayer and its layer guide"); + assert_eq!(nodes.drop_beyond_canvas(), gone, "a guide node goes with its sublayer, counted as a saved one is"); + assert_eq!(nodes.ruler_guides().len(), 1); assert_eq!(d.saved_guides.len(), 1, "the guide of a layer that stays, stays"); assert_eq!(d.saved_selections[0].objects, [NodeId(10)]); assert_eq!(d.assets.iter().map(|a| (a.id, a.nodes.clone())).collect::>(), [(2, vec![NodeId(10)])]); diff --git a/crates/doc/src/cmyk.rs b/crates/doc/src/cmyk.rs index e487226d4f..e89d63cb54 100644 --- a/crates/doc/src/cmyk.rs +++ b/crates/doc/src/cmyk.rs @@ -133,6 +133,28 @@ pub(crate) fn tiff(bytes: &[u8]) -> Option<(tiff::ColorType, tiff::decoder::Deco Some((d.colortype().ok()?, d)) } +/// The Orientation tag of TIFF `bytes`' first image, of any unsigned type; `None` for other images +/// and TIFFs without one. Reads only its header. +pub fn tiff_orientation(bytes: &[u8]) -> Option { + let (_, mut d) = tiff(bytes)?; + d.find_tag_unsigned::(tiff::tags::Tag::Orientation).ok().flatten() +} + +/// The EXIF orientation of encoded image `bytes` when it turns or flips the pixels; `None` when +/// it leaves them as stored, or the image has none. A TIFF the image decoder can't open (one with +/// extra samples) has its Orientation tag read from its first image ([`tiff_orientation`]). Reads +/// only the image's header and metadata; `None` for an [`oversized_tiff`], which no decoder opens. +pub fn exif_orientation(bytes: &[u8]) -> Option { + use image::ImageDecoder as _; + use image::metadata::Orientation; + if oversized_tiff(bytes).is_some() { + return None; + } + let decoded = || image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?.into_decoder().ok()?.orientation().ok(); + let tagged = || tiff_orientation(bytes).and_then(|v| Orientation::from_exif(u8::try_from(v).ok()?)); + decoded().or_else(tagged).filter(|o| *o != Orientation::NoTransforms) +} + /// Does the TIFF `d` reads store one plane per channel (PlanarConfiguration 2)? fn planar(d: &mut tiff::decoder::Decoder>) -> bool { d.find_tag_unsigned::(tiff::tags::Tag::PlanarConfiguration).ok().flatten().is_some_and(|p| p != 1) @@ -143,25 +165,181 @@ fn planar(d: &mut tiff::decoder::Decoder>) -> bool { /// stores each pixel's samples together or one plane per channel. `None` when they don't decode to /// that many samples, which includes images whose planes together need more than the decoder's /// limit (256 MB of samples). -fn read_samples(d: &mut tiff::decoder::Decoder>, n: usize, per: usize) -> Option> { +pub(crate) fn read_samples(d: &mut tiff::decoder::Decoder>, n: usize, per: usize) -> Option> { + Some(match read_samples_at_depth(d, n, per)? { + Samples::Eight(v) => v, + Samples::Sixteen(v) => v.iter().map(|s| (s >> 8) as u8).collect(), + }) +} + +/// Samples of an image, pixel by pixel, at the depth its file stores them. +#[derive(Clone, Debug, PartialEq)] +enum Samples { + Eight(Vec), + Sixteen(Vec), +} + +impl Samples { + fn as_slice(&self) -> SampleSlice<'_> { + match self { + Self::Eight(v) => SampleSlice::Eight(v), + Self::Sixteen(v) => SampleSlice::Sixteen(v), + } + } +} + +/// [`Samples`], borrowed. +#[derive(Clone, Copy, Debug)] +enum SampleSlice<'a> { + Eight(&'a [u8]), + Sixteen(&'a [u16]), +} + +/// [`read_samples`], keeping 16-bit samples at 16 bits. +fn read_samples_at_depth(d: &mut tiff::decoder::Decoder>, n: usize, per: usize) -> Option { let mut buf = tiff::decoder::DecodingResult::U8(Vec::new()); let layout = d.read_image_to_buffer(&mut buf).ok()?; - let data = match buf { - tiff::decoder::DecodingResult::U8(v) => v, - tiff::decoder::DecodingResult::U16(v) => v.iter().map(|s| (s >> 8) as u8).collect(), - _ => return None, - }; + match buf { + tiff::decoder::DecodingResult::U8(v) => chunky(v, layout.planes, n, per).map(Samples::Eight), + tiff::decoder::DecodingResult::U16(v) => chunky(v, layout.planes, n, per).map(Samples::Sixteen), + _ => None, + } +} + +/// `data`, the samples of `n` pixels, `per` to a pixel, stored in `planes` planes, as the samples +/// pixel by pixel; `None` when it doesn't hold that many samples or a plane per sample. +fn chunky(data: Vec, planes: usize, n: usize, per: usize) -> Option> { if Some(data.len()) != n.checked_mul(per) { return None; } - if layout.planes <= 1 { + if planes <= 1 { return Some(data); } - if layout.planes != per { + if planes != per { return None; } - let planes: Vec<&[u8]> = data.chunks_exact(n).collect(); - Some((0..n).flat_map(|i| planes.iter().map(move |p| p.get(i).copied().unwrap_or(0))).collect()) + let planes: Vec<&[T]> = data.chunks_exact(n).collect(); + Some((0..n).flat_map(|i| planes.iter().filter_map(move |p| p.get(i).copied())).collect()) +} + +/// The color space an ICC profile's header names (bytes 16 to 19, such as `RGB `, `GRAY` or +/// `CMYK`); `None` when `icc` is shorter than a header. +pub fn icc_color_space(icc: &[u8]) -> Option<[u8; 4]> { + if icc.len() < 128 { + return None; + } + icc.get(16..20)?.try_into().ok() +} + +/// The ICC profile of TIFF tag 34675 (ICCProfile) of the image `d` reads; `None` without one. +fn tiff_icc(d: &mut tiff::decoder::Decoder>) -> Option> { + d.get_tag_u8_vec(tiff::tags::Tag::IccProfile).ok().filter(|icc| !icc.is_empty()) +} + +/// The ICC profile of TIFF `bytes`' first image (tag 34675), read with the `tiff` decoder's own +/// limits, whatever the size of the image; `None` for other images and TIFFs without one. +pub fn tiff_icc_profile(bytes: &[u8]) -> Option> { + let (_, mut d) = tiff(bytes)?; + tiff_icc(&mut d) +} + +/// The ICC profile of a JPEG, put together from all its numbered `ICC_PROFILE` APP2 segments; +/// `None` without one. +fn jpeg_icc(bytes: &[u8]) -> Option> { + let mut d = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(bytes), DecoderOptions::default()); + d.decode_headers().ok()?; + d.icc_profile().filter(|icc| !icc.is_empty()) +} + +/// `icc` when it is a profile of CMYK colors, which the samples of a CMYK image are in. +fn cmyk_icc(icc: Option>) -> Option> { + icc.filter(|icc| icc_color_space(icc) == Some(*b"CMYK")) +} + +/// The CMYK samples of a CMYK image at the depth its file stores them, and its ICC profile. +struct CmykSource { + width: u32, + height: u32, + samples: Samples, + icc: Option>, +} + +/// The samples of CMYK TIFF `bytes` (8 or 16 bits), their inks together or one plane per ink, with +/// the TIFF's CMYK ICC profile; `None` for other images and ones larger than [`MAX_CMYK_PIXELS`]. +fn tiff_source(bytes: &[u8]) -> Option { + let (kind, mut d) = tiff(bytes)?; + if !matches!(kind, tiff::ColorType::CMYK(8 | 16)) { + return None; + } + let (width, height) = d.dimensions().ok()?; + let n = usize::try_from(pixels(width, height)?).ok()?; + let icc = cmyk_icc(tiff_icc(&mut d)); + let samples = read_samples_at_depth(&mut d, n, 4)?; + Some(CmykSource { width, height, samples, icc }) +} + +/// The ink amounts of a four-component JPEG, 8 bits each, with its CMYK ICC profile. +fn jpeg_source(bytes: &[u8]) -> Option { + let Inks { width, height, data } = jpeg_inks(bytes)?; + Some(CmykSource { width, height, samples: Samples::Eight(data), icc: cmyk_icc(jpeg_icc(bytes)) }) +} + +/// A Deflate-compressed CMYK TIFF of `width` × `height` pixels of `samples` (inks together, 8 or 16 +/// bits as they are given), declaring the resolution `ppi` when both of its values are finite and +/// above 0, and carrying `icc` as tag 34675 (ICCProfile, of type UNDEFINED); `None` when it can't be +/// written. +fn write_cmyk_tiff(width: u32, height: u32, samples: SampleSlice<'_>, ppi: Option<(f64, f64)>, icc: Option<&[u8]>) -> Option> { + use tiff::encoder::colortype::{CMYK8, CMYK16, ColorType}; + use tiff::encoder::{Compression, ImageEncoder, Rational, TiffEncoder, TiffKind, compression::DeflateLevel}; + use tiff::tags::{ResolutionUnit, Tag}; + fn tags( + img: &mut ImageEncoder<'_, W, C, K>, + ppi: Option<(f64, f64)>, + icc: Option<&[u8]>, + ) -> Option<()> { + if let Some((x, y)) = ppi.filter(|(x, y)| [x, y].iter().all(|v| v.is_finite() && **v > 0.0)) { + // Ten-thousandths of a pixel per inch. + let r = |v: f64| Rational { n: (v * 10_000.0).round() as u32, d: 10_000 }; + img.encoder().write_tag(Tag::XResolution, r(x)).ok()?; + img.encoder().write_tag(Tag::YResolution, r(y)).ok()?; + img.encoder().write_tag(Tag::ResolutionUnit, ResolutionUnit::Inch).ok()?; + } + if let Some(icc) = icc { + img.encoder().write_tag(Tag::IccProfile, Undefined(icc)).ok()?; + } + Some(()) + } + let mut out = Cursor::new(Vec::new()); + let mut enc = TiffEncoder::new(&mut out).ok()?.with_compression(Compression::Deflate(DeflateLevel::Balanced)); + match samples { + SampleSlice::Eight(data) => { + let mut img = enc.new_image::(width, height).ok()?; + tags(&mut img, ppi, icc)?; + img.write_data(data).ok()?; + } + SampleSlice::Sixteen(data) => { + let mut img = enc.new_image::(width, height).ok()?; + tags(&mut img, ppi, icc)?; + img.write_data(data).ok()?; + } + } + Some(out.into_inner()) +} + +/// Bytes written as a TIFF field of type UNDEFINED, the type of an embedded ICC profile. +struct Undefined<'a>(&'a [u8]); + +impl tiff::encoder::TiffValue for Undefined<'_> { + const BYTE_LEN: u8 = 1; + const FIELD_TYPE: tiff::tags::Type = tiff::tags::Type::UNDEFINED; + + fn count(&self) -> usize { + self.0.len() + } + + fn data(&self) -> std::borrow::Cow<'_, [u8]> { + std::borrow::Cow::Borrowed(self.0) + } } impl ImageBlob { @@ -173,20 +351,8 @@ impl ImageBlob { /// [`ImageBlob::cmyk_tiff`], declaring the resolution `ppi` (horizontal, vertical pixels per /// inch) when it is given and both are finite and above 0. pub fn cmyk_tiff_at(inks: &Inks, ppi: Option<(f64, f64)>) -> Option { - use tiff::encoder::{Compression, Rational, TiffEncoder, colortype::CMYK8, compression::DeflateLevel}; - use tiff::tags::{ResolutionUnit, Tag}; - let mut out = Cursor::new(Vec::new()); - let mut enc = TiffEncoder::new(&mut out).ok()?.with_compression(Compression::Deflate(DeflateLevel::Balanced)); - let mut img = enc.new_image::(inks.width, inks.height).ok()?; - if let Some((x, y)) = ppi.filter(|(x, y)| [x, y].iter().all(|v| v.is_finite() && **v > 0.0)) { - // Ten-thousandths of a pixel per inch. - let r = |v: f64| Rational { n: (v * 10_000.0).round() as u32, d: 10_000 }; - img.encoder().write_tag(Tag::XResolution, r(x)).ok()?; - img.encoder().write_tag(Tag::YResolution, r(y)).ok()?; - img.encoder().write_tag(Tag::ResolutionUnit, ResolutionUnit::Inch).ok()?; - } - img.write_data(&inks.data).ok()?; - Some(Self::new("image/tiff", out.into_inner())) + let tiff = write_cmyk_tiff(inks.width, inks.height, SampleSlice::Eight(&inks.data), ppi, None)?; + Some(Self::new("image/tiff", tiff)) } /// Does the image hold CMYK samples (a four-component JPEG or a CMYK TIFF)? Reads only its @@ -309,17 +475,40 @@ fn tiff_inks(bytes: &[u8]) -> Option { Inks::new(w, h, read_samples(&mut d, n, 4)?) } -/// CMYK TIFF `bytes` as Open and Place store them: as they are, or, when they store one plane per -/// ink, which the image decoder doesn't read, their ink amounts written again by -/// [`ImageBlob::cmyk_tiff_at`] with the resolution `ppi`. `None` for other images and for CMYK -/// TIFFs whose inks [`ImageBlob::cmyk`] doesn't read. +/// CMYK TIFF `bytes` that no orientation turns ([`turned_cmyk`] stores the others) as Open and +/// Place store them: as they are, or, when they store one plane per ink, which the image decoder +/// doesn't read, their inks together in a CMYK TIFF with the resolution `ppi`, at the 8 or 16 bits +/// the file has, carrying the file's CMYK ICC profile. `None` for other images and for CMYK TIFFs +/// whose inks [`ImageBlob::cmyk`] doesn't read. pub fn stored_cmyk_tiff(bytes: &[u8], ppi: Option<(f64, f64)>) -> Option> { - let inks = tiff_inks(bytes)?; + let source = tiff_source(bytes)?; let (_, mut d) = tiff(bytes)?; if !planar(&mut d) { return Some(bytes.to_vec()); } - ImageBlob::cmyk_tiff_at(&inks, ppi).map(|b| Arc::unwrap_or_clone(b.bytes)) + write_cmyk_tiff(source.width, source.height, source.samples.as_slice(), ppi, source.icc.as_deref()) +} + +/// CMYK JPEG or TIFF `bytes` that `orientation` turns or flips, as Open and Place store them: their +/// inks turned and written again as a CMYK TIFF with the resolution `ppi` of the turned pixels, +/// with the turned width and height. A TIFF keeps its 8 or 16 bits, a JPEG has 8, and both keep +/// their CMYK ICC profile (a JPEG's put together from all its APP2 segments). `None` for other +/// images and for CMYK images whose inks [`ImageBlob::cmyk`] doesn't read. +pub fn turned_cmyk(bytes: &[u8], orientation: image::metadata::Orientation, ppi: Option<(f64, f64)>) -> Option<(Vec, (u32, u32))> { + let CmykSource { width, height, samples, icc } = if bytes.starts_with(&[0xFF, 0xD8]) { jpeg_source(bytes) } else { tiff_source(bytes) }?; + // Four inks to a pixel, turned as four channels of the same depth are. + let mut px = match samples { + Samples::Eight(v) => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(width, height, v)?), + Samples::Sixteen(v) => image::DynamicImage::ImageRgba16(image::ImageBuffer::from_raw(width, height, v)?), + }; + px.apply_orientation(orientation); + let size = (px.width(), px.height()); + let samples = match px { + image::DynamicImage::ImageRgba16(v) => Samples::Sixteen(v.into_raw()), + other => Samples::Eight(other.into_rgba8().into_raw()), + }; + let tiff = write_cmyk_tiff(size.0, size.1, samples.as_slice(), ppi, icc.as_deref())?; + Some((tiff, size)) } /// A TIFF whose pixels have samples after their colour, which the image decoder doesn't read at diff --git a/crates/doc/src/color_mask.rs b/crates/doc/src/color_mask.rs new file mode 100644 index 0000000000..8905d6fe60 --- /dev/null +++ b/crates/doc/src/color_mask.rs @@ -0,0 +1,197 @@ +//! Image Tools › Color Mask: colors of an image object that are hidden while its pixels stay as +//! they are. +//! +//! A masked image is an ordinary image ([`NodeKind::Image`]) with a [`ColorMask`] in its extras +//! ([`crate::node::NodeExtras::color_mask`]). The record holds the mask's settings and the key of +//! the image's pixels with the hidden colors made clear ([`ColorMask::key`]), made by the engine +//! from the pixels named by [`ColorMask::from`]. The image's own key keeps naming its own pixels, +//! so removing the mask gives them back. While the image's key is [`ColorMask::from`], it is drawn +//! and output with the masked pixels ([`Document::shown_image`]); when another key replaced it +//! (a link updated, the image cropped), it shows its own pixels until the engine makes the masked +//! pixels again. +//! +//! The concept is that of PDF's color key masking (ISO 32000-1, 8.9.6.4): samples in the chosen +//! colors are not painted and what is behind the image shows through. Which colors match, and how +//! near ones fade out, are VectorCraft's own rules. + +use std::borrow::Cow; + +use serde::{Deserialize, Serialize}; + +use crate::{Document, ImageObject, Node, NodeKind}; + +/// Where a color mask's colors come from. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum MaskBackground { + /// The most common color along the image's edges. + #[default] + Edges, + /// The average of the image's corner pixels that are not clear. + Corners, + /// The colors in [`ColorMask::colors`]. + Colors, +} + +/// How near a color must be to a masked one. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum MaskMatch { + /// The RGB distance, as a percentage of the largest one. + #[default] + Distance, + /// The largest difference on one of red, green and blue, as a percentage of a channel's range. + Channels, +} + +/// The colors an image object hides (see the module docs). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct ColorMask { + /// Key into [`Document::images`]: the pixels of [`Self::from`] with the hidden colors made + /// clear. Named `key` in the file, so the file keeps those pixels with the document. + pub key: String, + /// The image's own key when the masked pixels were made. + pub from: String, + #[serde(default)] + pub background: MaskBackground, + /// The hidden colors (8-bit RGB) with [`MaskBackground::Colors`]. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub colors: Vec<[u8; 3]>, + /// Only the matching pixels that reach in from an edge are hidden. A record without it reads + /// as `true`, the command's default. + #[serde(default = "default_contiguous")] + pub contiguous: bool, + #[serde(default, rename = "match")] + pub measure: MaskMatch, + /// How near a color must be to be hidden, 0 to 100 (see [`MaskMatch`]). A record without it + /// reads as 10, the command's default. + #[serde(default = "default_percent")] + pub tolerance: f64, + /// The band past the tolerance over which pixels fade from hidden to shown, 0 to 100. A record + /// without it reads as 10, the command's default. + #[serde(default = "default_percent")] + pub softness: f64, +} + +fn default_contiguous() -> bool { + true +} + +fn default_percent() -> f64 { + 10.0 +} + +impl ColorMask { + /// Whether the masked pixels were made from the pixels of `im`. + pub fn made_for(&self, im: &ImageObject) -> bool { + im.pixels.is_none() && self.from == im.key + } +} + +impl Document { + /// Image `im` of node `n` as it is drawn and output. With a color mask whose masked pixels were + /// made from the image's own pixels and are in this document ([`ColorMask::made_for`]): a copy + /// that shows those pixels and links to no file, so an output that refers to a linked file + /// writes the masked pixels instead. Otherwise, and for a mask that hides nothing (its masked + /// pixels are the image's own), `im` itself. + pub fn shown_image<'a>(&self, n: &Node, im: &'a ImageObject) -> Cow<'a, ImageObject> { + match n.extras().color_mask.as_deref() { + Some(m) if m.key != im.key && m.made_for(im) && self.images.contains_key(&m.key) => { + Cow::Owned(ImageObject { key: m.key.clone(), link: None, ..im.clone() }) + } + _ => Cow::Borrowed(im), + } + } + + /// The color mask of image node `n`, if it has one. + pub fn color_mask_of(n: &Node) -> Option<&ColorMask> { + matches!(n.kind, NodeKind::Image(_)).then(|| n.extras().color_mask.as_deref()).flatten() + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use vectorcraft_geom::Affine; + + use super::*; + use crate::{ImageBlob, NodeId}; + + fn image(key: &str) -> ImageObject { + ImageObject { key: key.into(), width: 2, height: 2, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None } + } + + fn mask(key: &str, from: &str) -> ColorMask { + ColorMask { + key: key.into(), + from: from.into(), + background: MaskBackground::Colors, + colors: vec![[255, 255, 255]], + contiguous: false, + measure: MaskMatch::Distance, + tolerance: 10.0, + softness: 0.0, + } + } + + #[test] + fn a_masked_image_shows_its_masked_pixels_while_they_were_made_from_its_own() { + let mut d = Document::new(100.0, 100.0); + d.images.insert("own".into(), ImageBlob::png(vec![1])); + d.images.insert("masked".into(), ImageBlob::png(vec![2])); + let mut n = Node::new(NodeId(5), NodeKind::Image(Box::new(image("own")))); + let NodeKind::Image(im) = &n.kind else { unreachable_kind() }; + assert_eq!(d.shown_image(&n, im).key, "own", "no mask: its own pixels"); + n.extras_mut().color_mask = Some(Box::new(mask("masked", "own"))); + let NodeKind::Image(im) = &n.kind else { unreachable_kind() }; + assert_eq!(d.shown_image(&n, im).key, "masked"); + // Linked: the shown copy links to nothing, so outputs write the masked pixels. + let mut linked = (**im).clone(); + linked.link = Some(crate::LinkInfo::new("/a.png")); + assert_eq!(d.shown_image(&n, &linked).link, None); + // Made from other pixels: its own until they are made again. + assert_eq!(d.shown_image(&n, &image("other")).key, "other"); + // Masked pixels the document doesn't have: its own. + n.extras_mut().color_mask = Some(Box::new(mask("gone", "own"))); + let NodeKind::Image(im) = &n.kind else { unreachable_kind() }; + assert_eq!(d.shown_image(&n, im).key, "own"); + // Pixels an image holds itself are drawn as they are. + let own = ImageObject { pixels: Some(Arc::new(ImageBlob::png(vec![3]))), ..image("own") }; + n.extras_mut().color_mask = Some(Box::new(mask("masked", "own"))); + assert_eq!(d.shown_image(&n, &own).key, "own"); + // A mask that hides nothing (its masked pixels are the image's own): the image itself, so + // a linked image stays linked in outputs. + n.extras_mut().color_mask = Some(Box::new(mask("own", "own"))); + assert_eq!(d.shown_image(&n, &linked).link, linked.link); + } + + #[test] + fn a_mask_saves_and_reads_back_with_its_node() { + let mut n = Node::new(NodeId(5), NodeKind::Image(Box::new(image("own")))); + n.extras_mut().color_mask = Some(Box::new(mask("masked", "own"))); + let json = serde_json::to_value(&n).unwrap(); + assert_eq!(json["color_mask"]["key"], "masked", "the masked pixels' key is a `key` member: {json}"); + assert_eq!(json["color_mask"]["match"], "distance"); + let back: Node = serde_json::from_value(json).unwrap(); + assert_eq!(back, n); + // A node without one writes none. + let plain = Node::new(NodeId(6), NodeKind::Image(Box::new(image("own")))); + assert!(serde_json::to_value(&plain).unwrap().get("color_mask").is_none()); + } + + /// A record that leaves out settings reads them as the command's defaults: edge color, + /// contiguous, distance, tolerance and softness 10. + #[test] + fn a_record_without_settings_reads_the_defaults() { + let m: ColorMask = serde_json::from_value(serde_json::json!({"key": "masked", "from": "own"})).unwrap(); + assert_eq!( + (m.background, m.colors.len(), m.contiguous, m.measure, m.tolerance, m.softness), + (MaskBackground::Edges, 0, true, MaskMatch::Distance, 10.0, 10.0) + ); + } + + fn unreachable_kind() -> ! { + panic!("an image node") + } +} diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 708d0aee03..057a9df6a6 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -286,7 +286,9 @@ impl Document { self.next_id = self.next_id.max(id); } - /// Ensure `next_id` is above every id in the tree (after deserializing foreign data). + /// Ensure `next_id` is above every id in the tree (after deserializing foreign data), then give + /// the objects outside the layer tree (opacity-mask art, symbols, graph designs and patterns) + /// whose id is missing or already taken a new one, so each stored object has an id of its own. pub fn fix_next_id(&mut self) { // Ids from [`MAX_NEXT_ID`] up (a damaged or hand-made file: #1718) are left out, as is a // counter up there: new ids start under them and never reach them, where counting on from @@ -297,13 +299,12 @@ impl Document { max = max.max(id); } }; - for l in &self.layers { - l.walk(&mut |n| see(n.id.0)); - } + self.visit_stored(|n, _| see(n.id.0)); self.slices.iter().for_each(|s| see(s.id.0)); self.assets.iter().for_each(|a| see(a.id)); let counter = Some(self.next_id).filter(|n| *n <= MAX_NEXT_ID).unwrap_or(0); self.next_id = counter.max(max.saturating_add(1)); + self.renumber_stored_duplicates(); } /// Find a node anywhere in the tree. diff --git a/crates/doc/src/document_guides.rs b/crates/doc/src/document_guides.rs index ca6b5ed882..14d0404bfc 100644 --- a/crates/doc/src/document_guides.rs +++ b/crates/doc/src/document_guides.rs @@ -503,6 +503,19 @@ impl Document { id } + /// [`Document::next_artboard_id`] when `top` is the highest id the artboards have (`None`: there + /// are none). It reads no artboard unless that id is `u32::MAX`, so a caller that adds many + /// artboards and keeps `top` up to date gets each id in constant time. + pub fn next_artboard_id_above(&self, top: Option) -> u32 { + match top.unwrap_or(0).max(self.retired_artboard_id.get()).checked_add(1) { + Some(id) => { + self.retired_artboard_id.raise(id); + id + } + None => self.next_artboard_id(), + } + } + /// Record that the artboard with `id` was deleted: no later artboard takes its id. pub fn retire_artboard_id(&self, id: u32) { self.retired_artboard_id.raise(id); @@ -541,6 +554,13 @@ impl Document { t.cached_baselines.clear(); t.cached_ink = None; } + // Opacity-mask art is stored art too: the copy's gets ids of its own. + if let Some(art) = n.extras().mask.as_ref().map(|m| Arc::clone(&m.art)) { + let art = Arc::new(self.reid(&art)); + if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) { + m.art = art; + } + } let on_path = n.extras().objects_on_path.is_some(); let mut renamed = std::collections::HashMap::new(); if let Some(ch) = n.children_mut() { diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index 94fbb5ff52..fd907a26cc 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -569,7 +569,7 @@ fn clip_contains(clip: &Node, p: Point) -> bool { /// The regions `clip` clips to ([`Node::clip_shapes`]), text counted by its frame as in /// [`clip_contains`]. -fn clip_regions(clip: &Node) -> Vec<(vectorcraft_geom::BezPath, vectorcraft_geom::FillRule)> { +pub fn clip_regions(clip: &Node) -> Vec<(vectorcraft_geom::BezPath, vectorcraft_geom::FillRule)> { let frame = |n: &Node| { let b = n.geometric_bounds()?; Some(Node::path(n.id, vectorcraft_geom::shapes::rectangle(b), Default::default())) @@ -640,7 +640,7 @@ fn source_of(n: &Node, scope: Option) -> bool { /// Do clicks and marquees skip the child `i` of `parent` with `scope` isolated? For a Shaper /// Group that is its original shapes (its first child), or, in Construction mode, when they are /// isolated, the art the group shows. -fn shaper_hides(parent: &Node, i: usize, scope: Option) -> bool { +pub fn shaper_hides(parent: &Node, i: usize, scope: Option) -> bool { parent.extras().shaper.is_some() && (i == 0) != source_of(parent, scope) } @@ -795,6 +795,10 @@ thread_local! { static LEAVES_TESTED: std::cell::Cell = const { std::cell::Cell::new(0) }; } +/// What a click at `p` hits on leaf object `n`: its outline, strokes and fills, its frame or its +/// bounds, by kind. Raster effects (drop shadows, glows, blurs) do not take clicks: the area they +/// paint beyond the object is left out here and in [`cull_reach`], so a click there reaches the +/// object under it. fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option { #[cfg(test)] LEAVES_TESTED.with(|c| c.set(c.get() + 1)); @@ -1352,7 +1356,7 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh /// The part of a marquee `r` in which it can touch the children of `parent`. For a clip group or a /// layer with a clipping mask, this is what [`marquee_in_clip`] returns for its clipping path (None /// when the marquee misses it); otherwise it is all of `r`. -fn marquee_in(parent: &Node, r: Rect) -> Option { +pub fn marquee_in(parent: &Node, r: Rect) -> Option { match parent.children().and_then(|c| c.first()) { Some(clip) if parent.clips() => marquee_in_clip(clip, r), _ => Some(r), diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index 2c0a6984d0..3eac4202b6 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -450,7 +450,7 @@ fn a_marquee_meets_blends_and_envelopes_by_their_box() { envelope, NodeKind::Envelope { content, - kind: Box::new(crate::live::EnvelopeKind::Warp { style: "arc".to_string(), bend: 0.0, h: 0.0, v: 0.0, horizontal: true }), + kind: Box::new(crate::live::EnvelopeKind::Warp { style: "arc".to_string(), bend: 0.0, h: 0.0, v: 0.0, horizontal: true, version: 0 }), fidelity: 100.0, editing: false, options: Default::default(), @@ -1192,7 +1192,7 @@ fn objects_at_edit_contents_uses_general_order() { d.alloc_id(), NodeKind::Envelope { content: vec![inner(a), inner(b)], - kind: Box::new(crate::live::EnvelopeKind::Warp { style: "arc".to_string(), bend: 0.0, h: 0.0, v: 0.0, horizontal: true }), + kind: Box::new(crate::live::EnvelopeKind::Warp { style: "arc".to_string(), bend: 0.0, h: 0.0, v: 0.0, horizontal: true, version: 0 }), fidelity: 100.0, editing: true, options: Default::default(), diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 41a684abde..63a2676f77 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -11,6 +11,7 @@ pub mod blend; pub mod cancel; pub mod clipnest; pub mod cmyk; +pub mod color_mask; pub mod compound_shape; pub mod corners; pub mod depth; @@ -32,8 +33,8 @@ pub use inline::{SYMBOL_HALF, SYMBOL_SIZES}; pub use shared::Shared; pub use symbol_export_type::{SYMBOL_EXPORT_TYPE, SymbolExportType}; pub use symbol_nine_slice::{ - EditedNineSlice, MAX_SLICE_GROWTH, MIN_CENTER_BAND, NineSliceGuide, NineSliceMap, PAINTED_EFFECTS, SYMBOL_NINE_SLICE, SymbolNineSlice, - charge_symbol_art, + EditedNineSlice, MAX_GUIDE_FRACTION, MAX_SLICE_GROWTH, MIN_CENTER_BAND, NineSliceGuide, NineSliceMap, PAINTED_EFFECTS, SYMBOL_NINE_SLICE, + SymbolNineSlice, charge_symbol_art, }; pub use symbol_overrides::SymbolOverride; pub use symbol_registration::{SYMBOL_REGISTRATION, SymbolRegistration}; @@ -51,7 +52,7 @@ pub mod overprint; pub mod pattern; pub mod perspective; mod pixels; -pub use pixels::{GraySource, MAX_RASTER_ALLOC}; +pub use pixels::{GraySource, MAX_RASTER_ALLOC, PixelPick}; pub mod placed_document; pub mod plugin_data; pub mod profiles; @@ -61,6 +62,7 @@ pub mod rastersettings; mod reach; pub mod recolor; pub mod selection; +pub mod separated; pub mod setup; pub mod shaper; pub mod slices; @@ -82,8 +84,8 @@ pub(crate) mod skip; pub use appearance::StrokeGradientMode; pub use appearance::{ - AngleProfile, Appearance, AppearanceItem, ArrowAlign, Arrowhead, Dash, Effect, FillLayer, LineCap, LineJoin, PressureProfile, ProfilePreset, - SavedProfile, StrokeAlign, StrokeLayer, WidthProfile, + AngleProfile, Appearance, AppearanceItem, ArrowAlign, Arrowhead, CustomArrowhead, Dash, Effect, FillLayer, LineCap, LineJoin, PressureProfile, + ProfilePreset, SavedProfile, StrokeAlign, StrokeLayer, WidthProfile, }; pub use assets::ExportAsset; pub use compound_shape::ShapeMode; @@ -140,6 +142,7 @@ mod graphic_style; mod guides; mod limits; mod records; +mod stored_art; mod units; pub use artboard::{ARTBOARD_GAP, Artboard, ArtboardSide, LockedArtboards, RetiredArtboardId, VIDEO_PIXEL_ASPECT_RANGE, VIDEO_SAFE_INSETS}; @@ -152,6 +155,7 @@ pub use guides::{GridPrefs, Guide, RulerMode}; use limits::MAX_NEXT_ID; pub use limits::{DocError, FORMAT_VERSION, MAX_COORD}; pub use records::{ImageBlob, MaskEdit, NewArtIds, SavedSelection, SavedView, SvgFilter, Symbol, SymbolEdit}; +pub use stored_art::{StoredPlace, StoredRoot}; pub use units::{ColorMode, Unit, parse_number}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -263,11 +267,11 @@ pub struct Document { /// File → Document Setup (bleed, transparency grid, paper, type options). #[serde(default, skip_serializing_if = "skip::is_default")] pub setup: DocSetup, - /// Layers panel → Paste Remembers Layers: pasted objects go back into the layers (by name) - /// they were copied from instead of the current layer. + /// Layers panel → Paste Remembers Layers: pasted objects go back into the layers and + /// sublayers they were copied from instead of the current layer. #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub paste_remembers_layers: bool, - /// File → File Info (the title is [`Document::title`]). + /// File → File Info (its title is [`Document::info_title`]). #[serde(default, skip_serializing_if = "skip::is_default")] pub metadata: DocMetadata, /// Effect → Document Raster Effects Settings besides the resolution diff --git a/crates/doc/src/live.rs b/crates/doc/src/live.rs index 304c4e70f6..3cf8312289 100644 --- a/crates/doc/src/live.rs +++ b/crates/doc/src/live.rs @@ -39,7 +39,7 @@ fn fifty() -> f64 { // ===================================================================================== pub use crate::blend::{ - Spine, blend_expand, blend_spine, blend_step_count, lerp_appearance, lerp_color, lerp_node, lerp_paint, lerp_path, pin_spine, + Spine, blend_expand, blend_layout_line, blend_spine, blend_step_count, lerp_appearance, lerp_color, lerp_node, lerp_paint, lerp_path, pin_spine, steps_knockout_shows, }; @@ -49,23 +49,23 @@ mod expand; mod mesh; mod warp; -pub use blend_spec::{BlendDefaults, BlendEase, BlendEaseType, BlendOrientation, BlendSpacing, BlendSpec}; +pub use blend_spec::{BlendDefaults, BlendEase, BlendEaseType, BlendOrientation, BlendSpacing, BlendSpec, BlendSpineMode}; #[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, 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, + envelope_content_boxes, envelope_content_boxes_with, envelope_expand, envelope_frame, envelope_grid, envelope_mapper, envelope_of, + envelope_overlay, envelope_stroke_margin, set_type_ink, smooth_handles, warp_grid, }; pub(crate) use expand::max_outset; pub use expand::{ Hooks, MAX_GENERATED, Outliner, PatternTiles, affine_near, expand_deep, expand_deep_hooks, expand_live, expand_live_hooks, expand_live_with, - expanded_group, expanded_group_hooks, is_live, mesh_quad_nodes, subtree_has_live, + expanded_group, expanded_group_hooks, is_live, mesh_quad_nodes, mesh_warp_cost, mesh_warp_image, subtree_has_live, }; #[cfg(test)] use mesh::grid_eval; pub use mesh::{Coons, GradientMesh, MeshAppearance, MeshPiece, MeshPoint, MeshQuad, default_fidelity, grid_points, nodes_bounds}; -pub use warp::{WarpStyle, fit_piece, map_nonlinear, map_nonlinear_within, pieces, warp_point}; +pub use warp::{WARP_NET, WarpNet, WarpStyle, fit_piece, map_nonlinear, map_nonlinear_within, pieces, uses_net, warp_point, warp_version}; #[cfg(test)] mod tests { @@ -132,6 +132,200 @@ mod tests { let (r0, a) = (4.0 / PI, 0.5 / (4.0 / PI)); assert!((nx - (r0 - 0.25) * a.sin()).abs() < 1e-12 && (ny - (r0 - (r0 - 0.25) * a.cos())).abs() < 1e-12); } + + /// Each warp style's Bézier net, at points worked out by a separate implementation of the same + /// nets: (style, bend %, horizontal and vertical distortion %, vertical, box w × h, (u, v)) → + /// the point in the box (origin at its top left, y down). + #[test] + fn warp_nets_bend_each_style_as_its_own_patch() { + #[rustfmt::skip] + let samples = [ + ("arc", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.1, 0.3, -31.1605665, 30.1243045), + ("arc", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.8, 0.9, 170.241998, 58.8743443), + ("arc", -40.0, 30.0, -50.0, true, 150.0, 60.0, 0.25, 0.6, 50.6087118, 47.6275948), + ("arcLower", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.1, 0.3, 18.8784581, 35.5028749), + ("arcLower", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.8, 0.9, 164.486168, 119.348666), + ("arcLower", -40.0, 30.0, -50.0, true, 150.0, 60.0, 0.25, 0.6, 38.1073767, 36.0911629), + ("arcUpper", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.1, 0.3, 17.3830689, 17.1599587), + ("arcUpper", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.8, 0.9, 160.498463, 86.7390371), + ("arcUpper", -40.0, 30.0, -50.0, true, 150.0, 60.0, 0.25, 0.6, 46.1081993, 36.0252855), + ("arch", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.1, 0.3, 16.261527, 11.6570838), + ("arch", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.8, 0.9, 164.984631, 57.3903712), + ("arch", -40.0, 30.0, -50.0, true, 150.0, 60.0, 0.25, 0.6, 49.2508226, 36.2064484), + ("bulge", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.1, 0.3, 16.261527, 22.6628335), + ("bulge", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.8, 0.9, 164.984631, 116.087703), + ("bulge", -40.0, 30.0, -50.0, true, 150.0, 60.0, 0.25, 0.6, 42.965576, 36.2064484), + ("shellLower", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.1, 0.3, 10.6489723, 25.9914004), + ("shellLower", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.8, 0.9, 208.565464, 99.4817585), + ("shellLower", -40.0, 30.0, -50.0, true, 150.0, 60.0, 0.25, 0.6, 41.043987, 36.1302767), + ("shellUpper", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.1, 0.3, -21.8346746, 41.6042708), + ("shellUpper", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.8, 0.9, 160.791499, 90.3680631), + ("shellUpper", -40.0, 30.0, -50.0, true, 150.0, 60.0, 0.25, 0.6, 42.9282896, 36.1475509), + ("flag", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.1, 0.3, 20.0, 55.92), + ("flag", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.8, 0.9, 160.0, 55.44), + ("flag", -40.0, 30.0, -50.0, true, 150.0, 60.0, 0.25, 0.6, 58.098, 35.91), + ("wave", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.1, 0.3, 20.0, 40.8864), + ("wave", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.8, 0.9, 160.0, 83.7792), + ("wave", -40.0, 30.0, -50.0, true, 150.0, 60.0, 0.25, 0.6, 42.33, 35.91), + ("fish", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.1, 0.3, 20.0, 19.632), + ("fish", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.8, 0.9, 160.0, 62.352), + ("fish", -40.0, 30.0, -50.0, true, 150.0, 60.0, 0.25, 0.6, 44.994, 35.91), + ("rise", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.1, 0.3, 20.0, 146.64), + ("rise", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.8, 0.9, 160.0, 102.48), + ("rise", -40.0, 30.0, -50.0, true, 150.0, 60.0, 0.25, 0.6, 118.686, 35.91), + ("fisheye", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.1, 0.3, 9.1136, 27.2784), + ("fisheye", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.8, 0.9, 166.2208, 94.1472), + ("fisheye", -40.0, 30.0, -50.0, true, 150.0, 60.0, 0.25, 0.6, 47.514, 35.7048), + ("inflate", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.1, 0.3, -0.16, 27.84), + ("inflate", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.8, 0.9, 166.48, 97.68), + ("inflate", -40.0, 30.0, -50.0, true, 150.0, 60.0, 0.25, 0.6, 45.75, 36.54), + ("squeeze", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.1, 0.3, 40.16, 27.84), + ("squeeze", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.8, 0.9, 153.52, 97.68), + ("squeeze", -40.0, 30.0, -50.0, true, 150.0, 60.0, 0.25, 0.6, 45.75, 36.0), + ("twist", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.1, 0.3, 32.2472, 27.9588), + ("twist", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.8, 0.9, 149.1136, 89.2224), + ("twist", -40.0, 30.0, -50.0, true, 150.0, 60.0, 0.25, 0.6, 45.56325, 33.8769), + ]; + for (style, bend, dh, dv, vertical, w, h, u, v, x, y) in samples { + let Some(st) = WarpStyle::from_id(style) else { panic!("{style}") }; + let p = WarpNet::new(st, bend / 100.0, dh / 100.0, dv / 100.0, w, h, vertical).at(u, v); + assert!(p.distance(Point::new(x, y)) < 1e-6, "{style} {bend} {dh} {dv} {vertical} ({u}, {v}): {p:?} vs ({x}, {y})"); + } + } + + /// Arc's edges are concentric circles: at 100 % on a 200 × 100 box the bottom edge is the half + /// circle through the bottom corners about the bottom's middle, and the top edge the one 100 + /// further out. One cubic for a half circle strays up to 1.84 % of the radius from the circle. + #[test] + fn warp_net_arc_edges_are_concentric_circles() { + let net = WarpNet::new(WarpStyle::Arc, 1.0, 0.0, 0.0, 200.0, 100.0, false); + let center = Point::new(100.0, 100.0); + for i in 0..=20 { + let u = f64::from(i) / 20.0; + for (v, r) in [(0.0, 200.0), (1.0, 100.0)] { + let d = net.at(u, v).distance(center); + assert!((d - r).abs() < 0.0184 * r, "u {u}, v {v}: {d} from the center, not {r}"); + // Its ends and middle lie on the circle. + if i % 10 == 0 { + assert!((d - r).abs() < 1e-9, "u {u}, v {v}: {d} from the center, not {r}"); + } + } + } + // Bend 0 leaves the box as it is. + for st in [WarpStyle::Arc, WarpStyle::ShellLower, WarpStyle::Bulge, WarpStyle::Twist] { + let flat = WarpNet::new(st, 0.0, 0.0, 0.0, 200.0, 100.0, false); + assert!(flat.at(0.3, 0.7).distance(Point::new(60.0, 70.0)) < 1e-9, "{st:?}"); + } + } + + /// The horizontal distortion scales each column of the net about its middle (narrowing the left + /// side for a positive value), then the vertical one each row (narrowing the top). + #[test] + fn warp_net_distortion_scales_the_columns_then_the_rows() { + let corners = |dh: f64, dv: f64| { + let net = WarpNet::new(WarpStyle::Arc, 0.0, dh, dv, 200.0, 100.0, false); + [net.at(0.0, 0.0), net.at(1.0, 0.0), net.at(0.0, 1.0), net.at(1.0, 1.0)] + }; + let near = |got: [Point; 4], want: [(f64, f64); 4]| got.iter().zip(want).all(|(p, (x, y))| p.distance(Point::new(x, y)) < 1e-9); + assert!(near(corners(0.5, 0.0), [(0.0, 25.0), (200.0, -25.0), (0.0, 75.0), (200.0, 125.0)]), "{:?}", corners(0.5, 0.0)); + assert!(near(corners(0.0, 0.5), [(50.0, 0.0), (150.0, 0.0), (-50.0, 100.0), (250.0, 100.0)]), "{:?}", corners(0.0, 0.5)); + // Both coordinates scale: after the columns the top row runs from (0, 15) to (200, -15), and + // it then scales by 1.4 about its middle, (100, 0). + assert!(near(corners(0.3, -0.4), [(-40.0, 21.0), (240.0, -21.0), (40.0, 91.0), (160.0, 109.0)]), "{:?}", corners(0.3, -0.4)); + } + + /// Numbers no warp can take still give a finite net: a bend or distortion that isn't a number + /// counts as 0, and out of range as its limit; a size that isn't a number as 0. + #[test] + fn warp_net_takes_any_numbers() { + for st in [WarpStyle::Arc, WarpStyle::ShellUpper, WarpStyle::Wave, WarpStyle::Inflate, WarpStyle::Twist] { + for (b, dh, w, h) in + [(f64::NAN, 0.2, 10.0, 10.0), (5.0, f64::INFINITY, 10.0, 0.0), (-1e300, -3.0, f64::NAN, 1e-300), (1e-300, 0.0, 0.0, 0.0)] + { + for vertical in [false, true] { + let p = WarpNet::new(st, b, dh, dh, w, h, vertical).at(0.3, 0.6); + assert!(p.x.is_finite() && p.y.is_finite(), "{st:?} {b} {dh} {w} {h}: {p:?}"); + } + } + } + let clamped = WarpNet::new(WarpStyle::Flag, 7.0, 0.0, 0.0, 200.0, 100.0, false); + assert_eq!(clamped, WarpNet::new(WarpStyle::Flag, 1.0, 0.0, 0.0, 200.0, 100.0, false)); + } + + /// A box near the largest finite size still warps: Flag on a 1e308 × 100 box moves points only + /// up and down, as on a 1 × 1e-306 one scaled up, and on a 1e308 × 1e-300 box keeps the box's + /// height. Fisheye at 100 % on a 1.7e308 square, whose net goes past the largest finite number, + /// gives finite points inside the box and past it, and the unit square's points scaled up where + /// those are finite. Fisheye moves y by the height alone, so on boxes of the largest finite + /// width and a height of 1e-300 or 100 every y is the unit square's times the height, also + /// where x goes past the largest finite number. + #[test] + fn warp_net_bends_a_huge_box_without_overflowing() { + let w = 1e308; + let flag = WarpNet::new(WarpStyle::Flag, 0.5, 0.0, 0.0, w, 100.0, false); + let small = WarpNet::new(WarpStyle::Flag, 0.5, 0.0, 0.0, 1.0, 100.0 / w, false); + for (u, v) in [(0.0, 0.0), (0.3, 0.6), (0.9, 1.0), (1.0, 0.5)] { + let (p, q) = (flag.at(u, v), small.at(u, v)); + assert!(p.is_finite(), "({u}, {v}): {p:?}"); + assert!((p.x - u * w).abs() <= 1e-12 * w, "({u}, {v}): {p:?}"); + assert!((p.y - q.y * w).abs() <= 1e-9 * p.y.abs().max(1.0), "({u}, {v}): {p:?} against {q:?}"); + } + let thin = WarpNet::new(WarpStyle::Flag, 0.5, 0.0, 0.0, w, 1e-300, false); + assert_eq!(thin.at(0.0, 1.0), Point::new(0.0, 1e-300)); + let fisheye = WarpNet::new(WarpStyle::Fisheye, 1.0, 0.0, 0.0, 1.7e308, 1.7e308, false); + for (u, v) in [(0.1, 0.1), (0.8, 0.3), (1.5, 0.5), (3.0, 3.0)] { + let p = fisheye.at(u, v); + assert!(p.is_finite(), "({u}, {v}): {p:?}"); + } + let unit = WarpNet::new(WarpStyle::Fisheye, 1.0, 0.0, 0.0, 1.0, 1.0, false); + let near = |a: f64, b: f64| (a - b).abs() <= 1e-12 * b.abs().max(f64::MIN_POSITIVE); + let (p, q) = (fisheye.at(0.1, 0.1), unit.at(0.1, 0.1)); + assert!(near(p.x, q.x * 1.7e308) && near(p.y, q.y * 1.7e308), "{p:?} against {q:?}"); + // The bottom of a box with a subnormal height stays exactly at that height: the net is + // built on the box halved, and the height's lowest bit but one is set. + let low = f64::MIN_POSITIVE / 4.0 + f64::from_bits(2); + let sub = WarpNet::new(WarpStyle::Fisheye, 1.0, 0.0, 0.0, f64::MAX, low, false).at(0.0, 1.0); + assert_eq!(sub.y, low, "{sub:?}"); + for h in [1e-300, 100.0] { + let tall = WarpNet::new(WarpStyle::Fisheye, 1.0, 0.0, 0.0, f64::MAX, h, false); + for (u, v) in [(0.1, 0.1), (0.9, 0.4), (0.5, 0.8)] { + let (p, q) = (tall.at(u, v), unit.at(u, v)); + assert!(p.is_finite() && near(p.y, q.y * h), "h {h}, ({u}, {v}): {p:?} against {q:?}"); + } + } + } + + /// Content with no width or no height takes the middle of a warp envelope's patch along that + /// side: under Arc a vertical line stays vertical, under Bulge a horizontal line stays straight. + #[test] + fn warp_envelopes_bend_flat_content_as_the_middle_of_the_patch() { + let warp = |style: &str| EnvelopeKind::Warp { style: style.into(), bend: 50.0, h: 0.0, v: 0.0, horizontal: true, version: WARP_NET }; + let arc = warp("arc"); + let map = envelope_mapper(&arc, Rect::new(100.0, 0.0, 100.0, 100.0)); + for y in [0.0, 30.0, 100.0] { + let p = map(Point::new(100.0, y)); + assert!((p.x - 100.0).abs() <= 1e-9, "{y}: {p:?}"); + } + let bulge = warp("bulge"); + let map = envelope_mapper(&bulge, Rect::new(0.0, 50.0, 200.0, 50.0)); + for x in [0.0, 70.0, 200.0] { + let p = map(Point::new(x, 50.0)); + assert!((p.y - 50.0).abs() <= 1e-9, "{x}: {p:?}"); + } + } + + /// A warp envelope's map version: none in a file reads as 0 (the earlier map), 0 is written + /// as none, so files keep their bytes, and the nets' version is written. + #[test] + fn warp_envelopes_write_their_map_version_only_when_it_has_one() { + let old: EnvelopeKind = serde_json::from_str(r#"{"type":"warp","style":"arc","bend":20}"#).unwrap(); + assert!(matches!(old, EnvelopeKind::Warp { version: 0, .. }), "{old:?}"); + assert!(!serde_json::to_string(&old).unwrap().contains("version")); + let new = EnvelopeKind::Warp { style: "arc".into(), bend: 20.0, h: 0.0, v: 0.0, horizontal: true, version: WARP_NET }; + let text = serde_json::to_string(&new).unwrap(); + assert!(text.contains(r#""version":1"#), "{text}"); + assert_eq!(serde_json::from_str::(&text).unwrap(), new); + } use vectorcraft_geom::shapes; fn rect_node(x: f64, y: f64, w: f64, h: f64, c: Color) -> Arc { @@ -374,23 +568,167 @@ mod tests { } } + /// The outline of a 200 × 100 box whose top side is `pieces`, end to end from (0, 0) to + /// (200, 0), and whose other sides are straight. + fn top_of_pieces(pieces: &[CubicBez]) -> PathData { + let pt = |p: Point| (p.x, p.y); + let mut knots: Vec = vec![]; + for (k, c) in pieces.iter().enumerate() { + let h_in = if k == 0 { pt(c.p0) } else { pt(pieces[k - 1].p2) }; + knots.push((pt(c.p0), h_in, pt(c.p1))); + } + let last = pieces.last().unwrap(); + knots.push(((200.0, 0.0), pt(last.p2), (200.0, 0.0))); + knots.extend([((200.0, 100.0), (200.0, 100.0), (200.0, 100.0)), ((0.0, 100.0), (0.0, 100.0), (0.0, 100.0))]); + outline(&knots) + } + + /// A top curve whose parameter runs fast at its start and slow at its end. + const UNEVEN_TOP: CubicBez = + CubicBez { p0: Point::new(0.0, 0.0), p1: Point::new(120.0, -60.0), p2: Point::new(190.0, -30.0), p3: Point::new(200.0, 0.0) }; + #[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(); + fn a_split_curve_keeps_the_top_object_patch() { + // Splitting the top curve at t = 0.3, or into thirds, keeps its shape, and the patch stays + // the unsplit curve's: the new anchors land at u = 0.3, 1/3 and 2/3 (to within how finely + // the side is sampled), where the pieces' control polygons would have put them several + // points away. + let whole = Coons::from_top_object(&top_of_pieces(&[UNEVEN_TOP]), None).unwrap(); + for cuts in [vec![0.3], vec![1.0 / 3.0, 2.0 / 3.0]] { + let ends: Vec = std::iter::once(0.0).chain(cuts.iter().copied()).chain([1.0]).collect(); + let pieces: Vec = ends.windows(2).map(|w| UNEVEN_TOP.subsegment(w[0]..w[1])).collect(); + let c = Coons::from_top_object(&top_of_pieces(&pieces), None).unwrap(); + let total: f64 = pieces.iter().map(|p| polygon(*p)).sum(); + for (k, t) in cuts.iter().enumerate() { + let anchor = pieces[k].p3; + assert!(c.eval(*t, 0.0).distance(anchor) < 0.02, "{cuts:?}: u {t} → {:?}, want {anchor:?}", c.eval(*t, 0.0)); + let share: f64 = pieces[..=k].iter().map(|p| polygon(*p)).sum::() / total; + assert!(c.eval(share, 0.0).distance(anchor) > 2.0, "{cuts:?}: the polygon share {share} lands on the anchor"); + } + for (u, v) in [(0.1, 0.0), (0.3, 0.2), (0.5, 0.5), (0.62, 0.0), (0.9, 0.7), (0.97, 1.0)] { + let (p, q) = (c.eval(u, v), whole.eval(u, v)); + assert!(p.distance(q) < 1e-9, "{cuts:?}: ({u}, {v}) → {p:?}, unsplit {q:?}"); + } + } + } + + #[test] + fn a_split_curve_keeps_the_top_object_patch_when_split_at_a_cusp() { + // The top curve stops at t = 0.25 (a cusp), and an anchor splits it there: both handles at + // the split lie on the anchor, and the patch with the corners given stays the unsplit + // curve's. + let cusp = CubicBez::new((0.0, 0.0), (30.0, -40.0), (-58.0, 24.0), (200.0, 0.0)); + let pieces = [cusp.subsegment(0.0..0.25), cusp.subsegment(0.25..1.0)]; + assert!(pieces[0].p2.distance(pieces[0].p3) < 1e-9 && pieces[1].p1.distance(pieces[1].p0) < 1e-9); + let whole = Coons::from_top_object(&top_of_pieces(&[cusp]), Some([0, 1, 2, 3])).unwrap(); + let c = Coons::from_top_object(&top_of_pieces(&pieces), Some([0, 2, 3, 4])).unwrap(); + for (u, v) in [(0.1, 0.0), (0.25, 0.0), (0.3, 0.2), (0.5, 0.5), (0.62, 0.0), (0.9, 0.7), (0.97, 1.0)] { + let (p, q) = (c.eval(u, v), whole.eval(u, v)); + assert!(p.distance(q) < 1e-6, "({u}, {v}) → {p:?}, unsplit {q:?}"); + } + } + + #[test] + fn a_split_curve_keeps_the_top_object_patch_where_it_barely_moves_and_runs_straight() { + // A straight top curve that barely moves at t = 0.25 and doesn't bend there: split there, + // the handles at the split are a few thousandths of a point long and the pieces don't bend + // at all, and the patch with the corners given stays the unsplit curve's. + let slow = CubicBez::new((0.0, 0.0), (28.578125, 0.0), (-57.109375, 0.0), (200.0, 0.0)); + let pieces = [slow.subsegment(0.0..0.25), slow.subsegment(0.25..1.0)]; + let (into, out) = (pieces[0].p3.distance(pieces[0].p2), pieces[1].p0.distance(pieces[1].p1)); + assert!(into > 0.0 && out > 0.0 && into.max(out) < 0.01, "{into} {out}"); + let whole = Coons::from_top_object(&top_of_pieces(&[slow]), Some([0, 1, 2, 3])).unwrap(); + let c = Coons::from_top_object(&top_of_pieces(&pieces), Some([0, 2, 3, 4])).unwrap(); + for (u, v) in [(0.1, 0.0), (0.25, 0.0), (0.3, 0.2), (0.5, 0.5), (0.62, 0.0), (0.9, 0.7), (0.97, 1.0)] { + let (p, q) = (c.eval(u, v), whole.eval(u, v)); + assert!(p.distance(q) < 1e-6, "({u}, {v}) → {p:?}, unsplit {q:?}"); + } + } + + #[test] + fn a_top_object_joins_a_split_curve_saved_with_rounded_coordinates() { + // A file saves the pieces of a curve split into thirds, or into tenths, with its + // coordinates rounded to 0.001 pt, on an outline 5, 200 or 5,000 pt wide: the side is + // still that curve, to within 0.02 pt. + let round = |p: Point| Point::new((p.x * 1000.0).round() / 1000.0, (p.y * 1000.0).round() / 1000.0); + for cuts in [3u32, 10] { + let pieces: Vec = + (0..cuts).map(|k| UNEVEN_TOP.subsegment(f64::from(k) / f64::from(cuts)..f64::from(k + 1) / f64::from(cuts))).collect(); + for scale in [0.025, 1.0, 25.0] { + let mut split = top_of_pieces(&pieces); + split.transform(Affine::scale(scale)); + for a in split.subpaths.iter_mut().flat_map(|sp| sp.anchors.iter_mut()) { + (a.p, a.h_in, a.h_out) = (round(a.p), round(a.h_in), round(a.h_out)); + } + let mut whole = top_of_pieces(&[UNEVEN_TOP]); + whole.transform(Affine::scale(scale)); + let (c, whole) = (Coons::from_top_object(&split, None).unwrap(), Coons::from_top_object(&whole, None).unwrap()); + for (u, v) in [(1.0 / 6.0, 0.0), (1.0 / 3.0, 0.0), (0.45, 0.0), (0.5, 0.5), (2.0 / 3.0, 0.0), (0.9, 0.3)] { + let (p, q) = (c.eval(u, v), whole.eval(u, v)); + assert!(p.distance(q) < 0.02, "{cuts} pieces at {scale}x: ({u}, {v}) → {p:?}, unsplit {q:?}"); + } + } + } + } + + #[test] + fn a_top_object_keeps_smoothly_joined_curves_apart() { + // The top side's second piece leaves the split anchor in line with the first piece's + // handle, but its far handle is 1 pt off the split curve's: the pieces are two curves, and + // each takes the share of its control polygon. + let (a, b) = (UNEVEN_TOP.subsegment(0.0..0.3), UNEVEN_TOP.subsegment(0.3..1.0)); + let b = CubicBez::new(b.p0, b.p1, b.p2 + Vec2::new(0.0, 1.0), b.p3); + let c = Coons::from_top_object(&top_of_pieces(&[a, b]), 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}"); + assert!((share - 0.3).abs() > 0.02, "{share}"); + } + + #[test] + fn a_top_object_side_partly_of_one_curve_keeps_the_polygon_shares() { + // The top side is a curve split at t = 0.3, then a straight segment: not all of it is one + // curve, so each piece keeps the share of its control polygon. + let curve = CubicBez::new((0.0, 0.0), (90.0, -45.0), (142.5, -22.5), (150.0, 0.0)); + let (a, b) = (curve.subsegment(0.0..0.3), curve.subsegment(0.3..1.0)); + let line = CubicBez::new((150.0, 0.0), (150.0 + 50.0 / 3.0, 0.0), (200.0 - 50.0 / 3.0, 0.0), (200.0, 0.0)); + let c = Coons::from_top_object(&top_of_pieces(&[a, b, line]), None).unwrap(); + let share = polygon(a) / (polygon(a) + polygon(b) + polygon(line)); + assert!(c.eval(share, 0.0).distance(a.p3) < 1e-9, "{:?}", c.eval(share, 0.0)); + // Joined into their curve, the two pieces would have put the anchor 0.3 of the way along + // their part of the side. + let joined = 0.3 * (polygon(a) + polygon(b)) / (polygon(a) + polygon(b) + polygon(line)); + assert!(c.eval(joined, 0.0).distance(a.p3) > 1.0, "{share} vs {joined}"); + } + + #[test] + fn a_top_object_side_of_many_arcs_stays_on_them() { + // A 120° arc of radius 500 drawn as `n` circular arcs, each close to a piece of one cubic + // while the whole arc is not one: the side stays on the circle, and the content's middle + // stays on the middle anchor, as the arcs' polygon shares put it. + let centre = Point::new(300.0, 600.0); + for n in [64u32, 128, 256] { + let step = 120f64.to_radians() / f64::from(n); + let reach = 500.0 * 4.0 / 3.0 * (step / 4.0).tan(); + let on = |a: f64| centre + Vec2::new(a.cos(), a.sin()) * 500.0; + let tangent = |a: f64| Vec2::new(-a.sin(), a.cos()) * reach; + let mut anchors: Vec = (0..=n) + .map(|i| { + let a = (-150f64).to_radians() + step * f64::from(i); + let p = on(a); + let h_in = if i == 0 { p } else { p - tangent(a) }; + let h_out = if i == n { p } else { p + tangent(a) }; + Anchor { p, h_in, h_out, ..Anchor::corner(p) } + }) + .collect(); + let (start, end) = (on((-150f64).to_radians()), on((-30f64).to_radians())); + anchors.extend([Anchor::corner(Point::new(end.x, 800.0)), Anchor::corner(Point::new(start.x, 800.0))]); + let path = PathData::single(SubPath::new(anchors, true)); + let c = Coons::from_top_object(&path, Some([0, n, n + 1, n + 2])).unwrap(); + let off = (0..=4000).map(|k| (c.eval(f64::from(k) / 4000.0, 0.0).distance(centre) - 500.0).abs()).fold(0.0, f64::max); + assert!(off < 0.001, "{n} arcs: the side lies {off} pt off the circle"); + let mid = c.eval(0.5, 0.0); + assert!(mid.distance(Point::new(300.0, 100.0)) < 0.001, "{n} arcs: the middle lands at {mid:?}"); + } } #[test] @@ -537,7 +875,7 @@ mod tests { #[test] fn an_envelope_maps_from_its_box_with_its_margins() { let rect = Node::path(NodeId(2), vectorcraft_geom::shapes::rectangle(Rect::new(10.0, 20.0, 110.0, 70.0)), crate::Appearance::default_art()); - let kind = EnvelopeKind::Warp { style: "arc".into(), bend: 0.0, h: 0.0, v: 0.0, horizontal: true }; + let kind = EnvelopeKind::Warp { style: "arc".into(), bend: 0.0, h: 0.0, v: 0.0, horizontal: true, version: 0 }; let content = [Arc::new(rect)]; let src = |content: &[Arc], frame: Affine, options: EnvelopeOptions| EnvelopeMap::new(content, &kind, frame, options).unwrap().src(); // Top, bottom, left and right. @@ -831,6 +1169,37 @@ mod tests { assert_eq!(m.locate_within(Point::new(30.0, 60.0), 3.0), m.locate(Point::new(30.0, 60.0))); } + /// A point on a mesh's outline locates on the edge it lies on, on all four sides alike, with no + /// tolerance; a point just outside does not, and a tolerance reaches only as far as it says. + /// A point that isn't finite locates nowhere. + #[test] + fn mesh_locate_takes_a_point_on_any_side_of_the_outline() { + for (rows, cols) in [(1, 1), (2, 3)] { + let m = + GradientMesh::for_path(&shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), rows, cols, Color::BLACK, MeshAppearance::Flat, 0.0) + .unwrap(); + let sides = [ + ("top", Point::new(30.0, 0.0), Vec2::new(0.0, -0.01)), + ("bottom", Point::new(30.0, 100.0), Vec2::new(0.0, 0.01)), + ("left", Point::new(0.0, 70.0), Vec2::new(-0.01, 0.0)), + ("right", Point::new(100.0, 70.0), Vec2::new(0.01, 0.0)), + ]; + for (side, p, out) in sides { + let (r, c, u, v) = m.locate(p).unwrap_or_else(|| panic!("{rows}×{cols} {side}: {p:?} is not located")); + assert!(r < m.rows as usize && c < m.cols as usize && (0.0..=1.0).contains(&u) && (0.0..=1.0).contains(&v), "{side}"); + assert!(m.eval(r, c, u, v).distance(p) < 1e-3, "{rows}×{cols} {side}: {:?}", m.eval(r, c, u, v)); + let mut e = m.clone(); + assert!(e.add_lines_at(p, 0.0).is_some(), "{rows}×{cols} {side}: no line at {p:?}"); + assert_eq!(m.locate(p + out), None, "{rows}×{cols} {side}: just outside"); + assert_eq!(m.locate_within(p + out * 100.0, 0.5), None, "{rows}×{cols} {side}: past the tolerance"); + assert!(m.locate_within(p + out * 100.0, 1.5).is_some(), "{rows}×{cols} {side}: within the tolerance"); + } + for p in [Point::new(f64::NAN, 0.0), Point::new(30.0, f64::INFINITY)] { + assert_eq!(m.locate_within(p, f64::INFINITY), None, "{p:?}"); + } + } + } + /// Corners all in CMYK mix in CMYK (the inks halfway), not in RGB. #[test] fn a_cmyk_mesh_mixes_its_inks() { diff --git a/crates/doc/src/live/blend_spec.rs b/crates/doc/src/live/blend_spec.rs index 75df5eee1f..047e1ad7b5 100644 --- a/crates/doc/src/live/blend_spec.rs +++ b/crates/doc/src/live/blend_spec.rs @@ -107,6 +107,11 @@ pub struct BlendSpec { /// on anchor points); `None`: chosen so closed shapes don't twist. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub starts: Vec>, + /// The blend was made without a spine (Create Spine › Never): it has no spine to show, edit, + /// reverse or release, and no easing. Its steps still sit on the straight lines between the + /// key centers. Replace Spine gives it one. + #[serde(default, rename = "noSpine", skip_serializing_if = "is_false", deserialize_with = "lenient_bool")] + pub no_spine: bool, } impl BlendSpec { @@ -114,6 +119,47 @@ impl BlendSpec { pub fn start(&self, i: usize) -> Option { self.starts.get(i).copied().flatten().map(|a| a as usize) } + + /// Whether [`Self::ease`] moves the steps: the blend has a spine ([`Self::no_spine`] is off) + /// and a replaced spine or Align to Path, the cases where the steps are placed along it. + pub fn eases_along_spine(&self) -> bool { + !self.no_spine && (self.spine.is_some() || self.orientation == BlendOrientation::AlignToPath) + } +} + +/// The Blend panel's Create Spine setting: whether a new blend gets a spine. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum BlendSpineMode { + /// The usual rule: every new blend gets a spine, the straight lines between its key centers. + #[default] + Auto, + /// Every new blend gets a spine, whatever its key objects are. + Always, + /// New blends get no spine. + Never, +} + +impl BlendSpineMode { + /// Every mode, in the order the Blend panel lists them. + pub const ALL: [Self; 3] = [Self::Auto, Self::Always, Self::Never]; + + pub fn id(self) -> &'static str { + match self { + Self::Auto => "auto", + Self::Always => "always", + Self::Never => "never", + } + } + + pub fn from_id(id: &str) -> Option { + Self::ALL.into_iter().find(|m| m.id() == id) + } + + /// Whether a new blend made with this mode gets a spine. + pub fn creates_spine(self) -> bool { + self != Self::Never + } } /// Blend Options set with no blend selected: what new blends start with. @@ -123,6 +169,29 @@ pub struct BlendDefaults { pub spacing: BlendSpacing, #[serde(default)] pub orientation: BlendOrientation, + /// Create Spine (`object.blend.createSpine`). + #[serde(default, rename = "createSpine", skip_serializing_if = "is_auto", deserialize_with = "spine_mode")] + pub create_spine: BlendSpineMode, +} + +fn is_false(v: &bool) -> bool { + !*v +} + +fn is_auto(v: &BlendSpineMode) -> bool { + *v == BlendSpineMode::Auto +} + +/// Reading a native file never fails over a `noSpine` that is not a boolean: the blend keeps its +/// spine. +fn lenient_bool<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + Ok(serde_json::Value::deserialize(d)?.as_bool().unwrap_or(false)) +} + +/// Reading the preferences never fails over an unknown Create Spine value: it becomes Auto. +fn spine_mode<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + let v = serde_json::Value::deserialize(d)?; + Ok(v.as_str().and_then(BlendSpineMode::from_id).unwrap_or_default()) } /// Reading a native file never fails over one bad blend number: out-of-range values clamp, diff --git a/crates/doc/src/live/envelope.rs b/crates/doc/src/live/envelope.rs index 8abe961841..5aa43b0a67 100644 --- a/crates/doc/src/live/envelope.rs +++ b/crates/doc/src/live/envelope.rs @@ -3,6 +3,10 @@ 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; +fn is_zero(n: &u32) -> bool { + *n == 0 +} + /// How an envelope distorts its content. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(tag = "type", rename_all = "camelCase")] @@ -19,6 +23,10 @@ pub enum EnvelopeKind { v: f64, #[serde(default = "yes")] horizontal: bool, + /// The map the warp draws with: [`WARP_NET`](super::WARP_NET) for its style's Bézier net, + /// 0 (as in files from before the version existed) for [`warp_point`](super::warp_point). + #[serde(default, skip_serializing_if = "is_zero")] + version: u32, }, /// A `(rows+1)×(cols+1)` grid of points (row-major) the content's bounding box maps onto. Mesh { @@ -141,20 +149,31 @@ impl EnvelopeOptions { /// its glyph outlines (see [`envelope_content_bounds`]). Strokes scale with the frame as /// [`Node::transform`] scales them. pub fn envelope_content_boxes(content: &[Arc], frame: Affine) -> Option<(Rect, Rect)> { + envelope_content_boxes_with(content, frame, false).or_else(|| envelope_content_boxes_with(content, frame, true)) +} + +/// [`envelope_content_boxes`] with type that draws nothing given its laid-out box when +/// `blank_type_box` is set and no box when it is not. A caller that measures the members of an +/// envelope's contents one at a time passes `true` only when the whole contents have no box with +/// `false`, so each member is measured as the whole contents measure it. +pub fn envelope_content_boxes_with(content: &[Arc], frame: Affine, blank_type_box: bool) -> 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| { - (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?)) + Some((content_set_box(content, true, to_frame, blank_type_box)?, content_set_box(content, false, to_frame, blank_type_box)?)) } /// 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. +/// [`set_type_ink`]. Type that draws nothing adds no box while other content has one; when +/// nothing else has a box, it keeps its laid-out box. pub fn envelope_content_bounds(content: &[Arc]) -> Option { - content.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, content_box(c, false, Affine::IDENTITY))) + content_set_box(content, false, Affine::IDENTITY, false).or_else(|| content_set_box(content, false, Affine::IDENTITY, true)) +} + +/// The union of the boxes [`content_box`] gives each of `content`. +fn content_set_box(content: &[Arc], stroked: bool, to: Affine, blank_type_box: bool) -> Option { + content.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, content_box(c, stroked, to, blank_type_box))) } /// The box of type's glyph outlines, underlines and strikethroughs with its text space mapped by @@ -359,15 +378,16 @@ fn find_type(n: &Node, typed: &mut std::collections::HashSet) -> bool { /// 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, stroked: bool, to: Affine) -> Option { +/// those axes. A character's strokes reach as far past its glyphs as past the laid-out box. Type +/// that draws nothing has its laid-out box with `blank_type_box`, and no box without it. +fn content_box(n: &Arc, stroked: bool, to: Affine, blank_type_box: bool) -> Option { let mut typed = std::collections::HashSet::new(); find_type(n, &mut typed); - content_box_in(n, stroked, to, &typed) + content_box_in(n, stroked, to, &typed, blank_type_box) } /// [`content_box`], with the addresses of the objects in `n` that hold type ([`find_type`]). -fn content_box_in(n: &Arc, stroked: bool, to: Affine, typed: &std::collections::HashSet) -> Option { +fn content_box_in(n: &Arc, stroked: bool, to: Affine, typed: &std::collections::HashSet, blank_type_box: bool) -> Option { // `n` in the axes of `to`. let moved = || { if to == Affine::IDENTITY { @@ -387,10 +407,13 @@ fn content_box_in(n: &Arc, stroked: bool, to: Affine, typed: &std::collect 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) }; + let ink = match ink { + Some(Some(ink)) => ink, + Some(None) if !blank_type_box => return None, + _ => return own(&m), + }; if !stroked { return Some(ink); } @@ -405,7 +428,13 @@ fn content_box_in(n: &Arc, stroked: bool, to: Affine, typed: &std::collect 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) + content_box_in( + clip, + stroked && matches!(clip.kind, NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Text(_)), + to, + typed, + blank_type_box, + ) } NodeKind::Layer { .. } | NodeKind::Group { .. } => { let layer = matches!(n.kind, NodeKind::Layer { .. }); @@ -416,9 +445,11 @@ fn content_box_in(n: &Arc, stroked: bool, to: Affine, typed: &std::collect 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))) + own_strokes.visual_of_members(members.map(|c| content_box_in(c, true, to, typed, blank_type_box))) } else { - members.filter(|c| c.visible || !layer).fold(None, |acc, c| vectorcraft_geom::union_opt(acc, content_box_in(c, false, to, typed))) + members + .filter(|c| c.visible || !layer) + .fold(None, |acc, c| vectorcraft_geom::union_opt(acc, content_box_in(c, false, to, typed, blank_type_box))) } } _ => own(&moved()), @@ -517,21 +548,106 @@ pub fn envelope_of(doc: &crate::Document, id: NodeId) -> Option<&Node> { doc.ancestry(id)?.into_iter().rev().find_map(|a| doc.node(a).filter(|n| matches!(n.kind, NodeKind::Envelope { .. }))) } -/// What a selected envelope shows on the canvas: its mesh lines (a warp's surface on a 4×4 grid, -/// a mesh envelope's own grid) or its top object's outline, and for a mesh envelope the grid to -/// edit (its points and handles). +/// What a selected envelope shows on the canvas: its mesh lines (a warp's surface on its +/// [`warp_grid`], a mesh envelope's own grid) or its top object's outline, and for a warp or mesh +/// envelope the grid to edit (its points and handles; none while its contents are edited). pub fn envelope_overlay(n: &Node) -> Option<(PathData, Option)> { - let NodeKind::Envelope { kind, .. } = &n.kind else { return None }; + let NodeKind::Envelope { kind, editing, .. } = &n.kind else { return None }; + let points = |grid: GradientMesh| (!*editing).then_some(grid); match &**kind { - EnvelopeKind::Mesh { rows, cols, points, handles } => { - let grid = envelope_grid(*rows, *cols, points, handles)?; - Some((grid.lines(), Some(grid))) + EnvelopeKind::Mesh { rows, cols, points: at, handles } => { + let grid = envelope_grid(*rows, *cols, at, handles)?; + Some((grid.lines(), points(grid))) } - EnvelopeKind::Warp { .. } => Some((EnvelopeMap::of(n)?.surface_mesh(4, 4, Color::BLACK).lines(), None)), + EnvelopeKind::Warp { .. } => match warp_grid(n) { + Some(grid) => Some((grid.lines(), points(grid))), + None => Some((EnvelopeMap::of(n)?.surface_mesh(4, 4, Color::BLACK).lines(), None)), + }, EnvelopeKind::TopObject { path, .. } => Some((path.clone(), None)), } } +/// The grid sizes [`warp_grid`] tries, in order: patches per row and per column. +const WARP_GRIDS: [u32; 3] = [4, 8, 16]; + +/// How far a [`warp_grid`] may draw from the warp it replaces, as a share of the diagonal of the +/// warp's bounds. +const WARP_GRID_TOLERANCE: f64 = 1e-3; + +/// The grid a warp envelope's points and handles are edited on: its surface sampled on the first +/// of 4×4, 8×8 and 16×16 patches whose curves draw within [`WARP_GRID_TOLERANCE`] of the warp, with +/// handles along it, as a gradient mesh with black points. Editing a point makes the envelope a +/// mesh envelope with this grid. `None` for other nodes, for content with no bounds, and for a warp +/// that no such grid follows closely enough or whose grid isn't finite. +/// Built again only when the envelope's content objects, warp, frame or options change, or what +/// type is measured with ([`set_type_ink`]). +pub fn warp_grid(n: &Node) -> Option { + let NodeKind::Envelope { content, kind, frame, options, .. } = &n.kind else { return None }; + if !matches!(**kind, EnvelopeKind::Warp { .. }) { + return None; + } + // `None` until a measure is registered, so a grid kept before then is built again after. + let inputs = TYPE_INK.get().map(|(_, inputs)| inputs()); + let key: Vec = content.iter().map(|c| Arc::as_ptr(c) as usize).collect(); + let same = |k: &KeptGrid| k.kind == **kind && k.frame == **frame && k.options == *options && k.inputs == inputs; + if let Some(grid) = WARP_GRIDS_KEPT.with_borrow(|kept| kept.get(&key).filter(|k| same(k)).map(|k| k.grid.clone())) { + return grid; + } + let grid = build_warp_grid(n); + WARP_GRIDS_KEPT.with_borrow_mut(|kept| { + if kept.len() >= WARP_GRID_KEPT { + // Entries for content that no longer exists go first, then one entry at a time. + kept.retain(|_, k| k.content.iter().all(|c| c.strong_count() > 0)); + if kept.len() >= WARP_GRID_KEPT + && let Some(any) = kept.keys().next().cloned() + { + kept.remove(&any); + } + } + // The weak pointers keep the content's addresses from being reused while the entry is kept. + let kept_content = content.iter().map(Arc::downgrade).collect(); + kept.insert(key, KeptGrid { content: kept_content, kind: (**kind).clone(), frame: **frame, options: *options, inputs, grid: grid.clone() }); + }); + grid +} + +/// A grid [`warp_grid`] built, with what it was built from. +struct KeptGrid { + content: Vec>, + kind: EnvelopeKind, + frame: Affine, + options: EnvelopeOptions, + inputs: Option, + grid: Option, +} + +/// How many grids [`warp_grid`] keeps on one thread. +const WARP_GRID_KEPT: usize = 1024; + +std::thread_local! { + /// The grids [`warp_grid`] built on this thread, by the addresses of their envelopes' content. + static WARP_GRIDS_KEPT: std::cell::RefCell, KeptGrid>> = Default::default(); +} + +/// [`warp_grid`], built from scratch. +fn build_warp_grid(n: &Node) -> Option { + let map = EnvelopeMap::of(n)?; + let bounds = map.bounds()?; + let tol = bounds.width().hypot(bounds.height()) * WARP_GRID_TOLERANCE; + if !tol.is_finite() { + return None; + } + WARP_GRIDS.into_iter().find_map(|k| { + let m = map.surface_mesh(k, k, Color::BLACK); + let finite = m.points.iter().all(|q| q.p.is_finite() && q.handles.iter().all(|h| h.is_finite())); + // Each patch is checked at its corners, the middles of its sides and its middle. + let steps = 2 * k as usize; + let at = |i: usize| i as f64 / steps as f64; + let fits = || (0..=steps).all(|j| (0..=steps).all(|i| mesh_at(&m, at(i), at(j)).distance(map.at(at(i), at(j))) <= tol)); + (finite && fits()).then_some(m) + }) +} + /// The frame an envelope keeps after transform `m` (its frame so far composed with the /// transform): identity when its axes stay square to the page, unflipped, since evaluating on /// the page axes gives the same result then. @@ -556,7 +672,7 @@ impl<'a> EnvelopeMap<'a> { pub fn new(content: &[Arc], kind: &'a EnvelopeKind, frame: Affine, options: EnvelopeOptions) -> Option { let frame = if frame.is_finite() && frame.determinant().abs() > 1e-12 { frame } else { Affine::IDENTITY }; let to_frame = frame.inverse(); - let src = content.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, content_box(c, false, to_frame)))?; + let src = content_set_box(content, false, to_frame, false).or_else(|| content_set_box(content, false, to_frame, true))?; let src = options.source_box(src); Some(Self { src, frame, to_frame, surface: surface_of(kind, src, frame) }) } @@ -742,14 +858,171 @@ mod tests { 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))); + let want = moved.visual_of_members(std::iter::once(content_box(&text, true, to, true))); assert!(want.is_some()); - assert_eq!(content_box(&group, true, to), want); + assert_eq!(content_box(&group, true, to, true), 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()); + assert!(content_box(&nested, false, Affine::IDENTITY, true).is_some()); + } + + /// A warp envelope of `style` at `bend` with map `version` around a 200×100 rectangle at + /// (100, 50). + fn warp_node(style: &str, bend: f64, h: f64, version: u32) -> Node { + let rect = vectorcraft_geom::shapes::rectangle(Rect::new(100.0, 50.0, 300.0, 150.0)); + let content = Arc::new(Node::path(NodeId(1), rect, crate::Appearance::default_art())); + let kind = EnvelopeKind::Warp { style: style.into(), bend, h, v: 0.0, horizontal: true, version }; + Node::new( + NodeId(2), + NodeKind::Envelope { + content: vec![content], + kind: Box::new(kind), + fidelity: 50.0, + editing: false, + options: EnvelopeOptions::NEW, + frame: Box::new(Affine::IDENTITY), + }, + ) + } + + const STYLES: [&str; 15] = [ + "arc", + "arcLower", + "arcUpper", + "arch", + "bulge", + "shellLower", + "shellUpper", + "flag", + "wave", + "fish", + "rise", + "fisheye", + "inflate", + "squeeze", + "twist", + ]; + + /// Every warp style's Bézier net has a grid to edit: its points lie on the warp, and the grid + /// draws within a thousandth of the warp's diagonal of it, between the grid lines too. The + /// overlay shows that grid's lines and points. + #[test] + fn every_warp_style_has_a_grid_that_keeps_its_shape() { + for style in STYLES { + for (bend, h) in [(50.0, 0.0), (100.0, 0.0), (-100.0, 60.0)] { + let n = warp_node(style, bend, h, crate::live::WARP_NET); + let grid = warp_grid(&n).unwrap_or_else(|| panic!("{style} {bend} {h}: no grid")); + assert!(WARP_GRIDS.contains(&grid.rows) && grid.rows == grid.cols, "{style}: {}×{}", grid.rows, grid.cols); + let map = EnvelopeMap::of(&n).unwrap(); + let b = map.bounds().unwrap(); + let tol = b.width().hypot(b.height()) * 1e-3; + let k = grid.cols as usize; + for (i, q) in grid.points.iter().enumerate() { + let want = map.at((i % (k + 1)) as f64 / k as f64, (i / (k + 1)) as f64 / k as f64); + assert!(q.p.distance(want) < 1e-9, "{style}: point {i} at {:?}, the warp at {want:?}", q.p); + } + for j in 0..=20 { + for i in 0..=20 { + let (u, v) = (i as f64 / 20.0, j as f64 / 20.0); + let off = mesh_at(&grid, u, v).distance(map.at(u, v)); + assert!(off <= tol, "{style} {bend} {h}: {off} off at ({u}, {v})"); + } + } + let (lines, shown) = envelope_overlay(&n).unwrap(); + assert_eq!(shown.as_ref(), Some(&grid), "{style}"); + assert_eq!(lines, grid.lines(), "{style}"); + } + } + } + + /// A kept warp grid is built again when the content, the warp, the frame or the options change, + /// and is the grid built from scratch otherwise. + #[test] + fn a_kept_warp_grid_follows_changes() { + let n = warp_node("arc", 50.0, 0.0, crate::live::WARP_NET); + let first = warp_grid(&n); + assert!(first.is_some()); + assert_eq!(warp_grid(&n), first); + assert_eq!(build_warp_grid(&n), first); + let changed = |f: &dyn Fn(&mut Node)| { + let mut m = n.clone(); + f(&mut m); + let grid = warp_grid(&m); + assert_eq!(grid, build_warp_grid(&m)); + assert_ne!(grid, first); + }; + changed(&|m| { + if let NodeKind::Envelope { content, .. } = &mut m.kind { + Arc::make_mut(&mut content[0]).transform(Affine::translate((40.0, 0.0)), true); + } + }); + changed(&|m| { + if let NodeKind::Envelope { kind, .. } = &mut m.kind + && let EnvelopeKind::Warp { bend, .. } = &mut **kind + { + *bend = -30.0; + } + }); + changed(&|m| { + if let NodeKind::Envelope { frame, .. } = &mut m.kind { + **frame = Affine::rotate(0.3); + } + }); + changed(&|m| { + if let NodeKind::Envelope { options, .. } = &mut m.kind { + options.bounds_margin = [0.1; 4]; + } + }); + } + + /// The table of kept warp grids stays bounded: full of envelopes that still exist, it drops one + /// entry at a time instead of emptying, and it drops the entries of envelopes that are gone + /// first. + #[test] + fn the_kept_warp_grids_stay_bounded() { + let nodes: Vec = (0..WARP_GRID_KEPT + 10).map(|i| warp_node("arc", (i % 100) as f64, 0.0, crate::live::WARP_NET)).collect(); + for n in &nodes { + assert!(warp_grid(n).is_some()); + } + assert_eq!(WARP_GRIDS_KEPT.with_borrow(|kept| kept.len()), WARP_GRID_KEPT); + // Once the envelopes are gone, their entries are the ones dropped. + drop(nodes); + assert!(warp_grid(&warp_node("arc", 10.0, 0.0, crate::live::WARP_NET)).is_some()); + assert_eq!(WARP_GRIDS_KEPT.with_borrow(|kept| kept.len()), 1); + } + + /// A warp drawn by the old point map that no grid of up to 16×16 patches follows closely + /// enough, content without bounds and other envelopes have no warp grid; the overlay still + /// draws the old warp's lines. While an envelope's contents are edited, it shows no points. + #[test] + fn a_warp_no_grid_follows_has_no_grid_to_edit() { + let n = warp_node("fisheye", 100.0, 0.0, 0); + assert!(warp_grid(&n).is_none()); + let (lines, grid) = envelope_overlay(&n).unwrap(); + assert!(grid.is_none()); + assert!(lines.anchor_count() > 0); + // The same style on its Bézier net has one. + assert!(warp_grid(&warp_node("fisheye", 100.0, 0.0, crate::live::WARP_NET)).is_some()); + let mut empty = warp_node("arc", 50.0, 0.0, crate::live::WARP_NET); + if let NodeKind::Envelope { content, .. } = &mut empty.kind { + content.clear(); + } + assert!(warp_grid(&empty).is_none()); + let mut mesh = warp_node("arc", 50.0, 0.0, crate::live::WARP_NET); + if let NodeKind::Envelope { kind, .. } = &mut mesh.kind { + **kind = EnvelopeKind::Mesh { rows: 1, cols: 1, points: grid_points(Rect::new(0.0, 0.0, 1.0, 1.0), 1, 1), handles: vec![] }; + } + assert!(warp_grid(&mesh).is_none()); + // While the contents are edited, a warp's and a mesh envelope's lines show without points. + for mut n in [warp_node("arc", 50.0, 0.0, crate::live::WARP_NET), mesh] { + if let NodeKind::Envelope { editing, .. } = &mut n.kind { + *editing = true; + } + let (lines, grid) = envelope_overlay(&n).unwrap(); + assert!(grid.is_none() && lines.anchor_count() > 0); + } } /// A table that fills up is emptied instead of growing, and what is looked up after that is diff --git a/crates/doc/src/live/expand.rs b/crates/doc/src/live/expand.rs index 8675dcc011..b8309f675b 100644 --- a/crates/doc/src/live/expand.rs +++ b/crates/doc/src/live/expand.rs @@ -119,7 +119,8 @@ pub(super) fn map_node(n: &Node, w: &Warper) -> Node { { out.appearance.warp_linear_gradients(b, &|p| affine_near(w.f, p, w.eps)); } - if let Some(m) = out.extras_if_any().and_then(|e| e.mask.as_mut()) { + // A linked opacity mask bends with the object it masks; an unlinked one stays where it is. + if let Some(m) = out.extras_if_any().and_then(|e| e.mask.as_mut()).filter(|m| m.linked) { m.art = Arc::new(map_node(&m.art, w)); } match &mut out.kind { @@ -178,29 +179,48 @@ fn affine_between(s: [Point; 3], d: [Point; 3]) -> Option { a.is_finite().then_some(a) } -/// Image `n` (`im`) pushed through the warp as a raster mesh warp: its frame cut into -/// `w.cells`² cells of two triangles, each a clip group showing the image under the affine map -/// that takes the triangle where the warp takes its corners (with Preserve Shape Using -/// Transparency, the image masked by the triangle; with Anti-Alias off, drawn without smoothing). -/// Each piece reaches a little past its edges (at most half a point) so neighbours overlap and no -/// seams show. +/// Image `n` (`im`) pushed through the envelope's warp as a raster mesh warp ([`mesh_warp_image`] +/// with `w.cells` cells, Preserve Shape Using Transparency and Anti-Alias as the envelope's +/// options say). fn warp_image(n: &Node, im: &ImageObject, w: &Warper) -> Node { let k = w.cells.max(1); - // Two triangles a cell, three objects each; an image an inner envelope already cut into - // pieces is cut again here, so the pieces count against [`MAX_GENERATED`]. Past it, the image - // is left out. - if !Generating::charge(k.saturating_mul(k).saturating_mul(6)) { + // An image an inner envelope already cut into pieces is cut again here, so the pieces count + // against [`MAX_GENERATED`]. Past it, the image is left out. + if !Generating::charge(mesh_warp_cost(k)) { let mut g = n.clone(); g.kind = NodeKind::Group { children: vec![], clip: false }; return g; } + mesh_warp_image(n, im, w.f, k, !w.options.anti_alias, w.options.preserve_shape == PreserveShape::Transparency) +} + +/// How many objects [`mesh_warp_image`] makes of one image with `cells` rows and columns: two +/// triangles a cell, three objects each. +pub fn mesh_warp_cost(cells: usize) -> usize { + let k = cells.max(1); + k.saturating_mul(k).saturating_mul(6) +} + +/// Image `n` (`im`) pushed through point map `f` as a raster mesh warp: its frame cut into +/// `cells`² cells of two triangles, each a clip group showing the image under the affine map +/// that takes the triangle where `f` takes its corners (with `masked`, the image masked by the +/// triangle instead; with `pixelated`, drawn without smoothing). Each piece reaches a little past +/// its edges (at most half a point) so neighbors overlap and no seams show. Each piece keeps the +/// color `n` colorizes a grayscale image with, and `n`'s color mask. The result is a group with `n`'s id, name, +/// transparency, opacity mask and appearance. +pub fn mesh_warp_image(n: &Node, im: &ImageObject, f: &dyn Fn(Point) -> Point, cells: usize, pixelated: bool, masked: bool) -> Node { + let k = cells.max(1); + // A grayscale image's fill color colorizes each piece; the group of pieces takes none. + let colorize = n.extras().colorize.clone(); + // Each piece shows what the image shows: its color mask's masked pixels. + let color_mask = n.extras().color_mask.clone(); let (pw, ph) = (im.width as f64, im.height as f64); let at = |i: usize, j: usize| Point::new(pw * i as f64 / k as f64, ph * j as f64 / k as f64); let mut pieces = Vec::with_capacity(2 * k * k); for j in 0..k { for i in 0..k { let s = [at(i, j), at(i + 1, j), at(i + 1, j + 1), at(i, j + 1)]; - let d = s.map(|p| (w.f)(im.xf * p)); + let d = s.map(|p| f(im.xf * p)); for t in [[0, 1, 2], [0, 2, 3]] { let (st, dt) = (t.map(|v| s[v]), t.map(|v| d[v])); let Some(xf) = affine_between(st, dt) else { continue }; @@ -216,8 +236,10 @@ fn warp_image(n: &Node, im: &ImageObject, w: &Warper) -> Node { .collect(); let shape = PathData::single(SubPath::polyline(&tri, true)); let mut image = Node::new(n.id, NodeKind::Image(Box::new(ImageObject { xf, ..im.clone() }))); - image.extras_mut().pixelated = !w.options.anti_alias; - if w.options.preserve_shape == PreserveShape::Transparency { + image.extras_mut().pixelated = pixelated; + image.extras_mut().colorize = colorize.clone(); + image.extras_mut().color_mask = color_mask.clone(); + if masked { // Preserve Shape Using Transparency: the triangle is the piece's alpha (a // white opacity mask) instead of its clipping path. let white = Node::path(n.id, shape, Appearance::basic(Paint::solid(Color::WHITE), Paint::None, 0.0)); @@ -234,6 +256,9 @@ fn warp_image(n: &Node, im: &ImageObject, w: &Warper) -> Node { } let mut g = n.clone(); g.kind = NodeKind::Group { children: pieces, clip: false }; + if let Some(e) = g.extras_if_any() { + e.colorize = None; + } g } diff --git a/crates/doc/src/live/mesh.rs b/crates/doc/src/live/mesh.rs index c59374dee9..b6d5bbc88d 100644 --- a/crates/doc/src/live/mesh.rs +++ b/crates/doc/src/live/mesh.rs @@ -1,5 +1,5 @@ use super::envelope::{EnvelopeKind, H_DOWN, H_LEFT, H_RIGHT, H_UP, envelope_grid, mesh_at}; -use super::warp::{WarpStyle, flatten_subpath, resample, warp_point}; +use super::warp::{WarpNet, WarpStyle, flatten_subpath, resample, uses_net, warp_point}; use super::{ Affine, Anchor, Arc, Color, CubicBez, Deserialize, Node, ParamCurve, PathData, Point, Rect, Serialize, Shape, SubPath, Vec2, fifty, lerp_color, one, @@ -147,14 +147,18 @@ impl Coons { /// 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. + /// curve parameter. A side whose pieces, from corner to corner, are all one cubic curve split at + /// anchors (each within 0.02 pt of that curve's piece) runs along that curve instead, by its + /// parameter: splitting the curve of such a side at more anchors, without changing its shape, + /// leaves how the side shares out the content as it was (corners found from the outline can + /// still move). 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 { 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(); @@ -212,11 +216,12 @@ impl Coons { 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. + // through pieces of segments, split at `a` and `b`; when all of them are one curve split + // at anchors ([`one_curve`]), it runs along that curve instead. 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) { @@ -232,8 +237,11 @@ impl Coons { } 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 = pieces.iter().map(polygon).collect(); + let pieces = match one_curve(&pieces) { + Some(one) => vec![one], + None => pieces, + }; + let mut weights: Vec = pieces.iter().map(control_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); @@ -336,6 +344,76 @@ impl Coons { /// anchors. const MAX_SIDE_POINTS: usize = 1 << 16; +/// How far, in points, each control point of each piece of a top object's side may lie from the +/// matching piece of one cubic curve for the side to run along that curve ([`one_curve`]); the side +/// then lies within this of the pieces it is drawn with. A curve split into thirds or tenths and +/// saved with its coordinates rounded to 0.001 pt stays within it, on outlines from 5 to 5,000 pt +/// wide; coarser rounding, or a piece of a much smaller share of the curve, can take it past this. +/// A smooth side that isn't one curve, such as an arc of a circle drawn in many pieces, lies +/// further off as a whole, even where each pair of its pieces would not. +const ONE_CURVE: f64 = 0.02; + +/// The length of `c`'s control polygon. +fn control_polygon(c: &CubicBez) -> f64 { + c.p0.distance(c.p1) + c.p1.distance(c.p2) + c.p2.distance(c.p3) +} + +/// The cubic curve that `pieces`, two or more end to end, are all pieces of, split at the anchors +/// between them, when each control point of each piece lies within [`ONE_CURVE`] of the matching +/// piece of that curve; `None` otherwise. Split at parameter `t`, a curve's handles on either side +/// of the split lie in line, their lengths in proportion to the spans of its parameter the two +/// pieces take; split where the curve stops (a cusp), both handles lie on the anchor, and the +/// pieces' second derivatives there, in proportion to the squares of the spans, give the proportion +/// instead (whichever of the two pairs is the longer). Those proportions give each piece's span, and the curve follows from the first +/// piece's start and its handle, and the last piece's end and its handle, scaled up by their spans. +/// Every piece is then checked against that curve's piece over its span, so error can't build up +/// from one split to the next (the first piece's start and handle, and the last piece's end and +/// handle, match by construction). +fn one_curve(pieces: &[CubicBez]) -> Option { + let (first, last) = (pieces.first()?, pieces.last()?); + if pieces.len() < 2 { + return None; + } + let mut spans = Vec::with_capacity(pieces.len()); + spans.push(1.0); + for pair in pieces.windows(2) { + let [a, b] = pair else { return None }; + let (into, out) = (a.p3.distance(a.p2), b.p0.distance(b.p1)); + // How far each piece bends away from the anchor goes with the squares of the spans. Split + // where the curve stops (a cusp), both handles lie on the anchor and say nothing of the + // spans, and the bends say it; where the curve runs straight through the split, the bends + // are nothing and the handles say it. Whichever pair is the longer is the one to go by. + let bend_in = ((a.p3 - a.p2) - (a.p2 - a.p1)).hypot(); + let bend_out = ((b.p2 - b.p1) - (b.p1 - b.p0)).hypot(); + let ratio = if into.min(out) >= bend_in.min(bend_out) { out / into } else { (bend_out / bend_in).sqrt() }; + let next = spans.last().copied().unwrap_or(1.0) * ratio; + if !(next.is_finite() && next > 0.0) { + return None; + } + spans.push(next); + } + let total: f64 = spans.iter().sum(); + let (head, tail) = (spans.first().copied().unwrap_or(1.0) / total, spans.last().copied().unwrap_or(1.0) / total); + if !(total.is_finite() && head > 0.0 && tail > 0.0) { + return None; + } + let one = CubicBez::new(first.p0, first.p0 + (first.p1 - first.p0) / head, last.p3 + (last.p2 - last.p3) / tail, last.p3); + if ![one.p1, one.p2].iter().all(|p| p.is_finite()) { + return None; + } + let near = |p: Point, q: Point| p.distance(q) <= ONE_CURVE; + let mut from = 0.0; + for (k, (piece, span)) in pieces.iter().zip(&spans).enumerate() { + let to = if k + 1 == pieces.len() { 1.0 } else { (from + span / total).min(1.0) }; + let part = one.subsegment(from..to); + if !(near(part.p0, piece.p0) && near(part.p1, piece.p1) && near(part.p2, piece.p2) && near(part.p3, piece.p3)) { + return None; + } + from = to; + } + Some(one) +} + /// 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; @@ -530,6 +608,10 @@ pub(super) const MAX_BORDER_LINES: usize = 256; /// The most rounds of new lines a mesh made from a path takes to keep its border on the outline. const MAX_BORDER_ROUNDS: usize = 64; +/// A point this close (in points) to a mesh's outline is on it, for [`GradientMesh::locate_within`] +/// with any tolerance. +const ON_OUTLINE: f64 = 1e-6; + /// An anchor whose directions in and out differ by more than this (radians) is a corner: a border /// edge that can't follow the outline takes a mesh line through its sharpest corner first. const SHARP_TURN: f64 = 0.01; @@ -1436,17 +1518,23 @@ impl GradientMesh { } /// As [`Self::locate`], and for a point outside the mesh within `tol` of its outline, the - /// patch and local (u, v) of the nearest point of the mesh's edge. + /// patch and local (u, v) of the nearest point of the mesh's edge. A point on the outline + /// (within [`ON_OUTLINE`]) locates on its edge on every side, with any `tol`. pub fn locate_within(&self, p: Point, tol: f64) -> Option<(usize, usize, f64, f64)> { - if !self.is_valid() { + if !self.is_valid() || !p.is_finite() { return None; } - let bp = self.outline().to_bezpath(); - if bp.winding(p) == 0 { + // A point on the outline takes the nearest point of the edge on every side: the nonzero + // winding number counts a point on some edges as outside (a rectangle's bottom and right + // edges) and on the others as inside. + if let Some((_, r, c, u, v)) = self.nearest_edge(p, ON_OUTLINE).filter(|e| e.0 <= ON_OUTLINE * ON_OUTLINE) { + return Some((r, c, u, v)); + } + if self.outline().to_bezpath().winding(p) == 0 { if tol.is_nan() || tol <= 0.0 { return None; } - return self.nearest_edge(p).filter(|e| e.0 <= tol * tol).map(|(_, r, c, u, v)| (r, c, u, v)); + return self.nearest_edge(p, tol).filter(|e| e.0 <= tol * tol).map(|(_, r, c, u, v)| (r, c, u, v)); } const N: usize = 16; let mut best = (f64::INFINITY, 0, 0, 0.0, 0.0); @@ -1484,12 +1572,20 @@ impl GradientMesh { } /// The point of the mesh's outer edge nearest `p`: its squared distance from `p`, and its - /// boundary patch and local (u, v). - fn nearest_edge(&self, p: Point) -> Option<(f64, usize, usize, f64, f64)> { + /// boundary patch and local (u, v). Edges whose control points all lie farther than `within` + /// from `p` are skipped, so `None` means no edge is within `within`. + fn nearest_edge(&self, p: Point, within: f64) -> Option<(f64, usize, usize, f64, f64)> { use vectorcraft_geom::kurbo::ParamCurveNearest; let (rows, cols) = (self.rows as usize, self.cols as usize); let mut best: Option<(f64, usize, usize, f64, f64)> = None; let mut take = |e: CubicBez, at: (usize, usize, Option, Option)| { + // The edge lies inside its control points' box, so a box farther than `within` holds + // no point of the edge within it. + let b = Rect::from_points(e.p0, e.p1).union_pt(e.p2).union_pt(e.p3); + let (dx, dy) = ((b.x0 - p.x).max(p.x - b.x1).max(0.0), (b.y0 - p.y).max(p.y - b.y1).max(0.0)); + if dx * dx + dy * dy > within * within { + return; + } let n = e.nearest(p, 1e-9); if best.is_none_or(|b| n.distance_sq < b.0) { let (r, c, u, v) = at; @@ -1731,10 +1827,19 @@ pub(super) fn grid_eval(rows: usize, cols: usize, pts: &[Point], u: f64, v: f64) pub(super) fn surface_of<'a>(kind: &'a EnvelopeKind, src: Rect, frame: Affine) -> Box Point + 'a> { let flat = move |u: f64, v: f64| frame * Point::new(src.x0 + u * src.width(), src.y0 + v * src.height()); match kind { - EnvelopeKind::Warp { style, bend, h: dh, v: dv, horizontal } => { + EnvelopeKind::Warp { style, bend, h: dh, v: dv, horizontal, version } => { let st = WarpStyle::from_id(style).unwrap_or(WarpStyle::Arc); let b = bend.clamp(-100.0, 100.0) / 100.0; let (dh, dv) = (dh.clamp(-100.0, 100.0) / 100.0, dv.clamp(-100.0, 100.0) / 100.0); + if uses_net(*version) { + let net = WarpNet::new(st, b, dh, dv, src.width(), src.height(), !*horizontal); + // Content with no width or no height takes the middle of the patch along that side. + let (flat_u, flat_v) = (src.width() <= 0.0, src.height() <= 0.0); + return Box::new(move |u: f64, v: f64| { + let (u, v) = (if flat_u { 0.5 } else { u }, if flat_v { 0.5 } else { v }); + frame * (src.origin() + net.at(u, v).to_vec2()) + }); + } let c = src.center(); let (hw, hh) = (src.width() / 2.0, src.height() / 2.0); let horizontal = *horizontal; diff --git a/crates/doc/src/live/warp.rs b/crates/doc/src/live/warp.rs index 6d7392ac5f..08bef91140 100644 --- a/crates/doc/src/live/warp.rs +++ b/crates/doc/src/live/warp.rs @@ -109,6 +109,337 @@ pub fn warp_point(style: WarpStyle, b: f64, dh: f64, dv: f64, aspect: f64, x: f6 (x2, y2) } +// ===================================================================================== +// Warp nets: each style as one Bézier patch over its box +// ===================================================================================== + +/// The `version` a Warp effect's params or a warp envelope carries for the [`WarpNet`] map. With +/// none (or 0) a warp draws with [`warp_point`], as every warp did before, so saved documents keep +/// their look; new and imported warps are given this one. +pub const WARP_NET: u32 = 1; + +/// Does a warp of map `version` draw with [`WarpNet`]? A version newer than this build knows draws +/// with the newest map it has. +pub fn uses_net(version: u32) -> bool { + version >= WARP_NET +} + +/// The map version `v` names when it is one this build draws: a whole number from 0 to +/// [`WARP_NET`], written as an integer or as a float (`1` or `1.0`). +pub fn warp_version(v: &serde_json::Value) -> Option { + let n = v.as_f64()?; + (n.fract() == 0.0 && (0.0..=f64::from(WARP_NET)).contains(&n)).then_some(n as u32) +} + +/// A style's own control net: `rows` × `cols` points (2 to 4 each) of a Bézier patch, row by row +/// from the top, in the box's coordinates (origin at its top left, y down). +#[derive(Clone, Copy, Debug)] +struct Net { + rows: usize, + cols: usize, + p: [[Point; 4]; 4], +} + +impl Net { + /// The undistorted box `w` × `h` as a `rows` × `cols` net. + fn flat(w: f64, h: f64, rows: usize, cols: usize) -> Self { + let mut p = [[Point::ZERO; 4]; 4]; + for (r, row) in p.iter_mut().enumerate().take(rows) { + for (c, q) in row.iter_mut().enumerate().take(cols) { + *q = Point::new(w * (c as f64 / (cols - 1) as f64), h * (r as f64 / (rows - 1) as f64)); + } + } + Self { rows, cols, p } + } + + /// Upside down within a box `h` high: the rows in reverse order, each point mirrored. + fn mirrored(self, h: f64) -> Self { + let mut out = self; + for (to, from) in out.p[..self.rows].iter_mut().zip(self.p[..self.rows].iter().rev()) { + for (q, f) in to.iter_mut().zip(from).take(self.cols) { + *q = Point::new(f.x, h - f.y); + } + } + out + } + + /// Rows and columns exchanged, and x with y: a net made on the box turned on its side. + fn transposed(self) -> Self { + let mut out = Self { rows: self.cols, cols: self.rows, p: [[Point::ZERO; 4]; 4] }; + for (r, row) in self.p[..self.rows].iter().enumerate() { + for (c, q) in row[..self.cols].iter().enumerate() { + out.p[c][r] = Point::new(q.y, q.x); + } + } + out + } + + /// Each column scaled about the midpoint of its end points by `1 + a (2t - 1)`, `t` running from + /// 0 at the left column to 1 at the right: a horizontal distortion `a` (-1..1). + fn distort_columns(&mut self, a: f64) { + let (rows, cols) = (self.rows, self.cols); + for c in 0..cols { + let s = 1.0 + a * (2.0 * c as f64 / (cols - 1) as f64 - 1.0); + let mid = half_way(self.p[0][c], self.p[rows - 1][c]); + for row in &mut self.p[..rows] { + row[c] = mid + (row[c] - mid) * s; + } + } + } + + /// Each row scaled about the midpoint of its end points by `1 + a (2t - 1)`, `t` running from 0 + /// at the top row to 1 at the bottom: a vertical distortion `a` (-1..1). + fn distort_rows(&mut self, a: f64) { + let (rows, cols) = (self.rows, self.cols); + for (r, row) in self.p[..rows].iter_mut().enumerate() { + let s = 1.0 + a * (2.0 * r as f64 / (rows - 1) as f64 - 1.0); + let mid = half_way(row[0], row[cols - 1]); + for q in &mut row[..cols] { + *q = mid + (*q - mid) * s; + } + } + } + + /// The same patch as a bicubic net (degree elevation, which leaves the surface as it is). + fn bicubic(self) -> [[Point; 4]; 4] { + let rows: Vec<[Point; 4]> = self.p[..self.rows].iter().map(|row| cubic_line(&row[..self.cols])).collect(); + let mut out = [[Point::ZERO; 4]; 4]; + for c in 0..4 { + let col: Vec = rows.iter().map(|row| row[c]).collect(); + for (to, q) in out.iter_mut().zip(cubic_line(&col)) { + to[c] = q; + } + } + out + } +} + +/// The point half way from `a` to `b`, as halves added: two finite points always give a finite one. +fn half_way(a: Point, b: Point) -> Point { + Point::new(0.5 * a.x + 0.5 * b.x, 0.5 * a.y + 0.5 * b.y) +} + +/// A Bézier curve of 2 to 4 control points as the 4 of the same curve's cubic form. +fn cubic_line(p: &[Point]) -> [Point; 4] { + match *p { + [a, b] => [a, a.lerp(b, 1.0 / 3.0), a.lerp(b, 2.0 / 3.0), b], + [a, b, c] => [a, a.lerp(b, 2.0 / 3.0), c.lerp(b, 2.0 / 3.0), c], + [a, b, c, d] => [a, b, c, d], + _ => [Point::ZERO; 4], + } +} + +/// The handle offsets (along the chord, across it) of a cubic circular arc over a chord `chord` +/// long that turns through θ = |`b`| × 180°: each handle is 4/3 tan(θ/4) of the radius long, along +/// the arc's end tangent. With the radius `chord / (2 sin(θ/2))` that length is +/// `chord / (3 cos²(θ/4))`, which a bend near 0 leaves at a third of the chord. +fn arc_handles(chord: f64, b: f64) -> (f64, f64) { + let th = b.abs().min(1.0) * PI; + let len = chord / (3.0 * (th / 4.0).cos().powi(2)); + (len * (th / 2.0).cos(), len * (th / 2.0).sin()) +} + +/// A row from (0, `y`) to (`w`, `y`) bent into a circular arc of |`b`| × 180°: up for a positive +/// `b` when `up`, down when not, the other way for a negative one. +fn arc_row(w: f64, y: f64, b: f64, up: bool) -> [Point; 4] { + let (ax, ay) = arc_handles(w, b); + let dy = if (b > 0.0) == up { -ay } else { ay }; + [Point::new(0.0, y), Point::new(ax, y + dy), Point::new(w - ax, y + dy), Point::new(w, y)] +} + +/// Arc at bend |`b`| as four rows: the bottom edge bends up through the bottom corners, the top +/// edge is the arc around the same center `h` further out, and the rows between are spaced evenly +/// along the radii. The top corners lie `h` out from the bottom ones along the radii, which lean +/// out by θ/2. +fn arc_rows(w: f64, h: f64, b: f64) -> [[Point; 4]; 4] { + let th = b.abs().min(1.0) * PI; + let (s, c) = (th / 2.0).sin_cos(); + let (tl, tr) = (Point::new(-h * s, h * (1.0 - c)), Point::new(w + h * s, h * (1.0 - c))); + let (ax, ay) = arc_handles(tr.x - tl.x, b); + let top = [tl, Point::new(tl.x + ax, tl.y - ay), Point::new(tr.x - ax, tr.y - ay), tr]; + let bottom = arc_row(w, h, b.abs(), true); + let mut out = [[Point::ZERO; 4]; 4]; + for (r, row) in out.iter_mut().enumerate() { + for (q, (t, u)) in row.iter_mut().zip(top.iter().zip(bottom)) { + *q = t.lerp(u, r as f64 / 3.0); + } + } + out +} + +/// Warp style `style`'s own net at bend `b` (-1..1) over the box `w` × `h`, before distortion. +/// `vertical`: the net of the box turned on its side, where Rise moves the other half. +fn style_net(style: WarpStyle, b: f64, w: f64, h: f64, vertical: bool) -> Net { + use WarpStyle::*; + let two = |top: [Point; 4], bottom: [Point; 4]| { + let mut p = [[Point::ZERO; 4]; 4]; + (p[0], p[1]) = (top, bottom); + Net { rows: 2, cols: 4, p } + }; + let flat_row = |y: f64| [0.0, 1.0, 2.0, 3.0].map(|c| Point::new(w * c / 3.0, y)); + match style { + Arc => { + let rows = arc_rows(w, h, b); + let net = two(rows[0], rows[3]); + if b < 0.0 { net.mirrored(h) } else { net } + } + ArcUpper => two(arc_row(w, 0.0, b, true), flat_row(h)), + ArcLower => two(flat_row(0.0), arc_row(w, h, b, false)), + Arch => { + let top = arc_row(w, 0.0, b, true); + two(top, top.map(|q| Point::new(q.x, q.y + h))) + } + Bulge => two(arc_row(w, 0.0, b, true), arc_row(w, h, b, false)), + ShellLower | ShellUpper => { + let a = arc_rows(w, h, b); + let mut net = Net::flat(w, h, 4, 4); + if b >= 0.0 { + // The outer arc and the ends of the row inside it, upside down for Shell Lower. + net.p[0] = a[0]; + (net.p[1][0], net.p[1][3]) = (a[1][0], a[1][3]); + if style == ShellLower { net.mirrored(h) } else { net } + } else { + // The inner arc and the ends of the row outside it, upside down for Shell Upper. + net.p[3] = a[3]; + (net.p[2][0], net.p[2][3]) = (a[2][0], a[2][3]); + if style == ShellUpper { net.mirrored(h) } else { net } + } + } + Flag | Fish | Rise => { + let mut net = Net::flat(w, h, 2, 4); + let d = 2.0 * b * h; + match style { + Flag => { + for row in &mut net.p[..2] { + (row[1].y, row[2].y) = (row[1].y + d, row[2].y - d); + } + } + Fish => { + (net.p[0][1].y, net.p[0][2].y) = (net.p[0][1].y - d, net.p[0][2].y + d); + (net.p[1][1].y, net.p[1][2].y) = (net.p[1][1].y + d, net.p[1][2].y - d); + } + _ => { + for row in &mut net.p[..2] { + if vertical { + (row[2].y, row[3].y) = (row[2].y - d, row[3].y - d); + } else { + (row[0].y, row[1].y) = (row[0].y + d, row[1].y + d); + } + } + } + } + net + } + Wave => { + let mut net = Net::flat(w, h, 3, 4); + let d = 2.0 * b * h; + (net.p[1][1].y, net.p[1][2].y) = (net.p[1][1].y + d, net.p[1][2].y - d); + net + } + Fisheye => { + let mut net = Net::flat(w, h, 4, 4); + let c = Point::new(w / 2.0, h / 2.0); + for row in &mut net.p[1..3] { + for q in &mut row[1..3] { + *q = c + (*q - c) * (1.0 + 4.0 * b); + } + } + net + } + Inflate | Squeeze => { + let mut net = Net::flat(w, h, 3, 3); + let side = if style == Inflate { b * w / 2.0 } else { -b * w / 2.0 }; + net.p[0][1].y -= b * h / 2.0; + net.p[2][1].y += b * h / 2.0; + net.p[1][0].x -= side; + net.p[1][2].x += side; + net + } + Twist => { + // The four inner points move round: clockwise for a positive bend. + let mut net = Net::flat(w, h, 4, 4); + let (dx, dy) = (b.abs() * w, b.abs() * h); + if b >= 0.0 { + net.p[1][1].x += dx; + net.p[1][2].y += dy; + net.p[2][2].x -= dx; + net.p[2][1].y -= dy; + } else { + net.p[1][1].y += dy; + net.p[1][2].x -= dx; + net.p[2][2].y -= dy; + net.p[2][1].x += dx; + } + net + } + } +} + +/// A warp as one bicubic Bézier patch over its box: the style's own net at the bend, its columns +/// scaled by the horizontal distortion and then its rows by the vertical one. Points are in the +/// box's coordinates (origin at its top left, y down). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct WarpNet { + /// The control points over the box divided by `scale`. + net: [[Point; 4]; 4], + /// 1, or a power of two when the net over the box itself does not fit in finite numbers. + scale: f64, + w: f64, + h: f64, +} + +impl WarpNet { + /// The net of `style` over a box `w` × `h` at bend `b` and distortions `dh` and `dv` (each + /// -1..1, clamped); `vertical` bends along the box's height. + pub fn new(style: WarpStyle, b: f64, dh: f64, dv: f64, w: f64, h: f64, vertical: bool) -> Self { + let unit = |x: f64| if x.is_finite() { x.clamp(-1.0, 1.0) } else { 0.0 }; + let size = |x: f64| if x.is_finite() { x.max(0.0) } else { 0.0 }; + let (b, dh, dv, w, h) = (unit(b), unit(dh), unit(dv), size(w), size(h)); + let build = |w: f64, h: f64| { + let mut net = if vertical { style_net(style, b, h, w, true).transposed() } else { style_net(style, b, w, h, false) }; + net.distort_columns(dh); + net.distort_rows(dv); + net.bicubic() + }; + // A box near the largest finite size can overflow the net. The net is then built on the box + // divided by the smallest power of two that fits (2 to 4096), an exact division for every + // side above the subnormal range, and points are multiplied back as they are read. + let mut out = Self { net: build(w, h), scale: 1.0, w, h }; + while out.scale < 4096.0 && !out.net.iter().flatten().all(|q| q.is_finite()) { + let scale = out.scale * 2.0; + out = Self { net: build(w / scale, h / scale), scale, w, h }; + } + out + } + + /// The point at `(u, v)` of the box (0..1 across and down; outside, the patch goes on). A + /// coordinate the patch would send past the largest finite number is the box's own, held to + /// the finite range. + pub fn at(&self, u: f64, v: f64) -> Point { + let p = self.at_scaled(u, v); + let held = |x: f64| if x.is_nan() { 0.0 } else { x.clamp(-f64::MAX, f64::MAX) }; + let coord = |x: f64, flat: f64| if (x * self.scale).is_finite() { x * self.scale } else { held(flat) }; + Point::new(coord(p.x, u * self.w), coord(p.y, v * self.h)) + } + + /// [`Self::at`] divided by the net's scale. + fn at_scaled(&self, u: f64, v: f64) -> Point { + let bern = |t: f64| { + let s = 1.0 - t; + [s * s * s, 3.0 * t * s * s, 3.0 * t * t * s, t * t * t] + }; + let (bu, bv) = (bern(u), bern(v)); + let (mut x, mut y) = (0.0, 0.0); + for (row, wv) in self.net.iter().zip(bv) { + for (q, wu) in row.iter().zip(bu) { + x += wv * wu * q.x; + y += wv * wu * q.y; + } + } + Point::new(x, y) + } +} + /// Segment as a cubic; straight lines get handles at 1/3 and 2/3 so a non-linear map bends them. fn seg_cubic(sp: &SubPath, i: usize) -> CubicBez { let c = sp.segment(i); diff --git a/crates/doc/src/mem.rs b/crates/doc/src/mem.rs index e2d27650b5..7ff6cdeea2 100644 --- a/crates/doc/src/mem.rs +++ b/crates/doc/src/mem.rs @@ -46,7 +46,7 @@ impl Document { return (0, 0); } let own = size_of::() + ALLOC + ARC; - let mut w = Walk { docs: [self, other], seen: [None, None], bytes: [own, own] }; + let mut w = Walk { docs: [self, other], seen: [None, None], bytes: [own, own], appearances: Default::default() }; w.list(&self.layers, &other.layers); for i in 0..self.symbols.len().max(other.symbols.len()) { match (self.symbols.get(i), other.symbols.get(i)) { @@ -134,6 +134,9 @@ struct Walk<'a> { seen: [Option>; 2], /// For each side, what it keeps that the other doesn't. bytes: [usize; 2], + /// For each side, the appearances counted so far (by address): objects that share one (a + /// graphic style applied to them all) count it once. + appearances: [HashSet; 2], } impl Walk<'_> { @@ -174,8 +177,9 @@ impl Walk<'_> { self.alone(1, b); return; } - self.bytes[0] += node_bytes(a, Some(b)); - self.bytes[1] += node_bytes(b, Some(a)); + let [ca, cb] = &mut self.appearances; + self.bytes[0] += node_bytes(a, Some(b), ca); + self.bytes[1] += node_bytes(b, Some(a), cb); match (a.children(), b.children()) { (Some(x), Some(y)) => self.list(x, y), (x, y) => { @@ -198,8 +202,8 @@ impl Walk<'_> { if self.other_holds(side, n) { return; } - if let Some(b) = self.bytes.get_mut(side) { - *b += node_bytes(n, None); + if let (Some(b), Some(counted)) = (self.bytes.get_mut(side), self.appearances.get_mut(side)) { + *b += node_bytes(n, None, counted); } for c in n.children().into_iter().flatten() { self.alone(side, c); @@ -242,20 +246,25 @@ impl Walk<'_> { } /// One node's own heap: the node, and what it owns besides its children and mask art (counted -/// as nodes of their own). Its appearance counts unless `other`, its other version, shares it. -fn node_bytes(n: &Node, other: Option<&Node>) -> usize { +/// as nodes of their own). Its appearance counts unless `other`, its other version, shares it, or +/// another node of the same side shares it and was counted already (its address is in `counted`). +fn node_bytes(n: &Node, other: Option<&Node>, counted: &mut HashSet) -> usize { fn boxed(b: &Option>) -> usize { b.as_ref().map_or(0, |_| ALLOC + size_of::()) } let mut b = ALLOC + ARC + size_of::(); b += n.name.as_ref().map_or(0, String::capacity); - if !other.is_some_and(|m| Shared::ptr_eq(&m.appearance, &n.appearance)) { + if !other.is_some_and(|m| Shared::ptr_eq(&m.appearance, &n.appearance)) && counted.insert(&*n.appearance as *const Appearance as usize) { b += ALLOC + ARC + appearance_heap_bytes(&n.appearance); } if let Some(e) = n.extras_box() { b += ALLOC + size_of::(); b += boxed(&e.mask) + boxed(&e.graph) + boxed(&e.shaper) + boxed(&e.attrs) + boxed(&e.slice) + boxed(&e.perspective); b += boxed(&e.dimension) + boxed(&e.live_paint_gaps) + boxed(&e.colorize); + b += e + .color_mask + .as_deref() + .map_or(0, |m| ALLOC + size_of::() + m.key.capacity() + m.from.capacity() + m.colors.capacity() * 3); b += e.trace.as_ref().map_or(0, |t| ALLOC + size_of::() + json_bytes(t)); b += e.intertwine.as_deref().map_or(0, |a| ALLOC + size_of::() + path_bytes(a)); if e.intertwine_tiers.capacity() > 0 { @@ -447,6 +456,29 @@ mod tests { assert!(added > kept + 3 * 300, "{added} for three new rectangles"); } + /// Objects given one shared appearance (a graphic style applied to them all) count it once. + #[test] + fn a_shared_appearance_counts_once() { + let n = 100; + let before = doc_with_rects(n); + let ids: Vec<_> = before.layers[0].children().unwrap().iter().map(|c| c.id).collect(); + let ap = Appearance::basic(Paint::None, Paint::solid(vectorcraft_color::Color::BLACK), 2.0); + let restyled = |each: bool| { + let mut d = before.clone(); + let one = Shared::new(ap.clone()); + for id in &ids { + d.node_mut(*id).unwrap().appearance = if each { Shared::new(ap.clone()) } else { one.clone() }; + } + d + }; + let (shared, copies) = (restyled(false), restyled(true)); + let (kept, added) = before.retained_bytes_each(&shared); + assert_eq!(shared.retained_bytes_each(&before), (added, kept)); + let (kept_copies, added_copies) = before.retained_bytes_each(&copies); + assert_eq!(kept, kept_copies, "the old version keeps the same either way"); + assert_eq!(added_copies - added, (n - 1) * (ALLOC + ARC + appearance_heap_bytes(&ap))); + } + #[test] fn a_resource_counts_only_when_changed() { let before = doc_with_rects(1); diff --git a/crates/doc/src/metadata.rs b/crates/doc/src/metadata.rs index 151365c5d2..908b649e4d 100644 --- a/crates/doc/src/metadata.rs +++ b/crates/doc/src/metadata.rs @@ -1,11 +1,15 @@ //! File → File Info: the document's descriptive metadata (author, description, keywords, rating, //! copyright) and its created and modified dates, which the SVG, PDF and PNG writers carry. The -//! document title is [`crate::Document::title`]. Every field is defaulted, so documents saved -//! before File Info existed load unchanged. +//! document title is [`Document::title`], the name it shows in its tab and offers Save As when it +//! has no file; a title the file it was opened from gave itself is [`DocMetadata::title`], and +//! [`Document::info_title`] is the title File Info shows and exports write. Every field is +//! defaulted, so documents saved before File Info existed load unchanged. use chrono::{Datelike, Timelike}; use serde::{Deserialize, Serialize}; +use crate::Document; + /// File Info → Copyright Status. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -44,6 +48,13 @@ pub const MAX_RATING: u8 = 5; #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] pub struct DocMetadata { + /// The title the file this document was opened from gives itself (an SVG's root ``, a + /// PDF's XMP `dc:title` or Info `Title`), which File Info shows and exports write in place of + /// [`Document::title`], the document's display name. `None`: the file gave none, so the + /// display name is the title. Left out of a saved document when unset, so other documents + /// save as they did. + #[serde(skip_serializing_if = "Option::is_none")] + pub title: Option<String>, pub author: String, /// The author's position or job title. pub author_title: String, @@ -83,6 +94,16 @@ impl DocMetadata { } } +impl Document { + /// The title File Info shows and the files an export writes carry (PDF `Title` and XMP + /// `dc:title`, SVG `<title>`, PNG `Title`): the title the file this document was opened from + /// gave itself ([`DocMetadata::title`]), else [`Document::title`]. The display name (the tab, the + /// default file name) is always [`Document::title`]. + pub fn info_title(&self) -> &str { + self.metadata.title.as_deref().filter(|t| !t.trim().is_empty()).unwrap_or(&self.title) + } +} + /// The time exported files record: PDF `CreationDate` and `ModDate`, the PNG `Creation Time` /// entry, a zip entry's date, and a saved document's `created` and `modified`. It is the clock, /// unless `SOURCE_DATE_EPOCH` is set, which replaces it so that the same commands produce the same @@ -191,6 +212,24 @@ mod tests { assert!(DocMetadata::default().png_text("").is_empty()); } + #[test] + fn the_info_title_is_the_files_own_title_else_the_display_name() { + let mut d = Document::new(10.0, 10.0); + d.title = "box.svg".into(); + assert_eq!(d.info_title(), "box.svg"); + d.metadata.title = Some("Access paths".into()); + assert_eq!((d.title.as_str(), d.info_title()), ("box.svg", "Access paths")); + d.metadata.title = Some(" ".into()); + assert_eq!(d.info_title(), "box.svg"); + // Saved only when set: other documents' metadata is as before, and the field comes back. + d.metadata.title = None; + assert!(!serde_json::to_string(&d.metadata).unwrap().contains("title")); + d.metadata.title = Some("Access paths".into()); + let json = serde_json::to_string(&d.metadata).unwrap(); + assert_eq!(serde_json::from_str::<DocMetadata>(&json).unwrap().title.as_deref(), Some("Access paths")); + assert_eq!(serde_json::from_str::<DocMetadata>("{}").unwrap().title, None); + } + /// `SOURCE_DATE_EPOCH` replaces the clock in exported output only when it is a non-negative /// decimal integer; anything else leaves the clock to decide, so an export is never refused. #[test] diff --git a/crates/doc/src/node/extras.rs b/crates/doc/src/node/extras.rs index 6865ff7e6c..7b130bf395 100644 --- a/crates/doc/src/node/extras.rs +++ b/crates/doc/src/node/extras.rs @@ -72,6 +72,9 @@ pub struct NodeExtras { /// 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, + /// Image Tools › Color Mask: the colors an image hides while its pixels stay as they are + /// ([`crate::color_mask`]). + pub color_mask: Option<Box<crate::color_mask::ColorMask>>, } /// No extras: what [`Node::extras`] gives for a node without any. @@ -99,6 +102,7 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras { symbol_overrides: Vec::new(), envelope_edit_margin: None, pixel_aligned: false, + color_mask: None, }; /// A node's [`NodeExtras`], if it has any ([`Node::extras`]). Extras that are all unset equal diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index 415b2946e3..415fc1cad1 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -819,7 +819,8 @@ impl Node { impl Node { /// Whether this object shows any transparency, itself or anything inside it: object, fill or /// stroke opacity below 100%, a blend mode, an opacity mask, effects, transparent gradient - /// stops or a colorized image. Hidden objects show none. + /// stops (characters' fills and strokes included) or a colorized image. Hidden objects show + /// none. pub fn shows_transparency(&self) -> bool { self.shows_transparency_with(&|_| true) } @@ -827,21 +828,31 @@ impl Node { /// [`Self::shows_transparency`], counting a colorized image by itself only when `colorize` /// accepts it, for files that write some colorized images in their colorize paint (EPS). pub fn shows_transparency_with(&self, colorize: &dyn Fn(&Node) -> bool) -> bool { + self.visible && (self.own_transparency(colorize) || self.children().is_some_and(|ch| ch.iter().any(|c| c.shows_transparency_with(colorize)))) + } + + /// [`Self::shows_transparency`] of the object alone, what it holds left out. + pub fn shows_own_transparency(&self) -> bool { + self.visible && self.own_transparency(&|_| true) + } + + /// The object's own transparency, as [`Self::shows_transparency_with`] counts it. + fn own_transparency(&self, colorize: &dyn Fn(&Node) -> bool) -> bool { use vectorcraft_color::Paint; let see_through = |p: &Paint| matches!(p, Paint::Gradient(g) if g.gradient.stops.iter().any(|s| s.opacity < 1.0)); let effects = |fx: &[crate::Effect]| fx.iter().any(|e| e.visible); - self.visible - && (self.opacity < 1.0 - || self.blend != BlendMode::Normal - || self.extras().mask.as_ref().is_some_and(|m| !m.disabled) - || (matches!(self.kind, NodeKind::Image(_)) && self.extras().colorize.is_some() && colorize(self)) - || effects(&self.appearance.effects) - || self - .appearance - .items - .iter() - .any(|i| i.visible() && (i.opacity() < 1.0 || i.blend() != BlendMode::Normal || see_through(i.paint()) || effects(i.effects()))) - || self.children().is_some_and(|ch| ch.iter().any(|c| c.shows_transparency_with(colorize)))) + self.opacity < 1.0 + || self.blend != BlendMode::Normal + || self.extras().mask.as_ref().is_some_and(|m| !m.disabled) + || (matches!(self.kind, NodeKind::Image(_)) && self.extras().colorize.is_some() && colorize(self)) + || effects(&self.appearance.effects) + || self + .appearance + .items + .iter() + .any(|i| i.visible() && (i.opacity() < 1.0 || i.blend() != BlendMode::Normal || see_through(i.paint()) || effects(i.effects()))) + // Characters' own fills and strokes, which draw with the object. + || matches!(&self.kind, NodeKind::Text(t) if t.runs.iter().any(|r| see_through(&r.style.fill) || (r.style.stroke_width > 0.0 && see_through(&r.style.stroke)))) } } diff --git a/crates/doc/src/node/wire.rs b/crates/doc/src/node/wire.rs index 2722e7bee0..34d8e99c53 100644 --- a/crates/doc/src/node/wire.rs +++ b/crates/doc/src/node/wire.rs @@ -55,6 +55,7 @@ impl Serialize for Node { e.symbol_overrides.is_empty(), e.envelope_edit_margin.is_none(), is_default(&e.pixel_aligned), + e.color_mask.is_none(), ]; let mut st = s.serialize_struct("Node", skips.iter().filter(|s| !**s).count())?; let mut skip = skips.into_iter(); @@ -98,6 +99,7 @@ impl Serialize for Node { field!("symbol_overrides", &e.symbol_overrides); field!("envelope_edit_margin", &e.envelope_edit_margin); field!("pixel_aligned", &e.pixel_aligned); + field!("color_mask", &e.color_mask); st.end() } } @@ -241,6 +243,8 @@ pub(super) struct NodeWire { envelope_edit_margin: Option<[f32; 4]>, #[serde(default)] pixel_aligned: bool, + #[serde(default)] + color_mask: Option<Box<crate::color_mask::ColorMask>>, } impl From<NodeWire> for Node { @@ -269,6 +273,7 @@ impl From<NodeWire> for Node { symbol_overrides: w.symbol_overrides, envelope_edit_margin: w.envelope_edit_margin, pixel_aligned: w.pixel_aligned, + color_mask: w.color_mask, }; Node { id: w.id, diff --git a/crates/doc/src/objects_on_path.rs b/crates/doc/src/objects_on_path.rs index cace68ce66..26a11cf733 100644 --- a/crates/doc/src/objects_on_path.rs +++ b/crates/doc/src/objects_on_path.rs @@ -180,6 +180,24 @@ impl ObjectsOnPath { }); Some((spacing, start)) } + /// Move the object `member` to the place on the path of the object `target`: the objects + /// between them each move one place toward where `member` was, except the objects for which + /// `fixed` is true, which keep their places and are passed over. Only the order changes, not the + /// Space or the start. Returns `member`'s new index, or `None` when either one is not an object + /// of the group. + pub fn move_member(&mut self, member: NodeId, target: NodeId, fixed: impl Fn(NodeId) -> bool) -> Option<usize> { + let moves = |id: NodeId| id == member || id == target || !fixed(id); + let slots: Vec<usize> = (0..self.members.len()).filter(|&i| moves(self.members[i].id)).collect(); + let from = slots.iter().position(|&i| self.members[i].id == member)?; + let to = slots.iter().position(|&i| self.members[i].id == target)?; + let mut moving: Vec<_> = slots.iter().map(|&i| self.members[i]).collect(); + let m = moving.remove(from); + moving.insert(to, m); + for (&i, m) in slots.iter().zip(moving) { + self.members[i] = m; + } + Some(slots[to]) + } /// The children given new ids (a copy of the group): the path and the objects by their new ids. pub fn rename(&mut self, ids: &HashMap<NodeId, NodeId>) { let to = |id: NodeId| ids.get(&id).copied().unwrap_or(id); @@ -487,6 +505,36 @@ mod tests { assert_eq!(layout(400.0, true, 4, Some(300.0), 400.0), (0.0, 100.0)); } + #[test] + fn moving_an_object_shifts_the_ones_between_it_and_its_new_place() { + let (a, b, c) = + (rect(2, Rect::new(0.0, 0.0, 10.0, 10.0)), rect(3, Rect::new(20.0, 0.0, 30.0, 10.0)), rect(4, Rect::new(40.0, 0.0, 50.0, 10.0))); + let rec = ObjectsOnPath { spacing: Some(30.0), start: 5.0, ..ObjectsOnPath::new(NodeId(1), &[&a, &b, &c], CENTER, 15.0) }; + let order = |r: &ObjectsOnPath| r.members.iter().map(|m| m.id.0).collect::<Vec<_>>(); + let free = |_: NodeId| false; + let mut fwd = rec.clone(); + assert_eq!(fwd.move_member(NodeId(2), NodeId(4), free), Some(2)); + assert_eq!(order(&fwd), [3, 4, 2], "the first to the last place"); + assert_eq!((fwd.spacing, fwd.start, fwd.pivot, fwd.rotate), (rec.spacing, rec.start, rec.pivot, rec.rotate)); + let mut back = rec.clone(); + assert_eq!(back.move_member(NodeId(4), NodeId(2), free), Some(0)); + assert_eq!(order(&back), [4, 2, 3], "the last to the first place"); + let mut same = rec.clone(); + assert_eq!(same.move_member(NodeId(3), NodeId(3), free), Some(1)); + assert_eq!(same, rec, "onto its own place"); + let mut other = rec.clone(); + assert_eq!(other.move_member(NodeId(1), NodeId(3), free), None, "the path is not one of the objects"); + assert_eq!(other.move_member(NodeId(3), NodeId(9), free), None); + assert_eq!(other, rec); + // A fixed object between them keeps its place; the others pass over it. + let mut over = rec.clone(); + assert_eq!(over.move_member(NodeId(2), NodeId(4), |id| id == NodeId(3)), Some(2)); + assert_eq!(order(&over), [4, 3, 2], "the first and last trade places round the fixed one"); + let mut back_over = rec.clone(); + assert_eq!(back_over.move_member(NodeId(4), NodeId(2), |id| id == NodeId(3)), Some(0)); + assert_eq!(order(&back_over), [4, 3, 2]); + } + #[test] fn a_group_saved_without_space_reads_as_auto() { let a = rect(2, Rect::new(0.0, 0.0, 10.0, 10.0)); diff --git a/crates/doc/src/pixels.rs b/crates/doc/src/pixels.rs index 30d8a7a63b..1c231f7bbe 100644 --- a/crates/doc/src/pixels.rs +++ b/crates/doc/src/pixels.rs @@ -11,6 +11,10 @@ use crate::ImageBlob; /// address and aborts when an allocation fails, so it keeps the decoder's own 512 MB. pub const MAX_RASTER_ALLOC: u64 = if cfg!(target_arch = "wasm32") { 512 << 20 } else { 2 << 30 }; +/// A box of an image to sample, in 0 to 1 units of its width and height (`None`: all of it), the +/// pixels to sample from it at most, and the pixel centres to take ([`ImageBlob::sample_pixels`]). +pub type PixelPick<'a> = (Option<[f64; 4]>, usize, &'a dyn Fn(f64, f64) -> bool); + /// The pixels of encoded image `bytes` as RGBA; `None` when they can't be decoded, would take /// more than `max` bytes as RGBA, or need more than `max` bytes to decode. The size is read from /// the header first: the decoder's limit is on the file's samples, and a gray image is a quarter @@ -61,6 +65,49 @@ impl ImageBlob { Some(Self::png(png)) } + /// For each of `picks`, at most its budget of the image's pixels (at least one), spread evenly + /// in rows and columns over the pick's box (`[u0, v0, u1, v1]`, where 0 to 1 spans the + /// image's width and height from the top left; clipped to the image; `None`: the whole image), + /// as straight RGBA. Only pixels whose centres the pick's function takes (in the same 0 to 1 + /// units) are given, and the function is called once for each pixel sampled. The image is + /// decoded once for all the picks. `None` when it can't be decoded within [`MAX_RASTER_ALLOC`]. + pub fn sample_pixels(&self, picks: &[PixelPick<'_>]) -> Option<Vec<Vec<[u8; 4]>>> { + let img = rgba_within(&self.bytes, MAX_RASTER_ALLOC)?; + let (w, h) = img.dimensions(); + let (fw, fh) = (f64::from(w), f64::from(h)); + let span = |a: f64, b: f64, n: f64| { + let (a, b) = (a.min(b), a.max(b)); + ((a * n).floor().clamp(0.0, n) as u32, (b * n).ceil().clamp(0.0, n) as u32) + }; + let sample = |area: Option<[f64; 4]>, budget: usize, keep: &dyn Fn(f64, f64) -> bool| { + let [u0, v0, u1, v1] = area.unwrap_or([0.0, 0.0, 1.0, 1.0]); + let (x0, x1) = span(u0, u1, fw); + let (y0, y1) = span(v0, v1, fh); + if x0 >= x1 || y0 >= y1 { + return vec![]; + } + // Rows and columns in proportion to the box, at most `budget` cells in all. + let (bw, bh, budget) = (f64::from(x1 - x0), f64::from(y1 - y0), budget.max(1) as f64); + let (sx, sy) = if bw * bh <= budget { + (1, 1) + } else { + let rows = (budget * bh / bw).sqrt().floor().clamp(1.0, bh.min(budget)); + let cols = (budget / rows).floor().clamp(1.0, bw); + ((bw / cols).ceil() as usize, (bh / rows).ceil() as usize) + }; + let mut out = vec![]; + for y in (y0..y1).step_by(sy) { + for x in (x0..x1).step_by(sx) { + if keep((f64::from(x) + 0.5) / fw, (f64::from(y) + 0.5) / fh) { + out.push(img.get_pixel(x, y).0); + } + } + } + out + }; + Some(picks.iter().map(|(area, budget, keep)| sample(*area, *budget, *keep)).collect()) + } + /// The image as a grayscale PNG: `f` gives each pixel's gray level from its (straight) RGB, and /// the PNG has an alpha channel only when some pixel isn't opaque. `f` runs once per distinct /// color. `None` when the image can't be decoded, or when its file stores grayscale already @@ -147,6 +194,27 @@ impl ImageBlob { .collect(); Some((w, h, cover)) } + + /// The pixels as straight RGBA, row by row from the top, with the width and the height; + /// `None` when the image can't be decoded within [`MAX_RASTER_ALLOC`]. + pub fn rgba(&self) -> Option<(u32, u32, Vec<u8>)> { + let img = rgba_within(&self.bytes, MAX_RASTER_ALLOC)?; + let (w, h) = img.dimensions(); + Some((w, h, img.into_raw())) + } + + /// The width and height in pixels the image's file says it has; `None` for data that isn't an + /// image the decoder reads. Reads only its header. + pub fn pixel_size(&self) -> Option<(u32, u32)> { + image::ImageReader::new(Cursor::new(self.bytes.as_slice())).with_guessed_format().ok()?.into_dimensions().ok() + } + + /// Whether the image's file is a PNG that stores palette indices (an indexed-color image). + /// Reads only its header. + pub fn indexed_png(&self) -> bool { + // The signature, then the IHDR chunk: length, type, width, height, bit depth, color type. + self.bytes.starts_with(b"\x89PNG\r\n\x1a\n") && self.bytes.get(12..16) == Some(b"IHDR".as_slice()) && self.bytes.get(25) == Some(&3) + } } impl ImageBlob { @@ -276,6 +344,33 @@ mod tests { image::load_from_memory(&b.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect() } + /// Sampling reads the pixels of a box of the image, spread to about the budget, and only those + /// whose centres `keep` takes. + #[test] + fn sampled_pixels_stay_in_their_box_and_budget() { + // 4 × 2: a red left half and a blue right half. + let (r, b) = ([255, 0, 0, 255], [0, 0, 255, 255]); + let img = blob(&[r, r, b, b, r, r, b, b], 4, 2); + let any = |_: f64, _: f64| true; + let one = |b: &ImageBlob, area: Option<[f64; 4]>, budget: usize| b.sample_pixels(&[(area, budget, &any)]).unwrap().remove(0); + assert_eq!(one(&img, None, 100).len(), 8, "the budget covers every pixel"); + assert_eq!(one(&img, Some([0.5, 0.0, 1.0, 1.0]), 100), vec![b; 4], "the right half"); + assert_eq!(one(&img, Some([1.0, 1.0, 0.5, 0.0]), 100), vec![b; 4], "a box given backwards"); + assert!(one(&img, Some([2.0, 0.0, 3.0, 1.0]), 100).is_empty(), "outside the image"); + assert_eq!(one(&img, None, 2).len(), 2, "every second pixel of every second row"); + assert_eq!(one(&img, None, 0), vec![r], "a budget of 0 counts as 1"); + let left = |u: f64, _: f64| u < 0.5; + let both = img.sample_pixels(&[(None, 100, &left), (Some([0.5, 0.0, 1.0, 1.0]), 100, &any)]).unwrap(); + assert_eq!(both, vec![vec![r; 4], vec![b; 4]], "several picks, each with the centres its function takes"); + let sizes: Vec<usize> = img.sample_pixels(&[(None, 2, &any), (None, 100, &any)]).unwrap().iter().map(Vec::len).collect(); + assert_eq!(sizes, [2, 8], "each pick keeps to its own budget"); + // A narrow image keeps to the budget too. + let tall = blob(&vec![r; 5000], 1, 5000); + let n = one(&tall, None, 100).len(); + assert!((50..=100).contains(&n), "{n} pixels"); + assert!(ImageBlob::png(b"not a png".to_vec()).sample_pixels(&[(None, 100, &any)]).is_none()); + } + /// A GIF whose `w` × `h` screen holds one opaque red pixel at the top left. The file holds no /// other pixels, and the decoder makes them transparent. fn gif_with_one_red_pixel(w: u16, h: u16) -> Vec<u8> { diff --git a/crates/doc/src/placed_document.rs b/crates/doc/src/placed_document.rs index 33eccb178a..86f7f6134c 100644 --- a/crates/doc/src/placed_document.rs +++ b/crates/doc/src/placed_document.rs @@ -517,7 +517,12 @@ fn rename(n: &mut Node, prefix: &str) { paint(&mut r.style.stroke); } } - NodeKind::Image(im) => im.key = format!("{prefix}{}", im.key), + NodeKind::Image(im) => { + im.key = format!("{prefix}{}", im.key); + if let Some(m) = n.extras.0.as_deref_mut().and_then(|e| e.color_mask.as_deref_mut()) { + (m.key, m.from) = (format!("{prefix}{}", m.key), format!("{prefix}{}", m.from)); + } + } NodeKind::PlacedDocument(p) => p.key = format!("{prefix}{}", p.key), NodeKind::SymbolInstance { symbol, .. } => *symbol = format!("{prefix}{symbol}"), _ => {} @@ -681,6 +686,30 @@ mod tests { Some((d, Node::new(NodeId(0), NodeKind::Group { children, clip: false }), Rect::new(0.0, 0.0, 40.0, 20.0))) } + /// A color-masked image in a placed document's art keeps its masked pixels under the prefixed + /// names its resources get. + #[test] + fn a_color_mask_takes_the_prefixed_image_names() { + let im = + ImageObject { key: "own".into(), width: 2, height: 2, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None }; + let mut n = Node::new(NodeId(7), NodeKind::Image(Box::new(im))); + n.extras_mut().color_mask = Some(Box::new(crate::color_mask::ColorMask { + key: "masked".into(), + from: "own".into(), + background: Default::default(), + colors: vec![], + contiguous: true, + measure: Default::default(), + tolerance: 10.0, + softness: 10.0, + })); + rename(&mut n, "p:"); + let NodeKind::Image(im) = &n.kind else { panic!("an image") }; + let m = Document::color_mask_of(&n).unwrap(); + assert_eq!((im.key.as_str(), m.key.as_str(), m.from.as_str()), ("p:own", "p:masked", "p:own")); + assert!(m.made_for(im)); + } + #[test] fn round_trips_through_json() { let n = Node::new(NodeId(3), NodeKind::PlacedDocument(Box::new(placed("doc1-1")))); diff --git a/crates/doc/src/reach.rs b/crates/doc/src/reach.rs index f6b9a4d013..8115d00954 100644 --- a/crates/doc/src/reach.rs +++ b/crates/doc/src/reach.rs @@ -1,6 +1,7 @@ //! Where a path's strokes paint, from the path's geometry without building their outlines: the //! visual bounds and the clicks of a stroke take in its alignment, its width profile, miter spikes -//! up to the miter limit, projecting caps and arrowheads. Butt caps end at the path's end points. +//! up to the miter limit, projecting caps and arrowheads. Butt caps end at the path's end points, +//! and a bevel ends at the corners of the two segments it joins. use vectorcraft_geom::bez::{CORNER_COS, has_length, kink, segments, subpaths, tangent, unit}; use vectorcraft_geom::hit::fill_contains; @@ -39,10 +40,20 @@ fn joints(segs: &[PathSeg], closed: bool) -> impl Iterator<Item = (Point, Vec2, /// path: its tip and the corner's outer offset points, or `None` when the path doesn't turn there /// or the miter limit bevels it. fn miter(at: Point, t_in: Vec2, t_out: Vec2, side: f64, limit: f64) -> Option<[Point; 3]> { - let cos = t_in.dot(t_out); // cos(half the turn) is sin(half the angle between the segments): the miter is side / it. - let half = ((1.0 + cos) / 2.0).max(0.0).sqrt(); - if cos >= CORNER_COS || half * limit < 1.0 { + let half = ((1.0 + t_in.dot(t_out)) / 2.0).max(0.0).sqrt(); + if half * limit < 1.0 { + return None; + } + let ([a, b], out) = bevel(at, t_in, t_out, side)?; + Some([a, at + out * (side / half), b]) +} + +/// The bevel at a corner with tangents `t_in`, `t_out` of a stroke reaching `side` from its path: +/// the outer corners of the two segments' strokes and the unit direction out of the turn, or +/// `None` when the path doesn't turn there. +fn bevel(at: Point, t_in: Vec2, t_out: Vec2, side: f64) -> Option<([Point; 2], Vec2)> { + if t_in.dot(t_out) >= CORNER_COS { return None; } let out = unit(t_in - t_out); @@ -51,7 +62,7 @@ fn miter(at: Point, t_in: Vec2, t_out: Vec2, side: f64, limit: f64) -> Option<[P let n = Vec2::new(-t.y, t.x); if n.dot(out) >= 0.0 { n } else { -n } }; - Some([at + outer(t_in) * side, at + out * (side / half), at + outer(t_out) * side]) + Some(([at + outer(t_in) * side, at + outer(t_out) * side], out)) } /// The heads' ends of `bp`: the start of its first subpath and the end of its last, when open (as @@ -80,10 +91,8 @@ fn head_ends(st: &StrokeLayer, bp: &BezPath) -> Vec<(Point, Vec2, bool)> { /// at `t`): the profile at that fraction of the subpath's length, or wider where an end of the /// segment is a corner. The stroke draws the sides there straight to the corner's join and inner /// meeting point, which can lie outside the exact width all along the segment. -fn profile_at(profile: &WidthProfile, segs: &[PathSeg], closed: bool, i: usize, t: f64) -> (f64, f64) { +fn profile_at(profile: &WidthProfile, segs: &[PathSeg], lens: &[f64], total: f64, closed: bool, i: usize, t: f64) -> (f64, f64) { let n = segs.len(); - let lens: Vec<f64> = segs.iter().map(|s| s.arclen(ARCLEN_ACCURACY)).collect(); - let total: f64 = lens.iter().sum::<f64>().max(1e-12); let before = lens[..i].iter().sum::<f64>(); let mut w = profile.at((before + segs[i].subsegment(0.0..t).arclen(ARCLEN_ACCURACY)) / total); let corner = |a: usize, b: usize| (closed || a < b) && kink(&segs[a], &segs[b]); @@ -189,26 +198,44 @@ fn in_convex(pts: &[Point], p: Point, tol: f64) -> bool { } impl StrokeLayer { - /// Does bounding this stroke need its path's shape: miter spikes, projecting caps, arrowheads, - /// an alignment that depends on whether the path is closed, or butt caps, which stop at the - /// ends of an open path? Else it reaches evenly round it. + /// Does bounding this stroke need its path's shape: miter spikes, bevels, projecting caps, + /// arrowheads, an alignment that depends on whether the path is closed, or butt caps, which + /// stop at the ends of an open path? Else it reaches evenly round it. fn needs_shape(&self) -> bool { - self.join == LineJoin::Miter + self.join != LineJoin::Round || self.cap != LineCap::Round || self.start_arrow.is_some() || self.end_arrow.is_some() || self.align != StrokeAlign::Center } - /// The box this stroke paints along `segs`, the segments with length of an open subpath, when - /// its caps are butt caps: each segment's [`swept_box`] and, with round joins, the arc each - /// joint between segments paints ([`round_join_box`]), a shallow one included. - /// `None` when `segs` is empty. Butt dashes stop inside the same box. The heads and miter tips - /// are measured apart. A segment in the middle is measured only when its own box grown by - /// `side`, which holds everything it paints, is not inside the box so far. - fn butt_body(&self, segs: &[PathSeg], side: f64) -> Option<Rect> { + /// Does this stroke stop at the corners of its segments along a subpath that is `closed` or + /// open, where its caps are butt caps on an open subpath or its joins are bevels or miters? + /// Dashes with round or projecting caps can end at a corner, so with them only butt caps stop. + fn stops_at_corners(&self, closed: bool) -> bool { + let capped_dashes = self.cap != LineCap::Butt && self.dash.as_ref().is_some_and(Dash::is_dashed); + (self.cap == LineCap::Butt && !closed) || (self.join != LineJoin::Round && !capped_dashes) + } + + /// Does this stroke reach past a subpath that is `closed` or open by a margin that follows the + /// direction of its segments at their corners: where it stops at them + /// ([`Self::stops_at_corners`]) or paints miter spikes, which dashes with round or projecting + /// caps also paint? + fn reaches_by_corners(&self, closed: bool) -> bool { + self.stops_at_corners(closed) || self.join == LineJoin::Miter + } + + /// The box this stroke's body paints along `segs`, the segments with length of a subpath, short + /// of its caps, joined with `within`: each segment's [`swept_box`] and, with round joins on an + /// open subpath, the arc each joint between segments paints ([`round_join_box`]), a shallow one + /// included. A bevel stays inside the boxes of the segments it joins. `None` when `segs` is + /// empty. Butt dashes stop inside the same box. The caps other than butt ones, the heads and + /// miter tips are measured apart. A segment in the middle is measured only when its own box + /// grown by `side`, which holds everything it paints, is not inside the box so far, which + /// starts as `within` and the first and last segments' boxes. + fn body_along(&self, segs: &[PathSeg], side: f64, within: Rect) -> Option<Rect> { let (first, last) = (segs.first()?, segs.last()?); - let ends = swept_box(first, side, 3).union(swept_box(last, side, 3)); + let ends = swept_box(first, side, 3).union(swept_box(last, side, 3)).union(within); let body = segs.iter().skip(1).take(segs.len().saturating_sub(2)).fold(ends, |b, s| { if b.contains_rect(ParamCurveExtrema::bounding_box(s).inflate(side, side)) { b } else { b.union(swept_box(s, side, 3)) } }); @@ -219,24 +246,28 @@ impl StrokeLayer { } /// The box this stroke paints along `bp` (geometric bounds `bounds`): an open subpath with butt - /// caps by [`Self::butt_body`], every other subpath by the box of its segments grown by its - /// reach, with `tips` and, when `measure_tips`, the miter spikes the limit keeps, the corners of - /// projecting caps and the reach of the arrowheads round their end points. + /// caps, and every subpath when the joins are bevels or miters, by [`Self::body_along`] with its + /// caps, every other subpath by the box of its segments grown by its reach, with `tips` and, + /// when `measure_tips`, the miter spikes the limit keeps, the corners of projecting caps and the + /// reach of the arrowheads round their end points. fn reach_along(&self, bp: &BezPath, bounds: Rect, tips: Option<Rect>, measure_tips: bool) -> Rect { let els = bp.elements(); let subs = subpaths(bp); let mut out = tips.map_or(bounds, |t| bounds.union(t)); let mut side_max: f64 = 0.0; - // Every subpath reaches evenly unless one is open and butt-capped; only then is each - // subpath's own box needed. - let even_only = self.cap != LineCap::Butt || subs.iter().all(|s| s.1); - let mut even = even_only.then_some(bounds); // Dashes put a cap on every dash: projecting ones reach a corner's diagonal anywhere. let capped_dashes = self.cap == LineCap::Square && self.dash.as_ref().is_some_and(Dash::is_dashed); + // A butt cap stops at an open subpath's end, and a bevel, or a miter the limit bevels, at + // the two segments' corners, so such a subpath is measured along its segments. Every + // subpath reaches evenly unless one is measured that way; only then is each subpath's own + // box needed. + let even_only = !subs.iter().any(|s| self.stops_at_corners(s.1)); + let mut even = even_only.then_some(bounds); for (r, closed) in subs { let side = self.side_reach(closed); let butt = self.cap == LineCap::Butt && !closed; - if !butt { + let along = self.stops_at_corners(closed); + if !along { side_max = side_max.max(if capped_dashes { side * std::f64::consts::SQRT_2 } else { side }); } if side <= 0.0 { @@ -244,10 +275,10 @@ impl StrokeLayer { } let square = self.cap == LineCap::Square && !closed; let miters = measure_tips && self.join == LineJoin::Miter; - if !(butt || square || miters || !even_only) { + if !(along || square || miters || !even_only) { continue; } - let segs = drawn(&els[r]); + let segs = drawn(&els[r.clone()]); if miters { for (at, t_in, t_out) in joints(&segs, closed) { if let Some([_, tip, _]) = miter(at, t_in, t_out, side, self.miter_limit) { @@ -255,13 +286,24 @@ impl StrokeLayer { } } } - if butt { - if let Some(body) = self.butt_body(&segs, side) { - out = out.union(body); + if along { + // The path's bounds are in the box already, so only the segments that can reach + // past them are measured. + match self.body_along(&segs, side, out) { + Some(body) => out = out.union(body), + // A subpath with no length paints at most its caps' dot. + None if !butt => { + let dot = segments(&els[r]).iter().map(ParamCurveExtrema::bounding_box).reduce(|a, b| a.union(b)); + out = dot.map_or(out, |d| out.union(d.inflate(side, side))); + } + None => {} } - continue; - } - if !even_only { + if self.cap == LineCap::Round && !closed { + for (at, _) in ends(&segs).into_iter().flatten() { + out = out.union(Rect::from_center_size(at, (2.0 * side, 2.0 * side))); + } + } + } else if !even_only { even = vectorcraft_geom::union_opt(even, segs.iter().map(ParamCurveExtrema::bounding_box).reduce(|a, b| a.union(b))); } if square { @@ -281,7 +323,8 @@ impl StrokeLayer { /// The box this stroke paints along `bp`, whose geometric bounds are `bounds`: the bounds grown /// by the body's reach, with the tips of the miter spikes the limit keeps, the corners of /// projecting caps and the reach of the arrowheads round their end points. An open subpath - /// with butt caps does not reach past its ends ([`Self::butt_body`]). + /// with butt caps does not reach past its ends, and a bevel does not reach round its corner + /// ([`Self::body_along`]). pub fn bounds_on(&self, bp: &BezPath, bounds: Rect) -> Rect { self.reach_along(bp, bounds, None, true) } @@ -306,7 +349,8 @@ impl StrokeLayer { /// Does this stroke along `bp` (filled with `rule`) paint within `tol` of `p`? Inside and /// outside strokes of closed paths count on their own side only (and within `tol` of the - /// path); a width profile counts at its width where `p` is nearest. + /// path); a width profile counts at the width of every segment that can reach `p`, as the + /// wider side of a farther one can paint past the nearest. pub fn hits(&self, bp: &BezPath, rule: FillRule, p: Point, tol: f64) -> bool { let reach = self.reach() + tol; if self.width.is_nan() || self.width <= 0.0 || !bp.bounding_box().inflate(reach, reach).contains(p) { @@ -330,17 +374,30 @@ impl StrokeLayer { let segs = drawn(&els[r]); let (half, region) = self.body(closed); let full = half * self.profile_max() * dash_caps.unwrap_or(1.0); - // The nearest point on this subpath. - let near = segs.iter().enumerate().map(|(i, s)| (i, s.nearest(p, 1e-9))).min_by(|a, b| a.1.distance_sq.total_cmp(&b.1.distance_sq)); - if let Some((i, nr)) = near - && nr.distance_sq.sqrt() <= full + tol - { + // Past a butt cap or a bevel the stroke stops at the segments' corners. A width profile + // keeps the round reach at the ends. + let squared = self.profile.is_none() && self.stops_at_corners(closed); + // Every segment near enough to reach `p`: with a width profile the wider side of a + // farther segment can paint past the nearest one, so the nearest alone is not enough. + let near = segs.iter().enumerate().filter_map(|(i, s)| { + let nr = s.nearest(p, 1e-9); + (nr.distance_sq.sqrt() <= full + tol).then_some((i, nr)) + }); + // The lengths are only needed when a profiled candidate reaches `p`; compute them + // once for the whole subpath rather than once per candidate. + let mut lengths: Option<(Vec<f64>, f64)> = None; + for (i, nr) in near { let d = nr.distance_sq.sqrt(); let factor = if dash_caps.is_some() { full / half.max(1e-12) } else { self.profile.as_ref().map_or(1.0, |pr| { - let (l, rt) = profile_at(pr, &segs, closed, i, nr.t); + let (lens, total) = lengths.get_or_insert_with(|| { + let lens: Vec<f64> = segs.iter().map(|s| s.arclen(ARCLEN_ACCURACY)).collect(); + let total = lens.iter().sum::<f64>().max(1e-12); + (lens, total) + }); + let (l, rt) = profile_at(pr, &segs, lens, *total, closed, i, nr.t); // Nearest to a segment's end, `p` is beside a join or past a cap, which // spans the widths of both sides. let at_end = nr.t <= 1e-9 || nr.t >= 1.0 - 1e-9; @@ -356,7 +413,8 @@ impl StrokeLayer { } }) }; - if d <= half * factor.max(0.0) + tol && on_side(region, d) { + if d <= half * factor.max(0.0) + tol && on_side(region, d) && (!squared || self.paints_at_end(&segs, closed, (i, nr.t), p, half, tol)) + { return true; } } @@ -384,6 +442,35 @@ impl StrokeLayer { false } + /// Does this stroke, where it stops at the corners of its segments ([`Self::stops_at_corners`]), + /// paint `p`, which is within `side` (and `tol`) of segment `i` of the subpath `segs` + /// (`closed`: a closed one) and nearest to it at `t`? It does when `p` is not past the end of + /// the segment that `t` is at, by more than `tol`, and past it when a round cap or a round join + /// paints there, when the path does not turn at that end, or when `p` is within `tol` of the + /// bevel's triangle. Projecting caps and + /// miter spikes are checked apart. A curve that bends more tightly than `side` ([`gentle`]) + /// counts as painting round its ends. + fn paints_at_end(&self, segs: &[PathSeg], closed: bool, (i, t): (usize, f64), p: Point, side: f64, tol: f64) -> bool { + let (n, at_start) = (segs.len(), t <= 1e-9); + let Some(seg) = segs.get(i) else { return true }; + if (!at_start && t < 1.0 - 1e-9) || !(matches!(seg, PathSeg::Line(_)) || gentle(seg, side)) { + return true; + } + let (at, out) = if at_start { (seg.start(), -tangent(seg, 0.0)) } else { (seg.end(), tangent(seg, 1.0)) }; + if (p - at).dot(out) <= tol { + return true; + } + // The segment on the other side of this end, `None` at the end of an open subpath. + let other = if at_start { (i > 0 || closed).then(|| (i + n - 1) % n) } else { (i + 1 < n || closed).then(|| (i + 1) % n) }; + let Some(other) = other.and_then(|o| segs.get(o)) else { return self.cap == LineCap::Round }; + if self.join == LineJoin::Round { + return true; + } + let (t_in, t_out) = if at_start { (tangent(other, 1.0), tangent(seg, 0.0)) } else { (tangent(seg, 1.0), tangent(other, 0.0)) }; + // A joint where the path does not turn has no bevel: the stroke runs on through it. + bevel(at, t_in, t_out, side).is_none_or(|([a, b], _)| in_convex(&[at, a, b], p, tol)) + } + /// Is `p` within `tol` of where the start (`end == false`) or end arrowhead at `at` (the path /// leaving along `out`) can paint? A head reaches [`crate::Arrowhead::reach`] weights from its tip and /// [`crate::Arrowhead::half_width`] either side of its line (4.6 and 2 for most). With @@ -391,13 +478,15 @@ impl StrokeLayer { /// past the end; with [`ArrowAlign::Tip`] its tip is on the end and it lies back along the /// chord the path bends through under it, so anywhere within its length of the end. fn head_contains(&self, at: Point, out: Vec2, end: bool, p: Point, tol: f64) -> bool { - let Some(kind) = (if end { self.end_arrow } else { self.start_arrow }) else { return false }; + let Some(kind) = (if end { &self.end_arrow } else { &self.start_arrow }) else { return false }; let (hw, v) = (self.arrow_weight(end), p - at); match self.arrow_align { ArrowAlign::Tip => v.hypot() <= kind.reach() * hw + tol, ArrowAlign::Extend => { let along = v.dot(out); - v.cross(out).abs() <= kind.half_width() * hw + tol && along <= 4.0 * hw + self.width / 2.0 + tol && along >= -kind.reach() * hw - tol + v.cross(out).abs() <= kind.half_width() * hw + tol + && along <= kind.length() * hw + self.width / 2.0 + tol + && along >= -kind.reach() * hw - tol } } } @@ -417,7 +506,7 @@ impl Appearance { } /// [`Self::stroked_bounds`] with the box of each visible stroke that needs the path's shape - /// (miter spikes, projecting or butt caps, arrowheads or an alignment) given by `shaped`. + /// (miter spikes, bevels, projecting or butt caps, arrowheads or an alignment) given by `shaped`. pub fn stroked_bounds_by(&self, bounds: Rect, mut shaped: impl FnMut(&StrokeLayer) -> Rect) -> Rect { self.painted_strokes().fold(bounds, |acc, s| { if !s.needs_shape() { @@ -428,17 +517,21 @@ impl Appearance { }) } - /// Does this appearance have a visible butt-capped stroke? - pub fn has_butt_stroke(&self) -> bool { - self.painted_strokes().any(|s| s.cap == LineCap::Butt) + /// Does this appearance have a visible stroke that stops at the corners of its segments on an + /// open subpath or a closed one, or paints miter spikes: butt caps, or bevel and miter joins + /// ([`StrokeLayer::reaches_by_corners`])? + pub fn has_cornered_stroke(&self) -> bool { + self.painted_strokes().any(|s| s.reaches_by_corners(false)) } - /// Does a visible butt-capped stroke of this appearance run along an open subpath of `bp` with - /// a segment that starts or ends at a slant, not square to the axes, once placed by `a`? The - /// visual box's margin at the stroke's corners there depends on their direction, which a scale - /// out of proportion changes. - pub fn has_slanted_butt_stroke(&self, bp: &BezPath, a: vectorcraft_geom::Affine) -> bool { - if !self.has_butt_stroke() { + /// Does a visible stroke of this appearance that stops at the corners of its segments (butt + /// caps on an open subpath, bevel and miter joins) or paints miter spikes, dashed ones with + /// round or projecting caps included, run along a subpath of `bp` where it does so, with a + /// segment that starts or ends at a slant, not square to the axes, once placed by `a`? The + /// visual box's margin at those corners, and at miter tips, depends on their direction, which a + /// scale out of proportion changes. + pub fn has_slanted_stroke_corners(&self, bp: &BezPath, a: vectorcraft_geom::Affine) -> bool { + if !self.has_cornered_stroke() { return false; } let slanted = |v: Vec2| { @@ -446,9 +539,10 @@ impl Appearance { (d.x * d.y).abs() > 1e-9 }; let els = bp.elements(); - subpaths(bp) - .into_iter() - .filter(|(_, closed)| !closed) + let subs = subpaths(bp); + let cornered = |closed: bool| self.painted_strokes().any(|s| s.reaches_by_corners(closed)); + subs.into_iter() + .filter(|(_, closed)| cornered(*closed)) .any(|(r, _)| drawn(&els[r]).iter().any(|s| slanted(tangent(s, 0.0)) || slanted(tangent(s, 1.0)))) } @@ -459,28 +553,28 @@ impl Appearance { } } -/// How many symbol instances [`crate::Node::has_slanted_butt_stroke`] looks into for one object +/// How many symbol instances [`crate::Node::has_slanted_stroke_corners`] looks into for one object /// before it answers yes without looking further. pub const SLANT_INSTANCES: usize = 4096; impl crate::Node { - /// Does a visible butt-capped stroke of this object, of an object in it or of an object in a - /// symbol instance's art from `symbols`, placed by `a`, run along an open path with a segment - /// at a slant ([`Appearance::has_slanted_butt_stroke`])? Past [`SLANT_INSTANCES`] instances it - /// answers yes. - pub fn has_slanted_butt_stroke(&self, symbols: &crate::SymbolBoxes, a: vectorcraft_geom::Affine) -> bool { - self.slanted_butt(symbols, a, &std::cell::Cell::new(SLANT_INSTANCES)) + /// Does a visible stroke of this object, of an object in it or of an object in a symbol + /// instance's art from `symbols`, placed by `a`, stop at the corners of a segment at a slant + /// ([`Appearance::has_slanted_stroke_corners`])? Past [`SLANT_INSTANCES`] instances it answers + /// yes. + pub fn has_slanted_stroke_corners(&self, symbols: &crate::SymbolBoxes, a: vectorcraft_geom::Affine) -> bool { + self.slanted_corners(symbols, a, &std::cell::Cell::new(SLANT_INSTANCES)) } - /// [`Self::has_slanted_butt_stroke`] with `left` instances still to look into. - fn slanted_butt(&self, symbols: &crate::SymbolBoxes, a: vectorcraft_geom::Affine, left: &std::cell::Cell<usize>) -> bool { + /// [`Self::has_slanted_stroke_corners`] with `left` instances still to look into. + fn slanted_corners(&self, symbols: &crate::SymbolBoxes, a: vectorcraft_geom::Affine, left: &std::cell::Cell<usize>) -> bool { if let crate::NodeKind::SymbolInstance { symbol, xf } = &self.kind { let Some(l) = left.get().checked_sub(1) else { return true }; left.set(l); - return symbols.measure_art(symbol, |art| art.slanted_butt(symbols, a * *xf, left)).unwrap_or(false); + return symbols.measure_art(symbol, |art| art.slanted_corners(symbols, a * *xf, left)).unwrap_or(false); } - (self.appearance.has_butt_stroke() && self.stroke_path().is_some_and(|bp| self.appearance.has_slanted_butt_stroke(&bp, a))) - || self.children().is_some_and(|c| c.iter().any(|c| c.slanted_butt(symbols, a, left))) + (self.appearance.has_cornered_stroke() && self.stroke_path().is_some_and(|bp| self.appearance.has_slanted_stroke_corners(&bp, a))) + || self.children().is_some_and(|c| c.iter().any(|c| c.slanted_corners(symbols, a, left))) } } @@ -557,6 +651,79 @@ mod tests { assert_eq!(stroke(4.0, |s| s.align = StrokeAlign::Outside).bounds_on(&sq, b), b.inflate(4.0, 4.0)); } + #[test] + fn a_bevel_stops_at_the_corners_of_the_segments_it_joins() { + // A 40 × 100 pt triangle stroked 20 pt: a miter limit of 2 or a bevel join bevels its + // 22.6° tip at (20, 0), so the stroke reaches 10 · 20 / √10400 pt above it, not 10 pt. + let mut tri = BezPath::new(); + tri.move_to((0.0, 100.0)); + tri.line_to((20.0, 0.0)); + tri.line_to((40.0, 100.0)); + tri.close_path(); + let tb = tri.bounding_box(); + let (top, side) = (-200.0 / 10400.0_f64.sqrt(), 1000.0 / 10400.0_f64.sqrt()); + let limited = stroke(20.0, |s| s.miter_limit = 2.0); + let bevel = stroke(20.0, |s| { + s.join = LineJoin::Bevel; + s.cap = LineCap::Round; + }); + let b = limited.bounds_on(&tri, tb); + assert!((b.y0 - top).abs() < 1e-9, "{b:?}"); + // The limit keeps the base corners' miters, whose tips reach about 12.2 pt left and right. + assert!(b.x0 < -12.0 && b.x1 > 52.0, "{b:?}"); + let mut ap = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 20.0); + *ap.stroke_mut().unwrap() = bevel.clone(); + let b = ap.stroked_bounds(tb, || tri.clone()); + for (got, want) in [(b.x0, -side), (b.y0, top), (b.x1, 40.0 + side), (b.y1, 110.0)] { + assert!((got - want).abs() < 1e-9, "{b:?}"); + } + // Open, the same corner is beveled and the round caps reach the half weight round the ends. + let chevron = polyline(&[(0.0, 100.0), (20.0, 0.0), (40.0, 100.0)]); + let b = bevel.bounds_on(&chevron, chevron.bounding_box()); + for (got, want) in [(b.x0, -10.0), (b.y0, top), (b.x1, 50.0), (b.y1, 110.0)] { + assert!((got - want).abs() < 1e-9, "{b:?}"); + } + // A round join, and the round caps of dashes, which can end at the tip, reach round it. + let round = stroke(20.0, |s| s.join = LineJoin::Round); + assert!((round.bounds_on(&tri, tb).y0 + 10.0).abs() < 1e-9); + let mut dashed = bevel.clone(); + dashed.dash = Some(Dash { pattern: vec![7.0, 4.0], offset: 0.0, align_corners: false }); + assert!((dashed.bounds_on(&chevron, chevron.bounding_box()).y0 + 10.0).abs() < 1e-9); + } + + #[test] + fn a_click_past_a_bevel_or_a_butt_end_misses() { + // 5 pt above the triangle's tip is within the half weight of it, but past the bevel, which + // reaches about 1.96 pt above it. A round join paints there. + let mut tri = polyline(&[(0.0, 100.0), (20.0, 0.0), (40.0, 100.0)]); + tri.close_path(); + let (above, on) = (Point::new(20.0, -5.0), Point::new(20.0, -1.5)); + for join in [LineJoin::Bevel, LineJoin::Miter] { + let st = stroke(20.0, |s| (s.join, s.miter_limit) = (join, 2.0)); + assert!(!st.hits(&tri, FillRule::NonZero, above, 0.5), "{join:?}"); + assert!(st.hits(&tri, FillRule::NonZero, on, 0.0), "{join:?}"); + } + assert!(stroke(20.0, |s| s.join = LineJoin::Round).hits(&tri, FillRule::NonZero, above, 0.5)); + // 1.5 pt past a butt end of a 4 pt line misses, and a quarter point within it hits; a round + // cap paints past it. + let line = polyline(&[(0.0, 0.0), (0.0, 50.0)]); + let butt = stroke(4.0, |s| s.cap = LineCap::Butt); + assert!(!butt.hits(&line, FillRule::NonZero, Point::new(1.0, -1.5), 0.25)); + assert!(butt.hits(&line, FillRule::NonZero, Point::new(1.0, -0.2), 0.25)); + assert!(stroke(4.0, |s| s.cap = LineCap::Round).hits(&line, FillRule::NonZero, Point::new(1.0, -1.5), 0.25)); + } + + #[test] + fn a_joint_too_shallow_to_bevel_paints_past_both_segments_ends() { + // The path turns by about 0.57° at (100, -0.5), too little to bevel, so the stroke runs on + // through the joint: 3.5 pt above it is past the end of both segments and still painted. + let kink = polyline(&[(0.0, 0.0), (100.0, -0.5), (200.0, 0.0)]); + let above = Point::new(100.0, -4.0); + for join in [LineJoin::Bevel, LineJoin::Miter, LineJoin::Round] { + assert!(stroke(10.0, |s| s.join = join).hits(&kink, FillRule::NonZero, above, 0.0), "{join:?}"); + } + } + /// An open path through `points`. fn polyline(points: &[(f64, f64)]) -> BezPath { let mut bp = BezPath::new(); @@ -682,15 +849,25 @@ mod tests { let mut ap = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 2.0); ap.stroke_mut().unwrap().cap = LineCap::Butt; let id = vectorcraft_geom::Affine::IDENTITY; - assert!(!ap.has_slanted_butt_stroke(&polyline(&[(0.0, 0.0), (0.0, 50.0), (30.0, 50.0)]), id)); + assert!(!ap.has_slanted_stroke_corners(&polyline(&[(0.0, 0.0), (0.0, 50.0), (30.0, 50.0)]), id)); // Square ends, slanted segments in the middle. let apex = polyline(&[(0.0, 50.0), (0.0, 40.0), (10.0, 0.0), (20.0, 40.0), (20.0, 50.0)]); - assert!(ap.has_slanted_butt_stroke(&apex, id)); - // A rotation slants a vertical line; a round cap is never slanted. + assert!(ap.has_slanted_stroke_corners(&apex, id)); + // A rotation slants a vertical line. let v = polyline(&[(0.0, 0.0), (0.0, 50.0)]); - assert!(ap.has_slanted_butt_stroke(&v, vectorcraft_geom::Affine::rotate(0.3))); + assert!(ap.has_slanted_stroke_corners(&v, vectorcraft_geom::Affine::rotate(0.3))); + // With round caps, the miter join still stops at the corners of the slanted segments, on a + // closed path too; round caps and round joins never do. ap.stroke_mut().unwrap().cap = LineCap::Round; - assert!(!ap.has_slanted_butt_stroke(&apex, id)); + assert!(ap.has_slanted_stroke_corners(&apex, id)); + let mut tri = polyline(&[(0.0, 100.0), (20.0, 0.0), (40.0, 100.0)]); + tri.close_path(); + ap.stroke_mut().unwrap().join = LineJoin::Bevel; + assert!(ap.has_slanted_stroke_corners(&tri, id)); + assert!(!ap.has_slanted_stroke_corners(&square(), id)); + ap.stroke_mut().unwrap().join = LineJoin::Round; + assert!(!ap.has_slanted_stroke_corners(&apex, id)); + assert!(!ap.has_slanted_stroke_corners(&tri, id)); } #[test] @@ -714,11 +891,11 @@ mod tests { } let top = Node::new(d.alloc_id(), crate::NodeKind::SymbolInstance { symbol: "S12".into(), xf: vectorcraft_geom::Affine::IDENTITY }); let symbols = d.symbol_boxes(); - assert!(top.has_slanted_butt_stroke(&symbols, vectorcraft_geom::Affine::IDENTITY)); + assert!(top.has_slanted_stroke_corners(&symbols, vectorcraft_geom::Affine::IDENTITY)); assert!(symbols.art_measured() <= SLANT_INSTANCES, "{}", symbols.art_measured()); // One instance of S1 holds three instances, all looked into. let one = Node::new(d.alloc_id(), crate::NodeKind::SymbolInstance { symbol: "S1".into(), xf: vectorcraft_geom::Affine::IDENTITY }); - assert!(!one.has_slanted_butt_stroke(&d.symbol_boxes(), vectorcraft_geom::Affine::IDENTITY)); + assert!(!one.has_slanted_stroke_corners(&d.symbol_boxes(), vectorcraft_geom::Affine::IDENTITY)); } #[test] diff --git a/crates/doc/src/selection.rs b/crates/doc/src/selection.rs index c514aab996..4ef6446247 100644 --- a/crates/doc/src/selection.rs +++ b/crates/doc/src/selection.rs @@ -59,6 +59,11 @@ pub struct Selection { /// that object ([`crate::symbol_overrides`]). Any other selection change clears it. #[serde(default, skip_serializing_if = "Option::is_none")] pub symbol_part: Option<SymbolPart>, + /// An object of an Objects on Path group, chosen with its Select/Move widget: the group is the + /// one selected object, and the object is one of its objects on the path + /// ([`crate::objects_on_path::ObjectsOnPath::members`]). Any other selection change clears it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub on_path_member: Option<NodeId>, } /// See [`Selection::symbol_part`]. @@ -94,6 +99,13 @@ impl Selection { self.guides.clear(); self.key_guide = None; self.symbol_part = None; + self.on_path_member = None; + } + /// Select only the Objects on Path group `group`, with its object `member` (see + /// [`Selection::on_path_member`]). + pub fn set_on_path_member(&mut self, group: NodeId, member: NodeId) { + self.set([group]); + self.on_path_member = Some(member); } /// Select only instance `instance`, with the object at `path` of its symbol's art (see /// [`Selection::symbol_part`]). @@ -115,6 +127,7 @@ impl Selection { self.target = None; self.slices.clear(); self.symbol_part = None; + self.on_path_member = None; if !self.objects.contains(&id) { self.objects.push(id); } @@ -123,6 +136,7 @@ impl Selection { self.target = None; self.slices.clear(); self.symbol_part = None; + self.on_path_member = None; self.objects.retain(|x| *x != id); self.anchors.remove(&id); self.segments.remove(&id); @@ -130,6 +144,25 @@ impl Selection { self.key = None; } } + /// [`Self::remove`] for each of `ids`, going through the selected objects once. + pub fn remove_all(&mut self, ids: impl IntoIterator<Item = NodeId>) { + let ids: HashSet<NodeId> = ids.into_iter().collect(); + if ids.is_empty() { + return; + } + self.target = None; + self.slices.clear(); + self.symbol_part = None; + self.on_path_member = None; + self.objects.retain(|x| !ids.contains(x)); + for id in &ids { + self.anchors.remove(id); + self.segments.remove(id); + } + if self.key.is_some_and(|k| ids.contains(&k)) { + self.key = None; + } + } /// Select slices `ids` (see [`Selection::slices`]) and nothing else. pub fn set_slices(&mut self, ids: impl IntoIterator<Item = NodeId>) { self.clear(); @@ -152,6 +185,7 @@ impl Selection { /// Shift-click on a guide). pub fn toggle_guide(&mut self, i: NodeId) { self.symbol_part = None; + self.on_path_member = None; if let Some(k) = self.guides.iter().position(|g| *g == i) { self.guides.remove(k); if self.key_guide == Some(i) { @@ -258,6 +292,22 @@ impl Selection { if !part_kept { self.symbol_part = None; } + // A chosen object on a path needs its Objects on Path group selected alone, with no anchors + // or guides, and still one of the group's objects, neither hidden nor locked. + let member_kept = self.on_path_member.is_some_and(|m| { + let [g] = self.objects.as_slice() else { return false }; + self.anchors.is_empty() + && self.guides.is_empty() + && doc.is_editable(m) + && found + .get(g) + .and_then(|p| doc.node_at(p)) + .and_then(|n| n.extras().objects_on_path.as_deref().filter(|_| crate::objects_on_path::is_objects_on_path(n))) + .is_some_and(|rec| rec.members.iter().any(|x| x.id == m)) + }); + if !member_kept { + self.on_path_member = None; + } } /// Deselect the objects that are hidden or locked, themselves or through a group or layer /// around them (and so the key object when it is one): hidden or locked art can't stay diff --git a/crates/doc/src/selection/tests.rs b/crates/doc/src/selection/tests.rs index d0d81faee6..b6090f8993 100644 --- a/crates/doc/src/selection/tests.rs +++ b/crates/doc/src/selection/tests.rs @@ -16,6 +16,35 @@ fn basic_ops() { assert!(s.is_empty()); } +#[test] +fn remove_all_does_what_removing_each_does() { + let mut s = Selection::default(); + for i in 1..=6 { + s.add(NodeId(i)); + } + for i in [2, 4, 5] { + s.anchors.insert(NodeId(i), BTreeSet::from([(0, 1)])); + s.segments.insert(NodeId(i), BTreeSet::from([(0, 0)])); + } + s.key = Some(NodeId(4)); + s.target = Some(NodeId(3)); + s.slices = vec![NodeId(9)]; + s.guides = vec![NodeId(10)]; + s.on_path_member = Some(NodeId(11)); + let mut one_by_one = s.clone(); + for id in [NodeId(4), NodeId(1), NodeId(4), NodeId(7)] { + one_by_one.remove(id); + } + let mut all = s.clone(); + all.remove_all([NodeId(4), NodeId(1), NodeId(4), NodeId(7)]); + assert_eq!(all, one_by_one); + assert_eq!(all.objects, [NodeId(2), NodeId(3), NodeId(5), NodeId(6)]); + // Removing nothing leaves the selection as it was. + let mut none = s.clone(); + none.remove_all([]); + assert_eq!(none, s); +} + #[test] fn guides_are_selected_on_their_own() { let mut s = Selection::default(); @@ -179,6 +208,49 @@ fn selection_changes_clear_the_target() { assert_eq!(s.target, None); } +#[test] +fn a_chosen_object_on_a_path_needs_its_group_selected_alone() { + use vectorcraft_geom::{Point, Rect, shapes}; + let mut d = Document::new(200.0, 200.0); + let l = d.layers[0].id; + let (line, a, b, g, other) = (d.alloc_id(), d.alloc_id(), d.alloc_id(), d.alloc_id(), d.alloc_id()); + let line = Node::path(line, shapes::line(Point::new(0.0, 100.0), Point::new(200.0, 100.0)), Default::default()); + let a = Node::path(a, shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Default::default()); + let b = Node::path(b, shapes::rectangle(Rect::new(20.0, 0.0, 30.0, 10.0)), Default::default()); + let rec = crate::objects_on_path::ObjectsOnPath::new(line.id, &[&a, &b], crate::objects_on_path::CENTER, 0.0); + let (line_id, a_id) = (line.id, a.id); + let mut group = Node::new(g, NodeKind::Group { children: vec![Arc::new(line), Arc::new(a), Arc::new(b)], clip: false }); + group.extras_mut().objects_on_path = Some(Box::new(rec)); + d.insert(Some(l), 0, group).unwrap(); + d.insert(Some(l), 1, Node::path(other, shapes::rectangle(Rect::new(150.0, 0.0, 160.0, 10.0)), Default::default())).unwrap(); + let mut s = Selection::default(); + s.set_on_path_member(g, a_id); + s.prune(&d); + assert_eq!((s.objects.as_slice(), s.on_path_member), (&[g][..], Some(a_id))); + s.add(other); + assert_eq!(s.on_path_member, None, "another object joins the selection"); + s.set_on_path_member(g, a_id); + s.set([g]); + assert_eq!(s.on_path_member, None, "a new selection"); + // The path is not one of the objects, nor is an object outside the group. + for m in [line_id, other] { + s.set_on_path_member(g, m); + s.prune(&d); + assert_eq!(s.on_path_member, None, "{m:?}"); + } + // A locked object is not chosen. + s.set_on_path_member(g, a_id); + d.node_mut(a_id).unwrap().locked = true; + s.prune(&d); + assert_eq!((s.objects.as_slice(), s.on_path_member), (&[g][..], None), "locked"); + d.node_mut(a_id).unwrap().locked = false; + // Once the group is a plain group, no object of it is chosen. + s.set_on_path_member(g, a_id); + d.node_mut(g).unwrap().extras_mut().objects_on_path = None; + s.prune(&d); + assert_eq!((s.objects.as_slice(), s.on_path_member), (&[g][..], None)); +} + #[test] fn a_key_object_needs_two_or_more_selected_objects() { let mut s = Selection::default(); diff --git a/crates/doc/src/separated.rs b/crates/doc/src/separated.rs new file mode 100644 index 0000000000..8eb7cefe66 --- /dev/null +++ b/crates/doc/src/separated.rs @@ -0,0 +1,533 @@ +//! Separated images: an image whose inks come as one plate each (a DCS file placed linked), kept +//! as a TIFF of several images. The first is the composite, the plates mixed into CMYK +//! ([`Separated::composite`]), which every reader of a CMYK TIFF sees. Each later image is one +//! plate's ink amounts in grayscale (0 is no ink), with its ink's name and CMYK equivalent in its +//! ImageDescription. Print separations take each plate from these ([`Separated::coverage`]). + +use std::io::Cursor; +use std::sync::Arc; + +use vectorcraft_color::cms::PROCESS_PLATES; +use vectorcraft_geom::PathData; + +use crate::ImageBlob; +use crate::cmyk::{Inks, MAX_CMYK_PIXELS}; + +/// Most plates a separated image holds. +pub const MAX_PLATES: usize = 64; +/// Most directories a separated image's TIFF holds: its composite and its plates. +const MAX_DIRECTORIES: usize = MAX_PLATES + 1; +/// Longest ink name kept (bytes). +pub const MAX_NAME: usize = 255; +/// Most ink amounts the plates of one image hold together (512 MB). +pub const MAX_SAMPLES: u64 = 1 << 29; +/// How a plate's ImageDescription starts. +const MARK: &str = "VectorCraft plate "; + +/// How the composite's ImageDescription starts when plates were read from files of their own. +const FILES_MARK: &str = "VectorCraft plate files"; + +/// A plate file of its own that a separated image was read from, as it was then: a change to it +/// changes the image as a change to the DCS file does. +#[derive(Clone, Debug, PartialEq)] +pub struct PlateFile { + /// Its file name, in the DCS file's folder. + pub name: String, + /// Its size (bytes). + pub size: u64, + /// Its modification time (ms since the Unix epoch; 0 when the file system keeps none). + pub modified: u64, +} + +/// `text` in hexadecimal (TIFF text is ASCII). +fn hex(text: &str) -> String { + text.bytes().map(|b| format!("{b:02x}")).collect() +} + +/// The text [`hex`] wrote, of at most `max` bytes. +fn unhex(hex: &str, max: usize) -> Option<String> { + if !hex.len().is_multiple_of(2) || hex.len() > max * 2 { + return None; + } + let bytes: Option<Vec<u8>> = (0..hex.len()).step_by(2).map(|i| u8::from_str_radix(hex.get(i..i + 2)?, 16).ok()).collect(); + String::from_utf8(bytes?).ok() +} + +/// One ink's plate: its ink amounts, one byte a pixel (0 is none, 255 is solid), row by row from +/// the top. +#[derive(Clone, Debug, PartialEq)] +pub struct InkPlate { + /// "Cyan", "Magenta", "Yellow", "Black", or a spot ink's name. + pub name: String, + /// The process inks the ink stands for (C, M, Y, K, 0..1): one process ink at 100% for a + /// process plate. + pub cmyk: [f32; 4], + pub data: Vec<u8>, +} + +impl InkPlate { + /// Is it a spot ink's plate (not one of the four process inks)? + pub fn spot(&self) -> bool { + !PROCESS_PLATES.contains(&self.name.as_str()) + } +} + +/// The plates of a separated image, all of one size. +#[derive(Clone, Debug, PartialEq)] +pub struct Separated { + pub width: u32, + pub height: u32, + pub plates: Vec<InkPlate>, +} + +impl Separated { + /// `plates` as a `width` × `height` image; `None` when there are none or more than + /// [`MAX_PLATES`], two have the same name, a name is empty or longer than [`MAX_NAME`], a plate + /// doesn't hold that many pixels, an equivalent isn't within 0..1, or the image is empty, has + /// more than [`MAX_CMYK_PIXELS`], or its plates together hold more than [`MAX_SAMPLES`] + /// ([`Self::fits`]). A process plate's equivalent is its own ink. + pub fn new(width: u32, height: u32, mut plates: Vec<InkPlate>) -> Option<Self> { + let n = u64::from(width) * u64::from(height); + if !Self::fits(width, height, plates.len()) { + return None; + } + for p in plates.iter_mut() { + if p.name.is_empty() || p.name.len() > MAX_NAME || p.data.len() as u64 != n { + return None; + } + if let Some(j) = PROCESS_PLATES.iter().position(|q| *q == p.name) { + p.cmyk = [0.0; 4]; + p.cmyk[j] = 1.0; + } + if !p.cmyk.iter().all(|v| (0.0..=1.0).contains(v)) { + return None; + } + } + let mut names = std::collections::HashSet::new(); + if !plates.iter().all(|p| names.insert(p.name.as_str())) { + return None; + } + Some(Self { width, height, plates }) + } + + /// May an image of `width` × `height` pixels hold `plates` plates? Not when it is empty, has + /// more than [`MAX_CMYK_PIXELS`], has no plate or more than [`MAX_PLATES`], or the plates + /// together would hold more than [`MAX_SAMPLES`]. + pub fn fits(width: u32, height: u32, plates: usize) -> bool { + let n = u64::from(width) * u64::from(height); + n > 0 && n <= MAX_CMYK_PIXELS && (1..=MAX_PLATES).contains(&plates) && n * plates as u64 <= MAX_SAMPLES + } + + /// The plates of spot inks. + pub fn spots(&self) -> impl Iterator<Item = &InkPlate> { + self.plates.iter().filter(|p| p.spot()) + } + + /// The plates mixed into process inks: each plate's ink amount times its equivalent, the + /// plates over one another as inks print (`1 − (1 − a)(1 − b)` for each process ink). + pub fn composite(&self) -> Inks { + let n = self.data_len(); + let mut data = vec![0u8; n * 4]; + for (i, px) in data.as_chunks_mut::<4>().0.iter_mut().enumerate() { + let mut clear = [1.0f32; 4]; + for p in &self.plates { + let t = f32::from(p.data[i]) / 255.0; + for (c, e) in clear.iter_mut().zip(p.cmyk) { + *c *= 1.0 - t * e; + } + } + for (o, c) in px.iter_mut().zip(clear) { + *o = ((1.0 - c) * 255.0).round() as u8; + } + } + Inks { width: self.width, height: self.height, data } + } + + /// The ink amounts that print on plate `plate` (a process ink's name or a spot ink's), one byte + /// a pixel. A spot plate for which `own` is true prints on its own plate only; every other spot + /// plate (the job prints no plate of that name) prints as its process equivalent, mixed as + /// [`Self::composite`] mixes it. A plate name the image has no plate for, and a spot plate that + /// prints as process, print nothing. + pub fn coverage(&self, plate: &str, own: &dyn Fn(&str) -> bool) -> Vec<u8> { + self.coverage_as(plate, own, &|p| p.cmyk) + } + + /// [`Self::coverage`], a spot plate that prints as process printing as the process inks + /// `equivalent` gives it (the document's swatch of its ink, when there is one). + pub fn coverage_as(&self, plate: &str, own: &dyn Fn(&str) -> bool, equivalent: &dyn Fn(&InkPlate) -> [f32; 4]) -> Vec<u8> { + let n = self.data_len(); + if let Some(j) = PROCESS_PLATES.iter().position(|q| *q == plate) { + let mixed: Vec<(&InkPlate, f32)> = self + .plates + .iter() + .filter(|p| !p.spot() || !own(&p.name)) + .map(|p| (p, if p.spot() { equivalent(p)[j].clamp(0.0, 1.0) } else { p.cmyk[j] })) + .filter(|(_, e)| *e > 0.0) + .collect(); + return (0..n) + .map(|i| { + let clear = mixed.iter().fold(1.0f32, |c, (p, e)| c * (1.0 - f32::from(p.data[i]) / 255.0 * e)); + ((1.0 - clear) * 255.0).round() as u8 + }) + .collect(); + } + match self.plates.iter().find(|p| p.name == plate && p.spot() && own(&p.name)) { + Some(p) => p.data.clone(), + None => vec![0; n], + } + } + + /// [`Self::coverage_as`] as a grayscale PNG, black for solid ink and white for none, as a plate + /// prints; `None` when it can't be written. + pub fn plate_png(&self, plate: &str, own: &dyn Fn(&str) -> bool, equivalent: &dyn Fn(&InkPlate) -> [f32; 4]) -> Option<ImageBlob> { + let gray: Vec<u8> = self.coverage_as(plate, own, equivalent).into_iter().map(|v| 255 - v).collect(); + let img = image::GrayImage::from_raw(self.width, self.height, gray)?; + let mut png = Vec::new(); + img.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?; + Some(ImageBlob::png(png)) + } + + fn data_len(&self) -> usize { + self.width as usize * self.height as usize + } +} + +/// A plate's ImageDescription: the mark, its equivalent and its name in hexadecimal (TIFF text is +/// ASCII). +fn description(p: &InkPlate) -> String { + let [c, m, y, k] = p.cmyk; + format!("{MARK}{c} {m} {y} {k} {}", hex(&p.name)) +} + +/// A plate's name and equivalent from its ImageDescription; `None` when it isn't one. +fn parse_description(s: &str) -> Option<(String, [f32; 4])> { + let rest = s.strip_prefix(MARK)?; + let mut words = rest.split(' '); + let mut cmyk = [0.0f32; 4]; + for v in &mut cmyk { + *v = words.next()?.parse().ok().filter(|v: &f32| v.is_finite())?; + } + let name = unhex(words.next()?, MAX_NAME)?; + words.next().is_none().then_some((name, cmyk)) +} + +/// Longest plate file name kept (bytes). +const MAX_FILE_NAME: usize = 4096; + +/// The composite's ImageDescription line for `files`: the mark, then each file's name in +/// hexadecimal, its size and its modification time. +fn files_description(files: &[PlateFile]) -> String { + let mut out = String::from(FILES_MARK); + for f in files.iter().take(MAX_PLATES) { + out.push_str(&format!(" {} {} {}", hex(&f.name), f.size, f.modified)); + } + out +} + +/// How the composite's ImageDescription line holding the clipping path starts. +const CLIP_MARK: &str = "VectorCraft clip "; + +/// Longest clipping path kept (bytes of its JSON). +const MAX_CLIP: usize = 16 << 20; + +/// The composite's ImageDescription line for clipping path `clip`: the mark, then the path's JSON +/// in hexadecimal; `None` when it is longer than [`MAX_CLIP`]. +fn clip_description(clip: &PathData) -> Option<String> { + let json = serde_json::to_string(clip).ok().filter(|j| j.len() <= MAX_CLIP)?; + Some(format!("{CLIP_MARK}{}", hex(&json))) +} + +/// The plate files of a composite's ImageDescription; none when it isn't one. +fn parse_files(s: &str) -> Vec<PlateFile> { + let Some(rest) = s.lines().find_map(|l| l.strip_prefix(FILES_MARK)) else { return vec![] }; + let words: Vec<&str> = rest.split(' ').filter(|w| !w.is_empty()).collect(); + let file = + |w: &[&str]| Some(PlateFile { name: unhex(w.first()?, MAX_FILE_NAME)?, size: w.get(1)?.parse().ok()?, modified: w.get(2)?.parse().ok()? }); + words.chunks(3).take(MAX_PLATES).filter_map(file).collect() +} + +impl ImageBlob { + /// A TIFF of separated image `s`: its composite in CMYK, then its plates (Deflate-compressed), + /// declaring the resolution `ppi` when it is given and both are finite and above 0, and noting + /// `files`, the plate files of their own the plates were read from ([`Self::plate_files`]); + /// `None` when it can't be written. + pub fn separated_tiff(s: &Separated, ppi: Option<(f64, f64)>, files: &[PlateFile]) -> Option<Self> { + Self::separated_tiff_clipped(s, ppi, files, None) + } + + /// [`Self::separated_tiff`], noting `clip` too, the clipping path its file draws it through, in + /// its pixel space ([`Self::separated_clip`]). + pub fn separated_tiff_clipped(s: &Separated, ppi: Option<(f64, f64)>, files: &[PlateFile], clip: Option<&PathData>) -> Option<Self> { + use tiff::encoder::{Compression, Rational, TiffEncoder, colortype, compression::DeflateLevel}; + use tiff::tags::{ResolutionUnit, Tag}; + let ppi = ppi.filter(|(x, y)| [x, y].iter().all(|v| v.is_finite() && **v > 0.0)); + // Ten-thousandths of a pixel per inch. + let r = |v: f64| Rational { n: (v * 10_000.0).round() as u32, d: 10_000 }; + let mut out = Cursor::new(Vec::new()); + let mut enc = TiffEncoder::new(&mut out).ok()?.with_compression(Compression::Deflate(DeflateLevel::Balanced)); + let mut img = enc.new_image::<colortype::CMYK8>(s.width, s.height).ok()?; + if let Some((x, y)) = ppi { + img.encoder().write_tag(Tag::XResolution, r(x)).ok()?; + img.encoder().write_tag(Tag::YResolution, r(y)).ok()?; + img.encoder().write_tag(Tag::ResolutionUnit, ResolutionUnit::Inch).ok()?; + } + // One line for the plate files, one for the clipping path. + let lines: Vec<String> = + [(!files.is_empty()).then(|| files_description(files)), clip.and_then(clip_description)].into_iter().flatten().collect(); + if !lines.is_empty() { + img.encoder().write_tag(Tag::ImageDescription, lines.join("\n").as_str()).ok()?; + } + img.write_data(&s.composite().data).ok()?; + for p in &s.plates { + // White is no ink, so a viewer that shows a plate shows it as it prints. + let mut img = enc.new_image::<colortype::Gray8>(s.width, s.height).ok()?; + img.encoder().write_tag(Tag::ImageDescription, description(p).as_str()).ok()?; + let inverted: Vec<u8> = p.data.iter().map(|v| 255 - v).collect(); + img.write_data(&inverted).ok()?; + } + Some(Self::new("image/tiff", out.into_inner())) + } + + /// Does the image hold plates ([`ImageBlob::separated_tiff`]), at most [`MAX_PLATES`] of them? + /// One with more, or with more directories than its composite and [`MAX_PLATES`] plates, is the + /// CMYK image of its composite only, as [`Self::separated`] refuses it. Reads only the TIFF's + /// directories, at most [`MAX_DIRECTORIES`]. + pub fn is_separated(&self) -> bool { + let Some((_, mut d)) = crate::cmyk::tiff(&self.bytes) else { return false }; + let (mut plates, mut directories) = (0usize, 1usize); + while d.more_images() { + directories += 1; + if directories > MAX_DIRECTORIES || d.next_image().is_err() { + return false; + } + if d.get_tag_ascii_string(tiff::tags::Tag::ImageDescription).ok().is_some_and(|s| s.starts_with(MARK)) { + plates += 1; + if plates > MAX_PLATES { + return false; + } + } + } + plates > 0 + } + + /// The plate files of their own a separated image was read from, as they were then; none for + /// other images. Reads only the TIFF's first directory. + pub fn plate_files(&self) -> Vec<PlateFile> { + let Some((_, mut d)) = crate::cmyk::tiff(&self.bytes) else { return vec![] }; + d.get_tag_ascii_string(tiff::tags::Tag::ImageDescription).ok().as_deref().map(parse_files).unwrap_or_default() + } + + /// The clipping path a separated image's file draws it through, in its pixel space, as + /// [`Self::separated_tiff_clipped`] noted it; `None` for other images. Reads only the TIFF's + /// first directory. + pub fn separated_clip(&self) -> Option<PathData> { + let (_, mut d) = crate::cmyk::tiff(&self.bytes)?; + let text = d.get_tag_ascii_string(tiff::tags::Tag::ImageDescription).ok()?; + let json = unhex(text.lines().find_map(|l| l.strip_prefix(CLIP_MARK))?, MAX_CLIP)?; + serde_json::from_str(&json).ok() + } + + /// The spot inks a separated image has plates for, each with its CMYK equivalent; none for + /// other images. Reads only the TIFF's directories. + pub fn spot_plates(&self) -> Vec<(String, [f32; 4])> { + if !self.is_separated() { + return vec![]; + } + let Some((_, mut d)) = crate::cmyk::tiff(&self.bytes) else { return vec![] }; + let mut inks = vec![]; + while d.more_images() && inks.len() < MAX_PLATES { + if d.next_image().is_err() { + break; + } + let plate = d.get_tag_ascii_string(tiff::tags::Tag::ImageDescription).ok().as_deref().and_then(parse_description); + inks.extend(plate.filter(|(name, _)| !PROCESS_PLATES.contains(&name.as_str()))); + } + inks + } + + /// The plates of a separated image; `None` for other images, and ones whose plates can't be + /// read. The plates of the last image read are kept for the next call (print separates one + /// image plate after plate). + pub fn separated(&self) -> Option<Arc<Separated>> { + thread_local! { + static LAST: std::cell::RefCell<Option<(String, Arc<Separated>)>> = const { std::cell::RefCell::new(None) }; + } + if !self.is_separated() { + return None; + } + let key = self.content_key(); + LAST.with_borrow_mut(|last| match last { + Some((k, s)) if *k == key => Some(s.clone()), + _ => { + let s = Arc::new(read_plates(&self.bytes)?); + *last = Some((key, s.clone())); + Some(s) + } + }) + } +} + +/// The plates of TIFF `bytes`, each the size of its first image. +fn read_plates(bytes: &[u8]) -> Option<Separated> { + let (_, mut d) = crate::cmyk::tiff(bytes)?; + let (w, h) = d.dimensions().ok()?; + let n = usize::try_from(u64::from(w) * u64::from(h)).ok()?; + let mut plates = vec![]; + // Every plate is read: a file with more than [`MAX_PLATES`] is refused ([`Separated::fits`]), + // not cut short, and so is one with more than [`MAX_DIRECTORIES`] directories. + let mut directories = 1usize; + while d.more_images() { + directories += 1; + if directories > MAX_DIRECTORIES { + return None; + } + d.next_image().ok()?; + let Some((name, cmyk)) = d.get_tag_ascii_string(tiff::tags::Tag::ImageDescription).ok().as_deref().and_then(parse_description) else { + continue; + }; + // Checked before the plate is decoded. + if d.dimensions().ok()? != (w, h) || !matches!(d.colortype().ok()?, tiff::ColorType::Gray(8)) || !Separated::fits(w, h, plates.len() + 1) { + return None; + } + let data = crate::cmyk::read_samples(&mut d, n, 1)?.into_iter().map(|v| 255 - v).collect(); + plates.push(InkPlate { name, cmyk, data }); + } + Separated::new(w, h, plates) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn plate(name: &str, cmyk: [f32; 4], data: &[u8]) -> InkPlate { + InkPlate { name: name.into(), cmyk, data: data.to_vec() } + } + + /// Two pixels: cyan 100% and a spot ink at 50% on the first, nothing on the second. + fn two() -> Separated { + let plates = vec![plate("Cyan", [0.0; 4], &[255, 0]), plate("Spot Orange", [0.0, 0.6, 1.0, 0.0], &[128, 0])]; + Separated::new(2, 1, plates).unwrap() + } + + #[test] + fn plates_mix_into_the_composite_as_inks_print() { + let s = two(); + assert_eq!(s.plates[0].cmyk, [1.0, 0.0, 0.0, 0.0], "a process plate stands for its own ink"); + let c = s.composite(); + // Magenta: 0.6 × 128/255; yellow: 128/255. + assert_eq!(&c.data[..4], &[255, 77, 128, 0]); + assert_eq!(&c.data[4..], &[0, 0, 0, 0]); + } + + #[test] + fn a_spot_plate_prints_on_its_own_plate_or_as_process() { + let s = two(); + let own = |_: &str| true; + assert_eq!(s.coverage("Spot Orange", &own), [128, 0]); + assert_eq!(s.coverage("Magenta", &own), [0, 0], "nothing of the spot on a process plate"); + assert_eq!(s.coverage("Cyan", &own), [255, 0]); + assert_eq!(s.coverage("Black", &own), [0, 0]); + let process = |_: &str| false; + assert_eq!(s.coverage("Spot Orange", &process), [0, 0]); + assert_eq!(s.coverage("Magenta", &process), [77, 0]); + assert_eq!(s.coverage("Yellow", &process), [128, 0]); + assert_eq!(s.coverage("Other", &own), [0, 0]); + } + + #[test] + fn the_tiff_keeps_every_plate_and_shows_the_composite() { + let s = two(); + let files = + [PlateFile { name: "pic (1).C".into(), size: 1234, modified: 1_700_000_000_000 }, PlateFile { name: "ü.K".into(), size: 0, modified: 0 }]; + let b = ImageBlob::separated_tiff(&s, Some((300.0, 300.0)), &files).unwrap(); + assert_eq!(b.plate_files(), files); + assert!(ImageBlob::separated_tiff(&s, None, &[]).unwrap().plate_files().is_empty()); + assert!(b.is_separated()); + assert!(b.is_cmyk(), "readers of a CMYK TIFF see the composite"); + assert_eq!(b.cmyk(), Some(s.composite())); + assert_eq!(*b.separated().unwrap(), s); + assert_eq!(b.spot_plates(), [("Spot Orange".to_string(), [0.0, 0.6, 1.0, 0.0])]); + assert!(ImageBlob::cmyk_tiff(&s.composite()).unwrap().spot_plates().is_empty()); + assert!(!ImageBlob::cmyk_tiff(&s.composite()).unwrap().is_separated()); + } + + #[test] + fn the_tiff_keeps_the_clipping_path_beside_the_plate_files() { + let s = two(); + let clip = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 1.5, 1.0)); + let files = [PlateFile { name: "a.C".into(), size: 1, modified: 2 }]; + let b = ImageBlob::separated_tiff_clipped(&s, None, &files, Some(&clip)).unwrap(); + assert_eq!(b.separated_clip(), Some(clip.clone())); + assert_eq!(b.plate_files(), files); + let alone = ImageBlob::separated_tiff_clipped(&s, None, &[], Some(&clip)).unwrap(); + assert_eq!(alone.separated_clip(), Some(clip)); + assert!(alone.plate_files().is_empty()); + assert_eq!(ImageBlob::separated_tiff(&s, None, &files).unwrap().separated_clip(), None); + } + + #[test] + fn a_tiff_with_more_plates_than_are_read_is_refused() { + use tiff::encoder::{TiffEncoder, colortype}; + let tiff = |plates: usize| { + let mut out = Cursor::new(Vec::new()); + let mut enc = TiffEncoder::new(&mut out).unwrap(); + enc.write_image::<colortype::CMYK8>(1, 1, &[0, 0, 0, 0]).unwrap(); + for i in 0..plates { + let mut img = enc.new_image::<colortype::Gray8>(1, 1).unwrap(); + img.encoder().write_tag(tiff::tags::Tag::ImageDescription, description(&plate(&format!("S{i}"), [0.0; 4], &[0])).as_str()).unwrap(); + img.write_data(&[255]).unwrap(); + } + ImageBlob::new("image/tiff", out.into_inner()) + }; + assert_eq!(tiff(MAX_PLATES).separated().map(|s| s.plates.len()), Some(MAX_PLATES)); + let over = tiff(MAX_PLATES + 1); + assert!(over.separated().is_none(), "not cut short to the first {MAX_PLATES}"); + assert!(!over.is_separated() && over.spot_plates().is_empty(), "the CMYK image of its composite only"); + assert!(tiff(MAX_PLATES).is_separated()); + } + + #[test] + fn a_tiff_with_more_directories_than_a_composite_and_its_plates_is_refused() { + use tiff::encoder::{TiffEncoder, colortype}; + let tiff = |others: usize| { + let mut out = Cursor::new(Vec::new()); + let mut enc = TiffEncoder::new(&mut out).unwrap(); + enc.write_image::<colortype::CMYK8>(1, 1, &[0, 0, 0, 0]).unwrap(); + let mut img = enc.new_image::<colortype::Gray8>(1, 1).unwrap(); + img.encoder().write_tag(tiff::tags::Tag::ImageDescription, description(&plate("S", [0.0; 4], &[0])).as_str()).unwrap(); + img.write_data(&[255]).unwrap(); + // Directories that are not plates. + for _ in 0..others { + enc.write_image::<colortype::Gray8>(1, 1, &[255]).unwrap(); + } + ImageBlob::new("image/tiff", out.into_inner()) + }; + let most = tiff(MAX_PLATES - 1); + assert!(most.is_separated() && most.separated().is_some()); + let over = tiff(MAX_PLATES); + assert!(!over.is_separated() && over.separated().is_none() && over.spot_plates().is_empty()); + assert!(read_plates(&over.bytes).is_none(), "read_plates stops at the limit too"); + } + + #[test] + fn names_that_are_not_ascii_are_kept() { + let s = Separated::new(1, 1, vec![plate("Grün 100 % (A)", [0.5, 0.0, 1.0, 0.0], &[9])]).unwrap(); + let b = ImageBlob::separated_tiff(&s, None, &[]).unwrap(); + assert_eq!(b.separated().unwrap().plates[0].name, "Grün 100 % (A)"); + } + + #[test] + fn bad_plates_are_refused() { + assert!(Separated::new(2, 1, vec![]).is_none(), "no plates"); + assert!(Separated::new(2, 1, vec![plate("Cyan", [0.0; 4], &[1])]).is_none(), "too few pixels"); + assert!(Separated::new(1, 1, vec![plate("A", [0.0; 4], &[1]), plate("A", [0.0; 4], &[1])]).is_none(), "the same name twice"); + assert!(Separated::new(1, 1, vec![plate("", [0.0; 4], &[1])]).is_none(), "no name"); + assert!(Separated::new(1, 1, vec![plate("A", [2.0, 0.0, 0.0, 0.0], &[1])]).is_none(), "equivalent past 100%"); + assert!(Separated::new(0, 1, vec![plate("A", [0.0; 4], &[])]).is_none(), "empty"); + let many: Vec<InkPlate> = (0..=MAX_PLATES).map(|i| plate(&format!("S{i}"), [0.0; 4], &[1])).collect(); + assert!(Separated::new(1, 1, many).is_none(), "too many plates"); + assert!(Separated::fits(1 << 13, 1 << 13, 8), "512 MB of ink amounts"); + assert!(!Separated::fits(1 << 13, 1 << 13, 9), "more than 512 MB together"); + assert!(!Separated::fits(1 << 14, 1 << 13, 1), "more pixels than a CMYK image is decoded with"); + } +} diff --git a/crates/doc/src/setup.rs b/crates/doc/src/setup.rs index 781bec84ea..bc558d2702 100644 --- a/crates/doc/src/setup.rs +++ b/crates/doc/src/setup.rs @@ -314,6 +314,13 @@ pub struct DocSetup { /// <https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/turn-fractional-character-widths-off-or-on.html> #[serde(default, rename = "systemLayout", skip_serializing_if = "crate::skip::is_default")] pub system_layout: bool, + /// Align New Objects to Pixel Grid (New Document › Advanced Options, Transform panel menu): + /// paths and compound paths drawn from then on are pixel-aligned. Objects already in the + /// document, and objects pasted, duplicated or placed, keep their own setting. Off by default + /// and for documents from before it, and saved only when on. + /// <https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/pixel-preview-mode-for-web-graphics.html> + #[serde(default, skip_serializing_if = "crate::skip::is_default")] + pub align_new_objects_to_pixel_grid: bool, } impl Default for DocSetup { @@ -337,6 +344,7 @@ impl Default for DocSetup { export_text: ExportText::Editable, background: Background::Transparent, system_layout: false, + align_new_objects_to_pixel_grid: false, } } } diff --git a/crates/doc/src/stored_art.rs b/crates/doc/src/stored_art.rs new file mode 100644 index 0000000000..e623e0ed0e --- /dev/null +++ b/crates/doc/src/stored_art.rs @@ -0,0 +1,376 @@ +//! Every object a document stores, wherever it is kept: in the layers, in opacity-mask art, and in +//! the art of symbols, graph designs and pattern swatches. [`Document::node`] finds objects in the +//! layer tree only; the lookups here find the others by their ids too, which +//! [`Document::fix_next_id`] keeps unique across all of them. + +use std::collections::HashSet; +use std::sync::Arc; + +use super::limits::MAX_NEXT_ID; +use super::{Document, Node, NodeId}; + +/// The art a stored object belongs to. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum StoredRoot { + /// Layer `index` of [`Document::layers`]. + Layer(usize), + /// Symbol `index` of [`Document::symbols`]. + Symbol(usize), + /// Graph design `index` of [`Document::graph_designs`]. + GraphDesign(usize), + /// Object `art` of pattern swatch `pattern` of [`Document::patterns`]. + Pattern { pattern: usize, art: usize }, +} + +/// Where a stored object is: its root and, inside opacity-mask art, the object that mask belongs +/// to (the innermost one when masks hold masks). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct StoredPlace { + pub root: StoredRoot, + pub mask_of: Option<NodeId>, +} + +impl StoredPlace { + /// Is the object in the layer tree itself, where [`Document::node`] finds it and the canvas + /// draws it as itself? + pub fn in_layers(self) -> bool { + matches!(self.root, StoredRoot::Layer(_)) && self.mask_of.is_none() + } +} + +/// One step down from a node: to its child at an index, or to its opacity-mask art. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Step { + Child(usize), + Mask, +} + +/// `n` and everything below it with its place, the opacity-mask art right after the object it +/// masks, then the children. +fn visit<'a>(n: &'a Arc<Node>, place: StoredPlace, f: &mut dyn FnMut(&'a Arc<Node>, StoredPlace)) { + f(n, place); + if let Some(m) = &n.extras().mask { + visit(&m.art, StoredPlace { mask_of: Some(n.id), ..place }, f); + } + for c in n.children().into_iter().flatten() { + visit(c, place, f); + } +} + +/// The steps from `n` to the first node in [`visit`] order with id `id`, and the object whose mask +/// holds it last on the way. +fn find(n: &Node, id: NodeId, steps: &mut Vec<Step>, mask_of: &mut Option<NodeId>) -> bool { + if n.id == id { + return true; + } + if let Some(m) = &n.extras().mask { + steps.push(Step::Mask); + let before = *mask_of; + *mask_of = Some(n.id); + if find(&m.art, id, steps, mask_of) { + return true; + } + *mask_of = before; + steps.pop(); + } + for (i, c) in n.children().into_iter().flatten().enumerate() { + steps.push(Step::Child(i)); + if find(c, id, steps, mask_of) { + return true; + } + steps.pop(); + } + false +} + +/// The node `steps` below `n`. +fn at<'a>(mut n: &'a Arc<Node>, steps: &[Step]) -> Option<&'a Arc<Node>> { + for s in steps { + n = match s { + Step::Mask => &n.extras().mask.as_ref()?.art, + Step::Child(i) => n.children()?.get(*i)?, + }; + } + Some(n) +} + +/// The node `steps` below `n` to change, the nodes on the way copied when shared. +fn at_mut<'a>(mut n: &'a mut Arc<Node>, steps: &[Step]) -> Option<&'a mut Node> { + for s in steps { + let node = Arc::make_mut(n); + n = match s { + Step::Mask => &mut node.extras_if_any()?.mask.as_mut()?.art, + Step::Child(i) => node.children_mut()?.get_mut(*i)?, + }; + } + Some(Arc::make_mut(n)) +} + +/// Gives every node from `n` down that `fresh` names a new id from `next`, counting nodes in +/// [`visit`] order from `*count`; only the nodes on the way to one are copied. Each part below is +/// renumbered through a second handle, so a new pointer marks a change. +fn renumber(n: &mut Arc<Node>, fresh: &HashSet<usize>, count: &mut usize, next: &mut u64) { + let own = fresh.contains(count); + *count += 1; + let mask = n.extras().mask.as_ref().and_then(|m| { + let mut art = Arc::clone(&m.art); + renumber(&mut art, fresh, count, next); + (!Arc::ptr_eq(&art, &m.art)).then_some(art) + }); + let mut slots = vec![]; + // Children's new ids by their old ones, for an Objects on Path group, which names its path and + // members by id. An id another child keeps still names that child. + let mut renamed = std::collections::HashMap::new(); + let mut kept = HashSet::new(); + for (i, c) in n.children().into_iter().flatten().enumerate() { + let mut new = Arc::clone(c); + renumber(&mut new, fresh, count, next); + if new.id == c.id { + kept.insert(c.id); + } else { + renamed.insert(c.id, new.id); + } + if !Arc::ptr_eq(&new, c) { + slots.push((i, new)); + } + } + renamed.retain(|old, _| !kept.contains(old)); + if !own && mask.is_none() && slots.is_empty() { + return; + } + let node = Arc::make_mut(n); + if own { + node.id = NodeId(*next); + *next += 1; + } + if let (Some(art), Some(m)) = (mask, node.extras_if_any().and_then(|e| e.mask.as_mut())) { + m.art = art; + } + if let Some(children) = node.children_mut() { + for (i, c) in slots { + if let Some(slot) = children.get_mut(i) { + *slot = c; + } + } + } + if !renamed.is_empty() + && let Some(on_path) = node.extras_if_any().and_then(|e| e.objects_on_path.as_mut()) + { + on_path.rename(&renamed); + } +} + +impl Document { + /// The roots of the art kept outside the layers, each with its [`StoredRoot`]. + fn definition_roots(&self) -> impl Iterator<Item = (&Arc<Node>, StoredRoot)> { + let symbols = self.symbols.iter().enumerate().map(|(i, s)| (&s.art, StoredRoot::Symbol(i))); + let designs = self.graph_designs.iter().enumerate().map(|(i, g)| (&g.art, StoredRoot::GraphDesign(i))); + let patterns = self + .patterns + .iter() + .enumerate() + .flat_map(|(p, def)| def.art.iter().enumerate().map(move |(a, n)| (n, StoredRoot::Pattern { pattern: p, art: a }))); + symbols.chain(designs).chain(patterns) + } + + /// Every root of stored art: the layers, then the art of symbols, graph designs and patterns. + fn stored_roots(&self) -> impl Iterator<Item = (&Arc<Node>, StoredRoot)> { + self.layers.iter().enumerate().map(|(i, l)| (l, StoredRoot::Layer(i))).chain(self.definition_roots()) + } + + /// The root `root` names, to change. + fn stored_root_mut(&mut self, root: StoredRoot) -> Option<&mut Arc<Node>> { + match root { + StoredRoot::Layer(i) => self.layers.get_mut(i), + StoredRoot::Symbol(i) => self.symbols.get_mut(i).map(|s| &mut s.art), + StoredRoot::GraphDesign(i) => self.graph_designs.get_mut(i).map(|g| &mut g.art), + StoredRoot::Pattern { pattern, art } => self.patterns.get_mut(pattern)?.art.get_mut(art), + } + } + + /// Visit every stored object with its place: the layer tree with the opacity-mask art of its + /// objects, then the art of symbols, graph designs and pattern swatches (their definitions, + /// once each, never the copies instances and tiles draw). + pub fn visit_stored<'a>(&'a self, mut f: impl FnMut(&'a Node, StoredPlace)) { + self.visit_stored_arcs(|n, place| f(n, place)); + } + + /// [`Self::visit_stored`] with each object's shared handle, which keeps its identity from one + /// look to the next while the object is unchanged (for caches such as thumbnails). + pub fn visit_stored_arcs<'a>(&'a self, mut f: impl FnMut(&'a Arc<Node>, StoredPlace)) { + for (root, r) in self.stored_roots() { + visit(root, StoredPlace { root: r, mask_of: None }, &mut f); + } + } + + /// Where object `id` is stored: the root, and the steps from it. + fn stored_path(&self, id: NodeId) -> Option<(StoredPlace, Vec<Step>)> { + if let Some(path) = self.index_path(id) { + let (first, rest) = path.split_first()?; + return Some((StoredPlace { root: StoredRoot::Layer(*first), mask_of: None }, rest.iter().map(|i| Step::Child(*i)).collect())); + } + // Not in the layer tree: in mask art (in the layers too) or in a definition's art. + for (root, r) in self.stored_roots() { + let (mut steps, mut mask_of) = (vec![], None); + if find(root, id, &mut steps, &mut mask_of) { + return Some((StoredPlace { root: r, mask_of }, steps)); + } + } + None + } + + /// Stored object `id` (see [`Self::visit_stored`]) with its place: one in the layer tree as + /// [`Self::node`] finds it, else the first in visiting order. + pub fn stored_node(&self, id: NodeId) -> Option<(&Arc<Node>, StoredPlace)> { + let (place, steps) = self.stored_path(id)?; + let root = self.stored_roots().find(|(_, r)| *r == place.root)?.0; + Some((at(root, &steps)?, place)) + } + + /// [`Self::stored_node`] to change; the nodes on the way are copied when shared. + pub fn stored_node_mut(&mut self, id: NodeId) -> Option<&mut Node> { + let (place, steps) = self.stored_path(id)?; + at_mut(self.stored_root_mut(place.root)?, &steps) + } + + /// Gives the objects outside the layer tree (in opacity-mask art and in the art of symbols, + /// graph designs and patterns) whose id is 0, past the id range, or already taken by an object + /// visited before them (the layer tree's own objects first) a new id, so every stored object + /// can be named by its id. Returns how many changed; the id counter then stands above them. + pub(crate) fn renumber_stored_duplicates(&mut self) -> usize { + let mut seen: HashSet<NodeId> = HashSet::new(); + for l in &self.layers { + l.walk(&mut |n| { + seen.insert(n.id); + }); + } + self.slices.iter().for_each(|s| { + seen.insert(s.id); + }); + // Per root, the visiting indices of the nodes that take a new id. + let mut fresh: Vec<(StoredRoot, HashSet<usize>)> = vec![]; + for (root, r) in self.stored_roots() { + let (mut i, mut here) = (0, HashSet::new()); + visit(root, StoredPlace { root: r, mask_of: None }, &mut |n, place| { + if !place.in_layers() && (n.id.0 == 0 || n.id.0 >= MAX_NEXT_ID || !seen.insert(n.id)) { + here.insert(i); + } + i += 1; + }); + if !here.is_empty() { + fresh.push((r, here)); + } + } + let total = fresh.iter().map(|(_, f)| f.len()).sum(); + if total == 0 { + return 0; + } + // No id left to give: the objects keep theirs rather than share one given out later. + if self.peek_next_id().saturating_add(total as u64) > MAX_NEXT_ID { + return 0; + } + let mut next = self.peek_next_id(); + for (r, f) in fresh { + if let Some(root) = self.stored_root_mut(r) { + renumber(root, &f, &mut 0, &mut next); + } + } + self.raise_next_id(next); + total + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{GraphDesign, OpacityMask, PatternDef, Symbol}; + use vectorcraft_geom::Rect; + + fn rect(id: u64) -> Node { + Node::path(NodeId(id), vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), crate::Appearance::default_art()) + } + + fn masked(id: u64, art: Node) -> Node { + rect(id).with_mask(Some(Box::new(OpacityMask::new(art, true)))) + } + + /// A document with object 10 in its layer, mask art 11 on it, and one object in a symbol, + /// a graph design and a pattern (ids `defs`). + fn doc(defs: [u64; 3]) -> Document { + let mut d = Document::new(100.0, 100.0); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, masked(10, rect(11))).unwrap(); + d.symbols.push(Symbol { name: "S".into(), art: Arc::new(rect(defs[0])), dynamic: false }); + d.graph_designs.push(GraphDesign { name: "G".into(), art: Arc::new(rect(defs[1])) }); + d.patterns.push(PatternDef::new("P", vec![Arc::new(rect(defs[2]))])); + d.raise_next_id(20); + d + } + + #[test] + fn stored_objects_are_found_in_every_art() { + let d = doc([12, 13, 14]); + let place = |id: u64| d.stored_node(NodeId(id)).map(|(n, p)| (n.id.0, p)); + assert!(place(10).unwrap().1.in_layers()); + assert_eq!(place(11).unwrap().1, StoredPlace { root: StoredRoot::Layer(0), mask_of: Some(NodeId(10)) }); + assert_eq!(place(12).unwrap().1.root, StoredRoot::Symbol(0)); + assert_eq!(place(13).unwrap().1.root, StoredRoot::GraphDesign(0)); + assert_eq!(place(14).unwrap().1.root, StoredRoot::Pattern { pattern: 0, art: 0 }); + assert!(d.node(NodeId(11)).is_none() && d.node(NodeId(12)).is_none(), "the layer lookup stays the layer tree's"); + assert!(d.stored_node(NodeId(99)).is_none()); + let mut seen = vec![]; + d.visit_stored(|n, _| seen.push(n.id.0)); + assert_eq!(seen, [d.layers[0].id.0, 10, 11, 12, 13, 14]); + } + + #[test] + fn stored_objects_change_by_id() { + let mut d = doc([12, 13, 14]); + let before = d.clone(); + d.stored_node_mut(NodeId(13)).unwrap().name = Some("changed".into()); + assert_eq!(d.graph_designs[0].art.name.as_deref(), Some("changed")); + assert!(Arc::ptr_eq(&d.symbols[0].art, &before.symbols[0].art), "other art is not copied"); + assert_eq!(before.graph_designs[0].art.name, None, "the earlier document is unchanged"); + d.stored_node_mut(NodeId(11)).unwrap().name = Some("mask".into()); + assert_eq!(d.stored_node(NodeId(11)).unwrap().0.name.as_deref(), Some("mask")); + } + + #[test] + fn fix_next_id_gives_nested_duplicates_new_ids() { + // The symbol's object repeats the layer's object, the design's has no id, and the pattern's + // repeats the mask art's. + let mut d = doc([10, 0, 11]); + d.next_id = 1; + d.fix_next_id(); + let mut ids = vec![]; + d.visit_stored(|n, _| ids.push(n.id.0)); + let unique: HashSet<u64> = ids.iter().copied().collect(); + assert_eq!(unique.len(), ids.len(), "{ids:?}"); + assert!(!ids.contains(&0)); + assert_eq!(&ids[..3], &[d.layers[0].id.0, 10, 11], "the layer tree and the first mask art keep theirs"); + assert!(ids.iter().all(|id| *id < d.peek_next_id()), "{ids:?} {}", d.peek_next_id()); + // Ids already unique are kept, and a second pass changes nothing. + let again = d.clone(); + assert_eq!(d.renumber_stored_duplicates(), 0); + assert_eq!(d, again); + } + + #[test] + fn renumbered_objects_on_path_keep_their_path_and_members() { + // A symbol's Objects on Path group whose path repeats the layer's object 10 and whose + // member has no id. + let mut d = doc([12, 13, 14]); + let (path, member) = (rect(10), rect(0)); + let rec = crate::objects_on_path::ObjectsOnPath::new(path.id, &[&member], crate::objects_on_path::CENTER, 0.0); + let mut g = Node::new(NodeId(15), crate::NodeKind::Group { children: vec![Arc::new(path), Arc::new(member)], clip: false }); + g.extras_mut().objects_on_path = Some(Box::new(rec)); + d.symbols[0].art = Arc::new(g); + d.fix_next_id(); + let art = &d.symbols[0].art; + let kids: Vec<NodeId> = art.children().unwrap().iter().map(|c| c.id).collect(); + assert!(kids.iter().all(|id| id.0 != 10 && id.0 != 0), "{kids:?}"); + let on_path = art.extras().objects_on_path.as_ref().unwrap(); + assert_eq!(on_path.path, kids[0]); + assert_eq!(on_path.members.iter().map(|m| m.id).collect::<Vec<_>>(), [kids[1]]); + } +} diff --git a/crates/doc/src/style_libs.rs b/crates/doc/src/style_libs.rs index f64bdb4300..1952060663 100644 --- a/crates/doc/src/style_libs.rs +++ b/crates/doc/src/style_libs.rs @@ -155,6 +155,8 @@ pub const STYLE_LIBRARIES: &[BuiltinStyleLibrary] = &[ BuiltinStyleLibrary { id: "shadows-glows", name: "Shadows and Glows", make: shadows_glows }, BuiltinStyleLibrary { id: "outlines-rules", name: "Outlines and Rules", make: outlines_rules }, BuiltinStyleLibrary { id: "hand-drawn", name: "Hand-Drawn", make: hand_drawn }, + BuiltinStyleLibrary { id: "textures", name: "Textures", make: textures }, + BuiltinStyleLibrary { id: "painted-sketched", name: "Painted and Sketched", make: painted_sketched }, BuiltinStyleLibrary { id: "gradient-finishes", name: "Gradient Finishes", make: gradient_finishes }, BuiltinStyleLibrary { id: "shape-effects", name: "Shape Effects", make: shape_effects }, BuiltinStyleLibrary { id: "blends-transparency", name: "Blends and Transparency", make: blends_transparency }, @@ -192,8 +194,14 @@ fn round(h: &str, width: f64) -> StrokeLayer { StrokeLayer { cap: LineCap::Round, join: LineJoin::Round, ..stroke(h, width) } } -/// Live effect `id` with `params` (the others keep the effect's defaults). -fn fx(id: &str, params: Value) -> Effect { +/// Live effect `id` with `params` (the others keep the effect's defaults). A Warp draws with its +/// style's Bézier net, as a new Warp does. +fn fx(id: &str, mut params: Value) -> Effect { + if id.starts_with("warp.") + && let Value::Object(m) = &mut params + { + m.entry("version").or_insert(json!(crate::live::WARP_NET)); + } Effect { id: id.into(), params, visible: true } } @@ -322,6 +330,97 @@ fn hand_drawn() -> Vec<GraphicStyle> { ] } +/// Painted and Sketched: one catalog paint or sketch effect over the whole appearance, so it +/// repaints the fill and the stroke together (watercolor, dry brush, pastels, charcoal and ink). +fn painted_sketched() -> Vec<GraphicStyle> { + vec![ + style( + "Washed Blue", + vec![F(fill("#8ab9c9"))], + vec![fx("artistic.watercolor", json!({"brushDetail": 8.0, "shadowIntensity": 2.0, "texture": 2.0}))], + ), + style( + "Bristle Ochre", + vec![F(fill("#c4975a")), S(stroke("#76533d", 1.0))], + vec![fx("artistic.dryBrush", json!({"brushSize": 4.0, "brushDetail": 7.0, "texture": 2.0}))], + ), + style( + "Pastel Heather", + vec![F(fill("#a78ca5"))], + vec![fx( + "artistic.roughPastels", + json!({ + "strokeLength": 8.0, + "strokeDetail": 9.0, + "texture": "canvas", + "scaling": 100.0, + "relief": 5.0, + "lightDirection": "topLeft", + "invert": false + }), + )], + ), + style( + "Charcoal Shade", + vec![F(fill("#666666"))], + vec![fx("sketch.charcoal", json!({"thickness": 3.0, "detail": 3.0, "lightDarkBalance": 55.0}))], + ), + style( + "Ink Contour", + vec![F(fill("#d9e2df")), S(stroke("#26323b", 1.0))], + vec![fx("brushStrokes.inkOutlines", json!({"strokeLength": 6.0, "darkIntensity": 24.0, "lightIntensity": 8.0}))], + ), + style( + "Wet Ink", + vec![F(fill("#637b85"))], + vec![fx("brushStrokes.sumiE", json!({"strokeWidth": 7.0, "strokePressure": 5.0, "contrast": 20.0}))], + ), + style( + "Fine Pen", + vec![F(fill("#d8d4c6"))], + vec![fx("sketch.graphicPen", json!({"strokeLength": 6.0, "lightDarkBalance": 55.0, "strokeDirection": "rightDiagonal"}))], + ), + ] +} + +/// Textures: fills and strokes painted with the catalog's texture effects (grain, canvas and +/// burlap surfaces, craquelure, tiles, patchwork, stained glass and water paper). +fn textures() -> Vec<GraphicStyle> { + let surface = |texture: &str, scaling: f64, relief: f64, light: &str| { + fx("texture.texturizer", json!({"texture": texture, "scaling": scaling, "relief": relief, "lightDirection": light, "invert": false})) + }; + vec![ + style( + "Fine Grain", + vec![F(fill("#c9ada7")), S(stroke("#4a4e69", 1.0))], + vec![fx("texture.grain", json!({"intensity": 35.0, "contrast": 55.0, "grainType": "regular"}))], + ), + style("Canvas Weave", vec![F(fill("#e9d8a6"))], vec![surface("canvas", 100.0, 6.0, "topLeft")]), + style("Burlap Sack", vec![F(fill("#bc8a5f")), S(stroke("#6f4518", 1.5))], vec![surface("burlap", 120.0, 8.0, "top")]), + style( + "Cracked Glaze", + vec![F(fill("#94d2bd")), S(stroke("#005f73", 1.0))], + vec![fx("texture.craquelure", json!({"crackSpacing": 12.0, "crackDepth": 5.0, "crackBrightness": 8.0}))], + ), + style( + "Mosaic Floor", + vec![F(fill("#0a9396"))], + vec![fx("texture.mosaicTiles", json!({"tileSize": 10.0, "groutWidth": 3.0, "lightenGrout": 8.0}))], + ), + style("Quilted Squares", vec![F(fill("#ee9b00"))], vec![fx("texture.patchwork", json!({"squareSize": 5.0, "relief": 10.0}))]), + style( + "Leaded Glass", + vec![F(FillLayer::new(linear(-45.0, &[(0.0, "#ae2012", 1.0), (0.5, "#ee9b00", 1.0), (1.0, "#005f73", 1.0)])))], + vec![fx("texture.stainedGlass", json!({"cellSize": 8.0, "borderThickness": 4.0, "lightIntensity": 3.0}))], + ), + style( + "Damp Paper", + vec![F(fill("#4895ef")), S(stroke("#3f37c9", 1.0))], + vec![fx("sketch.waterPaper", json!({"fiberLength": 12.0, "brightness": 55.0, "contrast": 60.0}))], + ), + ] +} + fn gradient_finishes() -> Vec<GraphicStyle> { let rim = |h: &str| S(stroke(h, 1.0)); vec![ @@ -550,6 +649,66 @@ mod tests { assert_eq!(status.name, "Status Effects"); let status_names: Vec<&str> = status.styles.iter().map(|g| g.name.as_str()).collect(); assert_eq!(status_names, ["Poison Tint", "Freeze Edge", "Burn Aura", "Stun Pulse", "Stealth Fade", "Shield Buff"]); + let textures = builtin_style_library("textures").unwrap(); + assert_eq!(textures.name, "Textures"); + let texture_names: Vec<&str> = textures.styles.iter().map(|g| g.name.as_str()).collect(); + let expected = + ["Fine Grain", "Canvas Weave", "Burlap Sack", "Cracked Glaze", "Mosaic Floor", "Quilted Squares", "Leaded Glass", "Damp Paper"]; + assert_eq!(texture_names, expected); + for b in STYLE_LIBRARIES.iter().filter(|b| b.id != "textures") { + let lib = builtin_style_library(b.id).unwrap(); + assert!(lib.styles.iter().all(|g| !expected.contains(&g.name.as_str())), "{} shares a name with Textures", b.id); + } + let ids: Vec<&str> = STYLE_LIBRARIES.iter().map(|b| b.id).collect(); + assert_eq!(ids.iter().position(|&i| i == "textures"), ids.iter().position(|&i| i == "hand-drawn").map(|i| i + 1), "after Hand-Drawn"); + } + + /// The built-in styles' Warps draw with the map a new Warp takes. + #[test] + fn builtin_warp_styles_take_the_nets_map() { + let mut warps = 0; + for b in STYLE_LIBRARIES { + let lib = builtin_style_library(b.id).unwrap(); + for g in &lib.styles { + let mut effects: Vec<&Effect> = g.appearance.effects.iter().collect(); + effects.extend(g.appearance.items.iter().flat_map(|i| i.effects())); + for e in effects.into_iter().filter(|e| e.id.starts_with("warp.")) { + assert_eq!(e.params["version"], json!(crate::live::WARP_NET), "{} › {}: {}", b.id, g.name, e.id); + warps += 1; + } + } + } + assert!(warps >= 3, "{warps}"); + } + + #[test] + fn painted_and_sketched_follows_textures_with_one_effect_per_style() { + let ids: Vec<&str> = STYLE_LIBRARIES.iter().map(|b| b.id).collect(); + let at = ids.iter().position(|&id| id == "painted-sketched").expect("listed"); + assert_eq!(ids[at - 1], "textures"); + let lib = builtin_style_library("painted-sketched").unwrap(); + assert_eq!(lib.name, "Painted and Sketched"); + let names: Vec<&str> = lib.styles.iter().map(|g| g.name.as_str()).collect(); + assert_eq!(names, ["Washed Blue", "Bristle Ochre", "Pastel Heather", "Charcoal Shade", "Ink Contour", "Wet Ink", "Fine Pen"]); + let effects: Vec<&str> = lib.styles.iter().flat_map(|g| g.appearance.effects.iter().map(|e| e.id.as_str())).collect(); + assert_eq!( + effects, + [ + "artistic.watercolor", + "artistic.dryBrush", + "artistic.roughPastels", + "sketch.charcoal", + "brushStrokes.inkOutlines", + "brushStrokes.sumiE", + "sketch.graphicPen" + ] + ); + assert!(lib.styles.iter().all(|g| g.appearance.items.iter().all(|i| i.effects().is_empty())), "no effects on a fill or stroke"); + // No other built-in library holds a style of the same name. + for b in STYLE_LIBRARIES.iter().filter(|b| b.id != "painted-sketched") { + let other = builtin_style_library(b.id).unwrap(); + assert!(other.styles.iter().all(|g| !names.contains(&g.name.as_str())), "{}", b.id); + } } #[test] diff --git a/crates/doc/src/swatches.rs b/crates/doc/src/swatches.rs index 80db3d923a..ba79f7c280 100644 --- a/crates/doc/src/swatches.rs +++ b/crates/doc/src/swatches.rs @@ -5,7 +5,7 @@ //! tint (`Paint::Solid.swatch` / `.tint`, `GradientStop.swatch` / `.tint`); a tint swatch is a //! swatch whose own paint links to its base that way. [`Document::map_solid_paints`] rewrites //! those links (and colours) wherever art and swatches hold them, copying only the nodes that -//! change. +//! change; [`Document::map_paints`] replaces whole paints of any kind in the same places. use std::collections::{HashMap, HashSet}; use std::sync::Arc; @@ -124,6 +124,52 @@ impl Document { /// ([`Paint::map_links`]). Only nodes holding a changed paint (and the paths to them) are /// copied. Returns the number of changed paints. pub fn map_solid_paints(&mut self, f: &mut LinkFn) -> usize { + let mut n = self.map_art_paints(&mut relink(f)); + for gs in &mut self.graphic_styles { + for it in &mut gs.appearance.items { + n += usize::from(item_paint_mut(it).map_links(f)); + } + } + for w in self.swatches_iter_mut() { + n += usize::from(w.paint.map_links(f)); + } + let mut g = relink(f); + for def in &mut self.char_styles { + for key in ["fill", "stroke"] { + n += usize::from(map_style_paint(&mut def.attrs, key, &mut g)); + } + } + n + } + + /// Visit every paint in the places [`Document::map_solid_paints`] visits (fills, strokes, text + /// runs, image colorize paints, dynamic symbol instances' own paints and graphs' stored series and + /// label paints in the art, opacity masks included, symbol definitions, graph designs, pattern tiles and the tile that pattern + /// editing's Cancel puts back; graphic styles; the swatches; character styles' fill and + /// stroke), whatever its kind. `f(paint)` gives the paint to put in its place, or `None` to keep + /// it. Only nodes holding a changed paint (and the paths to them) are copied. Returns the number + /// of changed paints. + pub fn map_paints(&mut self, f: &mut PaintFn) -> usize { + let mut n = self.map_art_paints(f); + for gs in &mut self.graphic_styles { + for it in &mut gs.appearance.items { + n += usize::from(replace_paint(item_paint_mut(it), f)); + } + } + for w in self.swatches_iter_mut() { + n += usize::from(replace_paint(&mut w.paint, f)); + } + for def in &mut self.char_styles { + for key in ["fill", "stroke"] { + n += usize::from(map_style_paint(&mut def.attrs, key, f)); + } + } + n + } + + /// [`Document::map_paints`] limited to the node trees: the art, symbol definitions, graph + /// designs, pattern tiles and the tile that pattern editing's Cancel puts back. + fn map_art_paints(&mut self, f: &mut PaintFn) -> usize { let mut n = map_trees(&mut self.layers, f); for s in &mut self.symbols { n += map_tree(&mut s.art, f); @@ -134,19 +180,6 @@ impl Document { for p in self.patterns.iter_mut().chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut())) { n += map_trees(&mut p.art, f); } - for gs in &mut self.graphic_styles { - for it in &mut gs.appearance.items { - n += usize::from(item_paint_mut(it).map_links(f)); - } - } - for w in self.swatches_iter_mut() { - n += usize::from(w.paint.map_links(f)); - } - for def in &mut self.char_styles { - for key in ["fill", "stroke"] { - n += usize::from(map_style_paint(&mut def.attrs, key, f)); - } - } n } @@ -156,9 +189,10 @@ impl Document { let roots: Vec<NodeId> = ids.iter().copied().filter(|id| !self.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| ids.contains(p)))).collect(); let mut n = 0; + let mut g = relink(f); for id in roots { let Some(node) = self.node(id) else { continue }; - if let Some((new, count)) = map_node(node, f) + if let Some((new, count)) = map_node(node, &mut g) && let Some(slot) = self.node_mut(id) { *slot = new; @@ -176,7 +210,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).chain(override_paints(m)).for_each(&mut *f); + node_paints(m).chain(override_paints(m)).chain(graph_paints(m)).for_each(&mut *f); if let NodeKind::Mesh(mesh) = &m.kind { mesh.points.iter().for_each(|p| f(&Paint::solid(p.color))); } @@ -258,14 +292,39 @@ impl FreeSwatchNames { /// true when it changed them. pub type LinkFn<'a> = dyn FnMut(&mut Color, &mut Option<String>, &mut f32) -> bool + 'a; -/// Apply `f` to the paint a character style's attribute `key` holds, as [`Paint::map_links`] -/// does, and store the result in the attribute. True when it changed. -fn map_style_paint(attrs: &mut serde_json::Map<String, serde_json::Value>, key: &str, f: &mut LinkFn) -> bool { - let Some(value) = attrs.get_mut(key) else { return false }; - let Ok(mut paint) = serde_json::from_value::<Paint>(value.clone()) else { return false }; - if !paint.map_links(f) { - return false; +/// What [`Document::map_paints`] applies to each paint: the paint to put in its place, or `None` +/// to keep it. +pub type PaintFn<'a> = dyn FnMut(&Paint) -> Option<Paint> + 'a; + +/// `f` as a [`PaintFn`]: a solid or gradient paint with `f` applied ([`Paint::map_links`]) when +/// `f` changed it, `None` for every other paint. +fn relink<'a>(f: &'a mut LinkFn<'_>) -> impl FnMut(&Paint) -> Option<Paint> + 'a { + move |p| match p { + Paint::Solid { .. } | Paint::Gradient(_) => { + let mut q = p.clone(); + q.map_links(f).then_some(q) + } + _ => None, } +} + +/// Put `f(p)` in place of `p` when it gives a paint. True when it did. +fn replace_paint(p: &mut Paint, f: &mut PaintFn) -> bool { + match f(p) { + Some(q) => { + *p = q; + true + } + None => false, + } +} + +/// Apply `f` to the paint a character style's attribute `key` holds and store the result in the +/// attribute. An attribute that is not a paint stays as it is. True when it changed. +fn map_style_paint(attrs: &mut serde_json::Map<String, serde_json::Value>, key: &str, f: &mut PaintFn) -> bool { + let Some(value) = attrs.get_mut(key) else { return false }; + let Ok(paint) = serde_json::from_value::<Paint>(value.clone()) else { return false }; + let Some(paint) = f(&paint) else { return false }; match serde_json::to_value(&paint) { Ok(changed) => { *value = changed; @@ -323,6 +382,23 @@ 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() } +/// The paints a graph keeps for its series and its labels ([`crate::graph::GraphSpec`]), which its +/// marks and labels take each time it is drawn again and which [`node_paints`] leaves out. +pub fn graph_paints(n: &Node) -> impl Iterator<Item = &Paint> { + let g = n.extras().graph.as_deref(); + let series = g.into_iter().flat_map(|g| &g.series_paints).flat_map(|s| [s.fill.as_ref(), s.stroke.as_ref()]).flatten(); + let labels = g.into_iter().flat_map(|g| [&g.label_styles.values, &g.label_styles.categories, &g.label_styles.legend]).flatten(); + series.chain(labels.flat_map(|st| [&st.fill, &st.stroke])) +} + +/// Mutable [`graph_paints`] of graph `g`, in the same order. +fn graph_paints_mut(g: &mut crate::graph::GraphSpec) -> impl Iterator<Item = &mut Paint> { + let series = g.series_paints.iter_mut().flat_map(|s| [s.fill.as_mut(), s.stroke.as_mut()]).flatten(); + let l = &mut g.label_styles; + let labels = [&mut l.values, &mut l.categories, &mut l.legend].into_iter().flatten(); + series.chain(labels.flat_map(|st| [&mut st.fill, &mut st.stroke])) +} + /// 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 { @@ -333,20 +409,11 @@ pub fn node_paints_mut(n: &mut Node) -> impl Iterator<Item = &mut Paint> { n.appearance.items.iter_mut().map(item_paint_mut).chain(runs.iter_mut().flat_map(|r| [&mut r.style.fill, &mut r.style.stroke])).chain(colorize) } -/// `n` with `f` applied to its subtree's linkable colours, or `None` when nothing changed (then -/// nothing was copied). Also returns the number of changed paints. -fn map_node(n: &Node, f: &mut LinkFn) -> Option<(Node, usize)> { - // Try each own solid or gradient paint on a scratch copy first, so unchanged nodes are never - // cloned. - let mut changes: Vec<(usize, Paint)> = vec![]; - for (i, p) in node_paints(n).enumerate() { - if matches!(p, Paint::Solid { .. } | Paint::Gradient(_)) { - let mut q = p.clone(); - if q.map_links(f) { - changes.push((i, q)); - } - } - } +/// `n` with `f` applied to its subtree's paints, or `None` when nothing changed (then nothing was +/// copied). Also returns the number of changed paints. +fn map_node(n: &Node, f: &mut PaintFn) -> Option<(Node, usize)> { + // `f` gives each own paint's replacement first, so unchanged nodes are never cloned. + let changes: Vec<(usize, Paint)> = node_paints(n).enumerate().filter_map(|(i, p)| f(p).map(|q| (i, q))).collect(); let mut count = changes.len(); let mut out: Option<Node> = None; if !changes.is_empty() { @@ -366,15 +433,29 @@ fn map_node(n: &Node, f: &mut LinkFn) -> Option<(Node, usize)> { 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; - } + k += usize::from(replace_paint(p, f)); } if k > 0 { out.get_or_insert_with(|| n.clone()).extras_mut().symbol_overrides = overrides; count += k; } } + // A graph's series and label paints, which its marks and labels take when it is drawn again. + let graph: Vec<(usize, Paint)> = graph_paints(n).enumerate().filter_map(|(i, p)| f(p).map(|q| (i, q))).collect(); + if !graph.is_empty() { + count += graph.len(); + let m = out.get_or_insert_with(|| n.clone()); + if let Some(spec) = m.extras_if_any().and_then(|e| e.graph.as_deref_mut()) { + let mut graph = graph.into_iter().peekable(); + for (i, p) in graph_paints_mut(spec).enumerate() { + if graph.peek().is_some_and(|c| c.0 == i) + && let Some((_, q)) = graph.next() + { + *p = q; + } + } + } + } if let Some(ch) = n.children() { for (i, c) in ch.iter().enumerate() { if let Some((new, k)) = map_node(c, f) { @@ -415,6 +496,13 @@ pub fn walk_with_masks<'a>(n: &'a Node, f: &mut dyn FnMut(&'a Node)) { /// brush: `f` applied to the linkable colors of `n` and its subtree (opacity masks included). Only /// the nodes holding a changed paint are copied. Returns the number of changed paints. pub fn map_node_solid_paints(n: &mut Node, f: &mut LinkFn) -> usize { + map_node_paints(n, &mut relink(f)) +} + +/// [`Document::map_paints`] for art a document keeps outside its trees, such as the art of a brush: +/// `f` applied to every paint of `n` and its subtree (opacity masks included). Only the nodes +/// holding a changed paint are copied. Returns the number of changed paints. +pub fn map_node_paints(n: &mut Node, f: &mut PaintFn) -> usize { match map_node(n, f) { Some((new, count)) => { *n = new; @@ -424,7 +512,7 @@ pub fn map_node_solid_paints(n: &mut Node, f: &mut LinkFn) -> usize { } } -fn map_tree(n: &mut Arc<Node>, f: &mut LinkFn) -> usize { +fn map_tree(n: &mut Arc<Node>, f: &mut PaintFn) -> usize { match map_node(n, f) { Some((new, count)) => { *n = Arc::new(new); @@ -434,7 +522,7 @@ fn map_tree(n: &mut Arc<Node>, f: &mut LinkFn) -> usize { } } -fn map_trees(v: &mut [Arc<Node>], f: &mut LinkFn) -> usize { +fn map_trees(v: &mut [Arc<Node>], f: &mut PaintFn) -> usize { v.iter_mut().map(|n| map_tree(n, f)).sum() } @@ -593,6 +681,35 @@ mod tests { assert_eq!(map_node_solid_paints(&mut loose, &mut to_blue), 0, "nothing left to change"); } + #[test] + fn mapping_reaches_the_series_and_label_paints_a_graph_keeps() { + let (mut d, a, _) = doc(); + let red = linked(Color::rgb(1.0, 0.0, 0.0), "Brand"); + let spec = crate::graph::GraphSpec { + series_paints: vec![crate::SeriesPaint { fill: Some(red.clone()), stroke: Some(red.clone()), ..Default::default() }], + label_styles: crate::graph::LabelStyles { + legend: Some(crate::CharStyle { fill: red.clone(), stroke: Paint::None, ..Default::default() }), + ..Default::default() + }, + ..Default::default() + }; + d.node_mut(a).unwrap().extras_mut().graph = Some(Box::new(spec)); + let mut seen = 0; + d.visit_paints(&mut |p| seen += usize::from(*p == red)); + assert_eq!(seen, 4, "the fill and the graph's series fill, series stroke and legend fill"); + let blue = Color::rgb(0.0, 0.0, 1.0); + let mut to_blue = |c: &mut Color, s: &mut Option<String>, _: &mut f32| s.as_deref() == Some("Brand") && std::mem::replace(c, blue) != blue; + assert_eq!(d.map_solid_paints(&mut to_blue), 4); + let g = d.node(a).unwrap().extras().graph.clone().unwrap(); + assert_eq!(g.series_paints[0].fill, Some(linked(blue, "Brand"))); + assert_eq!(g.series_paints[0].stroke, Some(linked(blue, "Brand"))); + let legend = g.label_styles.legend.unwrap(); + assert_eq!((legend.fill, legend.stroke), (linked(blue, "Brand"), Paint::None)); + let mut cleared = |p: &Paint| (*p == linked(blue, "Brand")).then_some(Paint::None); + assert_eq!(d.map_paints(&mut cleared), 4, "the fill and the graph's three"); + assert!(graph_paints(d.node(a).unwrap()).all(Paint::is_none)); + } + #[test] fn mapping_within_ids_visits_each_paint_once() { let (mut d, a, b) = doc(); diff --git a/crates/doc/src/symbol_nine_slice.rs b/crates/doc/src/symbol_nine_slice.rs index 6949aa86fb..53f84e869c 100644 --- a/crates/doc/src/symbol_nine_slice.rs +++ b/crates/doc/src/symbol_nine_slice.rs @@ -10,9 +10,19 @@ //! The cells are sized along the symbol's own axes, and the instance's rotation, shear, reflection //! and position then apply to them. //! -//! The guides are stored as fractions (0..1) of the symbol's natural size, measured from the left -//! and top edges and from the right and bottom edges, so they survive resizing the art. Stored -//! under [`SYMBOL_NINE_SLICE`] keyed by symbol name; symbols without 9-slice have no entry. +//! A guide may lie outside the art, and the instance still scales, by the slices the art falls in +//! ([the help page](https://help.adobe.com/archive/en/illustrator/cs6/illustrator_reference.pdf), +//! Use 9-slice scaling section). VectorCraft's own rules for that: a guide past an edge of the art +//! cuts the art at that edge, so the outer cell on its side holds no art; with both guides of an +//! axis past opposite edges the art scales as a whole along it; with both past the same edge the +//! art lies in the outer cell at the other edge and keeps its size, from that edge of the instance, +//! or shrinks to the instance's width or height when the instance is smaller than the art. +//! +//! The guides are stored as fractions of the symbol's natural size, measured from the left and top +//! edges and from the right and bottom edges, so they survive resizing the art. A fraction below 0 +//! puts a guide past its own edge, and one above 1 past the opposite edge; each lies within +//! ±[`MAX_GUIDE_FRACTION`], and the two guides of an axis keep their order. Stored under +//! [`SYMBOL_NINE_SLICE`] keyed by symbol name; symbols without 9-slice have no entry. //! //! [`NineSliceMap`] places such an instance's art for the canvas, bounds, Break Link, Expand and //! the exporters ([`Document::place_symbol_art`]). @@ -49,11 +59,16 @@ impl Default for SymbolNineSlice { } } +/// The farthest a guide may lie from its edge, as a fraction of the symbol's width or height, in +/// either direction (VectorCraft's own rule). +pub const MAX_GUIDE_FRACTION: f64 = 16.0; + impl SymbolNineSlice { - /// Guides from `[left, top, right, bottom]`; `None` unless each is finite, within 0..1, and the - /// two on each axis leave a gap between them. + /// Guides from `[left, top, right, bottom]`; `None` unless each is finite and within + /// ±[`MAX_GUIDE_FRACTION`], and the two on each axis leave a gap between them + /// (`left + right < 1`, `top + bottom < 1`). pub fn new(left: f64, top: f64, right: f64, bottom: f64) -> Option<Self> { - let ok = |v: f64| v.is_finite() && (0.0..=1.0).contains(&v); + let ok = |v: f64| v.is_finite() && (-MAX_GUIDE_FRACTION..=MAX_GUIDE_FRACTION).contains(&v); (ok(left) && ok(top) && ok(right) && ok(bottom) && left + right < 1.0 && top + bottom < 1.0).then_some(Self { left, top, right, bottom }) } @@ -102,7 +117,8 @@ pub struct EditedNineSlice { } impl EditedNineSlice { - /// Guide `g` as a line across the art's box, from one edge to the other, in the document. + /// Guide `g` as a line across the art's box, from one edge to the other, in the document. A + /// guide outside the art spans the art's height or width beside it. pub fn line(&self, g: NineSliceGuide) -> (Point, Point) { let (b, s) = (self.art, self.guides); let (a, c) = match g { @@ -126,14 +142,17 @@ impl EditedNineSlice { }) } - /// The guides with guide `g` moved across its axis to document point `p`. The guide stays - /// within the art's box, and [`MIN_CENTER_BAND`] short of the opposite guide, or where it is - /// when the guides are already closer than that. A point that is not finite leaves the guides - /// as they are. + /// The guides with guide `g` moved across its axis to document point `p`. The guide may pass + /// either edge of the art, up to [`MAX_GUIDE_FRACTION`] from its own edge, and stops + /// [`MIN_CENTER_BAND`] short of the opposite guide, or where it is when the guides are already + /// closer than that. A point that is not finite, or that gives a fraction that is not, leaves + /// the guides as they are. pub fn moved(&self, g: NineSliceGuide, p: Point) -> SymbolNineSlice { let (b, mut out) = (self.art, self.guides); let q = self.to_doc.inverse() * p; - let fit = |v: f64, other: f64, now: f64| if v.is_finite() { v.clamp(0.0, (1.0 - other - MIN_CENTER_BAND).max(now)) } else { now }; + let fit = |v: f64, other: f64, now: f64| { + if v.is_finite() { v.clamp(-MAX_GUIDE_FRACTION, (1.0 - other - MIN_CENTER_BAND).min(MAX_GUIDE_FRACTION).max(now)) } else { now } + }; match g { NineSliceGuide::Left => out.left = fit((q.x - b.x0) / b.width(), out.right, out.left), NineSliceGuide::Right => out.right = fit((b.x1 - q.x) / b.width(), out.left, out.right), @@ -181,20 +200,27 @@ const MAX_SLICE_DEPTH: u32 = 64; /// One axis of a 9-slice map: the three cells between the cuts and where each one goes. #[derive(Clone, Copy, Debug, PartialEq)] struct AxisMap { - /// The cuts in the art at its natural size: its start, the two guides, its end. + /// The cuts in the art at its natural size: its start, the two guides, its end. A guide + /// outside the art cuts it at the nearer end, so a cell can be empty. src: [f64; 4], /// Where the cuts go. The outer cells keep their length unless the scaled length is shorter - /// than both together; then both shrink in proportion and the middle cell is empty. + /// than both together; then both shrink in proportion and the middle cell is empty. An empty + /// cell's start is where the cell before it ends, so the map stays continuous. dst: [f64; 4], } impl AxisMap { - /// The axis from `lo` to `hi` with guides `near` and `far` (fractions of its length in from - /// each end), scaled by `k` (above 0). + /// The axis from `lo` to `hi` (`lo < hi`) with guides `near` and `far` (fractions of its + /// length in from each end, `near + far < 1`; either may lie past an end), scaled by `k` + /// (above 0). With both guides past the far end the art keeps its length from the scaled + /// start, and with both past the near end it keeps its length up to the scaled end; when the + /// scaled length is shorter than the art, the art shrinks to the scaled length. fn new(lo: f64, hi: f64, near: f64, far: f64, k: f64) -> Self { let len = hi - lo; - let (a, b) = (near * len, far * len); - let src = [lo, lo + a, hi - b, hi]; + let c1 = (lo + near * len).clamp(lo, hi); + let c2 = (hi - far * len).clamp(c1, hi); + let src = [lo, c1, c2, hi]; + let (a, b) = (c1 - lo, hi - c2); let (t0, t3) = (k * lo, k * hi); let room = t3 - t0; let (a, b) = if a + b <= room { @@ -203,9 +229,15 @@ impl AxisMap { let f = (room / (a + b)).max(0.0); (a * f, b * f) }; - let t1 = t0 + a; - let t2 = (t3 - b).max(t1); - Self { src, dst: [t0, t1, t2, t3] } + let dst = if c2 > c1 { + let t1 = t0 + a; + [t0, t1, (t3 - b).max(t1), t3] + } else if a > 0.0 { + [t0, t0 + a, t0 + a, t3] + } else { + [t3 - b, t3 - b, t3 - b, t3] + }; + Self { src, dst } } /// The cell `v` lies in; values outside the art belong to the outer cells. @@ -279,10 +311,11 @@ pub struct NineSliceMap { impl NineSliceMap { /// The map for an instance placed by `xf` that shows art with natural-size transform - /// `natural` and geometric bounds `art` (in symbol space). `None` when the art or the - /// transform is degenerate, or when the instance is at its natural size on both axes (then - /// `xf` places the art as it is). + /// `natural` and geometric bounds `art` (in symbol space). `None` when the guides are not ones + /// [`SymbolNineSlice::new`] accepts, when the art or the transform is degenerate, or when the + /// instance is at its natural size on both axes (then `xf` places the art as it is). pub fn new(guides: SymbolNineSlice, art: Rect, natural: Affine, xf: Affine) -> Option<Self> { + let guides = SymbolNineSlice::new(guides.left, guides.top, guides.right, guides.bottom)?; let b = natural.transform_rect_bbox(art); if ![b.x0, b.y0, b.x1, b.y1].into_iter().all(f64::is_finite) || b.width() <= 1e-9 || b.height() <= 1e-9 { return None; @@ -894,6 +927,113 @@ mod tests { assert!(got.iter().all(|b| finite(*b)), "{got:?}"); } + /// Guides may lie outside the art, up to 16 times its size from their edge, as long as the + /// two on each axis keep their order; values that are not finite are refused. + #[test] + fn guides_outside_the_art_are_accepted_in_order_and_within_the_limit() { + let ok = |l, t, r, b| SymbolNineSlice::new(l, t, r, b).is_some(); + assert!(ok(-0.25, 0.25, 0.25, 0.25)); + assert!(ok(1.25, 0.25, -0.5, 0.25), "both past the right edge"); + assert!(ok(0.25, -16.0, 0.25, 16.0) && ok(-16.0, 0.25, -16.0, 0.25)); + assert!(!ok(-16.5, 0.25, 0.25, 0.25) && !ok(0.25, 0.25, 0.25, 17.0)); + assert!(!ok(f64::NAN, 0.25, 0.25, 0.25) && !ok(0.25, f64::INFINITY, 0.25, 0.25) && !ok(0.25, 0.25, f64::NEG_INFINITY, 0.25)); + assert!(!ok(1.2, 0.25, -0.2, 0.25), "the left guide on the right one"); + assert!(!ok(0.25, 0.6, 0.25, 0.6), "crossed"); + let g = SymbolNineSlice::from_value(&json!([-0.25, 1.5, 0.5, -1.0])).unwrap(); + assert_eq!(g, SymbolNineSlice { left: -0.25, top: 1.5, right: 0.5, bottom: -1.0 }); + assert_eq!(SymbolNineSlice::from_value(&g.to_value()), Some(g)); + assert!(SymbolNineSlice::from_value(&json!([-0.25, 0.1, 1.5])).is_none()); + assert!(SymbolNineSlice::from_value(&json!([-20.0, 0.1, 0.5, 0.1])).is_none()); + // Guides built without the check are not used to place art. + let bad = SymbolNineSlice { left: f64::NAN, ..SymbolNineSlice::default() }; + assert!(NineSliceMap::new(bad, Rect::new(0.0, 0.0, 100.0, 100.0), Affine::IDENTITY, Affine::scale(2.0)).is_none()); + // Art without width or height has no map, whatever the guides. + let out = SymbolNineSlice::new(-0.25, 1.25, 0.25, -0.5).unwrap(); + for art in [Rect::new(0.0, 0.0, 0.0, 100.0), Rect::new(0.0, 0.0, 100.0, 0.0)] { + assert!(NineSliceMap::new(out, art, Affine::IDENTITY, Affine::scale(2.0)).is_none(), "{art:?}"); + } + } + + /// At 200 × 150, a left guide 25 % outside the art leaves the art in the center and right + /// columns: the left column holds no art, the center one (0..75) stretches to 0..175 and the + /// right one keeps its 25. Both guides outside on opposite sides scale the art as a whole on + /// that axis; both past the same side keep the art at its size in the outer cell at the other + /// side, from that side of the instance. + #[test] + fn art_scales_by_the_cells_it_falls_in_when_guides_lie_outside_it() { + let xf = Affine::scale_non_uniform(2.0, 1.5); + let d = markers(SymbolNineSlice::new(-0.25, 0.25, 0.25, 0.25)); + let got = boxes(&d, xf); + let k = 175.0 / 75.0; + assert!(near(got[0], Rect::new(0.0, 0.0, 200.0, 150.0)), "{:?}", got[0]); + assert!(near(got[1], Rect::new(0.0, 0.0, 10.0 * k, 10.0)), "the top-left square stretches: {:?}", got[1]); + assert!(near(got[2], Rect::new(190.0, 0.0, 200.0, 10.0)), "the top-right corner keeps its size: {:?}", got[2]); + assert!(near(got[5], Rect::new(45.0 * k, 65.0, 55.0 * k, 85.0)), "{:?}", got[5]); + // Both vertical guides outside, on opposite sides: the art scales as a whole across. + let d = markers(SymbolNineSlice::new(-0.25, 0.25, -1.0, 0.25)); + let got = boxes(&d, xf); + assert!(near(got[1], Rect::new(0.0, 0.0, 20.0, 10.0)) && near(got[2], Rect::new(180.0, 0.0, 200.0, 10.0)), "{got:?}"); + assert!(near(got[5], Rect::new(90.0, 65.0, 110.0, 85.0)), "{:?}", got[5]); + // Both past the right edge: the art keeps its width from the instance's left edge. + let d = markers(SymbolNineSlice::new(1.2, 0.25, -0.5, 0.25)); + let got = boxes(&d, xf); + assert!(near(got[0], Rect::new(0.0, 0.0, 100.0, 150.0)), "{:?}", got[0]); + assert!(near(got[2], Rect::new(90.0, 0.0, 100.0, 10.0)) && near(got[5], Rect::new(45.0, 65.0, 55.0, 85.0)), "{got:?}"); + // Both past the left edge: the art keeps its width up to the instance's right edge. + let d = markers(SymbolNineSlice::new(-0.5, 0.25, 1.2, 0.25)); + let got = boxes(&d, xf); + assert!(near(got[0], Rect::new(100.0, 0.0, 200.0, 150.0)), "{:?}", got[0]); + assert!(near(got[1], Rect::new(100.0, 0.0, 110.0, 10.0)), "{:?}", got[1]); + // The same rules apply to rows: both horizontal guides above the art keep its height up to + // the instance's bottom edge. + let d = markers(SymbolNineSlice::new(0.25, -0.5, 0.25, 1.2)); + let got = boxes(&d, xf); + assert!(near(got[0], Rect::new(0.0, 50.0, 200.0, 150.0)), "{:?}", got[0]); + assert!(near(got[3], Rect::new(0.0, 140.0, 10.0, 150.0)), "{:?}", got[3]); + // Smaller than the art, an art-covered outer cell shrinks in proportion. + let d = markers(SymbolNineSlice::new(1.2, 0.25, -0.5, 0.25)); + let got = boxes(&d, Affine::scale_non_uniform(0.5, 1.5)); + assert!(near(got[0], Rect::new(0.0, 0.0, 50.0, 150.0)) && near(got[1], Rect::new(0.0, 0.0, 5.0, 10.0)), "{got:?}"); + } + + /// With guides outside the art, the map stays finite, never runs backward, and does not jump + /// at the art's edges or at the guides; objects keep to the cells that hold art. + #[test] + fn the_map_with_guides_outside_the_art_is_continuous_and_monotone() { + let cases = [(-0.25, 0.25), (-0.25, -1.0), (1.2, -0.5), (-0.5, 1.2), (0.0, -16.0), (-16.0, 16.0), (0.25, 0.25)]; + for (l, r) in cases { + let d = markers(SymbolNineSlice::new(l, 0.25, r, 0.25)); + for sx in [0.3, 2.0, 1e6] { + let m = d.symbol_slice_map("S", Affine::scale_non_uniform(sx, 1.5)).unwrap(); + let at = |x: f64| m.map_point(Point::new(x, 40.0)).x; + let mut last = f64::NEG_INFINITY; + for i in 0..=1200 { + let x = -10.0 + i as f64 * 0.1; + let v = at(x); + assert!(v.is_finite() && v >= last - 1e-12 * last.abs().max(1.0), "{l} {r} {sx}: {x} → {v} after {last}"); + last = v; + } + for edge in [0.0, 75.0, 100.0] { + let jump = (at(edge + 1e-9) - at(edge - 1e-9)).abs(); + assert!(jump < 1e-6 * sx.max(1.0), "{l} {r} {sx}: a jump of {jump} at {edge}"); + } + } + } + // A gradient bar across the art with the left guide outside is drawn in the two columns + // that hold art, not three. + let mut d = markers(SymbolNineSlice::new(-0.25, 0.25, 0.25, 0.25)); + let gradient = Paint::Gradient(Box::new(GradientPaint::new(Gradient::default()))); + let bar = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 40.0, 100.0, 60.0)), Appearance::basic(gradient, Paint::None, 0.0)); + let m = d.symbol_slice_map("S", Affine::scale_non_uniform(2.0, 1.5)).unwrap(); + assert_eq!(m.place(&bar, &d).children().map(Vec::len), Some(2)); + assert_eq!(m.most_placed(&bar, &d), 7); + // With both guides outside on opposite sides, the bar lies in one cell and is moved whole. + let d = markers(SymbolNineSlice::new(-0.25, 0.25, -0.25, 0.25)); + let m = d.symbol_slice_map("S", Affine::scale_non_uniform(2.0, 1.5)).unwrap(); + assert!(matches!(m.place(&bar, &d).kind, NodeKind::Path { .. })); + assert_eq!(m.most_placed(&bar, &d), 1); + } + /// A negative scale reflects the sized cells; a rotation turns them, the corners keeping /// their size along the symbol's own axes. #[test] @@ -1456,27 +1596,37 @@ mod tests { assert!(d.edited_nine_slice().is_none()); } - /// Moving a guide changes that guide alone, follows the pointer across its axis only, stays - /// within the art's box and stops short of the opposite guide. + /// Moving a guide changes that guide alone, follows the pointer across its axis only, may pass + /// either edge of the art up to [`MAX_GUIDE_FRACTION`], and stops short of the opposite guide. #[test] - fn a_moved_guide_stays_in_the_art_and_short_of_the_opposite_guide() { + fn a_moved_guide_passes_the_arts_edges_and_stops_short_of_the_opposite_guide() { let xf = Affine::translate((10.0, 20.0)) * Affine::scale(2.0); let e = editing(Some(SymbolNineSlice::default()), xf).edited_nine_slice().unwrap(); let q = SymbolNineSlice { left: 0.25, top: 0.25, right: 0.25, bottom: 0.25 }; assert_eq!(e.moved(NineSliceGuide::Left, Point::new(30.0, 999.0)), SymbolNineSlice { left: 0.1, ..q }); assert_eq!(e.moved(NineSliceGuide::Bottom, Point::new(-50.0, 180.0)), SymbolNineSlice { bottom: 0.2, ..q }); - assert_eq!(e.moved(NineSliceGuide::Top, Point::new(0.0, -500.0)), SymbolNineSlice { top: 0.0, ..q }); - assert_eq!(e.moved(NineSliceGuide::Right, Point::new(1e6, 0.0)), SymbolNineSlice { right: 0.0, ..q }); + // Past the art's near edges: the art spans 10..210 across and 20..220 down. + assert_eq!(e.moved(NineSliceGuide::Left, Point::new(-40.0, 50.0)), SymbolNineSlice { left: -0.25, ..q }); + assert_eq!(e.moved(NineSliceGuide::Top, Point::new(0.0, -500.0)), SymbolNineSlice { top: -2.6, ..q }); + assert_eq!(e.moved(NineSliceGuide::Right, Point::new(1e6, 0.0)), SymbolNineSlice { right: -MAX_GUIDE_FRACTION, ..q }); + assert_eq!(e.moved(NineSliceGuide::Left, Point::new(-1e300, 0.0)), SymbolNineSlice { left: -MAX_GUIDE_FRACTION, ..q }); let crossed = e.moved(NineSliceGuide::Left, Point::new(200.0, 50.0)); assert!((crossed.left - (0.75 - MIN_CENTER_BAND)).abs() < 1e-12, "{crossed:?}"); assert!(SymbolNineSlice::new(crossed.left, crossed.top, crossed.right, crossed.bottom).is_some()); assert_eq!(e.moved(NineSliceGuide::Top, Point::new(f64::NAN, f64::NAN)), q); + assert_eq!(e.moved(NineSliceGuide::Top, Point::new(0.0, f64::INFINITY)), q); + // With the right guide past the art's right edge, the left one may pass that edge too. + let wide = SymbolNineSlice { right: -0.5, ..q }; + let e = editing(Some(wide), xf).edited_nine_slice().unwrap(); + assert_eq!(e.moved(NineSliceGuide::Left, Point::new(260.0, 50.0)), SymbolNineSlice { left: 1.25, ..wide }); + assert!(near_point(e.line(NineSliceGuide::Right).0, Point::new(310.0, 20.0))); + assert!(near_point(e.line(NineSliceGuide::Right).1, Point::new(310.0, 220.0))); // Saved guides closer than the minimum center band keep their place when a drag does not // move them closer. let narrow = SymbolNineSlice::new(0.00005, 0.25, 0.9999, 0.25).unwrap(); let e = editing(Some(narrow), xf).edited_nine_slice().unwrap(); assert_eq!(e.moved(NineSliceGuide::Left, Point::new(200.0, 50.0)), narrow); - assert_eq!(e.moved(NineSliceGuide::Left, Point::new(0.0, 50.0)), SymbolNineSlice { left: 0.0, ..narrow }); + assert_eq!(e.moved(NineSliceGuide::Left, Point::new(0.0, 50.0)), SymbolNineSlice { left: -0.05, ..narrow }); // A mirrored placement measures along the symbol's own axes. let e = editing(Some(SymbolNineSlice::default()), Affine::scale_non_uniform(-1.0, 1.0)).edited_nine_slice().unwrap(); assert!(near_point(e.line(NineSliceGuide::Left).0, Point::new(-25.0, 0.0))); diff --git a/crates/doc/src/symbols.rs b/crates/doc/src/symbols.rs index 2cf260cbec..dde6621993 100644 --- a/crates/doc/src/symbols.rs +++ b/crates/doc/src/symbols.rs @@ -87,6 +87,8 @@ pub struct SymbolBoxes<'a> { sliced_placed: Cell<u64>, /// The most objects of symbol art [`Self::sliced_visual`] places: [`MAX_SYMBOL_NODES`]. sliced_most: u64, + /// The widths [`Self::measured_width`] has measured, by kind and symbol name. + widths: RefCell<HashMap<(&'static str, String), Option<f64>>>, } impl Document { @@ -107,6 +109,7 @@ impl Document { sliced: RefCell::default(), sliced_placed: Cell::new(0), sliced_most: MAX_SYMBOL_NODES, + widths: RefCell::default(), } } } @@ -247,6 +250,18 @@ impl<'a> SymbolBoxes<'a> { self.art(name)?.brush } + /// The width `measure` gives for the symbol named `name`, measured once for these boxes for each + /// `kind`, which names what `measure` measures. `measure` may call this again for other names. + pub fn measured_width(&self, kind: &'static str, name: &str, measure: impl FnOnce() -> Option<f64>) -> Option<f64> { + let key = (kind, name.to_string()); + if let Some(w) = self.widths.borrow().get(&key) { + return *w; + } + let w = measure(); + self.widths.borrow_mut().insert(key, w); + w + } + /// How far the visual box of an instance of the symbol named `name` grows in boxes made by /// [`Self::with_brush_art`]: `16 × max(w, 1) + 8` for the widest stroke `w` that /// [`Self::brush_width`] finds, as far as the renderer grows the cull bounds of a brushed path diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index 05f9c29041..d69da9bae2 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -17,7 +17,7 @@ mod wrap; pub use area::{AreaFit, AreaOptions, PathAlign, PathEffect, TextFlow, TextWrap, VerticalAlign, WrapShape}; use char_style::yes; -pub use char_style::{CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, ScriptMetrics}; +pub use char_style::{CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, MAX_AKI, ScriptMetrics}; pub use composite::{ COMPOSITE_BASELINE, COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, COMPOSITE_SCALE, COMPOSITE_SIZE, CharClass, CompositeFont, CompositePart, CompositeParts, @@ -52,7 +52,7 @@ pub struct TextObject { /// the object, so the runs (and their styles) stay the text itself. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub ruby: Vec<RubySpan>, - #[serde(default)] + #[serde(default = "ParaStyle::omitted")] pub para: ParaStyle, /// Per-paragraph attributes (see the type's docs); empty = every paragraph uses `para`. #[serde(default, skip_serializing_if = "Vec::is_empty")] diff --git a/crates/doc/src/text/char_style.rs b/crates/doc/src/text/char_style.rs index fd828c79af..a880a2a2bc 100644 --- a/crates/doc/src/text/char_style.rs +++ b/crates/doc/src/text/char_style.rs @@ -28,6 +28,22 @@ pub struct CharStyle { /// Manual pair spacing in 1/1000 em, as [`Self::tracking`]; None uses the automatic mode. #[serde(default, skip_serializing_if = "Option::is_none")] pub kerning: Option<f64>, + /// Space before the character in 1/1000 em, as [`Self::kerning`], when it starts a line by + /// itself: the first character of the text, of a paragraph, or after a forced line break. The + /// Type tool's caret before such a character kerns with it (#5111), since there is no character + /// before it whose [`Self::kerning`] could space it. Elsewhere it has no effect. + #[serde(default, rename = "kerningBefore", skip_serializing_if = "crate::skip::is_default")] + pub kerning_before: f64, + /// Insert Aki Left (Character panel, East Asian options): space added before the character in + /// reading order, in 1/1000 em as [`Self::tracking`], 0 to 1000. Before is on the left in + /// left-to-right type, on the right in right-to-left type and above in vertical type. A + /// cluster takes the value of its first character, and full justification leaves it as it is. + /// <https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html> + #[serde(default, rename = "akiLeft", skip_serializing_if = "crate::skip::is_default")] + pub aki_left: f64, + /// Insert Aki Right: space added after the character in reading order, as [`Self::aki_left`]. + #[serde(default, rename = "akiRight", skip_serializing_if = "crate::skip::is_default")] + pub aki_right: f64, /// Use glyph shapes for automatic pair spacing; false uses font metrics. #[serde(default, rename = "opticalKerning", skip_serializing_if = "crate::skip::is_default")] pub optical_kerning: bool, @@ -51,7 +67,9 @@ pub struct CharStyle { #[serde(default)] pub all_caps: bool, /// OpenType features that differ from the defaults (OpenType panel), as tags: `"dlig"` turns - /// a feature on, `"-liga"` off. + /// a feature on, `"-liga"` off, and `"salt=2"` turns a feature with alternates on at the font's + /// alternate number 2 (the value the shaper gets; a plain `"salt"` is value 1). Runs that + /// differ only in this list are shaped together, each with its own features. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub features: Vec<String>, /// Character style (Character Styles panel) these attributes come from; None = Normal. @@ -396,6 +414,9 @@ fn hundred() -> f64 { 100.0 } +/// The largest Insert Aki Left or Right ([`CharStyle::aki_left`]), in 1/1000 em: one em. +pub const MAX_AKI: f64 = 1000.0; + pub(super) fn yes() -> bool { true } @@ -411,6 +432,9 @@ impl Default for CharStyle { leading: None, tracking: 0.0, kerning: None, + kerning_before: 0.0, + aki_left: 0.0, + aki_right: 0.0, optical_kerning: false, baseline_shift: 0.0, h_scale: 100.0, @@ -459,7 +483,8 @@ impl CharStyle { /// becomes Auto, and a value past [`crate::MAX_COORD`] (a baseline shift past it either way) /// becomes the nearer end. A leading of 0, which legacy `.ai` import stores, stays, and a /// baseline shift that is not a number becomes 0. The Tate-chu-yoko Up/Down and Left/Right - /// offsets are kept as the baseline shift is. + /// offsets are kept as the baseline shift is. Insert Aki Left and Right are kept from 0 to + /// [`MAX_AKI`], and one that is not a number becomes 0. pub fn keep_dimensions_in_range(&mut self) { let default = Self::default(); let within = |v: f64, or: f64| if v > 0.0 { v.min(crate::MAX_COORD) } else { or }; @@ -471,6 +496,9 @@ impl CharStyle { self.baseline_shift = shift(self.baseline_shift); self.tcy_up_down = shift(self.tcy_up_down); self.tcy_left_right = shift(self.tcy_left_right); + let aki = |v: f64| if v.is_nan() { 0.0 } else { v.clamp(0.0, MAX_AKI) }; + self.aki_left = aki(self.aki_left); + self.aki_right = aki(self.aki_right); } /// Do the characters draw a stroke (a paint and a positive weight)? pub fn has_stroke(&self) -> bool { diff --git a/crates/doc/src/text/object.rs b/crates/doc/src/text/object.rs index d46b45b1f7..68f41abd5b 100644 --- a/crates/doc/src/text/object.rs +++ b/crates/doc/src/text/object.rs @@ -490,6 +490,8 @@ impl crate::Document { st.baseline_shift = num("baseline_shift").unwrap_or(st.baseline_shift); st.tcy_up_down = num("tcyUpDown").unwrap_or(st.tcy_up_down); st.tcy_left_right = num("tcyLeftRight").unwrap_or(st.tcy_left_right); + st.aki_left = num("akiLeft").unwrap_or(st.aki_left); + st.aki_right = num("akiRight").unwrap_or(st.aki_right); st.keep_dimensions_in_range(); let kept = [ ("size", Some(st.size)), @@ -498,6 +500,8 @@ impl crate::Document { ("baseline_shift", Some(st.baseline_shift)), ("tcyUpDown", Some(st.tcy_up_down)), ("tcyLeftRight", Some(st.tcy_left_right)), + ("akiLeft", Some(st.aki_left)), + ("akiRight", Some(st.aki_right)), ("leading", st.leading), ]; for (k, v) in kept { diff --git a/crates/doc/src/text/para_style.rs b/crates/doc/src/text/para_style.rs index f23de1d41f..45cf181f18 100644 --- a/crates/doc/src/text/para_style.rs +++ b/crates/doc/src/text/para_style.rs @@ -237,6 +237,10 @@ pub struct ParaStyle { /// Kinsoku Shori Type (Paragraph panel menu): how a line keeps those characters off its start /// and end, by pushing them in onto the line or out to the next one. No effect without kinsoku. pub kinsoku_type: KinsokuShoriType, + /// Bunri-Kinshi (Paragraph panel menu): a line never breaks inside an inseparable pair (two em + /// dashes, two ellipses, two two-dot leaders, a vertical kana repeat mark's two halves). Kept + /// with kinsoku None, where it has no effect. Off by default. + pub bunri_kinshi: bool, /// Roman Hanging Punctuation (Paragraph panel menu): quotation marks, hyphens, full stops and /// commas starting or ending a line hang outside the margin, and asterisks, tildes, ellipses, /// dashes, colons and semicolons hang by half. East Asian punctuation hangs by burasagari. @@ -244,9 +248,21 @@ pub struct ParaStyle { /// Insert Kashidas (Paragraph panel): justified lines lengthen their Arabic words with /// kashidas before they widen their word spaces. pub kashida: Kashida, + /// Korean Line Break Anywhere (Paragraph panel menu): a line may break between any two Hangul + /// syllables. Off, a Korean word (the characters between spaces, when any of them is Hangul) + /// breaks only at its spaces and punctuation, or where it is wider than the line. New type and + /// imported text have it off; paragraphs saved before it existed open with it on, the line + /// breaks they were laid out with. + pub korean_line_break_anywhere: bool, } impl ParaStyle { + /// The attributes a text object saved without `para` reads with: the defaults, with Korean + /// Line Break Anywhere on, as a saved paragraph without that field reads. + pub(crate) fn omitted() -> Self { + Self { korean_line_break_anywhere: true, ..Self::default() } + } + /// Keeps the indents and the space before and after to -[`crate::MAX_COORD`] to /// [`crate::MAX_COORD`], and the tab stop positions to 0 to 100,000 pt, the range /// `text.tabs.set` takes. A value outside its range becomes the nearer end, and one that is @@ -327,9 +343,15 @@ struct ParaStyleFile { #[serde(default, skip_serializing_if = "crate::skip::is_default")] kinsoku_type: KinsokuShoriType, #[serde(default, skip_serializing_if = "crate::skip::is_default")] + bunri_kinshi: bool, + #[serde(default, skip_serializing_if = "crate::skip::is_default")] roman_hanging: bool, #[serde(default, skip_serializing_if = "crate::skip::is_default")] kashida: Kashida, + /// Written only when off: a paragraph saved without it was laid out breaking between Hangul + /// syllables. + #[serde(default = "crate::yes", skip_serializing_if = "crate::skip::is_true")] + korean_line_break_anywhere: bool, } impl From<ParaStyle> for ParaStyleFile { @@ -359,8 +381,10 @@ impl From<ParaStyle> for ParaStyleFile { burasagari, kinsoku, kinsoku_type, + bunri_kinshi, roman_hanging, kashida, + korean_line_break_anywhere, .. } = p; Self { @@ -384,8 +408,10 @@ impl From<ParaStyle> for ParaStyleFile { burasagari, kinsoku, kinsoku_type, + bunri_kinshi, roman_hanging, kashida, + korean_line_break_anywhere, } } } @@ -413,8 +439,10 @@ impl From<ParaStyleFile> for ParaStyle { burasagari, kinsoku, kinsoku_type, + bunri_kinshi, roman_hanging, kashida, + korean_line_break_anywhere, .. } = f; Self { @@ -437,8 +465,10 @@ impl From<ParaStyleFile> for ParaStyle { burasagari, kinsoku, kinsoku_type, + bunri_kinshi, roman_hanging, kashida, + korean_line_break_anywhere, } } } @@ -478,6 +508,21 @@ pub enum Mojikumi { /// Consecutive punctuation shares one half-em space (JLREQ 3.1.4), and a closing bracket, /// comma or full stop ending a line is set half width. LineEndHalf, + /// YakumonoHankaku: every opening and closing bracket, comma and full stop is set half width, + /// a middle dot loses a quarter em on each side, and a quarter em separates Japanese and Latin + /// letters or digits. + YakumonoHankaku, + /// GyomatsuYakumonoHankaku: punctuation keeps its full width, except that an opening bracket + /// starting a line is set flush with the line's start, a closing bracket, comma or full stop + /// ending a line is set half width and a middle dot ending a line loses the quarter em after + /// it; a quarter em separates Japanese and Latin letters or digits. + GyomatsuYakumonoHankaku, + /// GyomatsuYakumonoZenkaku: punctuation keeps its full width at a line's end too; a quarter em + /// separates Japanese and Latin letters or digits. + GyomatsuYakumonoZenkaku, + /// YakumonoZenkaku: punctuation keeps its full width, with no added space between Japanese and + /// Latin text. + YakumonoZenkaku, } impl Mojikumi { diff --git a/crates/doc/src/text/tabs_lists.rs b/crates/doc/src/text/tabs_lists.rs index c4ec92b70b..4fcaa8d078 100644 --- a/crates/doc/src/text/tabs_lists.rs +++ b/crates/doc/src/text/tabs_lists.rs @@ -28,6 +28,15 @@ pub struct TabStop { pub align_on: char, } +impl TabStop { + /// The largest stop position `text.tabs.set` and a paragraph style take, in points. + pub const MAX_POSITION: f64 = 100_000.0; + /// The most leader characters a stop repeats. + pub const MAX_LEADER: usize = 8; + /// The most stops `text.tabs.set` and a paragraph style take in one list. + pub const MAX_STOPS: usize = 256; +} + fn default_align_on() -> char { '.' } @@ -348,7 +357,7 @@ impl ParaList { /// The style the marker is set in: `first` (the style of the paragraph's first character) /// without its baseline shift, rotation, superscript or subscript, tracking, manual kerning, - /// tate-chu-yoko, underline and strikethrough. + /// Insert Aki, tate-chu-yoko, underline and strikethrough. pub fn marker_style(first: &CharStyle) -> CharStyle { CharStyle { baseline_shift: 0.0, @@ -356,6 +365,9 @@ impl ParaList { position: CharPosition::Normal, tracking: 0.0, kerning: None, + kerning_before: 0.0, + aki_left: 0.0, + aki_right: 0.0, optical_kerning: first.optical_kerning, tate_chu_yoko: false, underline: false, diff --git a/crates/doc/src/text/tests.rs b/crates/doc/src/text/tests.rs index aa403b4218..0f474d2ed8 100644 --- a/crates/doc/src/text/tests.rs +++ b/crates/doc/src/text/tests.rs @@ -92,6 +92,43 @@ fn font_height_reference_is_saved_only_when_not_the_em_box() { assert_eq!(serde_json::from_value::<CharStyle>(old).unwrap().font_height_reference, FontHeightReference::EmBox); } +/// Insert Aki Left and Right are 0 by default and saved only when not 0, each side on its own; +/// styles written before them read as 0, and a value out of range from a file is kept from 0 to one +/// em. +#[test] +fn insert_aki_is_saved_only_when_set() { + let st = CharStyle::default(); + assert_eq!((st.aki_left, st.aki_right), (0.0, 0.0)); + let saved = serde_json::to_value(&st).unwrap(); + assert!(saved.get("akiLeft").is_none() && saved.get("akiRight").is_none()); + for set in [ + CharStyle { aki_left: 250.0, ..CharStyle::default() }, + CharStyle { aki_right: 500.0, ..CharStyle::default() }, + CharStyle { aki_left: 125.5, aki_right: 1000.0, ..CharStyle::default() }, + ] { + let saved = serde_json::to_value(&set).unwrap(); + assert_eq!(saved.get("akiLeft").and_then(serde_json::Value::as_f64).unwrap_or(0.0), set.aki_left); + assert_eq!(saved.get("akiRight").and_then(serde_json::Value::as_f64).unwrap_or(0.0), set.aki_right); + assert_eq!(saved.get("akiLeft").is_some(), set.aki_left != 0.0); + assert_eq!(serde_json::from_value::<CharStyle>(saved).unwrap(), set); + } + let old = serde_json::to_value(&st).unwrap(); + let read = serde_json::from_value::<CharStyle>(old).unwrap(); + assert_eq!((read.aki_left, read.aki_right), (0.0, 0.0)); + let mut damaged = CharStyle { aki_left: -20.0, aki_right: 4000.0, ..CharStyle::default() }; + damaged.keep_dimensions_in_range(); + assert_eq!((damaged.aki_left, damaged.aki_right), (0.0, MAX_AKI)); + let mut damaged = CharStyle { aki_left: f64::NAN, aki_right: f64::INFINITY, ..CharStyle::default() }; + damaged.keep_dimensions_in_range(); + assert_eq!((damaged.aki_left, damaged.aki_right), (0.0, MAX_AKI)); + // A character style from a file is kept in range the same way. + let mut d = crate::Document::new(100.0, 100.0); + let attrs = serde_json::json!({"akiLeft": 5000, "akiRight": -1}); + d.char_styles.push(TextStyleDef { name: "Spaced".into(), attrs: attrs.as_object().cloned().unwrap_or_default() }); + d.keep_type_values_in_range(); + assert_eq!((d.char_styles[0].attrs["akiLeft"].as_f64(), d.char_styles[0].attrs["akiRight"].as_f64()), (Some(MAX_AKI), Some(0.0))); +} + /// Each Indic numeral system draws 0–9 (and the Arabic-Indic sets) as the ten digits of its /// script's block; every system saves under its id, which reads back, and other names are refused. #[test] @@ -184,6 +221,29 @@ fn justification_options_read_from_a_file_stay_in_range() { assert_eq!(same, d); } +/// Korean Line Break Anywhere is off for a new paragraph and saved only when off; a paragraph +/// saved before it existed, or a text object saved without paragraph attributes, reads with it on, +/// and both values read back as saved. +#[test] +fn korean_line_break_anywhere_is_saved_only_when_off() { + let off = ParaStyle::default(); + assert!(!off.korean_line_break_anywhere); + let saved = serde_json::to_value(&off).unwrap(); + assert_eq!(saved["korean_line_break_anywhere"], false); + assert_eq!(serde_json::from_value::<ParaStyle>(saved).unwrap(), off); + let on = ParaStyle { korean_line_break_anywhere: true, ..ParaStyle::default() }; + let saved = serde_json::to_value(&on).unwrap(); + assert!(saved.get("korean_line_break_anywhere").is_none()); + assert_eq!(serde_json::from_value::<ParaStyle>(saved).unwrap(), on); + let old: ParaStyle = serde_json::from_str(r#"{"justify":"Left"}"#).unwrap(); + assert!(old.korean_line_break_anywhere); + let mut saved = serde_json::to_value(TextObject::point(Point::ZERO, "가나", CharStyle::default())).unwrap(); + assert_eq!(saved["para"]["korean_line_break_anywhere"], false); + saved.as_object_mut().unwrap().remove("para"); + let old: TextObject = serde_json::from_value(saved).unwrap(); + assert_eq!(old.para, ParaStyle { korean_line_break_anywhere: true, ..ParaStyle::default() }); +} + /// Numbered lists: each number style writes its numbers and rolls over (letters after Z, /// roman numerals in subtractive forms, zero-padded numbers past their digits), the marker adds /// a period, and the count runs through list paragraphs, skips empty and bulleted ones and diff --git a/crates/doc/tests/warp_grid_type_ink.rs b/crates/doc/tests/warp_grid_type_ink.rs new file mode 100644 index 0000000000..ae000a3f6a --- /dev/null +++ b/crates/doc/tests/warp_grid_type_ink.rs @@ -0,0 +1,49 @@ +//! A warp grid kept before type's measure is registered is built again once it is, even when the +//! registered inputs number is 0. One test in its own process, so nothing has registered the +//! measure before it runs. +// 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::live::{EnvelopeOptions, set_type_ink, warp_grid}; +use vectorcraft_doc::{CharStyle, EnvelopeKind, Node, NodeId, NodeKind, TextObject}; +use vectorcraft_geom::{Affine, Point, Rect}; + +/// A measure that gives every type the same box, well away from its laid-out box. +fn fixed_ink(_: &TextObject, _: Affine, _: Option<(vectorcraft_geom::Homography, Affine)>) -> Option<Rect> { + Some(Rect::new(0.0, 0.0, 400.0, 300.0)) +} + +fn no_inputs() -> u64 { + 0 +} + +/// An arc warp around `t`, its content in a new `Arc`. +fn warp_of(t: &TextObject) -> Node { + let content = Arc::new(Node::new(NodeId(1), NodeKind::Text(Box::new(t.clone())))); + let kind = EnvelopeKind::Warp { style: "arc".into(), bend: 50.0, h: 0.0, v: 0.0, horizontal: true, version: 1 }; + Node::new( + NodeId(2), + NodeKind::Envelope { + content: vec![content], + kind: Box::new(kind), + fidelity: 50.0, + editing: false, + options: EnvelopeOptions::NEW, + frame: Box::new(Affine::IDENTITY), + }, + ) +} + +#[test] +fn a_warp_grid_kept_before_the_type_measure_is_built_again() { + let t = TextObject::point(Point::new(100.0, 100.0), "Type", CharStyle::default()); + let n = warp_of(&t); + let before = warp_grid(&n); + set_type_ink(fixed_ink, no_inputs); + let fresh = warp_grid(&warp_of(&t)); + assert!(fresh.is_some()); + assert_ne!(fresh, before, "the registered measure moves the grid"); + assert_eq!(warp_grid(&n), fresh, "the grid kept from before the registration is built again"); +} diff --git a/crates/effects/Cargo.toml b/crates/effects/Cargo.toml index 4078312855..6d58ad9d74 100644 --- a/crates/effects/Cargo.toml +++ b/crates/effects/Cargo.toml @@ -15,6 +15,7 @@ vectorcraft-doc = { workspace = true } vectorcraft-pathops = { workspace = true } vectorcraft-text = { workspace = true } vectorcraft-plugins = { workspace = true } +vectorcraft-trace = { 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 @@ -26,3 +27,7 @@ serde_json = { workspace = true } [dev-dependencies] vectorcraft-color = { workspace = true } +# A face built in code from the bundled Source Sans 3 (no font file is committed). +vectorcraft-text = { workspace = true, features = ["test-fonts"] } +# Test live-effect plug-ins written in WebAssembly text. +wat = { workspace = true } diff --git a/crates/effects/src/adjust.rs b/crates/effects/src/adjust.rs index c345136255..4193b085ef 100644 --- a/crates/effects/src/adjust.rs +++ b/crates/effects/src/adjust.rs @@ -435,11 +435,19 @@ impl ColorVisitor for Live<'_, '_> { /// adjustments of an object `n` is the art of) on everything it paints. The adjustment effects /// are gone from the result; embedded images take the keys `images` gives. `swatches` tells the /// document's global and spot swatches apart ([`crate::addons::duotone::swatch_kind`]). -pub fn adjust(n: &Node, outer: Option<&ColorMap>, swatches: &SwatchKinds, images: &mut ImageHook<'_>) -> Option<Node> { +/// `has_image` tells whether the document holds an image: an image whose color mask's pixels are +/// missing is recoloured from its own pixels, as it is drawn without the adjustment. +pub fn adjust( + n: &Node, + outer: Option<&ColorMap>, + swatches: &SwatchKinds, + images: &mut ImageHook<'_>, + has_image: &dyn Fn(&str) -> bool, +) -> Option<Node> { let mut m: Option<Node> = None; if let Some(ch) = n.children() { for (i, c) in ch.iter().enumerate() { - if let Some(new) = adjust(c, None, swatches, images) + if let Some(new) = adjust(c, None, swatches, images, has_image) && let Some(slot) = m.get_or_insert_with(|| n.clone()).children_mut().and_then(|ch| ch.get_mut(i)) { *slot = Arc::new(new); @@ -462,11 +470,57 @@ pub fn adjust(n: &Node, outer: Option<&ColorMap>, swatches: &SwatchKinds, images if let Some(map) = map { let mm = m.get_or_insert_with(|| n.clone()); mm.appearance.effects.retain(|e| !is_adjustment(&e.id)); + show_color_masks(mm, has_image); recolor_node(mm, Reach::ALL, &mut Live { map: &map, swatches, images }); } m } +/// Whether `n` is an image that [`recolor_node`] recolours (embedded, not colorized, without +/// pixels of its own) with a color mask made from its pixels. +fn recoloured_with_mask(n: &Node) -> bool { + match (&n.kind, Document::color_mask_of(n)) { + (NodeKind::Image(im), Some(m)) => im.link.is_none() && n.extras().colorize.is_none() && m.made_for(im), + _ => false, + } +} + +/// Whether `n` is or holds an image [`recoloured_with_mask`] counts. +fn holds_recoloured_with_mask(n: &Node) -> bool { + recoloured_with_mask(n) || n.children().is_some_and(|ch| ch.iter().any(|c| holds_recoloured_with_mask(c))) +} + +/// Give each image in `n` that [`recoloured_with_mask`] counts its masked pixels as its own, +/// without the mask, so [`recolor_node`] recolours the pixels it shows and the colors the mask +/// hides stay hidden. An image whose masked pixels the document does not hold (`has_image`) is +/// drawn from its own pixels ([`Document::shown_image`]): it keeps its key and loses the mask, so +/// the recoloured copy is drawn the same way. +fn show_color_masks(n: &mut Node, has_image: &dyn Fn(&str) -> bool) { + if recoloured_with_mask(n) + && let Some(masked) = Document::color_mask_of(n).map(|m| m.key.clone()) + { + if let NodeKind::Image(im) = &mut n.kind + && has_image(&masked) + { + im.key = masked; + } + n.extras_mut().color_mask = None; + } + for c in n.children_mut().into_iter().flatten() { + if holds_recoloured_with_mask(c) { + show_color_masks(Arc::make_mut(c), has_image); + } + } +} + +/// The keys of the masked pixels of the color masks in `n` and its members. +fn color_mask_keys<'a>(n: &'a Node, out: &mut Vec<&'a str>) { + out.extend(Document::color_mask_of(n).map(|m| m.key.as_str())); + for c in n.children().into_iter().flatten() { + color_mask_keys(c, out); + } +} + /// [`adjust`] for export and Expand Appearance: recoloured embedded images become new images in /// `d` (named by their content), and a symbol instance stands for its symbol's art: `symbol_art` /// when given, otherwise the symbol's art with the instance's own appearance changes. @@ -482,13 +536,16 @@ pub fn adjust_in_document(d: &mut Document, n: &Node, symbol_art: Option<Node>) _ => n, }; let kinds = crate::addons::duotone::swatch_kinds(d); + let mut masked = vec![]; + color_mask_keys(src, &mut masked); + masked.retain(|k| d.images.contains_key(*k)); let mut hook = |key: &str, map: &ColorMap| -> Option<String> { let blob = d.images.get(key)?.map_rgb(|rgb| map.apply_rgb8(rgb))?; let k = blob.content_key(); d.images.entry(k.clone()).or_insert(blob); Some(k) }; - adjust(src, None, &|name| kinds.get(name).copied(), &mut hook) + adjust(src, None, &|name| kinds.get(name).copied(), &mut hook, &|key| masked.contains(&key)) } #[cfg(test)] @@ -551,17 +608,17 @@ mod tests { let mut g = Node::group(NodeId(1), vec![leaf(2), leaf(3)]); g.appearance.effects.push(Effect { id: "adjust.hueSaturation".into(), params: json!({"hue": 120}), visible: true }); assert!(has_adjustment(&g)); - let out = adjust(&g, None, &|_| None, &mut |_, _| None).unwrap(); + let out = adjust(&g, None, &|_| None, &mut |_, _| None, &|_| true).unwrap(); assert!(out.appearance.effects.is_empty()); for c in out.children().unwrap() { assert_eq!(c.appearance.fill_paint().color().unwrap().to_hex(), "#00ff00"); } // A hidden effect does nothing; a stroke's own effect recolours just that stroke. g.appearance.effects[0].visible = false; - assert!(!has_adjustment(&g) && adjust(&g, None, &|_| None, &mut |_, _| None).is_none()); + assert!(!has_adjustment(&g) && adjust(&g, None, &|_| None, &mut |_, _| None, &|_| true).is_none()); let mut p = Node::path(NodeId(5), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()); p.appearance.items[1].effects_mut().push(Effect { id: "adjust.levels".into(), params: json!({"outputBlack": 255}), visible: true }); - let out = adjust(&p, None, &|_| None, &mut |_, _| None).unwrap(); + let out = adjust(&p, None, &|_| None, &mut |_, _| None, &|_| true).unwrap(); assert_eq!(out.appearance.items[1].paint().color().unwrap().to_hex(), "#ffffff"); assert_eq!(out.appearance.items[0].paint(), p.appearance.items[0].paint()); assert!(out.appearance.items[1].effects().is_empty()); @@ -576,7 +633,7 @@ mod tests { let fill = Appearance::basic(Paint::Gradient(Box::new(gp)), Paint::None, 0.0); let mut p = Node::path(NodeId(1), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), fill); p.appearance.effects.push(Effect { id: "adjust.hueSaturation".into(), params: json!({"hue": 120}), visible: true }); - let out = adjust(&p, None, &|_| None, &mut |_, _| None).unwrap(); + let out = adjust(&p, None, &|_| None, &mut |_, _| None, &|_| true).unwrap(); let Paint::Gradient(g) = out.appearance.fill_paint() else { panic!("a gradient fill") }; // The points are what a freeform gradient draws from, not its stops. let hexes: Vec<String> = g.freeform.as_ref().unwrap().points.iter().map(|p| p.color.to_hex()).collect(); diff --git a/crates/effects/src/bake.rs b/crates/effects/src/bake.rs index 795fc69bdf..7e42147443 100644 --- a/crates/effects/src/bake.rs +++ b/crates/effects/src/bake.rs @@ -29,7 +29,7 @@ use crate::group::{has_own_paint, paints}; use crate::reshape::{as_art, geometry_effects, glyph_outlines, outline_nested_text, reshape_leaves}; use crate::{ GeomContext, adjust_in_document, apply_geometry_carrying, crop_marks_art, evaluate_container, has_adjustment, has_crop_marks, has_geometry, - has_item_geometry, has_pathfinder, is_geometry, is_pathfinder, merged_params, needs_outline, outline_text, reshape, + has_item_geometry, has_pathfinder, is_pathfinder, merged_params, needs_outline, outline_text, reshape, }; fn item_effects(item: &AppearanceItem) -> &[vectorcraft_doc::Effect] { @@ -41,8 +41,8 @@ fn item_effects(item: &AppearanceItem) -> &[vectorcraft_doc::Effect] { fn clear_item_effects(item: &mut AppearanceItem) { match item { - AppearanceItem::Fill(f) => f.effects.retain(|e| !is_geometry(&e.id)), - AppearanceItem::Stroke(s) => s.effects.retain(|e| !is_geometry(&e.id)), + AppearanceItem::Fill(f) => f.effects = crate::raster::without_geometry(&f.effects), + AppearanceItem::Stroke(s) => s.effects = crate::raster::without_geometry(&s.effects), } } @@ -83,15 +83,17 @@ fn apply(effects: &[vectorcraft_doc::Effect], path: &PathData, ctx: &GeomContext /// The geometry `g` with the own effects of `item` (one of the fills and strokes `ctx` is the /// context of) applied, and `carried` (`item` as the object's effects left it) with its gradient -/// moved along with them. +/// moved along with them and the Transform effects the geometry pass left out hidden +/// ([`crate::Carry::hide_skipped`]). fn apply_item(item: &AppearanceItem, carried: &AppearanceItem, g: &PathData, ctx: &GeomContext) -> (PathData, AppearanceItem) { let (ig, carry) = apply(item_effects(item), g, &ctx.item(item)); let mut ap = Appearance { items: vec![carried.clone()], ..Default::default() }; - if !carry.moves(&ap) { - return (ig, carried.clone()); + if carry.moves(&ap) { + carry.apply(&mut ap); } - carry.apply(&mut ap); - (ig, ap.items.pop().unwrap_or_else(|| carried.clone())) + let mut out = ap.items.pop().unwrap_or_else(|| carried.clone()); + carry.hide_skipped(out.effects_mut()); + (ig, out) } /// A path node of `kind`'s flavour (compound when the result has several subpaths). @@ -104,6 +106,15 @@ fn path_kind(d: &mut Document, path: PathData, rule: FillRule) -> NodeKind { } } +thread_local! { + /// How many symbol instances deep [`bake_node`] is baking, through the art of instances whose + /// effects reshape it. + static INSTANCE_DEPTH: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; + /// The objects of symbol art that [`bake_document`] has baked for instances inside the art of + /// other instances, counted against [`crate::SYMBOL_ART_MAX_NODES`]. + static NESTED_NODES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) }; +} + /// `n` with its geometry effects evaluated (`None` = unchanged). fn bake_node(d: &mut Document, n: &Node) -> Option<Node> { // A cancelled export leaves the rest of the document as it is: the caller drops the result. @@ -143,8 +154,27 @@ fn bake_node(d: &mut Document, n: &Node) -> Option<Node> { } _ => None, }; + // Instances baked inside the art of others stop at the depth limit, or once their art + // passes the objects one export bakes that way: an instance of a symbol whose art holds + // instances of itself is kept as it is there. + let instance = matches!(n.kind, NodeKind::SymbolInstance { .. }); + if instance && INSTANCE_DEPTH.with(|c| c.get()) > 0 { + let count = symbol.as_ref().map_or(0, |a| a.count() as u64); + let spent = NESTED_NODES.with(|c| c.get()).saturating_add(count); + if INSTANCE_DEPTH.with(|c| c.get()) >= vectorcraft_doc::depth::MAX_DEPTH || spent > crate::SYMBOL_ART_MAX_NODES { + return None; + } + NESTED_NODES.with(|c| c.set(spent)); + } let m = reshape(Some(d), n, symbol.as_ref())?; - return Some(bake_node(d, &m).unwrap_or(m)); + if instance { + INSTANCE_DEPTH.with(|c| c.set(c.get() + 1)); + } + let baked = bake_node(d, &m); + if instance { + INSTANCE_DEPTH.with(|c| c.set(c.get() - 1)); + } + return Some(baked.unwrap_or(m)); } // A path whose Transform effect copies it with a gradient, or scales its strokes or moves its // patterns: each copy an object of its own, so its gradient fits it rather than spanning @@ -337,7 +367,7 @@ fn moved_type_group(n: &Node) -> Option<Node> { g.knockout = Knockout::Off; g.knockout_shape = n.knockout_shape; g.extras_mut().mask = n.extras().mask.clone(); - g.appearance.effects = n.appearance.effects.iter().filter(|e| !is_geometry(&e.id)).cloned().collect(); + g.appearance.effects = crate::raster::without_geometry(&n.appearance.effects); Some(g) } @@ -396,8 +426,11 @@ fn container_keeping_type(d: &Document, n: &Node) -> Option<Node> { if !kept { return None; } + // The members' own effects run first, as on the canvas. + crate::group::members_as_drawn(Some(d), &mut m); reshape_leaves(&mut m, &fx, &n.appearance.effects, Some(d)); - m.appearance.effects.retain(|e| !is_pathfinder(&e.id) && !is_geometry(&e.id)); + m.appearance.effects = crate::raster::without_geometry(&m.appearance.effects); + m.appearance.effects.retain(|e| !is_pathfinder(&e.id)); m.appearance.items.clear(); m.appearance.contents_index = None; Some(m) @@ -439,7 +472,10 @@ fn leaf_base(n: &Node) -> Option<(PathData, FillRule, GeomContext<'_>, Node)> { if carry.moves(&m.appearance) { carry.apply(&mut m.appearance); } - m.appearance.effects.retain(|e| !is_geometry(&e.id)); + carry.hide_skipped(&mut m.appearance.effects); + // The raster effects of its fills and strokes follow its Transform effects, as on the canvas. + crate::raster::follow_items(&mut m); + m.appearance.effects = crate::raster::without_geometry(&m.appearance.effects); Some((g, rule, ctx, m)) } @@ -528,7 +564,9 @@ fn hoist_transparency(mut p: Node) -> Node { } /// [`expand_leaf`] every path and compound path in `n` (art made for Expand Appearance, such as a -/// group's own fills and strokes or outlined type), in place. +/// group's own fills and strokes or outlined type), in place. A group or layer in it with an +/// appearance of its own ([`crate::has_container_appearance`]) is first made into the art that +/// appearance paints ([`crate::evaluate_container`]). pub fn expand_art(d: &mut Document, n: &mut Node, stroke_art: StrokeArt) { if matches!(n.kind, NodeKind::Path { clipping: false, guide: false, .. } | NodeKind::Compound { .. }) { if let Some(m) = expand_leaf(d, n, stroke_art) { @@ -536,6 +574,11 @@ pub fn expand_art(d: &mut Document, n: &mut Node, stroke_art: StrokeArt) { } return; } + if crate::has_container_appearance(n) + && let Some(m) = crate::evaluate_container(Some(&*d), n) + { + *n = m; + } for c in n.children_mut().into_iter().flatten() { expand_art(d, Arc::make_mut(c), stroke_art); } @@ -658,6 +701,7 @@ pub fn bake_document(doc: &Document) -> Option<Document> { }; } let mut d = placed.into_owned(); + NESTED_NODES.with(|c| c.set(0)); let layers = d.layers.clone(); d.layers = layers.iter().map(|l| bake_node(&mut d, l).map(Arc::new).unwrap_or_else(|| l.clone())).collect(); Some(d) diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index e9bbaf4bbf..424beebe17 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -1,4 +1,7 @@ -use super::{CLASSIC_EXTRUDE, CROP_MARKS, EXTRUDE, INFLATE, PATHFINDER_EFFECTS, RASTERIZE, REVOLVE, ROTATE, TRAP, Value, json, trap}; +use super::{ + CLASSIC_EXTRUDE, CLASSIC_REVOLVE, CLASSIC_ROTATE, CROP_MARKS, EXTRUDE, INFLATE, PATHFINDER_EFFECTS, RASTERIZE, REVOLVE, ROTATE, TRAP, Value, + json, trap, +}; /// Catalogue entry for one effect. #[derive(Clone, Debug, PartialEq)] @@ -81,6 +84,7 @@ fn lengths_of(id: &str) -> Lengths { "threeD.revolve" => always(&["offset"]), "threeD.extrude" => always(&["depth", "bevelWidth", "bevelHeight"]), "threeD.classicExtrude" => always(&["depth", "bevelHeight"]), + "threeD.classicRevolve" => always(&["offset"]), "threeD.inflate" => always(&["depth"]), "path.outlineStroke" => always(&["width"]), "stylize.roundCorners" | "stylize.feather" | "blur.gaussian" | "blur.smart" | "sharpen.unsharpMask" => always(&["radius"]), @@ -90,6 +94,8 @@ fn lengths_of(id: &str) -> Lengths { "stylize.glowingEdges" => always(&["edgeWidth", "smoothness"]), "brushStrokes.accentedEdges" => always(&["edgeWidth"]), "artistic.paletteKnife" => always(&["strokeSize"]), + "artistic.coloredPencil" => always(&["pencilWidth"]), + "artistic.paintDaubs" => always(&["brushSize"]), "brushStrokes.angledStrokes" | "brushStrokes.crosshatch" | "brushStrokes.inkOutlines" => always(&["strokeLength"]), "brushStrokes.spatter" => always(&["sprayRadius"]), "brushStrokes.sprayedStrokes" => always(&["strokeLength", "sprayRadius"]), @@ -112,7 +118,7 @@ fn lengths_of(id: &str) -> Lengths { } } -const WARP_DOC: &str = "{bend: % (-100..100, 50; with a bend or a distortion, placed gradients move and scale from the object's bounds to its warped bounds), horizontal: % distortion (0), vertical: % distortion (0), orientation: \"horizontal\"|\"vertical\"}"; +const WARP_DOC: &str = "{bend: % (-100..100, 50; with a bend or a distortion, placed gradients move and scale from the object's bounds to its warped bounds, and images bend as 10 × 10 cells of two triangles unless the pieces would make the art pass 2,000,000 objects or the image's frame keeps its shape past the anchor budget), horizontal: % distortion (0), vertical: % distortion (0), orientation: \"horizontal\"|\"vertical\", version: 0|1 (the map: 1 bends each style as one Bézier patch over the bounds, which new and imported warps get; 0, or none, is VectorCraft's earlier map, which warps saved without a version keep)}"; const DT: &[&str] = &["Effect", "Distort & Transform"]; @@ -176,29 +182,29 @@ pub fn effect_catalog() -> Vec<EffectInfo> { REVOLVE, "Revolve…", &["Effect", "3D and Materials"], - "{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), cap: bool (true, close circular ends of open profiles; partial-sweep cut sides stay open), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.", - json!({"angle":360.0,"offset":0.0,"edge":"left","rotationX":0.0,"rotationY":0.0,"rotationZ":0.0,"perspectiveAngle":0.0,"segments":64,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"cap":true,"expandVisibleOnly":true}), + "{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true, close circular ends of open profiles; partial-sweep cut sides stay open), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.", + json!({"angle":360.0,"offset":0.0,"edge":"left","rotationX":0.0,"rotationY":0.0,"rotationZ":0.0,"perspectiveAngle":0.0,"segments":64,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"cap":true,"expandVisibleOnly":true,"graphics":[]}), ), g( EXTRUDE, "Extrude & Bevel…", &["Effect", "3D and Materials"], - "{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).", - json!({"depth":50.0,"twist":0.0,"taper":100.0,"cap":true,"bevel":"none","bevelWidth":4.0,"bevelHeight":4.0,"bevelRepeat":1,"bevelSpace":0.0,"bevelInside":false,"bevelBothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0}), + "{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the cap and clipped to it, on a solid cap only)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).", + json!({"depth":50.0,"twist":0.0,"taper":100.0,"cap":true,"bevel":"none","bevelWidth":4.0,"bevelHeight":4.0,"bevelRepeat":1,"bevelSpace":0.0,"bevelInside":false,"bevelBothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[]}), ), g( INFLATE, "Inflate…", &["Effect", "3D and Materials"], - "{depth: pt (0..2000, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth)}. Painted with the top fill (else the top stroke).", - json!({"depth":0.0,"twist":0.0,"taper":100.0,"cap":true,"volume":50.0,"bothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0}), + "{depth: pt (0..2000, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across)}. Painted with the top fill (else the top stroke).", + json!({"depth":0.0,"twist":0.0,"taper":100.0,"cap":true,"volume":50.0,"bothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0}), ), g( ROTATE, "Rotate…", &["Effect", "3D and Materials"], - "{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.", - json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0}), + "{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the plane, as Extrude & Bevel's, with face front only)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.", + json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[]}), ), g( CLASSIC_EXTRUDE, @@ -207,6 +213,20 @@ pub fn effect_catalog() -> Vec<EffectInfo> { "{depth: pt (0..2000, 50), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelHeight: pt (1..100, 4; the bevel is as wide as it is tall), bevelInside: bool (false: added around the shape; true: carved into it), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face, hidden ones included, and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none (black; the color the faces darken toward; none keeps the paint and adds only the highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), drawHiddenFaces: bool (false; also draws the faces turned away, behind the others)}. The front face is the art, extruded backwards about the center of its bounds; a solid is built for the top fill and for each stroke, each in its own paint. The defaults are VectorCraft's own.", json!({"depth":50.0,"cap":true,"bevel":"none","bevelHeight":4.0,"bevelInside":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","drawHiddenFaces":false}), ), + g( + CLASSIC_REVOLVE, + "Revolve (Classic)…", + &["Effect", "3D and Materials", "3D (Classic)"], + "{angle: degrees (0..360, 360; how far the profile sweeps round the axis), cap: bool (true: solid, the open ends closed; false: hollow), offset: pt (0..1000, 0; the axis's distance from the profile, a ring past 0), edge: left|right (left; the axis is at the left or the right edge of the profile's bounds), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none (black; the color the faces darken toward; none keeps the paint and adds only the highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward)}. The profile sweeps round a vertical axis, as Revolve's does, painted with the top fill (else the top stroke); every face is drawn, back to front. The defaults are VectorCraft's own.", + json!({"angle":360.0,"cap":true,"offset":0.0,"edge":"left","rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000"}), + ), + g( + CLASSIC_ROTATE, + "Rotate (Classic)…", + &["Effect", "3D and Materials", "3D (Classic)"], + "{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: none|diffuse (diffuse; none keeps the paint unlit; diffuse lights the art softly), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, the art whichever way it faces), blendSteps: integer (1..256, 25; how many levels the shading is rounded to), shadingColor: black|custom|none (black; the color the art darkens toward; none keeps the paint), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward)}. Every fill and stroke turns as one flat plane about the center of the object's bounds, as Rotate's do, each in its own paint, and is seen from either side. The defaults are VectorCraft's own.", + json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"diffuse","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000"}), + ), g( "convertToShape.rectangle", "Rectangle…", @@ -240,14 +260,14 @@ pub fn effect_catalog() -> Vec<EffectInfo> { "distort.roughen", "Roughen…", DT, - "{size: 0..100 (5), relative: bool (true: % of size; false: pt), detail: per inch 0..100 (10), points: \"smooth\"|\"corner\", seed: int (0)}", + "{size: 0..100 (5; 0 keeps the outline and adds its points along it), relative: bool (true: % of size; false: pt), detail: per inch 0..100 (10), points: \"smooth\"|\"corner\", seed: int (0)}", json!({"size": 5.0, "relative": true, "detail": 10.0, "points": "smooth", "seed": 0}), ), g( "distort.transform", "Transform…", DT, - "{scaleH: % (100), scaleV: % (100), moveH: pt (0; right = +), moveV: pt (0; down = +), rotate: deg (0; counter-clockwise; when the effect turns, reflects or scales the object unevenly, a gradient fitted to the object is fixed to its fit and turns with the object and with each copy), copies: 0..1000 (0; each copy transforms the last again and is painted below it, the object on top; a group's copies each hold all its members, and a group with a member that carries a geometry, Pathfinder or 3D effect copies each member in its place; placed gradients transform with the object and with each copy), reflectX: bool (false; flips left to right), reflectY: bool (false; flips top to bottom), reference: 0..8 (4; the point of the bounds' 9-point grid it scales, rotates and reflects about: 0 top left, 4 centre, 8 bottom right), random: bool (false; each scale goes a random share of the way from 100 % to its value, each move and the angle a random share of theirs, differently for each object and the same on every redraw), objects: bool (true; Transform Objects: off, the geometry stays where it is and makes no copies, and only the two options below apply, once), patterns: bool (false; Transform Patterns: pattern fills and strokes transform along; with copies the original keeps its pattern and copy k takes the transformation k times), strokes: bool (false; Scale Strokes & Effects: stroke weights and dashes, and the distances of the effects on the fills and strokes, scale by the mean scale √|scaleH·scaleV|, copy k by its k-th power)}", + "{scaleH: % (100), scaleV: % (100), moveH: pt (0; right = +), moveV: pt (0; down = +), rotate: deg (0; counter-clockwise; when the effect turns, reflects or scales the object unevenly, a gradient fitted to the object is fixed to its fit and turns with the object and with each copy), copies: 0..1000 (0; each copy transforms the last again and is painted below it, the object on top; a group's copies each hold all its members, and a group with a member that carries a geometry, Pathfinder or 3D effect copies each member in its place; placed gradients transform with the object and with each copy), reflectX: bool (false; flips left to right), reflectY: bool (false; flips top to bottom), reference: 0..8 (4; the point of the bounds' 9-point grid it scales, rotates and reflects about: 0 top left, 4 centre, 8 bottom right), random: bool (false; each scale goes a random share of the way from 100 % to its value, each move and the angle a random share of theirs, differently for each object and the same on every redraw), objects: bool (true; Transform Objects: off, the geometry stays where it is and makes no copies, and only the two options below apply, once; on, without copies or random, the raster effects listed before this effect (Rasterize and SVG filters excepted) transform with the art whatever strokes says: their sizes scale by the mean scale and a Drop Shadow's offset turns, reflects and scales, while the angles and light directions of pixel filters stay as they are; so do the raster effects of the object's fills and strokes and, on a group, those of its members, of their fills and strokes and of their linked opacity masks' art, after their own Transform effects, including those that a member's own Transform effect with copies or random holds back), patterns: bool (false; Transform Patterns: pattern fills and strokes transform along; with copies the original keeps its pattern and copy k takes the transformation k times), strokes: bool (false; Scale Strokes & Effects: stroke weights and dashes, and the distances of the effects on the fills and strokes, scale by the mean scale √|scaleH·scaleV|, copy k by its k-th power; raster effects that transform with the art are not scaled again; on a fill or stroke, the effects listed after this effect in that fill's or stroke's own list keep their distances and apply to the transformed art, and with objects off so do the effects before it)}", json!({"scaleH": 100.0, "scaleV": 100.0, "moveH": 0.0, "moveV": 0.0, "rotate": 0.0, "copies": 0, "reflectX": false, "reflectY": false, "reference": 4, "random": false, "objects": true, "patterns": false, "strokes": false}), ), g( @@ -276,7 +296,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> { "path.outlineObject", "Outline Object", PATH, - "{} type is drawn, exported and expanded as its glyph outlines and stays editable, and the effects after it reshape those outlines; paths and images do not change", + "{} type is drawn, exported and expanded as its glyph outlines and stays editable, and the effects after it reshape those outlines; paths and images do not change. On an image's own fill or stroke it gives the outline of the image's pixels that are at least half opaque (VectorCraft's own cutoff), and nothing when no pixel is; it gives the image's frame when the image has no transparency, its pixels can't be read, or the image or its outline is too large to trace", json!({}), ), g( @@ -369,7 +389,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> { "artistic.paintDaubs", "Paint Daubs…", ARTISTIC, - "{brushSize: 1..50 (10; dab centres farther apart), sharpness: 0..40 (25; harder dab edges), brushType: \"simple\"|\"lightRough\"|\"darkRough\"|\"wideSharp\"|\"wideBlurry\"|\"sparkle\" (\"simple\")} repaints the object with thick round brush dabs in the local colours, keeping its coverage. Original visual approximation; chosen VectorCraft defaults.", + "{brushSize: 1..50 (10; spacing of the dab centers in document units),sharpness: 0..40 (25; harder dab edges), brushType: \"simple\"|\"lightRough\"|\"darkRough\"|\"wideSharp\"|\"wideBlurry\"|\"sparkle\" (\"simple\")} repaints the object with thick round brush dabs in the local colours, keeping its coverage. Original visual approximation; chosen VectorCraft defaults.", json!({"brushSize": 10.0, "sharpness": 25.0, "brushType": "simple"}), ), r( diff --git a/crates/effects/src/distort.rs b/crates/effects/src/distort.rs index c070457027..a5bc941b16 100644 --- a/crates/effects/src/distort.rs +++ b/crates/effects/src/distort.rs @@ -3,6 +3,7 @@ use serde_json::Value; use vectorcraft_geom::kurbo::ParamCurveArclen; use vectorcraft_geom::{Affine, Anchor, ParamCurve, PathData, Point, Rect, SubPath, Vec2}; +use vectorcraft_pathops::addons::pathtools::insert_at; use crate::util::{catmull_rom, fit_piece, flag, map_nonlinear_within, mean_size, noise, normal_at, num, pieces, seed, seg_cubic, smooth_points}; @@ -79,7 +80,8 @@ const MAX_ROUGHEN_POINTS: usize = 2000; /// Roughen: resample at `detail` points per inch and jitter each point by up to `size`. Where /// that would make more than `max` anchors, the points are spaced further apart until it doesn't -/// (stacked Roughens multiply their points, #3578). +/// (stacked Roughens multiply their points, #3578). At size 0 no point moves: each segment is +/// split into its pieces, evenly along its length, and the outline stays as it is. pub fn roughen(path: &PathData, b: Rect, p: &Value, max: usize) -> PathData { let size = num(p, "size", 5.0).clamp(0.0, 1e4); let amp = if flag(p, "relative", true) { size / 100.0 * mean_size(b) } else { size }; @@ -89,6 +91,23 @@ pub fn roughen(path: &PathData, b: Rect, p: &Value, max: usize) -> PathData { let lens: Vec<f64> = path.subpaths.iter().flat_map(|sp| (0..sp.segment_count()).map(|i| sp.segment(i).arclen(0.1))).collect(); let spacing = fit_piece(&lens, spacing, MAX_ROUGHEN_POINTS, max.saturating_sub(path.anchor_count())); let mut lens = lens.iter(); + if amp == 0.0 { + // Each segment's pieces, cut at equal lengths as `pathtools::add_points` cuts them. + let mut subs = Vec::with_capacity(path.subpaths.len()); + for sp in &path.subpaths { + let mut places = vec![]; + for (i, &coarse) in (0..sp.segment_count()).zip(&mut lens) { + let k = pieces(coarse, spacing, MAX_ROUGHEN_POINTS); + let c = sp.segment(i); + let len = c.arclen(ROUGHEN_ARCLEN_ACCURACY); + if len > 1e-9 && len.is_finite() { + places.extend((1..k).map(|j| (i, c.inv_arclen(len * j as f64 / k as f64, ROUGHEN_ARCLEN_ACCURACY)))); + } + } + subs.push(insert_at(sp, &places).0); + } + return PathData::new(subs); + } let smooth = smooth_points(p); let seed = seed(p); let mut subs = vec![]; @@ -118,6 +137,8 @@ pub fn roughen(path: &PathData, b: Rect, p: &Value, max: usize) -> PathData { PathData::new(subs) } +const ROUGHEN_ARCLEN_ACCURACY: f64 = 1e-4; + /// The move and the number of copies of a Transform effect with params `p` that only moves what /// it applies to, as [`transform_map`] reads them; `None` when it also scales, rotates or reflects, /// or moves by a random share, or moves pattern paints along (Transform Patterns), or scales diff --git a/crates/effects/src/geometry.rs b/crates/effects/src/geometry.rs index a2e5478b28..39924835fd 100644 --- a/crates/effects/src/geometry.rs +++ b/crates/effects/src/geometry.rs @@ -200,8 +200,12 @@ pub fn apply_geometry_bez_carrying(effects: &[Effect], path: &BezPath, bounds: R /// it unevenly (a map after which a refit would not match the mapped gradient): it is fixed to its /// fit on the geometry that effect takes, and then follows that effect and the ones after it as a /// placed gradient does. +/// +/// It also lists the visible Transform effects that move the art once and that the pass left out, +/// their results past the budget, by their index in the effect list it was given: the raster +/// effects before such an effect stay as they are, as the art does ([`Self::hide_skipped`]). #[derive(Clone, Debug, Default, PartialEq)] -pub struct Carry(Vec<CarryStep>); +pub struct Carry(Vec<CarryStep>, Vec<usize>); /// Does `m` fix a gradient fitted to the object to its fit before mapping it? It does when a refit /// would not reproduce the map (a turn, a reflection or an uneven scale) and `m` keeps area: a map @@ -265,7 +269,7 @@ impl Carry { _ => None, }, }; - Carry(step.into_iter().collect()) + Carry(step.into_iter().collect(), vec![]) } /// Does it leave gradients where they are? @@ -310,6 +314,30 @@ impl Carry { pub(crate) fn push(&mut self, more: Carry) { self.0.extend(more.0); + self.1.extend(more.1); + } + + /// Did the pass leave out a Transform effect that moves the art once ([`Self::hide_skipped`])? + pub fn skipped(&self) -> bool { + !self.1.is_empty() + } + + /// Hide each Transform effect of `effects`, the list the pass was given, that it left out (its + /// result past the budget): the art stays where it was, so the raster effects listed before it + /// do not follow it ([`crate::raster::followed`]). Other effects stay as they are. + pub fn hide_skipped(&self, effects: &mut [Effect]) { + for &i in &self.1 { + if let Some(e) = effects.get_mut(i).filter(|e| e.id == "distort.transform") { + e.visible = false; + } + } + } + + /// Note that the Transform effect at index `i` of the pass's list was left out. + pub(crate) fn skip(&mut self, i: usize) { + if !self.1.contains(&i) { + self.1.push(i); + } } } @@ -354,6 +382,13 @@ pub(crate) fn apply_geometry_carrying_within( c.push(Carry::of(&e.id, &p, b, cur.bounds(), next.bounds(), ctx.seed)); } cur = next; + } else if let Some(c) = carry.as_deref_mut() + && e.id == "distort.transform" + && !crate::raster::holds_back(e) + && let Some(i) = effects.iter().position(|x| std::ptr::eq(x, e)) + { + // The raster effects before it stay as the art does. + c.skip(i); } } cur diff --git a/crates/effects/src/group.rs b/crates/effects/src/group.rs index 99e9d9e6fe..bb2f605a91 100644 --- a/crates/effects/src/group.rs +++ b/crates/effects/src/group.rs @@ -209,6 +209,8 @@ fn reshaped_art(doc: Option<&Document>, n: &Node, hook: Option<OutlineHook>, nod Some(area) => Some(reshaped(&area, n, doc)), None => { let mut m = crate::reshape::outlined_members_with(None, doc, n, outline, nodes); + // The members' own effects run first, as on the canvas. + members_as_drawn(doc, &mut m); let carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, &n.appearance.effects, doc); // The group's own fills and strokes follow the effects as its members do. if carry.moves(&m.appearance) { @@ -225,6 +227,7 @@ fn reshaped_art(doc: Option<&Document>, n: &Node, hook: Option<OutlineHook>, nod let art = h(n).filter(|art| nodes.charge(art))?; let mut art = crate::reshape::symbol_art_with(&art, h, nodes, symbol); crate::reshape::outline_nested_text(doc, &mut art, false); + members_as_drawn(doc, &mut art); let carry = crate::reshape::reshape_leaves_carrying(&mut art, &fx, &n.appearance.effects, doc); // The art's own fills and strokes follow the effects as its members do. if carry.moves(&art.appearance) { @@ -257,6 +260,18 @@ fn reshaped(src: &Node, n: &Node, doc: Option<&Document>) -> Node { if carry.moves(&m.appearance) { carry.apply(&mut m.appearance); } + // So do the raster effects of its fills and strokes, by `n`'s Transform effects + // ([`crate::follow_items`]) that moved the outline. + let mut owner = std::borrow::Cow::Borrowed(n.appearance.effects.as_slice()); + if carry.skipped() { + carry.hide_skipped(owner.to_mut()); + if m.appearance.effects == n.appearance.effects { + let mut ap = (*m.appearance).clone(); + ap.effects = owner.to_vec(); + m.appearance = ap.into(); + } + } + crate::raster::follow_items_of(&mut m, &owner); } without_geometry_effects(&mut m); m @@ -265,7 +280,7 @@ fn reshaped(src: &Node, n: &Node, doc: Option<&Document>) -> Node { fn without_geometry_effects(n: &mut Node) { if n.appearance.effects.iter().any(|e| crate::is_geometry(&e.id)) { let mut ap = (*n.appearance).clone(); - ap.effects.retain(|e| !crate::is_geometry(&e.id)); + ap.effects = crate::raster::without_geometry(&ap.effects); n.appearance = ap.into(); } } @@ -686,7 +701,7 @@ pub fn member_shapes(doc: Option<&Document>, n: &Node) -> Vec<(PathData, FillRul } /// A path node of `id` on `path` (filled under `rule`) painted by `ap`. -fn shape_node(id: NodeId, path: PathData, rule: FillRule, ap: Appearance) -> Node { +pub(crate) fn shape_node(id: NodeId, path: PathData, rule: FillRule, ap: Appearance) -> Node { let mut n = Node::path(id, path, ap); if let NodeKind::Path { rule: r, .. } = &mut n.kind { *r = rule; @@ -719,8 +734,40 @@ fn item_art(id: NodeId, item: &AppearanceItem, shapes: &[(PathData, FillRule)], Some(g) } +/// Whether a sublayer among the members of `n`, or among its groups' members, holds a ruler guide. +fn sublayer_guides(n: &Node) -> bool { + n.children().is_some_and(|ch| ch.iter().any(|c| c.holds_ruler_guides() || (!c.is_layer() && sublayer_guides(c)))) +} + +/// Move the ruler guides of the sublayers among the members of `n`, and among its groups' +/// members, to `out`, in order. A guide taken from a hidden or locked sublayer, or from one inside +/// such a sublayer or group, is hidden or locked itself. Only containers holding one are copied. +fn take_sublayer_guides(n: &mut Node, out: &mut Vec<Arc<Node>>, hidden: bool, locked: bool) { + let Some(ch) = n.children_mut() else { return }; + for c in ch.iter_mut().filter(|c| c.holds_ruler_guides() || (!c.is_layer() && sublayer_guides(c))) { + let c = Arc::make_mut(c); + let (hidden, locked) = (hidden || !c.visible, locked || c.locked); + if c.is_layer() + && let Some(lc) = c.children_mut() + { + let (taken, art): (Vec<_>, Vec<_>) = std::mem::take(lc).into_iter().partition(|g| g.is_ruler_guide()); + *lc = art; + out.extend(taken.into_iter().map(|mut g| { + if hidden || locked { + let g = Arc::make_mut(&mut g); + g.visible &= !hidden; + g.locked |= locked; + } + g + })); + } + take_sublayer_guides(c, out, hidden, locked); + } +} + /// `n`, a group or layer, as plain art: its Pathfinder effects evaluated, its geometry effects -/// reshaping all its members as one piece (the whole art's bounds as their reference box), and its +/// reshaping all its members as one piece (the whole art's bounds as their reference box) after +/// the members' own geometry and Pathfinder effects ([`members_as_drawn`]), and its /// own fills and strokes turned into art painting the members' geometry ([`member_shapes`]) below /// the members (after a clipping path) or above them, as its contents slot says. Its /// transparency, opacity mask and raster effects stay. `None` when it has none of these. Live @@ -739,7 +786,12 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> { } let mut m = n.clone(); // A layer's ruler guides take no part: they go back above the evaluated art at the end. - let guides = m.children_mut().map(|ch| ch.split_off(Node::guide_run_start(ch))).unwrap_or_default(); + let mut guides = m.children_mut().map(|ch| ch.split_off(Node::guide_run_start(ch))).unwrap_or_default(); + // So do its sublayers' guides, which would otherwise go with the art the effects replace or + // copy: they stay on this layer, hidden and locked as their sublayers were. + if m.is_layer() && (pathfinder || !fx.is_empty()) { + take_sublayer_guides(&mut m, &mut guides, false, false); + } if pathfinder { let hook = |c: &Node| crate::outline_object(doc, c); let result = pathfinder_children(doc, &m, Some(&hook)).unwrap_or_default(); @@ -751,6 +803,7 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> { } if !fx.is_empty() { m = crate::reshape::outlined_members(doc, &m); + members_as_drawn(doc, &mut m); let carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, &n.appearance.effects, doc); // The group's own fills and strokes paint the members as a whole: their gradients follow // the effects as the members' do. @@ -758,7 +811,8 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> { carry.apply(&mut m.appearance); } } - m.appearance.effects.retain(|e| !is_pathfinder(&e.id) && !crate::is_geometry(&e.id)); + m.appearance.effects = crate::raster::without_geometry(&m.appearance.effects); + m.appearance.effects.retain(|e| !is_pathfinder(&e.id)); if paint { let shapes = member_shapes(doc, &m); let bounds = m.geometric_bounds(); @@ -781,5 +835,83 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> { Some(m) } +/// Replace each visible member of `n` with geometry or Pathfinder effects of its own, at every +/// depth of its groups and layers, by the art it draws ([`evaluate_container`], +/// [`crate::reshape::own_effects_art`]), so the geometry effects of `n` reshape what its members +/// draw. A clip group's clipping path stays as it is, and so do images, symbol instances and the +/// other objects that `own_effects_art` leaves alone, and a group or layer with a 3D effect with +/// everything in it. Calls nested in one another, through the +/// groups and layers it walks and the art it evaluates (symbol art and Pathfinder members +/// included), stop at [`vectorcraft_doc::depth::MAX_DEPTH`] deep, and together they replace at +/// most [`crate::SYMBOL_ART_MAX_NODES`] members: past either limit, members stay as they are. +pub(crate) fn members_as_drawn(doc: Option<&Document>, n: &mut Node) { + let Some(_frame) = DrawnFrame::enter() else { return }; + let clip = usize::from(n.clips()); + let Some(ch) = n.children_mut() else { return }; + for c in ch.iter_mut().skip(clip).filter(|c| c.visible) { + if !DrawnFrame::take_member() { + return; + } + // A group or layer with a 3D effect stays whole: the geometry effects listed after its 3D + // effect reshape its 3D art. + if is_container(c) && (crate::has_solid(c) || crate::has_revolve(c)) { + continue; + } + let art = if !is_container(c) { + crate::reshape::own_effects_art(doc, c) + } else if has_pathfinder(c) || !crate::reshape::geometry_effects(c).is_empty() { + evaluate_container(doc, c) + } else { + None + }; + match art { + Some(a) => *c = Arc::new(a), + None if is_container(c) => members_as_drawn(doc, Arc::make_mut(c)), + None => {} + } + } +} + +thread_local! { + /// How many [`members_as_drawn`] calls are running, one inside another, and how many members + /// they have visited since the outermost one started. + static DRAWN: std::cell::Cell<(usize, u64)> = const { std::cell::Cell::new((0, 0)) }; +} + +/// One running [`members_as_drawn`] call, counted in [`DRAWN`] until it is dropped. +struct DrawnFrame; + +impl DrawnFrame { + /// Count one more call; `None` when [`vectorcraft_doc::depth::MAX_DEPTH`] are running. The + /// outermost call starts the count of members again. + fn enter() -> Option<Self> { + let (frames, members) = DRAWN.with(|d| d.get()); + if frames >= vectorcraft_doc::depth::MAX_DEPTH { + return None; + } + DRAWN.with(|d| d.set((frames + 1, if frames == 0 { 0 } else { members }))); + Some(DrawnFrame) + } + + /// Count one more member visited; `false` once [`crate::SYMBOL_ART_MAX_NODES`] have been. + fn take_member() -> bool { + let (frames, members) = DRAWN.with(|d| d.get()); + if members >= crate::SYMBOL_ART_MAX_NODES { + return false; + } + DRAWN.with(|d| d.set((frames, members + 1))); + true + } +} + +impl Drop for DrawnFrame { + fn drop(&mut self) { + DRAWN.with(|d| { + let (frames, members) = d.get(); + d.set((frames.saturating_sub(1), members)); + }); + } +} + #[cfg(test)] mod tests; diff --git a/crates/effects/src/group/tests.rs b/crates/effects/src/group/tests.rs index bf702b2732..c6e2a78c73 100644 --- a/crates/effects/src/group/tests.rs +++ b/crates/effects/src/group/tests.rs @@ -555,6 +555,298 @@ fn a_nested_groups_own_gradient_follows_the_outer_groups_transform_and_free_dist assert!(near(s, Point::new(0.0, 5.0)) && near(e, Point::new(20.0, 5.0)), "{s:?} {e:?}"); } +/// The bounds of what `n` draws, as the renderer draws it: a group or layer with an appearance of +/// its own as the art [`evaluate_container`] makes of it, and each visible path and compound path +/// with the geometry effects still on it applied, then those of each visible fill and stroke that +/// has some. +fn drawn_bounds(n: &Node) -> Option<Rect> { + if !n.visible { + return None; + } + if let Some(m) = evaluate_container(None, n) { + return drawn_bounds(&m); + } + if let Some(ch) = n.children() + && !matches!(n.kind, NodeKind::Compound { .. }) + { + return ch.iter().filter_map(|c| drawn_bounds(c)).reduce(|a, b| a.union(b)); + } + let (path, _) = crate::reshape::leaf_geometry(n)?; + let geometry = |fx: &[Effect]| -> Vec<Effect> { fx.iter().filter(|e| e.visible && crate::is_geometry(&e.id)).cloned().collect() }; + let apply = |fx: &[Effect], p: &PathData| crate::apply_geometry(&geometry(fx), p, p.bounds().unwrap()); + let g = apply(&n.appearance.effects, &path); + let items: Vec<&AppearanceItem> = n.appearance.items.iter().filter(|i| paints(i) && !geometry(i.effects()).is_empty()).collect(); + if items.is_empty() { + return g.bounds(); + } + items.iter().filter_map(|i| apply(i.effects(), &g).bounds()).reduce(|a, b| a.union(b)) +} + +fn black() -> Appearance { + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0) +} + +/// A black 100 pt square from (100, 100). +fn square_at_100() -> Node { + Node::path(NodeId(1), shapes::rectangle(Rect::new(100.0, 100.0, 200.0, 200.0)), black()) +} + +fn effect(id: &str, params: serde_json::Value) -> Effect { + Effect { id: id.into(), params, visible: true } +} + +fn offset_10() -> Effect { + effect("path.offsetPath", serde_json::json!({"offset": 10})) +} + +fn scaled(s: f64) -> Effect { + effect("distort.transform", serde_json::json!({"scaleH": s, "scaleV": s})) +} + +fn with_effect(mut n: Node, e: Effect) -> Node { + n.appearance.effects.push(e); + n +} + +/// The width that a group with `e` holding `member` draws at. +fn drawn_width(member: Node, e: Effect) -> f64 { + let g = with_effect(Node::group(NodeId(10), vec![Arc::new(member)]), e); + drawn_bounds(&g).unwrap().width() +} + +/// A member's own Offset Path runs before its group's Transform: the square offset by 10 pt to +/// 120 pt, then scaled by half, is 60 pt wide (70 pt the other way round). +#[test] +fn a_members_own_offset_runs_before_its_groups_scale() { + let w = drawn_width(with_effect(square_at_100(), offset_10()), scaled(50.0)); + assert!((w - 60.0).abs() < 1e-6, "{w}"); +} + +/// A member's own Transform runs before its group's Offset Path: the square scaled to 200 pt, then +/// offset by 10 pt, is 220 pt wide (240 pt the other way round). +#[test] +fn a_members_own_scale_runs_before_its_groups_offset() { + let w = drawn_width(with_effect(square_at_100(), scaled(200.0)), offset_10()); + assert!((w - 220.0).abs() < 1e-6, "{w}"); +} + +/// A member inside a plain group inside the group takes its own effects first too. +#[test] +fn a_member_of_a_plain_nested_group_takes_its_own_effects_first() { + let w = drawn_width(Node::group(NodeId(5), vec![Arc::new(with_effect(square_at_100(), offset_10()))]), scaled(50.0)); + assert!((w - 60.0).abs() < 1e-6, "{w}"); +} + +/// A nested group's own geometry effects run before the outer group's. +#[test] +fn a_nested_groups_own_effects_run_before_its_groups() { + let w = drawn_width(with_effect(Node::group(NodeId(5), vec![Arc::new(square_at_100())]), offset_10()), scaled(50.0)); + assert!((w - 60.0).abs() < 1e-6, "{w}"); +} + +/// A nested group's Pathfinder effect runs before the outer group's geometry effects: the back +/// square minus the front one is 50 pt wide, and offset by 10 pt it is 70 pt (offsetting the +/// squares first leaves 50 pt). +#[test] +fn a_nested_groups_pathfinder_runs_before_its_groups_effects() { + let back = square_at_100(); + let front = Node::path(NodeId(2), shapes::rectangle(Rect::new(150.0, 100.0, 250.0, 200.0)), black()); + let nested = with_effect(Node::group(NodeId(5), vec![Arc::new(back), Arc::new(front)]), effect("pathfinder.subtract", serde_json::json!({}))); + let w = drawn_width(nested, offset_10()); + assert!((w - 70.0).abs() < 1e-6, "{w}"); +} + +/// The geometry effects of a member's own fill run before its group's: 60 pt, as for the +/// member's own effect. +#[test] +fn a_members_fill_effects_run_before_its_groups() { + let mut member = square_at_100(); + member.appearance.items[0].effects_mut().push(offset_10()); + let w = drawn_width(member, scaled(50.0)); + assert!((w - 60.0).abs() < 1e-6, "{w}"); +} + +/// A member whose fills have geometry effects stays one element of a knockout group: its fills do +/// not knock each other out. +#[test] +fn a_member_drawn_as_its_fills_stays_one_knockout_element() { + let mut member = square_at_100(); + member.appearance.items.push(AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::solid(Color::rgb(1.0, 0.0, 0.0))))); + member.appearance.items[0].effects_mut().push(offset_10()); + let mut g = with_effect(Node::group(NodeId(10), vec![Arc::new(member)]), scaled(50.0)); + g.knockout = vectorcraft_doc::Knockout::On; + let art = evaluate_container(None, &g).unwrap(); + let elements = Node::knockout_elements(art.children().unwrap()); + assert_eq!(elements.len(), 1, "{:?}", elements.iter().map(|e| (e.id, &e.kind)).collect::<Vec<_>>()); +} + +/// The art a Pathfinder operation or compound shape takes from a group with geometry effects has +/// the members' own effects applied first, as the canvas draws it. +#[test] +fn shape_art_of_a_group_applies_its_members_effects_first() { + let g = with_effect(Node::group(NodeId(10), vec![Arc::new(with_effect(square_at_100(), offset_10()))]), scaled(50.0)); + let art = shape_art(None, &g, None).unwrap(); + let w = drawn_bounds(&art).unwrap().width(); + assert!((w - 60.0).abs() < 1e-6, "{w}"); + let leaves = member_leaves(None, &g, None); + let w = leaves.iter().filter_map(drawn_bounds).reduce(|a, b| a.union(b)).unwrap().width(); + assert!((w - 60.0).abs() < 1e-6, "leaves: {w}"); +} + +/// A symbol instance's own geometry effects run after those of its symbol's members, as the canvas +/// draws it and in the art a Pathfinder operation takes from it. +#[test] +fn a_symbol_instances_effects_run_after_its_symbols_members_own() { + let art = Node::group(NodeId(20), vec![Arc::new(with_effect(square_at_100(), offset_10()))]); + let instance = + with_effect(Node::new(NodeId(6), NodeKind::SymbolInstance { symbol: "s".into(), xf: vectorcraft_geom::Affine::IDENTITY }), scaled(50.0)); + let drawn = crate::reshape(None, &instance, Some(&art)).unwrap(); + let w = drawn_bounds(&drawn).unwrap().width(); + assert!((w - 60.0).abs() < 1e-6, "drawn: {w}"); + let hook = move |_: &Node| Some(art.clone()); + let w = drawn_bounds(&shape_art(None, &instance, Some(&hook)).unwrap()).unwrap().width(); + assert!((w - 60.0).abs() < 1e-6, "shape art: {w}"); +} + +/// Export bakes the group as the canvas draws it. +#[test] +fn a_baked_group_applies_its_members_effects_first() { + let mut d = Document::new(800.0, 800.0); + let layer = d.layers[0].id; + let g = with_effect(Node::group(NodeId(10), vec![Arc::new(with_effect(square_at_100(), offset_10()))]), scaled(50.0)); + d.insert(Some(layer), 0, g).unwrap(); + let baked = crate::bake_document(&d).unwrap(); + let w = baked.node(NodeId(10)).unwrap().geometric_bounds().unwrap().width(); + assert!((w - 60.0).abs() < 1e-6, "{w}"); +} + +/// A group whose Transform effect only moves and copies keeps its type when baked; a nested +/// group's own Transform still runs before the copies: the nested square scaled by half to 50 pt +/// and copied 200 pt to the right spans 250 pt (copying first, then scaling both copies about +/// their middle, spans 150 pt). +#[test] +fn a_baked_group_that_keeps_its_type_applies_its_members_effects_first() { + if skip_without_craft_fonts() { + return; + } + let style = CharStyle { size: 24.0, fill: Paint::solid(Color::BLACK), ..Default::default() }; + let text = Node::new(NodeId(3), NodeKind::Text(Box::new(TextObject::point(Point::new(20.0, 60.0), "Type", style)))); + let nested = with_effect(Node::group(NodeId(5), vec![Arc::new(square_at_100())]), scaled(50.0)); + let g = with_effect( + Node::group(NodeId(10), vec![Arc::new(text), Arc::new(nested)]), + effect("distort.transform", serde_json::json!({"moveH": 200, "copies": 1})), + ); + let mut d = Document::new(800.0, 800.0); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, g).unwrap(); + let baked = crate::bake_document(&d).unwrap(); + let mut text = 0; + baked.walk(|n| text += usize::from(matches!(n.kind, NodeKind::Text(_)))); + assert_eq!(text, 2, "the type stays type, copied"); + let w = baked.node(NodeId(5)).unwrap().geometric_bounds().unwrap().width(); + assert!((w - 250.0).abs() < 1e-6, "{w}"); +} + +/// A clip group's clipping path keeps its own effects; the clipped members take theirs first. +#[test] +fn a_clipping_path_keeps_its_own_effects_under_a_groups_effects() { + let mut clip = with_effect(square_at_100(), offset_10()); + clip.id = NodeId(2); + if let NodeKind::Path { clipping, .. } = &mut clip.kind { + *clipping = true; + } + let clipped = + Node::new(NodeId(5), NodeKind::Group { children: vec![Arc::new(clip), Arc::new(with_effect(square_at_100(), offset_10()))], clip: true }); + let g = with_effect(Node::group(NodeId(10), vec![Arc::new(clipped)]), scaled(50.0)); + let art = evaluate_container(None, &g).unwrap(); + let clip_group = art.children().unwrap()[0].clone(); + let ch = clip_group.children().unwrap(); + assert!(matches!(ch[0].kind, NodeKind::Path { clipping: true, .. }), "{:?}", ch[0].kind); + assert_eq!(crate::reshape::geometry_effects(&ch[0]).len(), 1, "the clipping path keeps its Offset Path"); + assert!(matches!(ch[1].kind, NodeKind::Group { .. }) && crate::reshape::geometry_effects(&ch[1]).is_empty(), "the member is drawn as its art"); +} + +/// A member with a linked opacity mask keeps its own effects on it, so its mask moves with it +/// under the group's Transform; so does a member with a 3D effect, whose later geometry effects +/// apply to its 3D art. +#[test] +fn members_with_linked_masks_or_3d_effects_keep_their_own_effects() { + let mut masked = with_effect(square_at_100(), offset_10()); + masked.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new( + Node::path(NodeId(2), shapes::rectangle(Rect::new(100.0, 100.0, 200.0, 200.0)), black()), + true, + ))); + let mut solid = with_effect(square_at_100(), effect(crate::solids::EXTRUDE, serde_json::json!({}))); + solid.id = NodeId(3); + solid.appearance.effects.push(scaled(50.0)); + let moved = effect("distort.transform", serde_json::json!({"moveH": 50, "strokes": true})); + let g = with_effect(Node::group(NodeId(10), vec![Arc::new(masked), Arc::new(solid)]), moved); + let art = evaluate_container(None, &g).unwrap(); + let ch = art.children().unwrap(); + assert!(matches!(ch[0].kind, NodeKind::Path { .. }) && crate::reshape::geometry_effects(&ch[0]).len() == 1, "{:?}", ch[0].kind); + let mask = ch[0].extras().mask.as_deref().unwrap().art.geometric_bounds().unwrap(); + assert!((mask.x0 - 150.0).abs() < 1e-6, "the mask moves with the square: {mask:?}"); + assert!(matches!(ch[1].kind, NodeKind::Path { .. }) && ch[1].appearance.effects.len() == 2, "{:?}", ch[1].kind); +} + +/// A nested group with a 3D effect stays as it is, with its members: the Transform listed after +/// its Extrude still applies to its 3D art. +#[test] +fn a_nested_group_with_a_3d_effect_keeps_its_own_effects() { + let inner = with_effect(square_at_100(), offset_10()); + let mut solid = with_effect(Node::group(NodeId(5), vec![Arc::new(inner)]), effect(crate::solids::EXTRUDE, serde_json::json!({}))); + solid.appearance.effects.push(scaled(50.0)); + let moved = effect("distort.transform", serde_json::json!({"moveH": 50})); + let g = with_effect(Node::group(NodeId(10), vec![Arc::new(solid)]), moved); + let art = evaluate_container(None, &g).unwrap(); + let ch = art.children().unwrap(); + assert!( + matches!(ch[0].kind, NodeKind::Group { .. }) && ch[0].id == NodeId(5) && ch[0].appearance.effects.len() == 2, + "{:?}", + ch[0].appearance.effects + ); + let member = &ch[0].children().unwrap()[0]; + assert!(matches!(member.kind, NodeKind::Path { .. }) && crate::reshape::geometry_effects(member).len() == 1, "{:?}", member.kind); +} + +/// Members nested deeper than the depth limit keep their own effects as they are. +#[test] +fn members_past_the_depth_limit_stay_as_they_are() { + let mut n = with_effect(square_at_100(), offset_10()); + for i in 0..vectorcraft_doc::depth::MAX_DEPTH { + n = Node::group(NodeId(100 + i as u64), vec![Arc::new(n)]); + } + let g = with_effect(Node::group(NodeId(10), vec![Arc::new(n)]), scaled(50.0)); + let art = evaluate_container(None, &g).unwrap(); + let mut deepest = None; + art.walk(&mut |c: &Node| { + if c.id == NodeId(1) { + deepest = Some(c.clone()); + } + }); + let deepest = deepest.unwrap(); + assert!(matches!(deepest.kind, NodeKind::Path { .. }), "{:?}", deepest.kind); + assert_eq!(crate::reshape::geometry_effects(&deepest).len(), 1); +} + +/// The depth limit counts nested groups with effects of their own too. +#[test] +fn nested_groups_with_effects_count_toward_the_depth_limit() { + let mut n = with_effect(square_at_100(), offset_10()); + for i in 0..vectorcraft_doc::depth::MAX_DEPTH { + n = with_effect(Node::group(NodeId(100 + i as u64), vec![Arc::new(n)]), effect("distort.transform", serde_json::json!({"moveH": 1}))); + } + let g = with_effect(Node::group(NodeId(10), vec![Arc::new(n)]), scaled(50.0)); + let art = evaluate_container(None, &g).unwrap(); + let mut deepest = None; + art.walk(&mut |c: &Node| { + if c.id == NodeId(1) && matches!(c.kind, NodeKind::Path { .. }) { + deepest = Some(c.clone()); + } + }); + assert!(deepest.is_some_and(|d| crate::reshape::geometry_effects(&d).len() == 1), "the deepest member keeps its effect"); +} + /// An image or a symbol instance that a group's Transform effect moves takes the placed gradients /// of its own fills along, as a path does, and each copy takes them as many times as it takes the /// transform. @@ -690,6 +982,525 @@ fn a_transform_on_a_group_paints_each_copy_with_its_own_gradient() { } } +/// A white 10 pt square with id `id` at the origin. +fn white_square(id: u64) -> Node { + Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(Paint::solid(Color::WHITE), Paint::None, 0.0)) +} + +/// `n` masked by `art`, linked or not. +fn masked_by(mut n: Node, art: Node, linked: bool) -> Node { + let mut mask = vectorcraft_doc::OpacityMask::new(art, true); + mask.linked = linked; + n.extras_mut().mask = Some(Box::new(mask)); + n +} + +/// The geometry effects that reshape a group's members, one at a time. +fn reshaping_effects() -> Vec<Effect> { + let fx = |id: &str, params: serde_json::Value| Effect { id: id.into(), params, visible: true }; + let corners = serde_json::json!({"corners": [[1.0 / 3.0, 0.0], [4.0 / 3.0, 0.0], [1.0, 1.0], [0.0, 1.0]]}); + vec![ + fx("distort.transform", serde_json::json!({"moveH": 30})), + fx("distort.transform", serde_json::json!({"rotate": 90})), + fx("distort.twist", serde_json::json!({"angle": 90})), + fx("distort.freeDistort", corners), + fx("warp.arc", serde_json::json!({})), + fx("distort.roughen", serde_json::json!({"size": 5, "seed": 3})), + fx("distort.zigZag", serde_json::json!({})), + fx("distort.puckerBloat", serde_json::json!({"amount": 50})), + fx("distort.tweak", serde_json::json!({})), + fx("path.offsetPath", serde_json::json!({"offset": 3})), + fx("stylize.roundCorners", serde_json::json!({"radius": 3})), + ] +} + +/// A group's geometry effect reshapes the art of a member's linked opacity mask as it reshapes the +/// member: a mask drawn over the member still covers it. An unlinked mask stays where it is. +#[test] +fn a_groups_geometry_effects_reshape_a_members_linked_mask_with_it() { + let square = white_square(1); + let original = square.path_data().cloned(); + for e in reshaping_effects() { + for linked in [true, false] { + let member = masked_by(square.clone(), white_square(4), linked); + let mut g = Node::group(NodeId(10), vec![Arc::new(member), sq(2, 20.0, Color::BLACK)]); + g.appearance.effects.push(e.clone()); + let art = evaluate_container(None, &g).unwrap(); + let member = &art.children().unwrap()[0]; + let mask = member.extras().mask.as_deref().unwrap(); + assert!(member.path_data().cloned() != original, "{}: the member is reshaped", e.id); + let want = if linked { member.path_data().cloned() } else { original.clone() }; + assert_eq!(mask.art.path_data().cloned(), want, "{} (linked: {linked})", e.id); + assert_eq!(mask.linked, linked); + } + } +} + +/// The mask of a group inside the group, the mask of a path in it, a mask inside that mask's art and +/// an inverted mask all take the outer group's effect with the paths they mask. +#[test] +fn a_groups_geometry_effects_reshape_nested_and_inverted_masks() { + for e in reshaping_effects() { + let innermost = masked_by(white_square(7), white_square(8), true); + let path = masked_by(white_square(1), masked_by(white_square(6), innermost, true), true); + let mut inner = masked_by(Node::group(NodeId(5), vec![Arc::new(path)]), white_square(4), true); + if let Some(m) = inner.extras_if_any().and_then(|x| x.mask.as_mut()) { + m.invert = true; + } + let mut g = Node::group(NodeId(10), vec![Arc::new(inner), sq(2, 20.0, Color::BLACK)]); + g.appearance.effects.push(e.clone()); + let art = evaluate_container(None, &g).unwrap(); + let inner = &art.children().unwrap()[0]; + let path = &inner.children().unwrap()[0]; + let want = path.path_data().cloned(); + let mask_of = |n: &Node| n.extras().mask.as_deref().map(|m| (*m.art).clone()).unwrap(); + let (outer_mask, path_mask) = (mask_of(inner), mask_of(path)); + assert!(inner.extras().mask.as_deref().is_some_and(|m| m.invert)); + assert_eq!(outer_mask.path_data().cloned(), want, "{}: the inner group's inverted mask", e.id); + assert_eq!(path_mask.path_data().cloned(), want, "{}: the path's mask", e.id); + assert_eq!(mask_of(&path_mask).path_data().cloned(), want, "{}: the mask inside the mask's art", e.id); + assert_eq!(mask_of(&mask_of(&path_mask)).path_data().cloned(), want, "{}: one level deeper", e.id); + } +} + +/// A Transform effect's copies of a path with a linked mask are objects of their own, each with the +/// mask moved with it; the original keeps its mask where it was. +#[test] +fn each_transform_copy_of_a_masked_member_carries_its_mask() { + let member = masked_by(white_square(1), white_square(4), true); + let mut g = Node::group(NodeId(10), vec![Arc::new(member)]); + let params = serde_json::json!({"moveH": 30, "copies": 2}); + g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true }); + let art = evaluate_container(None, &g).unwrap(); + let copies = art.children().unwrap()[0].children().expect("the object and its copies are objects of their own"); + assert_eq!(copies.len(), 3); + for c in copies { + let mask = c.extras().mask.as_deref().unwrap(); + assert_eq!(mask.art.geometric_bounds(), c.geometric_bounds()); + } +} + +/// A Transform effect's copies of the paths of a member group give the group's linked mask the same +/// copies: the mask covers each copy. +#[test] +fn a_member_groups_mask_takes_the_transform_copies_of_its_paths() { + let inner = masked_by(Node::group(NodeId(2), vec![Arc::new(white_square(1))]), white_square(4), true); + let mut g = Node::group(NodeId(10), vec![Arc::new(inner)]); + let params = serde_json::json!({"moveH": 30, "copies": 1}); + g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true }); + let art = evaluate_container(None, &g).unwrap(); + let inner = &art.children().unwrap()[0]; + let want = inner.geometric_bounds(); + assert_eq!(want, Some(Rect::new(0.0, 0.0, 40.0, 10.0)), "the path and its copy"); + assert_eq!(inner.extras().mask.as_deref().unwrap().art.geometric_bounds(), want); +} + +/// A mask's art of several objects takes Transform copies whole, as the art it masks does: each copy +/// of the mask's art is a group of its objects, so the copies do not interleave object by object. +#[test] +fn a_masks_art_of_several_objects_is_copied_whole() { + let mask_art = Node::group(NodeId(3), vec![Arc::new(white_square(4)), sq(5, 5.0, Color::WHITE)]); + let inner = masked_by(Node::group(NodeId(2), vec![Arc::new(white_square(1))]), mask_art, true); + let mut g = Node::group(NodeId(10), vec![Arc::new(inner)]); + let params = serde_json::json!({"moveH": 30, "copies": 1}); + g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true }); + let art = evaluate_container(None, &g).unwrap(); + let mask = &art.children().unwrap()[0].extras().mask.as_deref().unwrap().art; + let copies = mask.children().unwrap(); + assert_eq!(copies.len(), 2, "the mask's art and its copy"); + for c in copies { + let ids: Vec<NodeId> = c.children().into_iter().flatten().map(|m| m.id).collect(); + assert_eq!(ids, [NodeId(4), NodeId(5)], "each copy holds the mask's objects"); + } + assert_eq!(mask.geometric_bounds(), Some(Rect::new(0.0, 0.0, 45.0, 10.0))); +} + +/// The linked mask of a mask's art that is copied whole takes the same Transform copies. +#[test] +fn the_mask_of_a_masks_art_copied_whole_takes_its_copies() { + let parts = Node::group(NodeId(3), vec![Arc::new(white_square(4)), sq(5, 5.0, Color::WHITE)]); + let mask_art = masked_by(parts, white_square(6), true); + let inner = masked_by(Node::group(NodeId(2), vec![Arc::new(white_square(1))]), mask_art, true); + let mut g = Node::group(NodeId(10), vec![Arc::new(inner)]); + let params = serde_json::json!({"moveH": 30, "copies": 1}); + g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true }); + let art = evaluate_container(None, &g).unwrap(); + let mask = &art.children().unwrap()[0].extras().mask.as_deref().unwrap().art; + assert_eq!(mask.geometric_bounds(), Some(Rect::new(0.0, 0.0, 45.0, 10.0)), "the mask's art and its copy"); + let own = &mask.extras().mask.as_deref().expect("the mask's art keeps its own mask").art; + assert_eq!(own.geometric_bounds(), Some(Rect::new(0.0, 0.0, 40.0, 10.0)), "its mask covers the copy too"); +} + +/// The mask of a mask's art copied whole stays in the budget while that art is copied: when the +/// budget has no room for that mask's copy, the art keeps its shape with its masks. +#[test] +fn the_mask_of_a_masks_art_copied_whole_counts_against_the_budget() { + let transform = Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": 30, "copies": 1}), visible: true }; + let parts = Node::group(NodeId(3), vec![Arc::new(white_square(4)), sq(5, 5.0, Color::WHITE)]); + let mask_art = masked_by(parts, white_square(6), true); + let inner = masked_by(Node::group(NodeId(2), vec![Arc::new(white_square(1))]), mask_art, true); + let mut art = Node::group(NodeId(10), vec![Arc::new(inner)]); + let one = crate::Budget::of(white_square(1).path_data().unwrap()).lines; + // Room for the four squares and the copies of three of them, not for the copy of the fourth. + let budget = crate::Budget { anchors: usize::MAX / 4, lines: 7 * one }; + crate::reshape::reshape_leaves_within(&mut art, &[&transform], budget, None); + let inner = &art.children().unwrap()[0]; + let square = Some(Rect::new(0.0, 0.0, 10.0, 10.0)); + assert_eq!(inner.geometric_bounds(), square, "the path keeps its shape"); + let mask = &inner.extras().mask.as_deref().unwrap().art; + assert_eq!(mask.geometric_bounds(), Some(Rect::new(0.0, 0.0, 15.0, 10.0)), "and so does its mask"); +} + +/// When a member group's linked mask can't take all the Transform copies its paths take (past the +/// budget), the art keeps its shape under the effect, so the mask still covers the paths. +#[test] +fn art_whose_mask_would_take_fewer_copies_keeps_its_shape() { + let transform = Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": 30, "copies": 1}), visible: true }; + let member = masked_by(Node::group(NodeId(2), vec![Arc::new(white_square(1))]), white_square(4), true); + let mut art = Node::group(NodeId(10), vec![Arc::new(member)]); + let one = crate::Budget::of(white_square(1).path_data().unwrap()).lines; + // Room for the path, its mask and a copy of the path, not for a copy of the mask. + let budget = crate::Budget { anchors: usize::MAX / 4, lines: 3 * one }; + crate::reshape::reshape_leaves_within(&mut art, &[&transform], budget, None); + let member = &art.children().unwrap()[0]; + let square = Some(Rect::new(0.0, 0.0, 10.0, 10.0)); + assert_eq!(member.geometric_bounds(), square, "the path keeps its shape"); + assert_eq!(member.extras().mask.as_deref().unwrap().art.geometric_bounds(), square, "and so does its mask"); +} + +/// The copies of a path with a linked mask count the art of the mask each copy carries against the +/// budget: they stop where the masks would pass it. +#[test] +fn transform_copies_count_the_art_of_their_masks() { + let transform = Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": 30, "copies": 2}), visible: true }; + let member = masked_by(white_square(1), white_square(4), true); + let mut art = Node::group(NodeId(10), vec![Arc::new(member)]); + let one = crate::Budget::of(white_square(1).path_data().unwrap()).lines; + // Room for the path, its mask and one copy of both, not for a second copy. + let budget = crate::Budget { anchors: usize::MAX / 4, lines: 4 * one }; + crate::reshape::reshape_leaves_within(&mut art, &[&transform], budget, None); + let copies = art.children().unwrap()[0].children().expect("the object and its copy are objects of their own"); + assert_eq!(copies.len(), 2); + for c in copies { + assert_eq!(c.extras().mask.as_deref().unwrap().art.geometric_bounds(), c.geometric_bounds()); + } +} + +/// A Transform effect that scales strokes moves a group's paths as objects, their masks with them. +/// The mask of a member group, whose art holds a path with a mask of its own, moves with the group's +/// paths too. +#[test] +fn a_transform_that_moves_paths_as_objects_moves_a_member_groups_nested_mask() { + let mask_art = masked_by(white_square(4), white_square(5), true); + let inner = masked_by(Node::group(NodeId(2), vec![Arc::new(white_square(1))]), mask_art, true); + let mut g = Node::group(NodeId(10), vec![Arc::new(inner), sq(3, 20.0, Color::BLACK)]); + let params = serde_json::json!({"moveH": 30, "strokes": true}); + g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true }); + let art = evaluate_container(None, &g).unwrap(); + let inner = &art.children().unwrap()[0]; + let want = inner.children().unwrap()[0].geometric_bounds(); + assert_eq!(want, Some(Rect::new(30.0, 0.0, 40.0, 10.0))); + let mask = &inner.extras().mask.as_deref().unwrap().art; + assert_eq!(mask.geometric_bounds(), want, "the group's mask"); + assert_eq!(mask.extras().mask.as_deref().unwrap().art.geometric_bounds(), want, "the mask inside its art"); +} + +/// A group's Transform effect moves an image member's linked opacity mask with the image, and its +/// copies' masks with the copies; an unlinked mask stays. +#[test] +fn a_groups_transform_moves_an_image_members_linked_mask() { + for linked in [true, false] { + for copies in [0, 2] { + let im = vectorcraft_doc::ImageObject { + key: "k".into(), + width: 10, + height: 10, + xf: vectorcraft_geom::Affine::IDENTITY, + link: None, + placement: Default::default(), + pixels: None, + }; + let image = masked_by(Node::new(NodeId(1), NodeKind::Image(Box::new(im))), white_square(4), linked); + let mut g = Node::group(NodeId(10), vec![Arc::new(image)]); + let params = serde_json::json!({"moveH": 30, "copies": copies}); + g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true }); + let art = evaluate_container(None, &g).unwrap(); + let first = &art.children().unwrap()[0]; + let images: Vec<&Node> = match first.children() { + Some(ch) => ch.iter().map(|c| &**c).collect(), + None => vec![first], + }; + assert_eq!(images.len(), copies + 1); + for im in images { + let mask = im.extras().mask.as_deref().unwrap(); + let want = if linked { im.geometric_bounds() } else { Some(Rect::new(0.0, 0.0, 10.0, 10.0)) }; + assert_eq!(mask.art.geometric_bounds(), want, "linked {linked}, copies {copies}"); + } + } + } +} + +/// When a path in a member's mask art would pass the effects' budget, the whole mask stays as it +/// was, rather than part of its art moving with the member, and the member keeps its shape with it. +#[test] +fn a_mask_whose_art_passes_the_budget_stays_whole() { + // Bloat bends a path's sides into curves drawn with more lines the larger they are: many more + // on the mask's large square. + let bloat = Effect { id: "distort.puckerBloat".into(), params: serde_json::json!({"amount": 50}), visible: true }; + let large = Node::path(NodeId(5), shapes::rectangle(Rect::new(0.0, 0.0, 1000.0, 1000.0)), Appearance::default()); + let mask_art = Node::group(NodeId(3), vec![Arc::new(white_square(4)), Arc::new(large.clone())]); + let member = masked_by(white_square(1), mask_art.clone(), true); + let mut art = Node::group(NodeId(10), vec![Arc::new(member)]); + // Room for the member and the mask's small square to take the effect, not for the large one. + let bounds = art.geometric_bounds().unwrap(); + let ctx = crate::GeomContext { seed: 10, ..crate::GeomContext::of(&art) }; + let square = white_square(1).path_data().cloned().unwrap(); + let made = crate::Budget::of(&crate::apply_geometry_with(std::slice::from_ref(&bloat), &square, bounds, &ctx)).lines; + let budget = crate::Budget { anchors: usize::MAX / 4, lines: 2 * made + crate::Budget::of(large.path_data().unwrap()).lines }; + let large_made = crate::Budget::of(&crate::apply_geometry_with(std::slice::from_ref(&bloat), large.path_data().unwrap(), bounds, &ctx)).lines; + assert!(large_made > crate::Budget::of(large.path_data().unwrap()).lines, "the large square's curves cost more lines"); + crate::reshape::reshape_leaves_within(&mut art, &[&bloat], budget, None); + let member = &art.children().unwrap()[0]; + assert_eq!(member.path_data(), Some(&square), "the member keeps its shape with its mask"); + assert_eq!(*member.extras().mask.as_deref().unwrap().art, mask_art, "the mask stays whole"); +} + +/// Live objects in a member's linked mask are evaluated before the group's geometry effects run +/// over the mask's art, so the mask still covers the member: a Repeat in it moves and bends with +/// the member. +#[test] +fn a_groups_effects_reshape_a_live_object_in_a_members_mask() { + let mut grid = vectorcraft_doc::RepeatSpec::grid(vec![Arc::new(white_square(5))], 0.0, 0.0); + if let vectorcraft_doc::RepeatKind::Grid { rows, cols, .. } = &mut grid.kind { + (*rows, *cols) = (1, 1); + } + let repeat = Node::new(NodeId(4), NodeKind::Repeat(grid)); + let drawn: Vec<Node> = crate::expand_live(None, &repeat); + let leaf = |n: &Node| { + let mut found = None; + n.walk(&mut |c| found = found.take().or_else(|| c.path_data().cloned())); + found + }; + assert_eq!(drawn.iter().find_map(leaf), white_square(1).path_data().cloned(), "the Repeat draws one square over the member"); + for e in [reshaping_effects()[0].clone(), reshaping_effects()[4].clone()] { + let member = masked_by(white_square(1), repeat.clone(), true); + let mut g = Node::group(NodeId(10), vec![Arc::new(member), sq(2, 20.0, Color::BLACK)]); + g.appearance.effects.push(e.clone()); + let art = evaluate_container(None, &g).unwrap(); + let member = &art.children().unwrap()[0]; + let mask = &member.extras().mask.as_deref().unwrap().art; + assert!(member.path_data() != white_square(1).path_data(), "{}: the member is reshaped", e.id); + assert_eq!(leaf(mask), member.path_data().cloned(), "{}: the mask's square takes the effect with it", e.id); + } +} + +/// Type in a member's linked mask is outlined before the group's Transform effect moves the mask's +/// art with the member. +#[test] +fn a_groups_transform_moves_type_in_a_members_mask() { + if skip_without_craft_fonts() { + return; + } + let member = masked_by(white_square(1), type_h(), true); + let before = crate::reshape::outline_text(&type_h()).unwrap().geometric_bounds().unwrap(); + let mut g = Node::group(NodeId(10), vec![Arc::new(member)]); + g.appearance.effects.push(reshaping_effects()[0].clone()); + let art = evaluate_container(None, &g).unwrap(); + let mask = &art.children().unwrap()[0].extras().mask.as_deref().unwrap().art; + let mut text = false; + mask.walk(&mut |c| text |= matches!(c.kind, NodeKind::Text(_))); + assert!(!text, "the type is outlined"); + let after = mask.geometric_bounds().unwrap(); + assert!((after.x0 - before.x0 - 30.0).abs() < 0.5 && (after.y0 - before.y0).abs() < 0.5, "{before:?} -> {after:?}"); +} + +/// The linked mask of a compound path in a group, and of a path in a layer, takes the geometry +/// effects with the art it masks. +#[test] +fn a_compound_paths_and_a_layers_members_masks_take_the_effects() { + let geometry = |n: &Node| crate::reshape::leaf_geometry(n).map(|(p, _)| p); + for e in reshaping_effects() { + let square = white_square(1); + let compound = Node::new(NodeId(1), NodeKind::Compound { children: vec![Arc::new(square.clone())], rule: FillRule::NonZero }); + let compound = masked_by(compound, white_square(4), true); + let mut g = Node::group(NodeId(10), vec![Arc::new(compound), sq(2, 20.0, Color::BLACK)]); + g.appearance.effects.push(e.clone()); + let art = evaluate_container(None, &g).unwrap(); + let member = &art.children().unwrap()[0]; + assert!(geometry(member) != square.path_data().cloned(), "{}: the compound path is reshaped", e.id); + assert_eq!(geometry(&member.extras().mask.as_deref().unwrap().art), geometry(member), "{}: compound path", e.id); + + let mut layer = Node::layer(NodeId(10), "Layer", vectorcraft_doc::LayerColor::Preset(0)); + if let Some(ch) = layer.children_mut() { + ch.extend([Arc::new(masked_by(square.clone(), white_square(4), true)), sq(2, 20.0, Color::BLACK)]); + } + layer.appearance.effects.push(e.clone()); + let art = evaluate_container(None, &layer).unwrap(); + let member = &art.children().unwrap()[0]; + assert!(member.path_data() != square.path_data(), "{}: the layer's path is reshaped", e.id); + assert_eq!(member.extras().mask.as_deref().unwrap().art.path_data(), member.path_data(), "{}: layer", e.id); + } +} + +/// A group's Transform effect moves a symbol instance member's linked mask with the instance. +#[test] +fn a_groups_transform_moves_a_symbol_instance_members_linked_mask() { + let instance = Node::new(NodeId(1), NodeKind::SymbolInstance { symbol: "s".into(), xf: vectorcraft_geom::Affine::IDENTITY }); + let mut g = Node::group(NodeId(10), vec![Arc::new(masked_by(instance, white_square(4), true)), sq(2, 20.0, Color::BLACK)]); + g.appearance.effects.push(reshaping_effects()[0].clone()); + let art = evaluate_container(None, &g).unwrap(); + let instance = &art.children().unwrap()[0]; + let NodeKind::SymbolInstance { xf, .. } = &instance.kind else { panic!("an instance: {instance:?}") }; + assert!((xf.translation().x - 30.0).abs() < 1e-9, "the instance moves: {xf:?}"); + let mask = instance.extras().mask.as_deref().unwrap().art.geometric_bounds().unwrap(); + assert!((mask.x0 - 30.0).abs() < 1e-9 && (mask.x1 - 40.0).abs() < 1e-9, "its mask moves with it: {mask:?}"); +} + +/// With Scale Strokes & Effects on, a group's Transform effect scales the stroke of an image +/// member's linked mask as it scales that of a path member's mask. +#[test] +fn a_transform_with_scale_strokes_scales_the_masks_of_images_and_paths_alike() { + let stroked = + Node::path(NodeId(4), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(Paint::None, Paint::solid(Color::WHITE), 2.0)); + let im = vectorcraft_doc::ImageObject { + key: "k".into(), + width: 10, + height: 10, + xf: vectorcraft_geom::Affine::IDENTITY, + link: None, + placement: Default::default(), + pixels: None, + }; + let image = masked_by(Node::new(NodeId(1), NodeKind::Image(Box::new(im))), stroked.clone(), true); + let path = masked_by(white_square(2), stroked, true); + let mut g = Node::group(NodeId(10), vec![Arc::new(image), Arc::new(path)]); + let params = serde_json::json!({"scaleH": 200, "scaleV": 200, "strokes": true}); + g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true }); + let art = evaluate_container(None, &g).unwrap(); + let width = |n: &Node| n.extras().mask.as_deref().unwrap().art.appearance.stroke().map(|s| s.width); + let ch = art.children().unwrap(); + assert_eq!(width(&ch[1]), Some(4.0), "the path's mask"); + assert_eq!(width(&ch[0]), width(&ch[1]), "the image's mask"); +} + +/// With Transform Objects off and Scale Strokes & Effects on, a group's Transform effect scales the +/// strokes of a member's linked mask as it scales the member's, and moves neither. +#[test] +fn a_transform_of_strokes_only_scales_a_members_mask_strokes() { + let stroked = |id: u64| { + Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(Paint::None, Paint::solid(Color::WHITE), 2.0)) + }; + let mut g = Node::group(NodeId(10), vec![Arc::new(masked_by(stroked(1), stroked(4), true))]); + let params = serde_json::json!({"scaleH": 200, "scaleV": 200, "objects": false, "strokes": true}); + g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true }); + let art = evaluate_container(None, &g).unwrap(); + let member = &art.children().unwrap()[0]; + let mask = &member.extras().mask.as_deref().unwrap().art; + assert_eq!(member.appearance.stroke().map(|s| s.width), Some(4.0), "the member's stroke"); + assert_eq!(mask.appearance.stroke().map(|s| s.width), Some(4.0), "the mask's stroke"); + assert_eq!(mask.geometric_bounds(), member.geometric_bounds()); +} + +/// The art of a member group's mask is copied as it was before the first effect: a mask of one +/// path takes a second Transform effect's copies path by path, as the path it masks does, though +/// the first effect (with Scale Strokes & Effects) made it a group of copies. +#[test] +fn a_masks_art_is_copied_as_it_was_before_the_first_effect() { + let inner = masked_by(Node::group(NodeId(2), vec![Arc::new(white_square(1))]), white_square(4), true); + let mut g = Node::group(NodeId(10), vec![Arc::new(inner)]); + for strokes in [true, false] { + let params = serde_json::json!({"moveH": 30, "copies": 2, "strokes": strokes}); + g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true }); + } + let art = evaluate_container(None, &g).unwrap(); + let inner = &art.children().unwrap()[0]; + let mask = &inner.extras().mask.as_deref().unwrap().art; + assert_eq!(mask.geometric_bounds(), inner.geometric_bounds()); + let kinds = |n: &Node| n.children().unwrap().iter().map(|c| std::mem::discriminant(&c.kind)).collect::<Vec<_>>(); + let paths = &inner.children().unwrap()[0]; + assert_eq!(kinds(paths).len(), 3, "the first effect's three paths"); + assert!(paths.children().unwrap().iter().all(|c| matches!(c.kind, NodeKind::Compound { .. })), "each with its copies"); + assert_eq!(kinds(mask), kinds(paths), "the mask's art takes the copies as the paths do"); +} + +/// A 10 × 10 image with id `id` at the origin. +fn image_node(id: u64) -> Node { + let im = vectorcraft_doc::ImageObject { + key: "k".into(), + width: 10, + height: 10, + xf: vectorcraft_geom::Affine::IDENTITY, + link: None, + placement: Default::default(), + pixels: None, + }; + Node::new(NodeId(id), NodeKind::Image(Box::new(im))) +} + +/// A linked mask whose art is an image moves with the path it masks under a group's Transform +/// effect, and a member group's image mask takes the copies its paths take. +#[test] +fn a_groups_transform_moves_a_linked_mask_whose_art_is_an_image() { + let mut g = Node::group(NodeId(10), vec![Arc::new(masked_by(white_square(1), image_node(4), true)), sq(2, 20.0, Color::BLACK)]); + g.appearance.effects.push(reshaping_effects()[0].clone()); + let art = evaluate_container(None, &g).unwrap(); + let member = &art.children().unwrap()[0]; + assert_eq!(member.geometric_bounds(), Some(Rect::new(30.0, 0.0, 40.0, 10.0))); + assert_eq!(member.extras().mask.as_deref().unwrap().art.geometric_bounds(), member.geometric_bounds()); + + let inner = masked_by(Node::group(NodeId(2), vec![Arc::new(white_square(1))]), image_node(4), true); + let mut g = Node::group(NodeId(10), vec![Arc::new(inner)]); + let params = serde_json::json!({"moveH": 30, "copies": 2}); + g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true }); + let art = evaluate_container(None, &g).unwrap(); + let inner = &art.children().unwrap()[0]; + assert_eq!(inner.geometric_bounds(), Some(Rect::new(0.0, 0.0, 70.0, 10.0))); + let mask = &inner.extras().mask.as_deref().unwrap().art; + assert_eq!(mask.geometric_bounds(), inner.geometric_bounds(), "the image and its copies"); +} + +/// An image in a linked mask's art takes no geometry effect but Transform, so under a Warp effect +/// the art keeps its shape with its mask. +#[test] +fn art_whose_mask_holds_an_image_keeps_its_shape_under_a_warp() { + let member = masked_by(white_square(1), Node::group(NodeId(3), vec![Arc::new(image_node(4))]), true); + let mut g = Node::group(NodeId(10), vec![Arc::new(member), sq(2, 20.0, Color::BLACK)]); + g.appearance.effects.push(reshaping_effects()[4].clone()); + let art = evaluate_container(None, &g).unwrap(); + let member = &art.children().unwrap()[0]; + assert_eq!(member.path_data(), white_square(1).path_data(), "the path keeps its shape"); + assert_eq!(member.extras().mask.as_deref().unwrap().art.geometric_bounds(), Some(Rect::new(0.0, 0.0, 10.0, 10.0))); +} + +/// A Warp effect bends an image's pixels but not the art of its linked mask, so art with such an +/// image keeps its shape under the warp, with the image and its mask. +#[test] +fn art_with_a_masked_image_keeps_its_shape_under_a_warp() { + let image = masked_by(image_node(1), white_square(4), true); + let mut g = Node::group(NodeId(10), vec![Arc::new(image.clone()), sq(2, 20.0, Color::BLACK)]); + g.appearance.effects.push(reshaping_effects()[4].clone()); + let art = evaluate_container(None, &g).unwrap(); + let ch = art.children().unwrap(); + assert_eq!(*ch[0], image, "the image and its mask"); + assert_eq!(ch[1].path_data(), sq(2, 20.0, Color::BLACK).path_data(), "the path keeps its shape"); +} + +/// A symbol instance in perspective projects the linked masks of the objects in its art with them. +#[test] +fn perspective_projects_the_masks_in_a_symbols_art() { + let art = Node::group(NodeId(20), vec![Arc::new(masked_by(white_square(21), white_square(22), true))]); + let mut instance = Node::new(NodeId(1), NodeKind::SymbolInstance { symbol: "s".into(), xf: vectorcraft_geom::Affine::IDENTITY }); + let mut at = vectorcraft_doc::PerspectiveAttachment::new("left", 0.0); + at.projection = Some([1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.01, 0.0, 1.0]); + instance.extras_mut().perspective = Some(Box::new(at)); + let out = crate::reshape::reshape(None, &instance, Some(&art)).unwrap(); + let mut masked = vec![]; + out.walk(&mut |c| masked.extend(c.extras().mask.as_deref().map(|m| (c.path_data().cloned(), m.art.path_data().cloned())))); + let [(path, mask)] = masked.as_slice() else { panic!("one masked path: {masked:?}") }; + assert!(path != &white_square(21).path_data().cloned(), "the path is projected"); + assert_eq!(mask, path, "and so is its mask"); +} + /// A group with `effect` holding `n` vertical then `n` horizontal bars, 2 wide on a 4-unit /// pitch, each crossing every bar of the other direction: n² crossings. fn crossing_bars(n: usize, effect: &str) -> Node { @@ -762,6 +1573,23 @@ fn compound_shape(mode: ShapeMode) -> Node { g } +/// A compound shape's Transform effect turns its fill's drop shadow with the area it turns. +#[test] +fn a_compound_shapes_transform_turns_its_fills_shadow() { + let mut shape = compound_shape(ShapeMode::Add); + if let Some(item) = shape.appearance.items.first_mut() { + *item.effects_mut() = + vec![Effect { id: "stylize.dropShadow".into(), params: serde_json::json!({"x": 10, "y": 0, "blur": 0}), visible: true }]; + } + shape.appearance.effects.push(Effect { id: "distort.transform".into(), params: serde_json::json!({"rotate": 90}), visible: true }); + let art = shape_art(None, &shape, None).unwrap(); + let item = art.appearance.items.first().unwrap(); + match crate::raster_effects(item.effects()).first() { + Some(crate::RasterFx::DropShadow { dx, dy, .. }) => assert!(dx.abs() < 1e-9 && (dy + 10.0).abs() < 1e-9, "{dx} {dy}"), + other => panic!("expected a drop shadow, got {other:?}"), + } +} + /// A compound shape draws the area its members' modes make, one unpainted path that its own /// appearance paints; evaluated, it is plain art painted with that appearance. #[test] @@ -862,3 +1690,70 @@ fn a_layers_ruler_guides_stay_last_through_its_effects() { painted.appearance.items = Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0).items; assert_eq!(tail(&evaluate_container(None, &painted).unwrap()), guides); } + +/// The ruler guides of a sublayer in a layer with a Pathfinder effect, or a Transform effect that +/// copies its art, stay on a layer of the evaluated art, once, hidden and locked as the sublayer is. +#[test] +fn a_sublayers_ruler_guides_survive_its_layers_effects() { + use vectorcraft_doc::LayerColor; + let layer = |effect: &str, params: serde_json::Value, shown: bool| { + let mut sub = Node::layer(NodeId(11), "Sub", LayerColor::Preset(1)); + (sub.visible, sub.locked) = (shown, !shown); + if let Some(ch) = sub.children_mut() { + *ch = vec![ + sq(2, 5.0, Color::rgb(0.0, 0.0, 1.0)), + Arc::new(Node::new(NodeId(20), NodeKind::RulerGuide { vertical: true, pos: 3.0, artboard: None })), + ]; + } + let mut l = Node::layer(NodeId(10), "Layer 1", LayerColor::Preset(0)); + if let Some(ch) = l.children_mut() { + *ch = vec![sq(1, 0.0, Color::rgb(1.0, 0.0, 0.0)), Arc::new(sub)]; + } + l.appearance.effects.push(Effect { id: effect.into(), params, visible: true }); + l + }; + // The guides found where ruler guides are looked for: directly in a layer or sublayer. + fn listed(n: &Node, out: &mut Vec<(NodeId, bool, bool)>) { + for c in n.children().into_iter().flatten() { + if c.is_ruler_guide() { + out.push((c.id, c.visible, c.locked)); + } else if c.is_layer() { + listed(c, out); + } + } + } + for (effect, params) in [("pathfinder.add", serde_json::json!({})), ("distort.transform", serde_json::json!({"moveH": 30, "copies": 2}))] { + for shown in [true, false] { + let art = evaluate_container(None, &layer(effect, params.clone(), shown)).unwrap(); + let mut found = vec![]; + listed(&art, &mut found); + assert_eq!(found, [(NodeId(20), shown, !shown)], "{effect}: the sublayer's guide, once, on a layer"); + } + } +} + +/// A sublayer's ruler guide inside a hidden or locked group stays hidden or locked when its layer's +/// Pathfinder effect moves it onto the layer, as the group made it. +#[test] +fn a_sublayers_ruler_guide_in_a_hidden_or_locked_group_stays_hidden_or_locked() { + use vectorcraft_doc::LayerColor; + for (hidden, locked) in [(true, false), (false, true), (false, false)] { + let mut sub = Node::layer(NodeId(11), "Sub", LayerColor::Preset(1)); + if let Some(ch) = sub.children_mut() { + *ch = vec![ + sq(2, 5.0, Color::rgb(0.0, 0.0, 1.0)), + Arc::new(Node::new(NodeId(20), NodeKind::RulerGuide { vertical: true, pos: 3.0, artboard: None })), + ]; + } + let mut group = Node::group(NodeId(12), vec![Arc::new(sub)]); + (group.visible, group.locked) = (!hidden, locked); + let mut l = Node::layer(NodeId(10), "Layer 1", LayerColor::Preset(0)); + if let Some(ch) = l.children_mut() { + *ch = vec![sq(1, 0.0, Color::rgb(1.0, 0.0, 0.0)), Arc::new(group)]; + } + l.appearance.effects.push(Effect { id: "pathfinder.add".into(), params: serde_json::json!({}), visible: true }); + let art = evaluate_container(None, &l).unwrap(); + let guides: Vec<_> = art.children().into_iter().flatten().filter(|c| c.is_ruler_guide()).map(|c| (c.id, c.visible, c.locked)).collect(); + assert_eq!(guides, [(NodeId(20), !hidden, locked)], "hidden {hidden}, locked {locked}"); + } +} diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index 67b4b464fd..ac61746266 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -78,23 +78,32 @@ pub use lighting_presets::{LIGHTING_PRESETS, LightingPreset, lighting_preset_par pub use live::{expand_live, expand_live_deep, expanded_live_group, outline_object, text_outliner}; pub use marks::{CROP_MARKS, crop_marks_art, has_crop_marks}; pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace}; -pub use raster::{RASTERIZE, RasterFx, Rasterize, color_param, outset, raster_effects}; +pub use raster::{RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item_effects_in, outset, raster_effects, without_geometry}; pub use reshape::{ - SYMBOL_ART_MAX_NODES, expand_outlined, gives_image_shape, has_gradient_copies, has_item_geometry, has_painted_effects, has_transform_art, - has_transform_copies, has_transform_options, image_paint, needs_outline, outline_art, outline_text, reshape, + SYMBOL_ART_MAX_NODES, expand_outlined, follows_image_pixels, gives_image_shape, has_gradient_copies, has_item_geometry, has_painted_effects, + has_transform_art, has_transform_copies, has_transform_options, image_paint, needs_outline, outline_art, outline_text, reshape, +}; +pub use revolve::{ + CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in, }; -pub use revolve::{REVOLVE, has_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in}; pub use solids::{ - CLASSIC_EXTRUDE, EXTRUDE, INFLATE, ROTATE, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options, - classic_shading, extrude_options, has_solid, inflate_options, is_three_d, solid_art, solid_art_in, three_d_meshes, three_d_meshes_in, - three_d_meshes_of, three_d_meshes_of_in, three_d_params_as, validate_solid, validate_solid_in, validate_three_d, validate_three_d_at, - validate_three_d_at_in, validate_three_d_in, validate_three_d_params, view_options, + CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, GRAPHICS, GraphicFrame, INFLATE, MAX_GRAPHICS, MappedGraphic, ROTATE, ROTATE_SURFACES, + ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options, classic_shading, extrude_options, graphic_bounds, + graphic_frame, graphic_symbols, has_solid, inflate_options, is_classic_three_d, is_three_d, mapped_graphics, missing_symbol, + names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, solid_art, solid_art_in, takes_graphics, three_d_meshes, + three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as, three_d_wireframe_in, validate_solid, validate_solid_in, + validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in, validate_three_d_params, view_options, with_graphic, +}; +pub use solids::{ + GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, graphic_frame_at, graphics_reshaped_after, + rename_appearance_graphic_symbol, }; 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}; +pub use vectorcraft_three_d::PlanarFace; +pub use warp::{WARP_NET, WarpNet, WarpStyle, map_version, warp_point, warp_version}; mod catalog; mod geometry; diff --git a/crates/effects/src/params.rs b/crates/effects/src/params.rs index 7785aff335..1e3c8c1d31 100644 --- a/crates/effects/src/params.rs +++ b/crates/effects/src/params.rs @@ -31,7 +31,8 @@ pub fn merged_params(id: &str, params: &Value) -> Value { /// (`lightRotation`, `lightHeight`, `lightBehind`). Scribble took one `variation` before its /// separate `overlapVariation` and `spacingVariation`. Earlier values (from a file or a script of /// then) become the current ones that show exactly the same, unless those are given too, which win. -/// Scribble's angle is also stored above -180° and up to 180° (270° becomes -90°). +/// Scribble's angle is also stored above -180° and up to 180° (270° becomes -90°), and a Warp's +/// map `version` given as a whole float is stored as an integer. pub fn upgrade_params(id: &str, params: &Value) -> Value { match params { Value::Object(m) => { @@ -39,6 +40,7 @@ pub fn upgrade_params(id: &str, params: &Value) -> Value { upgrade_perspective(id, &mut m); upgrade_light(id, &mut m); upgrade_scribble(id, &mut m); + upgrade_warp_version(id, &mut m); Value::Object(m) } other => other.clone(), @@ -71,6 +73,19 @@ fn upgrade_perspective(id: &str, m: &mut Map<String, Value>) { } } +/// A Warp's map `version` given as a whole float (`1.0`) is stored as the integer. +fn upgrade_warp_version(id: &str, m: &mut Map<String, Value>) { + if !id.starts_with("warp.") { + return; + } + if let Some(v) = m.get_mut("version") + && !v.is_u64() + && let Some(n) = crate::warp::warp_version(v) + { + *v = json!(n); + } +} + fn upgrade_scribble(id: &str, m: &mut Map<String, Value>) { if id != "stylize.scribble" { return; @@ -91,7 +106,15 @@ pub fn new_effect(id: &str, params: &Value) -> Option<Effect> { if !catalog_index().contains_key(id) { vectorcraft_plugins::effect::installed(id)?; } - Some(Effect { id: id.to_string(), params: merged_params(id, params), visible: true }) + let mut params = merged_params(id, params); + // A new Warp takes its style's Bézier net unless a map is given; the catalog's defaults carry + // no version, so warps saved without one keep the earlier map. + if id.starts_with("warp.") + && let Value::Object(m) = &mut params + { + m.entry("version").or_insert(json!(crate::warp::WARP_NET)); + } + Some(Effect { id: id.to_string(), params, visible: true }) } /// Scale the distance parameters of `e` by `s` (Scale Strokes & Effects; see diff --git a/crates/effects/src/raster.rs b/crates/effects/src/raster.rs index cfa51ca2b0..b59d61beb2 100644 --- a/crates/effects/src/raster.rs +++ b/crates/effects/src/raster.rs @@ -1,11 +1,13 @@ //! Raster (painted) effects: descriptions for the renderer. -use serde_json::Value; +use std::borrow::Cow; + +use serde_json::{Map, Value, json}; use vectorcraft_doc::color::{BlendMode, Color}; use vectorcraft_doc::rastersettings::MAX_ADD_AROUND; -use vectorcraft_doc::{Effect, RasterColorModel, RasterEffectsSettings}; +use vectorcraft_doc::{AppearanceItem, Effect, Node, RasterColorModel, RasterEffectsSettings}; -use vectorcraft_geom::{Point, Rect}; +use vectorcraft_geom::{Affine, Point, Rect, Vec2}; use crate::merged_params; use crate::pixel::{self, PixelFx, PixelSpace}; @@ -384,9 +386,10 @@ fn opacity(p: &Value) -> f32 { (num(p, "opacity", 75.0) / 100.0).clamp(0.0, 1.0) as f32 } -/// The visible raster effects of `effects`, in stack order. +/// The visible raster effects of `effects`, in stack order, each following the Transform effects +/// listed after it ([`followed`]). pub fn raster_effects(effects: &[Effect]) -> Vec<RasterFx> { - effects + followed(effects) .iter() .filter(|e| e.visible) .filter_map(|e| { @@ -426,6 +429,214 @@ pub fn raster_effects(effects: &[Effect]) -> Vec<RasterFx> { .collect() } +/// `effects` with each raster effect following the visible Transform effects listed after it +/// ([`follow_transform`]): effects apply in the order they are listed, so a Transform effect +/// transforms what the raster effects before it paint, whatever its Scale Strokes & Effects says. +/// A hidden raster effect follows too, so it draws the same when it is shown after the Transform +/// effect has been expanded. A raster effect that a Transform effect making copies or moving at +/// random follows stays as it is, as does one after the last Transform effect. Borrowed when +/// nothing changes. +pub(crate) fn followed(effects: &[Effect]) -> Cow<'_, [Effect]> { + if !effects.iter().any(|e| e.visible && e.id == "distort.transform") { + return Cow::Borrowed(effects); + } + let mut out: Option<Vec<Effect>> = None; + // The linear part of the Transform effects after the effect at hand, the last one outermost; + // `None` once one of them makes copies or moves at random. + let mut after = Some(Affine::IDENTITY); + for (i, e) in effects.iter().enumerate().rev() { + if e.id == "distort.transform" { + after = after.and_then(|a| transform_step(e).map(|s| a * s)); + continue; + } + let Some(a) = after.filter(|a| *a != Affine::IDENTITY && follows(&e.id)) else { continue }; + let list = out.get_or_insert_with(|| effects.to_vec()); + if let Some(e) = list.get_mut(i) { + follow_transform(e, a); + } + } + out.map_or(Cow::Borrowed(effects), Cow::Owned) +} + +/// `effects` without their geometry effects, each raster effect following the Transform effects +/// it loses ([`followed`]): what an object, or a fill or stroke, keeps once its geometry effects +/// are applied to its art. +pub fn without_geometry(effects: &[Effect]) -> Vec<Effect> { + followed(effects).iter().filter(|e| !crate::is_geometry(&e.id)).cloned().collect() +} + +/// Make the raster effects of `effects`, all listed before Transform effect `t`, follow `t` as +/// [`followed`] makes them follow it, for art that applies its effects one at a time. `false` +/// when `t` leaves them as they are. +pub(crate) fn follow_one(effects: &mut [Effect], t: &Effect) -> bool { + let Some(a) = transform_step(t).filter(|a| *a != Affine::IDENTITY) else { return false }; + let mut changed = false; + for e in effects.iter_mut().filter(|e| follows(&e.id)) { + follow_transform(e, a); + changed = true; + } + changed +} + +/// The linear part of the visible Transform effects of `owner`, an object's or a container's own +/// effects, in order: what they do to the raster effects of everything the object paints (its +/// fills and strokes, and a container's members and theirs), which those effects transform with +/// the rest of the art. `None` when they leave them as they are: no Transform effect moves the +/// art, or one of them makes copies or moves at random ([`followed`]). +pub(crate) fn contents_step(owner: &[Effect]) -> Option<Affine> { + let a = owner.iter().filter(|e| e.visible && e.id == "distort.transform").try_fold(Affine::IDENTITY, |a, e| transform_step(e).map(|s| s * a))?; + (a != Affine::IDENTITY).then_some(a) +} + +/// Make the raster effects of `effects`, the own effects of something inside an object (a fill's +/// or stroke's, or a member's), follow `a`, the linear part of the object's Transform effects +/// ([`contents_step`]), which apply after all of them. `outer` is what the Transform effects +/// between them and `a` do to them (those of the fill's or stroke's object and of the groups that +/// hold it inside the object). A raster effect that the Transform effects after it in `effects` +/// move ([`followed`]) is set so that it draws as those effects, then `outer` and then `a` +/// transform it, whichever of them is applied first. One that a Transform effect after it in +/// `effects` holds back keeps its value through those effects, so it is set to draw as `outer` and +/// then `a` transform it. `false` when nothing changed. +pub(crate) fn follow_contents(effects: &mut [Effect], a: Affine, outer: Affine) -> bool { + if a == Affine::IDENTITY || !effects.iter().any(|e| follows(&e.id)) { + return false; + } + let mut changed = false; + // The linear part of the Transform effects after the effect at hand, as `followed` reads it; + // `None` once one of them holds the effect back, which they then leave as it is. + let mut after = Some(Affine::IDENTITY); + for e in effects.iter_mut().rev() { + if e.id == "distort.transform" { + after = after.and_then(|b| transform_step(e).map(|s| b * s)); + continue; + } + if !follows(&e.id) { + continue; + } + let b = outer * after.unwrap_or(Affine::IDENTITY); + // The effect is still to be mapped by `b` when it is drawn, so it takes b⁻¹·a·b now: + // drawn, it is a·b of what it was. A `b` that flattens the art takes `a` alone. + let det = b.determinant(); + let c = if b == Affine::IDENTITY || !(det.is_finite() && det.abs() > 1e-12) { a } else { b.inverse() * a * b }; + if c.is_finite() { + follow_transform(e, c); + changed = true; + } + } + changed +} + +/// Make the raster effects of the fills and strokes of `n` follow the Transform effects of its own +/// effect list ([`contents_step`]), as they do while the object is drawn with them: for art that +/// applies those effects and keeps the fills and strokes. `false` when nothing changed. +pub fn follow_items(n: &mut Node) -> bool { + let Some(a) = contents_step(&n.appearance.effects) else { return false }; + follow_items_by(n, a) +} + +/// [`follow_items`] for `n` holding the fills and strokes of an object whose own effects are +/// `owner` (the area of a compound shape, which carries none of the shape's effects). +pub(crate) fn follow_items_of(n: &mut Node, owner: &[Effect]) -> bool { + let Some(a) = contents_step(owner) else { return false }; + follow_items_by(n, a) +} + +/// Make the raster effects of the fills and strokes of `n` follow `a` ([`follow_contents`]). +fn follow_items_by(n: &mut Node, a: Affine) -> bool { + if !n.appearance.items.iter().any(|i| i.effects().iter().any(|e| follows(&e.id))) { + return false; + } + let mut changed = false; + for item in &mut n.appearance.items { + changed |= follow_contents(item.effects_mut(), a, Affine::IDENTITY); + } + changed +} + +/// Make the raster effects of `items`, the fills and strokes of an object whose own effects are +/// `owner`, follow the Transform effects of `owner` ([`follow_contents`]): for art that applies +/// those effects to the object's path and draws each fill and stroke on it as a node of its own. +pub(crate) fn follow_paints(items: &mut [AppearanceItem], owner: &[Effect]) { + let Some(a) = contents_step(owner) else { return }; + for item in items { + follow_contents(item.effects_mut(), a, Affine::IDENTITY); + } +} + +/// `effects`, those of a fill or stroke of an object whose own effects are `owner`, with each +/// raster effect following the Transform effects of `owner` as well ([`follow_contents`]): the +/// list to draw that fill's or stroke's raster effects from ([`raster_effects`]). Borrowed when +/// nothing changes. +pub fn item_effects_in<'a>(owner: &[Effect], effects: &'a [Effect]) -> Cow<'a, [Effect]> { + let Some(a) = contents_step(owner) else { return Cow::Borrowed(effects) }; + if !effects.iter().any(|e| follows(&e.id)) { + return Cow::Borrowed(effects); + } + let mut out = effects.to_vec(); + if follow_contents(&mut out, a, Affine::IDENTITY) { Cow::Owned(out) } else { Cow::Borrowed(effects) } +} + +/// How many of the effects of `effects` that [`without_geometry`] keeps no longer follow the +/// Transform effects listed after `effects` ([`followed`]): those before the last visible Transform +/// effect among them that makes copies or moves at random. +pub(crate) fn held_back(effects: &[Effect]) -> usize { + let Some(last) = effects.iter().rposition(|e| transform_step(e).is_none()) else { return 0 }; + effects.get(..last).unwrap_or_default().iter().filter(|e| !crate::is_geometry(&e.id)).count() +} + +/// Does `e` stop the raster effects listed before it from following the Transform effects after +/// it ([`followed`]): is it a visible Transform effect that makes copies or moves at random? +pub(crate) fn holds_back(e: &Effect) -> bool { + transform_step(e).is_none() +} + +/// What `e` does to the raster effects listed before it ([`followed`]): the linear part of its map +/// when it is a visible Transform effect that moves the art once, the identity when it is no +/// Transform effect, is hidden or has Transform Objects off (the art stays where it is), and `None` +/// when it makes copies or moves at random. +fn transform_step(e: &Effect) -> Option<Affine> { + if e.id != "distort.transform" || !e.visible { + return Some(Affine::IDENTITY); + } + let p = merged_params(&e.id, &e.params); + if !flag(&p, "objects", true) { + return Some(Affine::IDENTITY); + } + let (map, copies) = crate::distort::transform_map(Rect::ZERO, &p, 0); + (copies == 0 && !flag(&p, "random", false)).then(|| map.with_translation(Vec2::ZERO)) +} + +/// Does raster effect `id` follow the Transform effects listed after it ([`followed`])? An SVG +/// filter does not, and neither does Rasterize, whose image keeps its own pixel grid and room +/// around the art. +pub(crate) fn follows(id: &str) -> bool { + crate::is_raster(id) && id != crate::SVG_FILTER && id != RASTERIZE +} + +/// Make raster effect `e` follow `a`, the linear part of a Transform effect listed after it, as +/// that effect transforms what `e` paints: its distances and raster sizes scale by `a`'s mean +/// scale ([`crate::scale_effect`]), and a Drop Shadow's offset turns, reflects and scales with +/// `a`. Effects that [`follows`] leaves out stay as they are. +fn follow_transform(e: &mut Effect, a: Affine) { + if !follows(&e.id) { + return; + } + let offset = (e.id == "stylize.dropShadow").then(|| { + let p = merged_params(&e.id, &e.params); + a * Point::new(num(&p, "x", 7.0), num(&p, "y", 7.0)) + }); + if let Some(k) = vectorcraft_doc::Scaling::factor(a) { + crate::scale_effect(e, k); + } + if let Some(o) = offset.filter(|o| o.x.is_finite() && o.y.is_finite()) { + if !e.params.is_object() { + e.params = Value::Object(Map::new()); + } + e.params["x"] = json!(o.x); + e.params["y"] = json!(o.y); + } +} + /// How far the visible raster effects of `effects` paint beyond `bounds`, the (effected) /// geometry's, in document units. Geometry effects are accounted for by evaluating them. pub fn outset(effects: &[Effect], bounds: Rect) -> f64 { diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index c629cc10ca..8c829d9e0b 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -4,19 +4,23 @@ //! Geometry effects reach them through outlines: [`outline_art`] turns the object into plain paths //! (glyph outlines, the evaluated live object, the symbol's art) and [`reshape`] runs each effect //! over all of them as one piece, with the whole art's bounds as the effect's reference box, so a -//! warp bends a line of type as a whole. An image is clipped by its reshaped frame. Raster effects -//! (shadows, glows, blur, feather) stay on the result for the renderer and exporters. Type without +//! warp bends a line of type as a whole. An image is clipped by its reshaped frame, and a Warp +//! effect bends its pixels with the frame ([`cut_warped_images`]). Raster effects (shadows, glows, blur, +//! feather) stay on the result for the renderer and exporters. Type without //! inline graphics whose own fills or strokes have geometry effects is outlined too: each of those //! effects reshapes the whole outline that its fill or stroke paints. An image's own fills and //! strokes paint only the shape that a Convert to Shape or Outline Object effect on them gives -//! them ([`image_rows`]). +//! them ([`image_rows`]): Outline Object follows the outline of the image's opaque area +//! ([`opaque_area`]). -use std::collections::HashSet; -use std::sync::Arc; +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::rc::Rc; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex, OnceLock, PoisonError, Weak}; use vectorcraft_doc::live::Hooks; -use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, Node, NodeId, NodeKind}; -use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Rect, Shape, shapes}; +use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, ImageObject, Node, NodeId, NodeKind}; +use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, Shape, shapes}; use crate::{Budget, GeomContext, OutlineHook, apply_one, is_geometry, merged_params}; @@ -127,19 +131,142 @@ pub fn has_painted_effects(n: &Node) -> bool { } /// Is `n` type without inline graphics that has a fill or stroke of its own that paints and has a -/// visible geometry effect, or an image with a fill or stroke of its own that paints a shape -/// ([`image_rows`])? On type, such an effect reshapes the whole outline that its fill or stroke -/// paints ([`outline_text`], which leaves inline graphics out). +/// visible geometry effect, an image with a fill or stroke of its own that paints a shape +/// ([`image_rows`]), or a symbol instance whose active fill or stroke has a visible geometry effect +/// ([`active_fill`], [`active_stroke`])? On type, such an effect reshapes the whole outline that its +/// fill or stroke paints ([`outline_text`], which leaves inline graphics out). On a symbol +/// instance, it reshapes the fills or strokes of the art it places ([`add_instance_row_effects`]). pub fn has_item_geometry(n: &Node) -> bool { match &n.kind { NodeKind::Text(t) => { t.runs.iter().all(|r| r.inline.is_none()) && n.appearance.items.iter().any(|i| crate::paints(i) && crate::has_geometry(i.effects())) } NodeKind::Image(_) => n.appearance.items.iter().any(shapes_image), + NodeKind::SymbolInstance { .. } => { + active_fill(n).is_some_and(|f| crate::has_geometry(&f.effects)) || active_stroke(n).is_some_and(|s| crate::has_geometry(&s.effects)) + } _ => false, } } +/// The fill of symbol instance `n` whose effects its art takes: its topmost fill, the one that +/// stains the art, when it is visible and its opacity is above 0. A lower fill's effects do not +/// reach the art. +fn active_fill(n: &Node) -> Option<&vectorcraft_doc::FillLayer> { + n.appearance.fill().filter(|f| f.visible && f.opacity > 0.0) +} + +/// The stroke of symbol instance `n` whose effects its art takes: its topmost stroke, when it is +/// visible and its opacity is above 0. +fn active_stroke(n: &Node) -> Option<&vectorcraft_doc::StrokeLayer> { + n.appearance.stroke().filter(|s| s.visible && s.opacity > 0.0) +} + +/// The visible geometry effects in `fx`, in order. +fn geometry_of(fx: &[Effect]) -> Vec<Effect> { + fx.iter().filter(|e| e.visible && is_geometry(&e.id)).cloned().collect() +} + +/// `art`, the art symbol instance `n` places, with the visible geometry effects of `n`'s active +/// fill added after the effects of every fill in it that paints, and those of its active stroke +/// after the effects of every stroke in it that paints ([`active_fill`], [`active_stroke`]). Each +/// fill or stroke keeps its paint, and the others keep their shapes. Live objects in it that are +/// reached are evaluated first (with the symbols of `doc`), so the effects reshape what they draw. +/// Clip groups' clipping paths, guides and the art of opacity masks keep their shapes. A symbol +/// instance in the art takes the effects on its own active fill or stroke, or on a new fill or +/// stroke without paint when it has none, and passes them on to its own art in turn; an instance +/// of a symbol whose art (in `doc`) holds an instance of `n`'s symbol, at any depth, keeps its +/// appearance, so the effects never pass round a symbol that holds itself. Without `doc`, no +/// instance in the art takes them. +fn add_instance_row_effects(doc: Option<&Document>, n: &Node, art: &mut Node) { + let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return }; + let fill = active_fill(n).map_or(vec![], |f| geometry_of(&f.effects)); + let stroke = active_stroke(n).map_or(vec![], |s| geometry_of(&s.effects)); + if !fill.is_empty() || !stroke.is_empty() { + add_row_effects(doc, symbol, art, &fill, &stroke); + } +} + +/// Does the art of the symbol named `from` in `doc` hold an instance of the symbol named `to`, at +/// any depth of the symbols placed in it? `seen` holds the symbols already looked into. +fn places_symbol(doc: &Document, from: &str, to: &str, seen: &mut HashSet<String>) -> bool { + if !seen.insert(from.to_string()) { + return false; + } + let Some(sym) = doc.symbols.iter().find(|s| s.name == from) else { return false }; + let mut names = vec![]; + sym.art.walk(&mut |c| { + if let NodeKind::SymbolInstance { symbol, .. } = &c.kind { + names.push(symbol.clone()); + } + }); + names.iter().any(|name| name == to || places_symbol(doc, name, to, seen)) +} + +/// [`add_instance_row_effects`] of `fill` and `stroke` to `n` and the art in it, the art of an +/// instance of the symbol named `outer`. +fn add_row_effects(doc: Option<&Document>, outer: &str, n: &mut Node, fill: &[Effect], stroke: &[Effect]) { + match &n.kind { + NodeKind::Path { clipping: true, .. } | NodeKind::Path { guide: true, .. } | NodeKind::RulerGuide { .. } => return, + NodeKind::SymbolInstance { symbol, .. } => { + if let Some(d) = doc + && !places_symbol(d, symbol, outer, &mut HashSet::new()) + { + add_to_instance(n, fill, stroke); + } + return; + } + _ if vectorcraft_doc::live::is_live(n) => *n = evaluated(doc, n), + _ => {} + } + let takes = |i: &AppearanceItem| { + crate::paints(i) && !matches!(i, AppearanceItem::Fill(_) if fill.is_empty()) && !matches!(i, AppearanceItem::Stroke(_) if stroke.is_empty()) + }; + if n.appearance.items.iter().any(takes) { + for item in n.appearance.items.iter_mut().filter(|i| takes(i)) { + let fx = if matches!(item, AppearanceItem::Fill(_)) { fill } else { stroke }; + item.effects_mut().extend_from_slice(fx); + } + } + // A compound path paints its members with its own fills and strokes. + if matches!(n.kind, NodeKind::Compound { .. }) { + return; + } + // A clip group's first member is its clipping path, whatever its kind. + let clips = n.clips(); + for (i, c) in n.children_mut().into_iter().flatten().enumerate() { + if !(clips && i == 0) { + add_row_effects(doc, outer, Arc::make_mut(c), fill, stroke); + } + } +} + +/// Add `fill` to the effects of symbol instance `n`'s active fill and `stroke` to those of its +/// active stroke ([`active_fill`], [`active_stroke`]); without one, to a new topmost fill or stroke +/// without paint, which neither stains nor strokes its art. +fn add_to_instance(n: &mut Node, fill: &[Effect], stroke: &[Effect]) { + if !fill.is_empty() { + match n.appearance.fill_mut().filter(|f| f.visible && f.opacity > 0.0) { + Some(f) => f.effects.extend_from_slice(fill), + None => { + let mut f = vectorcraft_doc::FillLayer::new(vectorcraft_doc::color::Paint::None); + f.effects = fill.to_vec(); + n.appearance.items.push(AppearanceItem::Fill(f)); + } + } + } + if !stroke.is_empty() { + match n.appearance.stroke_mut().filter(|s| s.visible && s.opacity > 0.0) { + Some(s) => s.effects.extend_from_slice(stroke), + None => { + let mut s = vectorcraft_doc::StrokeLayer::new(vectorcraft_doc::color::Paint::None, 0.0); + s.effects = stroke.to_vec(); + n.appearance.items.push(AppearanceItem::Stroke(s)); + } + } + } +} + /// Does effect `e` give an image's fill or stroke a shape to paint (a visible Convert to Shape or /// Outline Object)? fn gives_shape(e: &Effect) -> bool { @@ -161,8 +288,8 @@ pub fn gives_image_shape(effects: &[Effect]) -> bool { /// The fills and strokes of `items` (an image's own) that paint something ([`shapes_image`]), each /// without the effects before its first Convert to Shape or Outline Object. Convert to Shape sizes -/// its shape from the image's box, and Outline Object gives the image's frame. The others paint -/// nothing. +/// its shape from the image's box, and Outline Object gives the outline of the image's opaque +/// area ([`opaque_area`]), or its frame when it has no transparency. The others paint nothing. fn image_rows(items: &[AppearanceItem]) -> Vec<AppearanceItem> { items .iter() @@ -177,11 +304,109 @@ fn image_rows(items: &[AppearanceItem]) -> Vec<AppearanceItem> { .collect() } +/// Does `item`, one of [`image_rows`], start from the outline of the image's opaque area (is its +/// first effect Outline Object rather than Convert to Shape)? +fn follows_opaque_area(item: &AppearanceItem) -> bool { + item.effects().first().is_some_and(|e| e.id == "path.outlineObject") +} + +/// Is `n` an image with a fill or stroke of its own that follows the outline of the image's opaque +/// area ([`image_rows`], [`opaque_area`])? The shape that fill or stroke paints then changes with +/// the image's pixels in the document while `n` stays the same. +pub fn follows_image_pixels(n: &Node) -> bool { + matches!(n.kind, NodeKind::Image(_)) + && n.appearance + .items + .iter() + .any(|i| shapes_image(i) && i.effects().iter().find(|e| gives_shape(e)).is_some_and(|e| e.id == "path.outlineObject")) +} + +/// The outline of a set of pixels' opaque area, in the pixel space they decode to, with that size +/// ([`traced_opaque_area`]). `None` for pixels that have no transparency or could not be traced. +type Traced = Option<(Arc<PathData>, (u32, u32))>; + +/// One of [`Outlines`]' entries: the pixels, held weakly, and their outline once it is traced. +type Entry = (Weak<Vec<u8>>, Arc<OnceLock<Traced>>); + +/// The outlines [`opaque_area`] has traced, by the address of the pixels each was traced from. +struct Outlines { + /// Each outline with its pixels. An entry does not keep its pixels, and while it is kept no + /// other pixels can take their address. Entries whose pixels are gone are dropped before a + /// new outline is traced and every [`PRUNE_EVERY`] lookups. + kept: BTreeMap<usize, Entry>, + /// The lookups since the last pruning. + lookups: usize, +} + +static OUTLINES: Mutex<Outlines> = Mutex::new(Outlines { kept: BTreeMap::new(), lookups: 0 }); + +/// How many lookups [`OUTLINES`] takes between two prunings of its entries for pixels that are gone. +const PRUNE_EVERY: usize = 256; + +#[cfg(test)] +thread_local! { + /// The outlines [`traced_opaque_area`] has traced on this thread. + pub(crate) static TRACES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; +} + +/// Does [`OUTLINES`] keep an entry for `pixels`? +#[cfg(test)] +pub(crate) fn keeps_outline(pixels: &Weak<Vec<u8>>) -> bool { + OUTLINES.lock().unwrap_or_else(PoisonError::into_inner).kept.values().any(|(w, _)| w.ptr_eq(pixels)) +} + +/// The outline of the opaque area of the image `im` in the document +/// ([`vectorcraft_trace::opaque_outline`]: its pixels that are at least half opaque, outlined with +/// fitted curves), its pixels taken from `im` itself or from the first of `docs` that holds them. +/// `None` when the image has no transparency, its pixels can't be read or are too large to read +/// ([`vectorcraft_trace::decode_alpha`]), or its outline would be too complex: Outline Object then +/// follows the image's frame. The outline is traced once for each set of pixels and kept while +/// those pixels are: a caller that asks while another thread traces the same pixels waits for that +/// trace. +pub(crate) fn opaque_area(docs: &[Option<&Document>], im: &ImageObject) -> Option<PathData> { + let blob = im.pixels.as_deref().or_else(|| docs.iter().flatten().find_map(|d| d.images.get(&im.key)))?; + let bytes = &blob.bytes; + let cell = { + let mut o = OUTLINES.lock().unwrap_or_else(PoisonError::into_inner); + o.lookups += 1; + if o.lookups >= PRUNE_EVERY { + o.lookups = 0; + o.kept.retain(|_, (w, _)| w.strong_count() > 0); + } + let key = Arc::as_ptr(bytes).addr(); + match o.kept.get(&key) { + Some((_, cell)) => Arc::clone(cell), + None => { + o.kept.retain(|_, (w, _)| w.strong_count() > 0); + let cell = Arc::new(OnceLock::new()); + o.kept.insert(key, (Arc::downgrade(bytes), Arc::clone(&cell))); + cell + } + } + }; + // Traced without the lock: another image's outline need not wait for this one. + let (path, (w, h)) = cell.get_or_init(|| traced_opaque_area(bytes)).clone()?; + let to_image = Affine::scale_non_uniform(f64::from(im.width) / f64::from(w.max(1)), f64::from(im.height) / f64::from(h.max(1))); + Some(path.transformed(im.xf * to_image)) +} + +/// [`opaque_area`]'s outline of the encoded image `bytes`. An image whose format has no alpha is +/// not decoded. +fn traced_opaque_area(bytes: &[u8]) -> Traced { + #[cfg(test)] + TRACES.with(|t| t.set(t.get() + 1)); + let (w, h, alpha) = vectorcraft_trace::decode_alpha(bytes).ok()??; + let outline = vectorcraft_trace::opaque_outline(w, h, alpha).ok()??; + Some((Arc::new(outline), (w, h))) +} + /// The shapes that the image `n`'s own fills and strokes paint ([`image_rows`]), each with its fill -/// rule and the fill or stroke that paints it: the paths (or compound paths) along its frame that -/// [`reshape`] makes, with each fill's or stroke's geometry effects applied as the renderer applies -/// them. Empty for anything but an image with such fills or strokes. The swatches and patterns that -/// live-effect plug-ins painting their pieces name are looked up in `doc`. +/// rule and the fill or stroke that paints it: the paths (or compound paths) that [`reshape`] +/// makes along its frame or, for those whose first effect is Outline Object, along the outline of +/// its opaque area ([`opaque_area`]), with each fill's or stroke's geometry effects applied as the +/// renderer applies them. Empty for anything but an image with such fills or strokes. The swatches +/// and patterns that live-effect plug-ins painting their pieces name are looked up in `doc`, and +/// the image's pixels in `doc` when the image does not hold them. pub fn image_paint(doc: Option<&Document>, n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> { if !matches!(n.kind, NodeKind::Image(_)) || !has_item_geometry(n) { return vec![]; @@ -299,7 +524,10 @@ fn with_id(art: &Node, id: NodeId) -> Node { /// `n` as plain art that geometry effects can reshape, without its transparency and object /// effects: type outlined ([`outline_text`]), live objects evaluated (type inside them outlined), /// a symbol instance as `symbol_art` (the symbol's art, stained as the caller draws it) placed by -/// the instance's transform (through the symbol's 9-slice guides in `doc`, when it has them). +/// the instance's transform (through the symbol's 9-slice guides in `doc`, when it has them), as +/// the art its members draw when the instance has geometry effects of its own +/// ([`crate::group::members_as_drawn`]), its fills and strokes carrying the geometry effects of the +/// instance's active fill and stroke ([`add_instance_row_effects`]). /// `None` for other kinds (images, paths, containers), and for an instance whose art placed /// through the guides could hold more than [`vectorcraft_doc::MAX_SYMBOL_NODES`] objects. A Repeat counts the Repeats in the art of /// `doc`'s symbols that its instances show toward its instance budget. @@ -335,19 +563,18 @@ fn outline_art_with( Node::group(n.id, vec![Arc::new(a)]) } // The object as the one piece the copies of its Transform effect are made from. - _ if has_transform_art(n) || (apart && has_transform_copies(n)) => { - let mut one = n.clone(); - one.opacity = 1.0; - one.blend = Default::default(); - one.isolate = false; - one.extras_mut().mask = None; - one.appearance.effects.clear(); - Node::group(n.id, vec![Arc::new(one)]) - } + _ if has_transform_art(n) || (apart && has_transform_copies(n)) => one_piece(n), _ if vectorcraft_doc::live::is_live(n) => evaluated_with(symbols, n, outline, nodes), _ => return None, }; outline_nested_text(paint_doc, &mut art, false); + if matches!(n.kind, NodeKind::SymbolInstance { .. }) { + // The instance's own geometry effects reshape what the symbol's members draw. + if !geometry_effects(n).is_empty() { + crate::group::members_as_drawn(paint_doc, &mut art); + } + add_instance_row_effects(symbols, n, &mut art); + } art.opacity = 1.0; art.blend = Default::default(); art.isolate = false; @@ -477,9 +704,10 @@ pub(crate) fn outline_nested_text(doc: Option<&Document>, n: &mut Node, clipping /// `n` (see [`needs_outline`]) with its object-level geometry effects and its perspective applied: /// its [`outline_art`] reshaped as one piece, or for an image the image clipped by its reshaped /// frame. Type's own fills and strokes keep their effects on its whole outline. An image's own -/// fills and strokes that paint a shape ([`image_rows`]) become paths along its frame below and -/// above it, reshaped with it, and keep their effects from their first Convert to Shape or Outline -/// Object on. The result is a group with `n`'s id, name, visibility, transparency, opacity mask +/// fills and strokes that paint a shape ([`image_rows`]) become paths below and above it, along +/// its frame or, from Outline Object, along the outline of its opaque area ([`opaque_area`]), +/// reshaped with it, and keep their effects from their first Convert to Shape or Outline Object +/// on. The result is a group with `n`'s id, name, visibility, transparency, opacity mask /// and remaining (raster) effects; `None` when `n` has no visible geometry effect, no perspective /// and is not type or an image with a fill or stroke of its own that [`has_item_geometry`] counts, /// or has no art (a symbol instance without `symbol_art`). A path with [`has_transform_art`] is @@ -494,8 +722,10 @@ pub fn reshape(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> O /// `n` (see [`needs_outline`], or a path with [`has_transform_art`]) as plain art for Expand /// Appearance: [`reshape`]d when it has -/// geometry effects, else type with fills or strokes of its own outlined, or an image with fills -/// or strokes of its own that paint a shape, in the same form. `None` when it has none of these. +/// geometry effects, else type with fills or strokes of its own outlined, an image with fills or +/// strokes of its own that paint a shape, or a symbol instance's art reshaped by the geometry +/// effects of its active fill or stroke ([`has_item_geometry`]), in the same form. `None` when it +/// has none of these. pub fn expand_outlined(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> Option<Node> { // A path whose Transform effect copies it, or scales its strokes or moves its patterns: each // copy an object of its own with the path's fills and strokes, the copies of each Transform @@ -548,7 +778,15 @@ fn as_art_opts( let mut art = match &n.kind { NodeKind::Image(im) => { let frame = shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf); - let image = Node::new(n.id, n.kind.clone()); + let mut image = Node::new(n.id, n.kind.clone()); + // Its pixels draw as the image's do: colorized by a grayscale image's fill color, + // smoothed or not, and with its color mask's masked pixels. + { + let mut e = image.extras_mut(); + e.colorize = n.extras().colorize.clone(); + e.pixelated = n.extras().pixelated; + e.color_mask = n.extras().color_mask.clone(); + } let clipped = || { let mut clip = Node::path(n.id, frame.clone(), Appearance::default()); if let NodeKind::Path { clipping, .. } = &mut clip.kind { @@ -556,15 +794,33 @@ fn as_art_opts( } Node::new(n.id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(image.clone())], clip: true }) }; - // The fills and strokes that paint a shape, as paths along the frame below and above - // the image. + // The fills and strokes that paint a shape, as paths below and above the image: along + // the frame, or for those whose first effect is Outline Object along the outline of + // the image's opaque area (traced only when one of them needs it). A run of either + // kind is one path; a fill or stroke whose outline is empty (an image with no opaque + // pixel) paints nothing. let (below, above) = n.appearance.split_contents(); let (below, above) = (image_rows(below), image_rows(above)); if below.is_empty() && above.is_empty() { clipped() } else { + let opaque = std::cell::OnceCell::new(); let rows = |items: Vec<AppearanceItem>| { - (!items.is_empty()).then(|| Arc::new(Node::path(n.id, frame.clone(), Appearance { items, ..Default::default() }))) + let mut out = vec![]; + let mut items = items.into_iter().peekable(); + while let Some(first) = items.next() { + let follows = follows_opaque_area(&first); + let mut run = vec![first]; + while let Some(next) = items.next_if(|i| follows_opaque_area(i) == follows) { + run.push(next); + } + let path = if follows { opaque.get_or_init(|| opaque_area(&[symbols, paint_doc], im)).as_ref() } else { None }; + let path = path.unwrap_or(&frame); + if !path.is_empty() { + out.push(Arc::new(Node::path(n.id, path.clone(), Appearance { items: run, ..Default::default() }))); + } + } + out }; // Without geometry effects, the image is not clipped. let image = if fx.is_empty() { image.clone() } else { clipped() }; @@ -580,27 +836,100 @@ fn as_art_opts( transform_items(&mut art, paint_doc); // Type and symbols in perspective: the art projected onto their plane. if let Some(h) = n.projection() { - project_leaves(&mut art, &h); + project_leaves(&mut art, &h, paint_doc); } // The art is a group with `n`'s id (for an image without fills or strokes that paint, a clip // group). - let mut out = art; - out.name = n.name.clone(); - out.visible = n.visible; - out.opacity = n.opacity; - out.blend = n.blend; - out.isolate = n.isolate; - // One element: its pieces never knock each other out. - out.knockout = vectorcraft_doc::Knockout::Off; - out.knockout_shape = n.knockout_shape; - out.extras_mut().mask = n.extras().mask.clone(); - out.appearance.effects = n.appearance.effects.iter().filter(|e| !is_geometry(&e.id)).cloned().collect(); - Some(out) + Some(dressed(art, n)) } -/// Map every path under `art` (and its gradients) through the projective map `h`, curves split -/// finely enough to follow it. -fn project_leaves(art: &mut Node, h: &vectorcraft_geom::Homography) { +/// `art`, the art made of `n`, with `n`'s name, visibility, transparency, opacity mask and +/// remaining (raster) effects. +fn dressed(mut art: Node, n: &Node) -> Node { + art.name = n.name.clone(); + art.visible = n.visible; + art.opacity = n.opacity; + art.blend = n.blend; + art.isolate = n.isolate; + // One element: its pieces never knock each other out. + art.knockout = vectorcraft_doc::Knockout::Off; + art.knockout_shape = n.knockout_shape; + art.extras_mut().mask = n.extras().mask.clone(); + art.appearance.effects = crate::raster::without_geometry(&n.appearance.effects); + art +} + +/// A group with `n`'s id holding `n` without its transparency, opacity mask and effects: the one +/// piece that `n`'s own geometry effects reshape. +fn one_piece(n: &Node) -> Node { + let mut one = n.clone(); + one.opacity = 1.0; + one.blend = Default::default(); + one.isolate = false; + one.extras_mut().mask = None; + one.appearance.effects.clear(); + Node::group(n.id, vec![Arc::new(one)]) +} + +/// Path or compound path `n` with its own geometry effects applied, as the art it draws: with +/// geometry effects in a visible fill or stroke of its own, a group of one path for each fill and +/// stroke, its effects and that fill's or stroke's applied ([`crate::bake_type_appearance`]); +/// otherwise a group with `n`'s id holding the path reshaped by its effects ([`reshape_leaves`]). +/// The art keeps `n`'s id, name, visibility, transparency, opacity mask and raster effects. `None` +/// for a guide, for other kinds of objects, for a path with a linked opacity mask or a 3D effect, +/// and when `n` has no visible geometry effect of its own or in a visible fill or stroke. +pub(crate) fn own_effects_art(doc: Option<&Document>, n: &Node) -> Option<Node> { + if !matches!(n.kind, NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. }) + || n.extras().mask.as_ref().is_some_and(|m| m.linked) + || crate::has_solid(n) + || crate::has_revolve(n) + { + return None; + } + if n.appearance.items.iter().any(|i| crate::paints(i) && crate::has_geometry(i.effects())) { + // One element: its pieces never knock each other out. + return crate::bake_type_appearance(doc, n).map(|art| Node { knockout: vectorcraft_doc::Knockout::Off, ..art }); + } + let fx = geometry_effects(n); + if fx.is_empty() { + return None; + } + let mut art = one_piece(n); + let carry = reshape_leaves_carrying(&mut art, &fx, &n.appearance.effects, doc); + transform_items(&mut art, doc); + let mut art = dressed(art, n); + // The raster effects before a Transform effect the path did not take stay as the path does. + if carry.skipped() { + let mut ran = n.appearance.effects.clone(); + carry.hide_skipped(&mut ran); + art.appearance.effects = crate::raster::without_geometry(&ran); + } + Some(art) +} + +/// Map every path under `art` (and its gradients), and every path in the art of the linked opacity +/// masks of the objects under it, through the projective map `h`, curves split finely enough to +/// follow it. The type and live objects in the art of those masks are outlined and evaluated +/// first ([`outlined_members`], with the symbols of `doc`). +fn project_leaves(art: &mut Node, h: &vectorcraft_geom::Homography, doc: Option<&Document>) { + project_paths(art, h); + each_linked_mask_mut(art, false, 0, &mut |m| { + *m = outlined_mask_art(doc, m); + project_paths(m, h); + }); +} + +/// `art`, the art of an opacity mask, with type and live objects in it outlined and evaluated +/// ([`outlined_members`]), and as art that keeps its look ([`as_art`]) when it is type itself. +fn outlined_mask_art(doc: Option<&Document>, art: &Node) -> Node { + match art.kind { + NodeKind::Text(_) => as_art(doc, art, None).unwrap_or_else(|| art.clone()), + _ => outlined_members(doc, art), + } +} + +/// The paths of [`project_leaves`] outside the art of masks. +fn project_paths(art: &mut Node, h: &vectorcraft_geom::Homography) { let f = |p: vectorcraft_geom::Point| h.apply(p).unwrap_or(p); let piece = art.geometric_bounds().map_or(1.0, |b| (b.width().max(b.height()) / 64.0).max(0.25)); let project = |path: &mut PathData| *path = vectorcraft_doc::live::map_nonlinear(path, piece, f); @@ -632,9 +961,9 @@ pub(crate) fn geometry_effects(n: &Node) -> Vec<&Effect> { /// Apply `fx` to every path under `art` as one piece: each effect takes the whole art's bounds as /// its reference box and the art's seed (a random Transform moves the pieces together). Images and -/// symbol instances follow a Transform effect the same way ([`transform_placed`]); other geometry -/// effects leave them as they are (a raster follows a non-affine map only as a mesh warp). The -/// paths keep to one [`Budget::EFFECTS`] together (or to what they cost, when that is more): a path +/// symbol instances follow a Transform effect the same way ([`transform_placed`]), and images +/// follow a Warp effect as a raster mesh warp ([`cut_warped_images`]); other geometry effects leave them +/// as they are. The paths keep to one [`Budget::EFFECTS`] together (or to what they cost, when that is more): a path /// whose effect would pass what the others leave of it keeps its shape. The swatches and patterns /// that live-effect plug-ins painting their pieces name are looked up in `doc`, and a deferred one /// is listed by its index in `owner`, the effect list `fx` was taken from ([`reshape_leaves_apart`]). @@ -675,59 +1004,173 @@ fn hoist_copies(art: &mut Node) { /// of their own ([`copy_leaf`]) whatever paints them, as Expand Appearance makes them. A live-effect /// plug-in that paints what it returns makes each path a group of its pieces ([`paint_leaf`]), /// whose swatches and patterns must be in `doc` (without one, pieces that name one are refused). -/// Returns how gradients that paint the art as a whole follow the effects. A deferred live-effect +/// Returns how gradients that paint the art as a whole follow the effects, and the Transform +/// effects that nothing in the art took past the budget ([`crate::Carry::skipped`]). A deferred live-effect /// plug-in is listed by its index in `owner`, the effect list `fx` was taken from, or in `fx` when -/// `owner` does not hold it. +/// `owner` does not hold it. The art of the linked opacity masks of the objects in `art` (not of +/// `art` itself) takes each effect as the paths it masks do ([`Step::reshape_masks`]), with the +/// type and live objects in it outlined and evaluated first ([`outlined_members`]). When a mask +/// stays as it was, or a Transform effect makes fewer copies than it asks for, art with linked +/// masks keeps its shape under that effect. fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget: Budget, apart: bool, doc: Option<&Document>) -> crate::Carry { let mut whole = crate::Carry::default(); if fx.is_empty() { return whole; } - let mut leaves_safe = true; - for_each_leaf(art, &mut |leaf| { - if !leaves_safe { - return; - } - if let Some((_, rule)) = leaf_geometry(leaf) { - let has_stroke = leaf.appearance.stroke().is_some_and(|s| !s.paint.is_none() && s.width > 0.0); - if rule != FillRule::NonZero || has_stroke { - leaves_safe = false; - } - } - }); + let masked = has_linked_mask(art, false); + if masked { + each_linked_mask_mut(art, false, 0, &mut |m| *m = outlined_mask_art(doc, m)); + } + let mut masks_safe = true; + each_linked_mask(art, false, 0, &mut |_, m| masks_safe &= leaves_safe(m)); let art_stroke = art.appearance.stroke().is_some_and(|s| !s.paint.is_none() && s.width > 0.0); - let style_safe = leaves_safe && !art_stroke; + let style_safe = leaves_safe(art) && masks_safe && !art_stroke; let listed = fx; let opt_fx = crate::geometry::optimize_geometry_effects(fx, style_safe); let fx = opt_fx.as_slice(); let seed = art.id.0; let mut used = art_cost(art); + each_linked_mask(art, false, 0, &mut |_, m| used = used.plus(art_cost(m))); let max = budget.at_least(used); - // Read before the effects run: a path's own copies don't make it art of several objects. + // Read before the effects run: a path's own copies don't make it art of several objects. The + // same holds for the art of each mask, listed by the object it masks. let copy_whole = copies_whole(art); + let mut wholes = HashMap::new(); + each_linked_mask(art, false, 0, &mut |id, m| { + wholes.entry(id).or_insert_with(|| copies_whole(m)); + }); + let mut warped = WarpedImages::new(); + // The raster effects of what the art holds follow each Transform effect that moves it once, + // whatever its options, unless one of the effects makes copies or moves at random + // ([`crate::raster::contents_step`], [`follow_art`]). + let held = listed.iter().any(|e| crate::raster::holds_back(e)); for e in fx { - let Some(bounds) = art.geometric_bounds() else { break }; + let Some(bounds) = warped.bounds(art) else { break }; let params = merged_params(&e.id, &e.params); // Where a live-effect plug-in sits, which it is listed by when it is deferred. let effect = owner.iter().position(|x| std::ptr::eq(x, *e)).or_else(|| listed.iter().position(|x| std::ptr::eq(*x, *e))); + let step = Step { e, params: ¶ms, bounds, seed, effect, apart, doc, wholes: &wholes, held }; + // Art with linked masks keeps its shape under an effect that a mask in it could not take + // as the art it masks did, so no mask is left apart from its art. + let before = masked.then(|| (art.clone(), used)); + let ran = step.run(art, max, &mut used, copy_whole, Some(&mut warped), false, 0); + if (ran.masks || ran.short) + && let Some((was, cost)) = before + { + *art = was; + used = cost; + continue; + } + // A Transform effect that moves the art once and that nothing in it took (past the budget) + // is left out ([`crate::Carry::hide_skipped`]), listed by its index in `owner`. + if ran.kept + && !ran.took + && e.id == "distort.transform" + && !crate::raster::holds_back(e) + && let Some(i) = owner.iter().position(|x| std::ptr::eq(x, *e)) + { + whole.skip(i); + } + if let Some(carry) = ran.whole { + whole.push(carry); + } + } + cut_warped_images(art, &warped); + whole +} + +/// One geometry effect of an object run over its art ([`reshape_leaves_apart`]): the effect, its +/// merged params, the reference box and seed of the object's art, where a deferred live-effect +/// plug-in is listed, whether each Transform copy becomes an object, the document that the +/// swatches and patterns of painted pieces are looked up in, [`copies_whole`] of the art of +/// each linked mask before the first effect, by the id of the object it masks, and whether one of +/// the object's effects holds the raster effects in its art back from its Transform effects +/// ([`follow_art`]). +struct Step<'a> { + e: &'a Effect, + params: &'a serde_json::Value, + bounds: Rect, + seed: u64, + effect: Option<usize>, + apart: bool, + doc: Option<&'a Document>, + wholes: &'a HashMap<NodeId, bool>, + held: bool, +} + +/// What [`Step::run`] did to a piece of art. +struct Ran { + /// A path in the art kept its shape (past the budget). + kept: bool, + /// A path, image or symbol instance in the art took the effect. + took: bool, + /// The linked opacity mask of an object in the art stayed as it was while the paths it masks + /// took the effect, or could have ([`Step::reshape_masks`]). + masks: bool, + /// A Transform effect made fewer copies of a path, image or symbol instance than it asks for + /// (past the budget or out of reach), where a linked mask could take a different number. + short: bool, + /// How what paints the art as a whole follows the effect, when it does. + whole: Option<crate::Carry>, +} + +impl Ran { + /// Nothing in the art kept its shape or made fewer copies, and every linked mask in it moved. + fn complete(&self) -> bool { + !self.kept && !self.masks && !self.short + } +} + +impl Step<'_> { + /// Run the effect over `art`, whose paths and those of the linked opacity masks in it keep to + /// `max` together with what they cost so far (`used`). `copy_whole` is [`copies_whole`] of the + /// art, or of a mask's art, before the first effect. `warped` lists the images Warp effects + /// bend in the art ([`WarpedImages`]); a mask's art has none. With `own`, `art` is the art of a + /// mask, and its own linked mask takes the effect too. `depth` counts the masks `art` is in. A + /// live-effect plug-in that paints its pieces leaves a mask's art, and art that holds objects + /// with linked masks, as they are and reports the masks as stayed: a mask can't take the + /// pieces as the art it masks does. So does a Warp effect that bends an image with a linked + /// mask. + #[allow(clippy::too_many_arguments)] + fn run( + &self, + art: &mut Node, + max: Budget, + used: &mut Budget, + copy_whole: bool, + mut warped: Option<&mut WarpedImages>, + own: bool, + depth: usize, + ) -> Ran { + let (e, params, bounds, seed) = (self.e, self.params, self.bounds, self.seed); + let stayed = Ran { kept: false, took: false, masks: true, short: false, whole: None }; if let Some(plugin) = painted_plugin(e) { - let at = effect.map(|effect| vectorcraft_plugins::deferred::Stage { object: seed, effect, item: None }); + if own || has_linked_mask(art, false) { + return stayed; + } + let at = self.effect.map(|effect| vectorcraft_plugins::deferred::Stage { object: seed, effect, item: None }); for_each_leaf(art, &mut |leaf| { let Some((path, _)) = leaf_geometry(leaf) else { return }; let before = Budget::of(&path); let room = max.minus(used.minus(before)); - if let Some(made) = paint_leaf(leaf, plugin, ¶ms, bounds, room, doc, at) { - used = used.minus(before).plus(made); + if let Some(made) = paint_leaf(leaf, plugin, params, bounds, room, self.doc, at) { + *used = used.minus(before).plus(made); } }); - continue; + return Ran { kept: false, took: true, masks: false, short: false, whole: None }; + } + // A Warp effect that bends images ([`mark_warped_images`]) bends an image's pixels, not the + // art of its linked mask. + let warp = e.id.strip_prefix("warp.").and_then(crate::warp::WarpStyle::from_id).filter(|_| crate::warp::bends(&e.id, params)); + if warp.is_some() && has_masked_image(art) { + return stayed; } // Placed gradients follow a Transform effect, Free Distort and the Warp effects // ([`crate::Carry`]): under Free Distort and Warp (`boxes`) each path's move and scale from // its bounds before the effect to its bounds after it. Under those and the other effects, // the placed gradients of type's outlines in `art` (`outline_text`) move and scale with // the outlines' bounds. - let follows = crate::Carry::follows(&e.id, ¶ms, bounds, seed); + let follows = crate::Carry::follows(&e.id, params, bounds, seed); let boxes = follows && crate::Carry::by_bounds(&e.id); let mut outlines = vec![]; if !follows || boxes { @@ -739,24 +1182,71 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget } let mut groups = vec![]; if follows { - group_marks(art, &mut vec![], &HashSet::new(), &mut groups); + group_marks(art, &mut vec![], &HashSet::new(), None, &mut groups); + // The images earlier Warps bend are measured by their pieces only when a group's + // gradient needs the bounds. + if !groups.is_empty() + && let Some(images) = warped.as_deref().and_then(|w| w.when_cut(art)) + { + groups.clear(); + group_marks(art, &mut vec![], &HashSet::new(), Some(images), &mut groups); + } } - // The ids of the paths that kept their shape (past the budget). + // The ids of the paths that kept their shape (past the budget), and their places in the + // order [`for_each_leaf`] visits the paths; and the ids of the paths whose linked masks + // moved with them as they were transformed as objects. let mut kept_ids = HashSet::new(); + let mut kept_leaves = HashSet::new(); + let mut leaf_at = 0usize; + let mut moved_ids = HashSet::new(); let transform = (e.id == "distort.transform").then(|| { - let (m, copies) = crate::distort::transform_map(bounds, ¶ms, seed); - let options = crate::distort::TransformOptions::of(¶ms); - (m, copies, options, crate::distort::transform_affine(bounds, ¶ms, seed)) + let (m, copies) = crate::distort::transform_map(bounds, params, seed); + let options = crate::distort::TransformOptions::of(params); + (m, copies, options, crate::distort::transform_affine(bounds, params, seed)) }); + // What the effect does to the raster effects in the art, when they follow it. + let raster_map = if self.held { None } else { crate::raster::contents_step(std::slice::from_ref(e)) }; + // In a mask's art, images and symbol instances take only a Transform effect + // ([`transform_placed`]): a mask's art that holds one can't take another effect as the art + // it masks does. + if own && transform.is_none() && (is_placed(art) || placed_count(art) > 0) { + return Ran { kept: false, took: false, masks: true, short: false, whole: None }; + } // Art of several objects is copied whole, so the copies don't interleave member by member. + // The copies of its members carry their linked masks, moved with them. if let Some((m, copies, options, _)) = transform && copies > 0 && copy_whole { - used = copy_art(art, m, copies, copy_scaling(options), max); - continue; + if !own { + *used = copy_art(art, m, copies, copy_scaling(options), max); + return Ran { kept: false, took: true, masks: false, short: false, whole: None }; + } + // A mask's art: its copies keep to what the rest of the art leaves of `max`, and the + // linked mask of the art itself takes them too. That mask's art stays in `used`, as + // [`copy_art`] counts only the members. + let before = copy_cost(art); + let rest = used.minus(before).plus(art.extras().mask.as_deref().map_or(Budget { anchors: 0, lines: 0 }, |k| copy_cost(&k.art))); + let made = copy_art(art, m, copies, copy_scaling(options), max.minus(rest)); + *used = rest.plus(made); + let short = art.children().is_some_and(|c| c.iter().filter(|c| !c.is_guide()).count() <= copies); + let none = HashSet::new(); + let masks = self.reshape_own_mask(art, &Skip { moved: &none, kept: &none }, max, used, depth); + return Ran { kept: false, took: true, masks, short, whole: None }; } + // A shortfall in the copies matters for the objects a linked mask above them covers, which + // the mask would take a different number of copies than, and anywhere in a mask's art. + let watch = transform.is_some_and(|(_, copies, options, _)| copies > 0 && options.objects) && (own || has_linked_mask(art, false)); + let mut covered = HashSet::new(); + if watch && !own { + masked_ids(art, false, &mut covered); + } + let counts = |id: NodeId| watch && (own || covered.contains(&id)); + let mut short = false; + let mut took = false; for_each_leaf(art, &mut |leaf| { + let at = leaf_at; + leaf_at += 1; let Some((path, rule)) = leaf_geometry(leaf) else { return }; // What the other paths leave of the budget. let before = Budget::of(&path); @@ -766,35 +1256,58 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget // strokes; a gradient paints each copy by itself, not the one piece the copies // make together; and Expand Appearance (`apart`) makes each copy an object. // Fills and strokes that stack paint each copy below the one before (#5920, #6316). + // Each copy of a path with a linked mask carries the mask, moved with it. let separate = copies > 0 - && (apart + && (self.apart || leaf.appearance.has_unplaced_gradient() || leaf.appearance.has_placed_gradient() - || paints_copies_apart(&leaf.appearance, rule)); + || paints_copies_apart(&leaf.appearance, rule) + || leaf.extras().mask.as_ref().is_some_and(|m| m.linked)); + // The copies of a path replace it by a group of them, the path included. + let copied = |leaf: &Node| leaf.children().map_or(0, Vec::len); if options.reach_appearance() { - let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room); - used = used.minus(before).plus(made); - if !moved { + let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, raster_map.is_some(), None); + *used = used.minus(before).plus(made); + took |= moved; + if moved { + // With Transform Objects off the path stays, and its mask takes the + // effect's stroke and pattern changes as its own art. + if options.objects { + moved_ids.insert(leaf.id); + } + short |= counts(leaf.id) && copied(leaf) <= copies; + } else { kept_ids.insert(leaf.id); } return; } if separate { let scaling = vectorcraft_doc::Scaling { keep_fit_when_flat: true, ..Default::default() }; - let made = copy_leaf(leaf, &path, m, copies, scaling, room); - used = used.minus(before).plus(made); + let made = copy_leaf(leaf, &path, m, copies, scaling, room, None); + *used = used.minus(before).plus(made); + took = true; + moved_ids.insert(leaf.id); + short |= counts(leaf.id) && copied(leaf) <= copies; return; } } - let stage = effect.map(|effect| vectorcraft_plugins::deferred::Stage { object: seed, effect, item: None }); - let Some(out) = apply_one(&e.id, ¶ms, &path, bounds, &GeomContext { seed, stage, ..GeomContext::of(leaf) }, room) else { + let stage = self.effect.map(|effect| vectorcraft_plugins::deferred::Stage { object: seed, effect, item: None }); + let Some(out) = apply_one(&e.id, params, &path, bounds, &GeomContext { seed, stage, ..GeomContext::of(leaf) }, room) else { kept_ids.insert(leaf.id); + kept_leaves.insert(at); return; }; - used = used.minus(before).plus(Budget::of(&out)); + took = true; + // A Transform effect's copies of a path are subpaths of it, each with the path's anchors. + if counts(leaf.id) + && let Some((_, copies, _, _)) = transform + { + short |= out.anchor_count() < path.anchor_count().saturating_mul(copies.saturating_add(1)); + } + *used = used.minus(before).plus(Budget::of(&out)); if follows && !boxes { // A gradient fitted to the path fits the path's own bounds. - let carry = crate::Carry::of(&e.id, ¶ms, bounds, path.bounds(), None, seed); + let carry = crate::Carry::of(&e.id, params, bounds, path.bounds(), None, seed); if carry.moves(&leaf.appearance) { carry.apply(&mut leaf.appearance); } @@ -804,27 +1317,245 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget if boxes { rebase_leaves(art, &mut leaves.into_iter()); } + // Warp bends images too: each one's pixels follow the warp's map over the same box. The + // images are cut into pieces once, after the last effect ([`cut_warped_images`]). An image + // whose clipping frame kept its shape (past the budget) keeps its pixels as they are. + if let Some(style) = warp + && let Some(warped) = warped.as_deref_mut() + { + let f: WarpMap = Rc::from(crate::warp::warp_map(bounds, style, params)); + warped.reserve(art); + mark_warped_images(art, &f, &kept_leaves, false, &mut 0, warped); + } if let Some((m, copies, options, _)) = transform && options.objects { - transform_placed(art, m, copies); + // A mask's art that is one image or symbol instance is placed as the only member of a + // group of it. + let root = is_placed(art); + if root { + let id = art.id; + let one = std::mem::replace(art, Node::group(id, vec![])); + *art = Node::group(id, vec![Arc::new(one)]); + } + let placed = if watch { masked_placed(art, own) } else { 0 }; + // Images and symbol instances take the effect whatever the budget. + took = took || placed_count(art) > 0; + // Scale Strokes & Effects leaves the raster effects that follow the effect to + // [`follow_art`]. + let mut scaling = copy_scaling(options); + if raster_map.is_some() { + scaling.effects = options.strokes.then_some(scale_unfollowed as fn(&mut Effect, f64)); + } + transform_placed(art, m, copies, scaling); + short |= watch && masked_placed(art, own) < placed.saturating_mul(copies.saturating_add(1)); + if root && let Some([one]) = art.children().map(Vec::as_slice) { + *art = (**one).clone(); + } + } + // A mask's art takes them as a group inside the art: its own raster effects follow too. + if let Some(a) = raster_map { + follow_art(art, a, &kept_ids, Some(&moved_ids), own.then_some(Affine::IDENTITY), depth); } if outlines.iter().any(Option::is_some) { rebase_type_outlines(art, &mut outlines.into_iter()); } + // Under Transform copies, a mask takes the copies as the paths it masks do; the copies of a + // path with a mask of its own each carry it ([`copy_leaf`]). + let masks = self.reshape_masks(art, own, &Skip { moved: &moved_ids, kept: &kept_ids }, max, used, depth); // What paints the art as a whole, and the own fills and strokes of the groups inside it, // follow their bounds under Free Distort and Warp (they stay when no path changed them). // Each stays when a path under it that its bounds measure kept its shape (past the budget). let mut after = vec![]; - let held = (!groups.is_empty() || !kept_ids.is_empty()) && group_marks(art, &mut vec![], &kept_ids, &mut after).1; + let images = if groups.is_empty() { None } else { warped.as_deref().and_then(|w| w.when_cut(art)) }; + let held = (!groups.is_empty() || !kept_ids.is_empty()) && group_marks(art, &mut vec![], &kept_ids, images, &mut after).1; if !groups.is_empty() { - carry_groups(art, groups, after, &|from, to| crate::Carry::of(&e.id, ¶ms, bounds, from, to, seed)); + carry_groups(art, groups, after, &|from, to| crate::Carry::of(&e.id, params, bounds, from, to, seed)); } - if follows && !held { - whole.push(crate::Carry::of(&e.id, ¶ms, bounds, Some(bounds), art.geometric_bounds(), seed)); + let drawn = warped.as_deref().map_or_else(|| art.geometric_bounds(), |w| w.bounds(art)); + let whole = (follows && !held).then(|| crate::Carry::of(&e.id, params, bounds, Some(bounds), drawn, seed)); + Ran { kept: !kept_ids.is_empty(), took, masks, short, whole } + } + + /// Run the effect over the art of the linked opacity mask of `n` (with `own`) and of each path, + /// compound path, group and layer under it, with the art's reference box, as the paths the mask + /// covers take it: the mask moves and bends with what it masks. The mask of an object + /// transformed as an object moved with it already and is left as it is. A mask stays as it was + /// past [`vectorcraft_doc::depth::MAX_DEPTH`] masks inside masks, and for the reasons + /// [`Step::reshape_own_mask`] gives. Returns whether a mask stayed for one of those reasons. + fn reshape_masks(&self, n: &mut Node, own: bool, skip: &Skip, max: Budget, used: &mut Budget, depth: usize) -> bool { + if depth >= vectorcraft_doc::depth::MAX_DEPTH || !has_linked_mask(n, own) { + return false; + } + let mut stayed = own && self.reshape_own_mask(n, skip, max, used, depth); + if let NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } = &mut n.kind { + for c in children.iter_mut() { + if has_linked_mask(c, true) { + stayed |= self.reshape_masks(Arc::make_mut(c), true, skip, max, used, depth); + } + } + } + stayed + } + + /// Run the effect over the art of the linked opacity mask of `n` itself, when `n` is a path, + /// compound path, group or layer that `skip` does not list as moved. The mask stays as it was + /// when a path it masks kept its shape, and when its own art could not take the effect whole: a + /// path in it would keep its shape, its copies would stop short, or a mask inside it would stay + /// (no mask is left half moved). Returns whether the mask stayed for one of those reasons. + fn reshape_own_mask(&self, n: &mut Node, skip: &Skip, max: Budget, used: &mut Budget, depth: usize) -> bool { + if depth >= vectorcraft_doc::depth::MAX_DEPTH || !reshapes_mask_of(n) || skip.moved.contains(&n.id) { + return false; + } + let stays = holds_any(n, skip.kept); + let id = n.id; + let Some(m) = n.extras_if_any().and_then(|x| x.mask.as_mut()).filter(|m| m.linked) else { return false }; + let before = *used; + let mut art = (*m.art).clone(); + let whole = self.wholes.get(&id).copied().unwrap_or_else(|| copies_whole(&art)); + let ran = (!stays).then(|| self.run(&mut art, max, used, whole, None, true, depth + 1)); + match ran { + Some(ran) if ran.complete() => { + // What paints the mask's art as a whole follows the effect as the art does. + if let Some(carry) = ran.whole + && carry.moves(&art.appearance) + { + carry.apply(&mut art.appearance); + } + m.art = Arc::new(art); + false + } + _ => { + *used = before; + true + } } } - whole +} + +/// The objects whose linked masks [`Step::reshape_masks`] leaves as they are: those transformed +/// as objects (`moved`), and those holding a path that kept its shape (`kept`). +struct Skip<'a> { + moved: &'a HashSet<NodeId>, + kept: &'a HashSet<NodeId>, +} + +/// Is `n` an object whose linked opacity mask a geometry effect on the art it is in reshapes with +/// it: a path, compound path, group or layer? An image or symbol instance moves its mask only +/// with the map a Transform effect places it by ([`transform_placed`]). +fn reshapes_mask_of(n: &Node) -> bool { + matches!(n.kind, NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } | NodeKind::Group { .. } | NodeKind::Layer { .. }) +} + +/// Does `n` (with `own`) or a path, compound path, group or layer under it carry a linked opacity +/// mask that [`Step::reshape_masks`] reshapes? +fn has_linked_mask(n: &Node, own: bool) -> bool { + let mine = own && reshapes_mask_of(n) && n.extras().mask.as_ref().is_some_and(|m| m.linked); + mine || match &n.kind { + NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => children.iter().any(|c| has_linked_mask(c, true)), + _ => false, + } +} + +/// Run `f` on the id of `n` (with `own`) and of each path, compound path, group and layer under it +/// that carries a linked opacity mask, with the art of that mask, and on the masks inside that +/// art, as [`Step::reshape_masks`] reaches them: `depth` masks deep already, up to +/// [`vectorcraft_doc::depth::MAX_DEPTH`]. +fn each_linked_mask(n: &Node, own: bool, depth: usize, f: &mut dyn FnMut(NodeId, &Node)) { + if depth >= vectorcraft_doc::depth::MAX_DEPTH { + return; + } + if own + && reshapes_mask_of(n) + && let Some(m) = n.extras().mask.as_deref().filter(|m| m.linked) + { + f(n.id, &m.art); + each_linked_mask(&m.art, true, depth + 1, f); + } + if let NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } = &n.kind { + for c in children { + each_linked_mask(c, true, depth, f); + } + } +} + +/// [`each_linked_mask`] that changes the art of each mask: `f` runs on a mask's art before the +/// masks inside it are reached. +fn each_linked_mask_mut(n: &mut Node, own: bool, depth: usize, f: &mut dyn FnMut(&mut Node)) { + if depth >= vectorcraft_doc::depth::MAX_DEPTH || !has_linked_mask(n, own) { + return; + } + if own + && reshapes_mask_of(n) + && let Some(m) = n.extras_if_any().and_then(|x| x.mask.as_mut()).filter(|m| m.linked) + { + let art = Arc::make_mut(&mut m.art); + f(art); + each_linked_mask_mut(art, true, depth + 1, f); + } + if let NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } = &mut n.kind { + for c in children.iter_mut() { + if has_linked_mask(c, true) { + each_linked_mask_mut(Arc::make_mut(c), true, depth, f); + } + } + } +} + +/// Does [`Step::reshape_masks`] reshape the linked opacity mask of `n` itself? +fn has_own_linked_mask(n: &Node) -> bool { + reshapes_mask_of(n) && n.extras().mask.as_ref().is_some_and(|m| m.linked) +} + +/// Add to `out` the ids of the objects under `n` that the linked opacity mask of an object above +/// them covers (every one of them with `under`). +fn masked_ids(n: &Node, under: bool, out: &mut HashSet<NodeId>) { + for c in n.children().into_iter().flatten() { + if under { + out.insert(c.id); + } + masked_ids(c, under || has_own_linked_mask(c), out); + } +} + +/// How many images and symbol instances under `n` the linked opacity mask of an object above them +/// covers (every one of them with `under`). +fn masked_placed(n: &Node, under: bool) -> usize { + n.children().into_iter().flatten().map(|c| usize::from(under && is_placed(c)) + masked_placed(c, under || has_own_linked_mask(c))).sum() +} + +/// Is `n`, or anything under it, one of `ids`? +fn holds_any(n: &Node, ids: &HashSet<NodeId>) -> bool { + if ids.is_empty() { + return false; + } + let mut any = false; + n.walk(&mut |c| any |= ids.contains(&c.id)); + any +} + +/// Do the paths under `n` that [`for_each_leaf`] visits all fill by the non-zero rule without a +/// stroke that paints? Effects then reshape their outlines alike in any order that the +/// optimization of [`crate::geometry::optimize_geometry_effects`] takes. +fn leaves_safe(n: &Node) -> bool { + match &n.kind { + NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => { + let has_stroke = n.appearance.stroke().is_some_and(|s| !s.paint.is_none() && s.width > 0.0); + leaf_geometry(n).is_none_or(|(_, rule)| rule == FillRule::NonZero && !has_stroke) + } + NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => children.iter().all(|c| leaves_safe(c)), + _ => true, + } +} + +/// Is there an image with a linked opacity mask among the members of `n`, or among its groups' +/// and layers' members, which [`mark_warped_images`] walks? +fn has_masked_image(n: &Node) -> bool { + let (NodeKind::Group { children, .. } | NodeKind::Layer { children, .. }) = &n.kind else { return false }; + children.iter().any(|c| match c.kind { + NodeKind::Image(_) => c.extras().mask.as_ref().is_some_and(|m| m.linked), + _ => has_masked_image(c), + }) } /// Largest factor a Transform effect's Scale Strokes & Effects scales one object's strokes by @@ -845,14 +1576,94 @@ fn copy_scaling(options: crate::distort::TransformOptions) -> vectorcraft_doc::S } } +/// [`crate::scale_effect`] for the effects that do not follow a Transform effect as raster effects +/// do ([`crate::raster::follows`]): Scale Strokes & Effects scales them, and [`follow_art`] moves +/// the others. +fn scale_unfollowed(e: &mut Effect, s: f64) { + if !crate::raster::follows(&e.id) { + crate::scale_effect(e, s); + } +} + +/// Make the raster effects under `art` follow `a`, the linear part of a Transform effect that moved +/// it ([`crate::raster::follow_contents`]): those of every object in it (its own and its fills' and +/// strokes'), the art's own effects excepted (`up` is `None` for the art itself). A path that kept +/// its shape (in `kept`), and a group with such a path under it, keep their own and their fills' +/// and strokes'. `up` is what the Transform effects of the groups between an object and the art do +/// to the object's effects. A Transform effect of an object's own that makes copies or moves at +/// random leaves the effects it holds back as they are, so those follow `a` and the groups' maps +/// alone. The linked opacity mask of an object that took the effect as an object (in `moved`, and +/// every image and symbol instance) moved with it, so the raster effects in the mask's art follow +/// `a` as those of a mask that takes the effect as art do ([`Step::reshape_masks`]); `moved` is +/// `None` inside such a mask's art, where every linked mask moved. The walk reaches the groups and +/// layers that [`for_each_leaf`] made the art's own, so it copies nothing. Returns whether a path in +/// `kept` is under `n`. +fn follow_art(n: &mut Node, a: Affine, kept: &HashSet<NodeId>, moved: Option<&HashSet<NodeId>>, up: Option<Affine>, depth: usize) -> bool { + if n.is_guide() { + return false; + } + if moved.is_none_or(|moved| moved.contains(&n.id)) || is_placed(n) { + follow_moved_mask(n, a, depth); + } + // What the object's own Transform effects then do to its fills' and strokes' effects and its + // members' (nothing when one of them holds those back); the art's own effects are the ones + // being applied. + let below = up.map_or(Affine::IDENTITY, |up| crate::raster::contents_step(&n.appearance.effects).map_or(up, |s| up * s)); + let keeps = match &mut n.kind { + NodeKind::Path { .. } | NodeKind::Compound { .. } => kept.contains(&n.id), + NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => { + let mut keeps = false; + for c in children.iter_mut() { + keeps |= follow_art(Arc::make_mut(c), a, kept, moved, Some(below), depth); + } + keeps + } + _ => false, + }; + if !keeps { + if let Some(up) = up + && contents_raster(&n.appearance.effects) + { + crate::raster::follow_contents(&mut n.appearance.effects, a, up); + } + if n.appearance.items.iter().any(|i| contents_raster(i.effects())) { + for item in &mut n.appearance.items { + crate::raster::follow_contents(item.effects_mut(), a, below); + } + } + } + keeps +} + +/// Make the raster effects in the art of the linked opacity mask of `n`, which moved with `n`, +/// follow `a` ([`follow_art`]), with those of the linked masks inside that art, which moved too. A +/// mask past [`vectorcraft_doc::depth::MAX_DEPTH`] masks inside masks stays as it is. +fn follow_moved_mask(n: &mut Node, a: Affine, depth: usize) { + if depth >= vectorcraft_doc::depth::MAX_DEPTH { + return; + } + let Some(m) = n.extras_if_any().and_then(|x| x.mask.as_mut()).filter(|m| m.linked) else { return }; + follow_art(Arc::make_mut(&mut m.art), a, &HashSet::new(), None, Some(Affine::IDENTITY), depth + 1); +} + +/// Does any of `effects` follow a Transform effect as a raster effect ([`crate::raster::follows`])? +fn contents_raster(effects: &[Effect]) -> bool { + effects.iter().any(|e| crate::raster::follows(&e.id)) +} + /// A Transform effect whose Transform Patterns or Scale Strokes & Effects is on (`options`), with /// map `m` and `copies`, applied to `leaf` (a path or compound path with geometry `path`) as Object /// › Transform with those options transforms an object (#885): the strokes' weights and dashes /// and the distances of the effects on its fills and strokes scale by `m`'s mean scale, and its /// pattern paints transform by `m`. With copies, the original keeps them and copy `k` takes them /// `k` times, each copy an object of its own ([`copy_leaf`], within `budget`). With Transform -/// Objects off the geometry stays and the options apply once. Returns what the leaf costs after, -/// and `false` when the path kept its shape because the moved path would pass `budget`. +/// Objects off the geometry stays and the options apply once. With `follows`, Scale Strokes & +/// Effects leaves the raster effects that follow the Transform effect ([`follow_art`]) to the +/// caller. The effects `kept` names keep their values on the leaf and on each copy +/// ([`keep_listed`]), whether Scale Strokes & Effects scaled them or left them to the caller. +/// Returns what the leaf costs after, and `false` when the path kept its shape because the moved +/// path would pass `budget`. +#[allow(clippy::too_many_arguments)] fn transform_leaf( leaf: &mut Node, path: &PathData, @@ -860,8 +1671,13 @@ fn transform_leaf( copies: usize, options: crate::distort::TransformOptions, budget: Budget, + follows: bool, + kept: Kept, ) -> (Budget, bool) { - let scaling = copy_scaling(options); + let mut scaling = copy_scaling(options); + if follows && copies == 0 { + scaling.effects = options.strokes.then_some(scale_unfollowed as fn(&mut Effect, f64)); + } if !options.objects { if options.strokes && let Some(k) = vectorcraft_doc::Scaling::factor(m).filter(|k| k.is_finite() && *k > 0.0) @@ -872,6 +1688,7 @@ fn transform_leaf( if options.patterns { vectorcraft_doc::pattern::transform_pattern_paints(leaf, m); } + keep_listed(leaf, kept); return (Budget::of(path), true); } if copies == 0 { @@ -881,9 +1698,10 @@ fn transform_leaf( return (Budget::of(path), false); } leaf.transform(m, scaling); + keep_listed(leaf, kept); return (Budget::of(&moved), true); } - (copy_leaf(leaf, path, m, copies, scaling, budget), true) + (copy_leaf(leaf, path, m, copies, scaling, budget, kept), true) } /// Does a Transform effect's copies of `art` copy it whole ([`copy_art`])? They do when `art` is a @@ -1029,9 +1847,10 @@ fn copy_art(art: &mut Node, m: Affine, copies: usize, scaling: vectorcraft_doc:: /// moves with it) rather than spanning every copy, and its strokes and patterns can differ from the /// others'. The copies stop where [`crate::distort::transform_within`]'s would, before they pass /// `budget` with what each copy's own geometry effects make ([`effects_cost`]), and before one's -/// strokes would scale past [`MAX_STROKE_SCALE`]. Returns what the copies cost, the original -/// included. -fn copy_leaf(leaf: &mut Node, path: &PathData, m: Affine, copies: usize, scaling: vectorcraft_doc::Scaling, budget: Budget) -> Budget { +/// strokes would scale past [`MAX_STROKE_SCALE`]. The effects `kept` names keep their values on +/// each copy, before its cost is counted ([`keep_listed`]). Returns what the copies cost, the +/// original included. +fn copy_leaf(leaf: &mut Node, path: &PathData, m: Affine, copies: usize, scaling: vectorcraft_doc::Scaling, budget: Budget, kept: Kept) -> Budget { let mut made = Budget::of(path).plus(effects_cost(leaf, path)); let mut placements: Vec<Arc<Node>> = vec![Arc::new(leaf.clone())]; let mut xf = Affine::IDENTITY; @@ -1044,8 +1863,11 @@ fn copy_leaf(leaf: &mut Node, path: &PathData, m: Affine, copies: usize, scaling } let mut copy = leaf.clone(); copy.transform(xf, scaling); + keep_listed(&mut copy, kept); // Each copy's own geometry effects make a different amount, as the copy and its effects scale. - let cost = Budget::of(&moved).plus(effects_cost(©, &moved)); + let mut cost = Budget::of(&moved).plus(effects_cost(©, &moved)); + // Each copy carries the art of its linked masks, moved with it. + each_linked_mask(©, true, 0, &mut |_, m| cost = cost.plus(art_cost(m))); if !budget.fits(made.plus(cost)) || !copy.geometric_bounds().is_some_and(crate::distort::within_reach) { break; } @@ -1105,22 +1927,30 @@ fn paint_leaf( /// effects' budget for the object it becomes, so that a budget of [`Budget::EFFECTS`] holds at most /// [`MAX_OBJECTS`](vectorcraft_plugins::objects::MAX_OBJECTS) pieces however small their paths. fn piece_cost(path: &PathData) -> Budget { + Budget::of(path).plus(piece_share()) +} + +/// The share of the effects' budget each painted piece costs besides its path ([`piece_cost`]). +fn piece_share() -> Budget { let max = vectorcraft_plugins::objects::MAX_OBJECTS; - Budget::of(path).plus(Budget { anchors: Budget::EFFECTS.anchors / max, lines: Budget::EFFECTS.lines / max }) + Budget { anchors: Budget::EFFECTS.anchors / max, lines: Budget::EFFECTS.lines / max } } /// Live-effect plug-in `plugin` (one that paints what it returns) with `params`, a later effect of -/// `item`, run on `leaf`, a path of [`transform_piece`] painted by copies of `item`, with reference -/// box `bounds`: `leaf` becomes a group of one path for each piece returned, in order. A piece that -/// gives fills (on a fill) or strokes (on a stroke) is painted by copies of `item`, the leaf's first -/// fill or stroke, with those paints ([`vectorcraft_plugins::painted::items`]), under the leaf's -/// other fills and strokes; one that gives none keeps the leaf's. Returns +/// `item`, run on `leaf`, a path of [`transform_piece`] painted by `item` (its first fill or stroke), +/// with reference box `bounds`: `leaf` becomes a group of one path for each piece returned, in +/// order. The plug-in is given `appearance`'s fills and strokes and told that it is on item `index` +/// of them. A piece that gives fills (on a fill) or strokes (on a stroke) is painted by copies of +/// `item` with those paints ([`vectorcraft_plugins::painted::items`]), under the leaf's other fills +/// and strokes; one that gives none keeps the leaf's. Returns /// what the paths cost ([`piece_cost`]); `None` (the leaf stays as it is) when the plug-in fails, /// the pieces are refused (a swatch or pattern not in `doc`, or any without one), or they would pass /// `budget`. A deferred run is listed by `at`. +#[allow(clippy::too_many_arguments)] fn paint_piece( leaf: &mut Node, item: &AppearanceItem, + (appearance, index): (&Appearance, usize), (plugin, params): (&str, &serde_json::Value), bounds: Rect, budget: Budget, @@ -1128,7 +1958,7 @@ fn paint_piece( at: Option<vectorcraft_plugins::deferred::Stage>, ) -> Option<Budget> { let (path, rule) = leaf_geometry(leaf)?; - let paints = vectorcraft_plugins::effect::Paints { appearance: Some(&leaf.appearance), item: Some(0), at }; + let paints = vectorcraft_plugins::effect::Paints { appearance: Some(appearance), item: Some(index), at }; let pieces = vectorcraft_plugins::effect::apply_painted(plugin, params, &path, bounds, rule, paints, doc)?; let made = pieces.iter().map(|p| piece_cost(&p.path)).fold(Budget { anchors: 0, lines: 0 }, Budget::plus); if !budget.fits(made) { @@ -1188,9 +2018,12 @@ fn item_makes_piece(item: &AppearanceItem) -> bool { /// effects. In paint order, each such fill or stroke is a path of its own: the leaf's geometry after /// the geometry effects of that fill or stroke before its first such Transform effect, transformed /// as [`transform_leaf`] transforms an object with that effect's map, copies and options, so the -/// stroke's weight and dashes, the distances of its remaining effects and its pattern follow the -/// map. The reference box is that geometry's bounds and the seed is the leaf's id, as the renderer -/// draws a fill's or stroke's own effects. The geometry effects after the Transform effect then +/// stroke's weight and dashes, the distances of the effects before the Transform effect and its +/// pattern follow the map, and the raster effects before it that follow it take their followed +/// values ([`follow_piece`]). The effects after it keep their values and apply to what it made +/// ([`keep_listed`]), and with Transform Objects off so do the effects before it. The reference box +/// is that geometry's bounds and the seed is the leaf's id, as the renderer draws a fill's or +/// stroke's own effects. The geometry effects after the Transform effect then /// apply to the transformed path and its copies as one piece ([`transform_piece`]), and its other /// effects stay on each of them. The other fills and strokes stay together on paths of the leaf's /// geometry between them, with their own effects. `max` is the budget of the whole art and `used` @@ -1263,9 +2096,21 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt let params = merged_params(&fx[at].id, &fx[at].params); // Where each effect the piece keeps sits among the item's effects. let kept: Vec<usize> = (0..at).filter(|&k| !is_geometry(&fx[k].id)).chain(at + 1..fx.len()).collect(); + // A Transform effect after this one that makes copies or moves at random holds the raster + // effects before this one back from every Transform effect ([`crate::raster::followed`]). + let held_later = fx.get(at + 1..).unwrap_or_default().iter().any(crate::raster::holds_back); + // The effects before the Transform effect that it keeps, each raster effect following the + // geometry effects before it that moved the geometry ([`crate::raster::without_geometry`], + // [`crate::Carry::hide_skipped`]) unless held back. + let mut ran = std::borrow::Cow::Borrowed(before); + if carry.skipped() { + carry.hide_skipped(ran.to_mut()); + } + let kept_before: Vec<Effect> = + if held_later { before.iter().filter(|e| !is_geometry(&e.id)).cloned().collect() } else { crate::without_geometry(&ran) }; if let Some(plugin) = painted_plugin(&fx[at]) { let mut it = item.clone(); - let rest: Vec<Effect> = before.iter().filter(|e| !is_geometry(&e.id)).chain(&fx[at + 1..]).cloned().collect(); + let rest: Vec<Effect> = kept_before.iter().chain(&fx[at + 1..]).cloned().collect(); *it.effects_mut() = rest; let mut one = Appearance { items: vec![it.clone()], ..Default::default() }; if carry.moves(&one) { @@ -1287,7 +2132,7 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt group.push(Arc::new(p)); } let mut p = Node::group(leaf.id, group); - transform_piece(&mut p, (ctx.seed, i, &kept), limit, used, doc); + transform_piece(&mut p, (ctx.seed, i, &kept), crate::raster::held_back(before), true, limit, used, doc); pieces.push(Arc::new(p)); continue; } @@ -1295,16 +2140,22 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt let options = crate::distort::TransformOptions::of(¶ms); let map = crate::distort::transform_affine(tb, ¶ms, ctx.seed); let mut it = item.clone(); - let rest: Vec<Effect> = before.iter().filter(|e| !is_geometry(&e.id)).chain(&fx[at + 1..]).cloned().collect(); - *it.effects_mut() = rest; + let rest: Vec<Effect> = kept_before.iter().chain(&fx[at + 1..]).cloned().collect(); + *it.effects_mut() = rest.clone(); let mut p = piece(vec![it]); if carry.moves(&p.appearance) { carry.apply(&mut p.appearance); } set_geometry(&mut p, g.clone(), rule); - let (made, _) = transform_leaf(&mut p, &g, map, copies, options, room); + let after = kept_before.len(); + let keep = |k: usize| k >= after || !options.objects; + let (made, moved) = transform_leaf(&mut p, &g, map, copies, options, room, false, Some((&rest, &keep))); *used = used.plus(made); - transform_piece(&mut p, (ctx.seed, i, &kept), limit, used, doc); + let from = crate::raster::held_back(before); + if moved && !held_later { + follow_piece(&mut p, kept_before.get(from..).unwrap_or_default(), from, &fx[at]); + } + transform_piece(&mut p, (ctx.seed, i, &kept), crate::raster::held_back(&fx[..=at]), false, limit, used, doc); pieces.push(Arc::new(p)); } if !plain.is_empty() { @@ -1317,66 +2168,252 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt leaf.kind = NodeKind::Group { children: pieces, clip: false }; } -/// Apply the visible geometry effects left on the one fill or stroke of each path under `p` (a +/// Apply the visible geometry effects left on the fills or strokes of each path under `p` (a /// transformed piece of [`transform_item_leaf`] and its copies) to all of `p`'s paths as one piece: /// each effect takes the bounds of all the paths as its reference box and `seed`, as an object's /// own effects reshape all its paths ([`reshape_leaves_carrying`]). Each path applies its own copy of -/// the effect, whose distances its Scale Strokes & Effects scaled. A Transform effect with -/// Transform Patterns or Scale Strokes & Effects on transforms each path as [`transform_leaf`] does. +/// the effect, at the effect's own distances. A Transform effect with Transform Patterns or Scale +/// Strokes & Effects on transforms each path as [`transform_leaf`] does, and leaves the values of +/// the effects after it, and with Transform Objects off those before it, as they are +/// ([`keep_listed`]). /// A live-effect plug-in that paints what it returns ([`painted_plugin`]) makes each path one path -/// for each piece it returns ([`paint_piece`]). The geometry effects then leave the fills and -/// strokes; their other effects stay. The paths keep to `max` together with the rest of the art -/// (`used`), and the swatches and patterns painted pieces name must be in `doc`. `(seed, source, -/// kept)`: the object's seed, the index in the object's appearance of the fill or stroke the -/// piece was made from, and the index among that item's effects of each effect the piece kept, -/// which a deferred live-effect plug-in is listed by. -fn transform_piece(p: &mut Node, (seed, source, kept): (u64, usize, &[usize]), max: Budget, used: &mut Budget, doc: Option<&Document>) { +/// for each piece it returns ([`paint_piece`]). A path with several fills or strokes (those a +/// painted plug-in returned) takes such an effect, a live-effect plug-in or a geometry effect on +/// strokes once for each of them, in paint order, given its own place among them +/// ([`shares_stage`]): each run's pieces replace only that fill or stroke, and a run that fails or +/// would pass the budget leaves that fill or stroke on the path as it was. The raster effects +/// before a Transform effect follow it ([`follow_piece`]), except the first `held` effects, which +/// a Transform effect before the piece's effects that makes copies or moves at random holds back, +/// and the effects before such a Transform effect among the piece's effects. The geometry effects then +/// leave the fills and strokes; their other effects stay. The paths keep to `max` together with +/// the rest of the art (`used`), and the swatches and patterns painted pieces name must be in +/// `doc`. `(seed, source, kept)`: the object's seed, the index in the object's appearance of the +/// fill or stroke the piece was made from, and the index among that item's effects of each effect +/// the piece kept, which a deferred live-effect plug-in is listed by. `painted`: `p`'s paths are +/// the pieces of a painted run, each of which `used` counts at [`piece_cost`]. +fn transform_piece( + p: &mut Node, + (seed, source, kept): (u64, usize, &[usize]), + held: usize, + painted: bool, + max: Budget, + used: &mut Budget, + doc: Option<&Document>, +) { let mut count = 0; for_each_leaf(p, &mut |l| { - if let Some(item) = l.appearance.items.first() { + for item in &l.appearance.items { count = count.max(item.effects().len()); } }); + // The effects before a Transform effect among the piece's effects that makes copies or moves at + // random are held back from the Transform effects before it too. + let mut held = held; + for_each_leaf(p, &mut |l| { + for item in &l.appearance.items { + if let Some(last) = item.effects().iter().rposition(crate::raster::holds_back) { + held = held.max(last); + } + } + }); + // Whether `used` counts each path under `p`, in the order `for_each_leaf` visits them, at + // [`piece_cost`] (its geometry and a painted piece's share) rather than at its geometry alone. + // The pieces of a painted run are counted so, and so is the first path an effect makes of one + // that was: the paths of a Transform effect's copies share their original's share. + let mut shares = vec![painted; leaf_count(p)]; for j in 0..count { let Some(bounds) = p.geometric_bounds() else { break }; - for_each_leaf(p, &mut |leaf| { - let Some(item) = leaf.appearance.items.first().cloned() else { return }; - let Some(e) = item.effects().get(j).filter(|e| e.visible && is_geometry(&e.id)).cloned() else { return }; - let Some((path, rule)) = leaf_geometry(leaf) else { return }; - // What the other paths leave of the budget. - let before = Budget::of(&path); - let room = max.minus(used.minus(before)); - let stage = vectorcraft_plugins::deferred::Stage { object: seed, effect: kept.get(j).copied().unwrap_or(j), item: Some(source) }; - if let Some(plugin) = painted_plugin(&e) { - if let Some(made) = paint_piece(leaf, &item, (plugin, &merged_params(&e.id, &e.params)), bounds, room, doc, Some(stage)) { - *used = used.minus(before).plus(made); - } - return; - } - if reaches_appearance(&e) { - let params = merged_params(&e.id, &e.params); - let (_, copies) = crate::distort::transform_map(bounds, ¶ms, seed); - let options = crate::distort::TransformOptions::of(¶ms); - let map = crate::distort::transform_affine(bounds, ¶ms, seed); - let (made, _) = transform_leaf(leaf, &path, map, copies, options, room); + let from = held.min(j); + let mut holds = false; + let stage = vectorcraft_plugins::deferred::Stage { object: seed, effect: kept.get(j).copied().unwrap_or(j), item: Some(source) }; + let at = PieceStage { j, from, seed, bounds, doc, stage }; + // Stage `j` on `leaf`, a path `used` counts at `piece_cost` when `share`: whether `used` + // counts each path it became so, or `None` when it stays as it was. + let mut on_leaf = |leaf: &mut Node, share: bool| -> Option<Vec<bool>> { + let effect = |item: &AppearanceItem| item.effects().get(j).filter(|e| e.visible && is_geometry(&e.id)).cloned(); + let items = &leaf.appearance.items; + let first = items.first()?; + let (path, _) = leaf_geometry(leaf)?; + // What `used` counts the path at; what the other paths leave of the budget is the rest. + let geometry = Budget::of(&path); + let counted = if share { piece_cost(&path) } else { geometry }; + if shares_stage(items, j) { + let e = effect(first)?; + holds |= crate::raster::holds_back(&e); + let appearance = leaf.appearance.clone(); + // A painted run's pieces each cost a share of their own ([`paint_piece`]); the + // paths of any other effect keep the leaf's. + let painted = painted_plugin(&e).is_some(); + let before = if painted { counted } else { geometry }; + let room = max.minus(used.minus(before)); + let made = piece_stage(leaf, &e, &at, (&appearance, 0), room)?; *used = used.minus(before).plus(made); - return; + return Some((0..leaf_count(leaf)).map(|k| painted || (share && k == 0)).collect()); } + // Each fill or stroke takes the effect on its own path, given the leaf's fills and + // strokes and its own place among them; those left with the same path as the one + // before them stay on it. Each path costs its geometry and a painted piece's share. + // Each run is first given all the room the art leaves. When a fill or stroke that keeps + // the leaf's path then finds no room for its copy of it, the results are placed again, + // each but the last leaving room for one more copy of the leaf's own path; a result + // that does not fit that room is left out. Only a fill or stroke that keeps the leaf's + // path right after one that changed costs such a copy (the ones after it stay on that + // copy), so every copy fits but the first fill's or stroke's, when the art leaves no + // room for it: the leaf then stays as it was. A live-effect plug-in is given all the + // room the art leaves, and each placing checks that its result fits; a built-in effect + // builds within the room of each placing. let appearance = leaf.appearance.clone(); - let stroke = match &item { - AppearanceItem::Stroke(s) => Some(s), - AppearanceItem::Fill(_) => None, + let one = piece_cost(&path); + let n = appearance.items.len(); + let base = used.minus(counted); + let alone = |item: &AppearanceItem| { + let mut sub = leaf.clone(); + sub.appearance.items = vec![item.clone()]; + sub }; - let ctx = GeomContext { stroke, rule, seed, appearance: Some(&appearance), item: Some(0), doc, stage: Some(stage) }; - let mut carry = crate::Carry::default(); - let out = crate::geometry::apply_geometry_carrying_within(std::slice::from_ref(&e), &path, bounds, &ctx, room, Some(&mut carry)); - *used = used.minus(before).plus(Budget::of(&out)); - // The fill's or stroke's gradient follows the effect as the object's does. - if carry.moves(&leaf.appearance) { - carry.apply(&mut leaf.appearance); - } - set_geometry(leaf, out, rule); + // `item`, the `k`th fill or stroke, alone on the leaf's path with effect `e` applied + // within `room`, and what its paths cost; `None` when it failed or found no room. + let apply = |item: &AppearanceItem, k: usize, e: &Effect, room: Budget| { + let painted = painted_plugin(e).is_some(); + let room = if painted { room } else { room.minus(piece_share()) }; + let mut sub = alone(item); + let made = piece_stage(&mut sub, e, &at, (&appearance, k), room)?; + Some((sub, if painted { made } else { made.plus(piece_share()) })) + }; + // Each fill's or stroke's live-effect plug-in run. A result is kept only while a + // placing places it on a path of its own; one that does not fit is dropped, with what + // it cost, and the plug-in runs again in the second placing only when that much room + // is left there (a result small enough to cache comes back from the cache). A result + // with the same path as the one before it costs nothing: it is placed on that path + // whatever room is left, and dropped once its fill or stroke is moved there. The + // results kept at once cost at most what the two placings place. + let mut runs: Vec<PluginRun> = vec![PluginRun::Not; n]; + let mut kept_cost = Budget { anchors: 0, lines: 0 }; + // Each placing gives the paths, whether `used` counts each of the paths they hold at + // `piece_cost` (all of a painted run's, and the first of any other result's), and what + // the art then spends. + let mut split = |reserve: bool| -> Option<(Vec<Node>, Vec<bool>, Budget)> { + let mut spent = base; + let mut out: Vec<Node> = vec![]; + let mut counts: Vec<bool> = vec![]; + for (k, (item, ran)) in appearance.items.iter().zip(runs.iter_mut()).enumerate() { + let room = if reserve && k + 1 < n { max.minus(spent).minus(one) } else { max.minus(spent) }; + let e = effect(item); + let paints = e.as_ref().is_some_and(|e| painted_plugin(e).is_some()); + // Does `sub` stay on the path of the result before it, at no cost? + let merges = |sub: &Node| out.last().is_some_and(|last| same_path(last, sub)); + // What the kept plug-in result this fill or stroke takes cost. + let mut taken = None; + let result = match e { + None => None, + Some(e) => { + holds |= crate::raster::holds_back(&e); + if vectorcraft_plugins::effect::plugin_id(&e.id).is_some() { + let again = match ran { + PluginRun::Not | PluginRun::Merged => true, + PluginRun::Left(cost) => room.fits(*cost), + PluginRun::Kept(..) | PluginRun::Failed => false, + }; + if again { + #[cfg(test)] + PLUGIN_RUNS.with(|n| n.set(n.get() + 1)); + *ran = match apply(item, k, &e, max.minus(base)) { + None => PluginRun::Failed, + Some((sub, cost)) if !room.fits(cost) && !merges(&sub) => PluginRun::Left(cost), + Some((sub, cost)) => { + kept_cost = kept_cost.plus(cost); + PluginRun::Kept(sub, cost) + } + }; + } + match ran { + PluginRun::Kept(sub, cost) if room.fits(*cost) || merges(sub) => { + taken = Some(*cost); + Some((sub.clone(), *cost)) + } + PluginRun::Kept(_, cost) => { + let cost = *cost; + kept_cost = kept_cost.minus(cost); + *ran = PluginRun::Left(cost); + None + } + PluginRun::Not | PluginRun::Merged | PluginRun::Left(_) | PluginRun::Failed => None, + } + } else { + // A built-in effect that finds no room within `room` leaves the + // leaf's path. When its result is not on the path before it, it + // is built again with all the room the art leaves and taken only + // when that result is on the path before it, which costs nothing. + let made = apply(item, k, &e, room); + let short = match &made { + None => true, + Some((sub, cost)) => !merges(sub) && (!room.fits(*cost) || same_path(sub, leaf)), + }; + match out.last() { + Some(_) if short => match apply(item, k, &e, max.minus(base)) { + Some((sub, cost)) if merges(&sub) => Some((sub, cost)), + _ => made, + }, + _ => made, + } + } + } + }; + let placed = match result { + Some((sub, cost)) if room.fits(cost) || merges(&sub) => Some((sub, cost, paints)), + _ => None, + }; + // A fill or stroke whose result is not placed stays on the leaf's path, which + // is copied only when the path before it is another. + let (mut sub, cost, all) = match placed { + Some(placed) => placed, + None => match out.last_mut() { + Some(last) if same_path(last, leaf) => { + last.appearance.items.push(item.clone()); + continue; + } + _ => (alone(item), one, true), + }, + }; + match out.last_mut() { + Some(last) if same_path(last, &sub) => { + last.appearance.items.append(&mut sub.appearance.items); + if let Some(cost) = taken { + kept_cost = kept_cost.minus(cost); + *ran = PluginRun::Merged; + } + } + _ if !max.minus(spent).fits(cost) => return None, + _ => { + spent = spent.plus(cost); + counts.extend((0..leaf_count(&sub)).map(|k| all || k == 0)); + out.push(sub); + } + } + #[cfg(test)] + HELD_PEAK.with(|p| p.set(p.get().at_least(kept_cost))); + } + Some((out, counts, spent)) + }; + let (mut out, counts, spent) = split(false).or_else(|| split(true))?; + *used = spent; + *leaf = match out.len() { + 1 => out.pop().unwrap_or_else(|| leaf.clone()), + _ => Node::group(leaf.id, out.into_iter().map(Arc::new).collect()), + }; + Some(counts) + }; + let mut next: Vec<bool> = vec![]; + let mut visited = 0; + for_each_leaf(p, &mut |leaf| { + let share = shares.get(visited).copied().unwrap_or(false); + visited += 1; + next.extend(on_leaf(leaf, share).unwrap_or_else(|| vec![share])); }); + shares = next; + if holds { + held = held.max(j); + } } for_each_leaf(p, &mut |leaf| { for item in &mut leaf.appearance.items { @@ -1385,6 +2422,184 @@ fn transform_piece(p: &mut Node, (seed, source, kept): (u64, usize, &[usize]), m }); } +/// A fill's or stroke's live-effect plug-in run in a placing of [`transform_piece`]: not run yet, +/// its result and what that costs while a placing places it on a path of its own, what a result +/// that did not fit cost (the result itself is dropped), a result dropped once its fill or stroke +/// was placed on the path before it, or failed. +#[derive(Clone)] +enum PluginRun { + Not, + Kept(Node, Budget), + Left(Budget), + Merged, + Failed, +} + +#[cfg(test)] +thread_local! { + /// The most the live-effect plug-in results [`transform_piece`] keeps from one fill or stroke + /// to the next have cost at once on this thread. + pub(crate) static HELD_PEAK: std::cell::Cell<Budget> = const { std::cell::Cell::new(Budget { anchors: 0, lines: 0 }) }; + /// How many times [`transform_piece`] has run a fill's or stroke's live-effect plug-in on this + /// thread when they did not share the stage. + pub(crate) static PLUGIN_RUNS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; +} + +/// Where a stage of [`transform_piece`] runs: `j`, the index of its effect among the piece's +/// effects; `from`, the first of the effects before it whose raster effects follow a Transform +/// effect; the object's `seed`; the reference box `bounds` of all the piece's paths; the document +/// that painted pieces' swatches and patterns must be in; and the `stage` a deferred live-effect +/// plug-in is listed by. +struct PieceStage<'a> { + j: usize, + from: usize, + seed: u64, + bounds: Rect, + doc: Option<&'a Document>, + stage: vectorcraft_plugins::deferred::Stage, +} + +/// Can stage `j` of [`transform_piece`] run once for all of a path's `items`: there is at most one, +/// or they hold the same effects and the effect at `j` is not a visible geometry effect, is a +/// Transform effect, or is a built-in geometry effect and they are all fills (an effect that +/// changes a fill's path does not depend on which fill it is on)? +fn shares_stage(items: &[AppearanceItem], j: usize) -> bool { + let Some(first) = items.first() else { return true }; + if items.len() == 1 { + return true; + } + if !items.iter().all(|i| i.effects() == first.effects()) { + return false; + } + match first.effects().get(j) { + Some(e) if e.visible && is_geometry(&e.id) => { + vectorcraft_plugins::effect::plugin_id(&e.id).is_none() && (reaches_appearance(e) || items.iter().all(AppearanceItem::is_fill)) + } + _ => true, + } +} + +/// Effect `e`, a visible geometry effect at stage `at` of [`transform_piece`], applied to `leaf`, a +/// path painted by its first fill or stroke (and, when they share the stage, [`shares_stage`], the +/// others): `appearance` is what the effect is given of the path's fills and strokes and `index` +/// which of them it is on. A live-effect plug-in that paints what it returns makes `leaf` a group +/// of its pieces ([`paint_piece`]), and a Transform effect that reaches its appearance transforms +/// it ([`transform_leaf`]). Returns what the new paths cost, within `room`; `None` when `leaf` +/// stays as it is. +fn piece_stage(leaf: &mut Node, e: &Effect, at: &PieceStage, (appearance, index): (&Appearance, usize), room: Budget) -> Option<Budget> { + let item = leaf.appearance.items.first()?.clone(); + // The effects before this one as they were before it moved the path. + let was = item.effects().get(at.from..at.j).unwrap_or_default(); + let (path, rule) = leaf_geometry(leaf)?; + if let Some(plugin) = painted_plugin(e) { + let params = merged_params(&e.id, &e.params); + return paint_piece(leaf, &item, (appearance, index), (plugin, ¶ms), at.bounds, room, at.doc, Some(at.stage)); + } + if reaches_appearance(e) { + let params = merged_params(&e.id, &e.params); + let (_, copies) = crate::distort::transform_map(at.bounds, ¶ms, at.seed); + let options = crate::distort::TransformOptions::of(¶ms); + let map = crate::distort::transform_affine(at.bounds, ¶ms, at.seed); + let j = at.j; + let keep = |k: usize| k > j || (k < j && !options.objects); + let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, false, Some((item.effects(), &keep))); + if moved { + follow_piece(leaf, was, at.from, e); + } + return Some(made); + } + let stroke = match &item { + AppearanceItem::Stroke(s) => Some(s), + AppearanceItem::Fill(_) => None, + }; + let ctx = GeomContext { stroke, rule, seed: at.seed, appearance: Some(appearance), item: Some(index), doc: at.doc, stage: Some(at.stage) }; + let mut carry = crate::Carry::default(); + let out = crate::geometry::apply_geometry_carrying_within(std::slice::from_ref(e), &path, at.bounds, &ctx, room, Some(&mut carry)); + let made = Budget::of(&out); + // The fill's or stroke's gradient follows the effect as the object's does. + if carry.moves(&leaf.appearance) { + carry.apply(&mut leaf.appearance); + } + set_geometry(leaf, out, rule); + // A Transform effect left out (past the budget) leaves the path and its raster effects as they were. + if !carry.skipped() { + follow_piece(leaf, was, at.from, e); + } + Some(made) +} + +/// Are `a` and `b` paths or compound paths that differ only in their fills and strokes? +fn same_path(a: &Node, b: &Node) -> bool { + let leaf = |n: &Node| matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }); + if !leaf(a) || !leaf(b) { + return false; + } + // Every field but the fills and strokes, compared in place; the geometry last. + let Node { id, name, visible, locked, opacity, blend, isolate, knockout, knockout_shape, appearance, kind, bbox_angle, extras } = a; + let Appearance { items: _, effects, contents_index } = &**appearance; + *id == b.id + && *name == b.name + && *visible == b.visible + && *locked == b.locked + && *opacity == b.opacity + && *blend == b.blend + && *isolate == b.isolate + && *knockout == b.knockout + && *knockout_shape == b.knockout_shape + && *bbox_angle == b.bbox_angle + && *extras == b.extras + && *effects == b.appearance.effects + && *contents_index == b.appearance.contents_index + && *kind == b.kind +} + +/// The effects a Transform effect in a fill's or stroke's own list leaves as they were +/// ([`keep_listed`]): the list as it was before the Transform effect was applied, and which of its +/// indices keep their values. `None` for an object's own Transform effect. +type Kept<'a> = Option<(&'a [Effect], &'a dyn Fn(usize) -> bool)>; + +/// Put back on the fills and strokes of each path under `p` the effect `kept`'s list holds at each +/// index it takes, in place of what a Transform effect in their own list scaled or moved with its +/// options ([`transform_leaf`]). The effects after the Transform effect apply to the art it made, +/// and with Transform Objects off the effects before it keep their values too. A piece's fills and +/// strokes share one list: a live-effect plug-in that paints what it returns gives each paint a copy +/// of the fill or stroke ([`vectorcraft_plugins::painted::items`]). +fn keep_listed(p: &mut Node, kept: Kept) { + let Some((was, keep)) = kept else { return }; + for_each_leaf(p, &mut |leaf| { + for item in &mut leaf.appearance.items { + for (k, (e, old)) in item.effects_mut().iter_mut().zip(was).enumerate() { + if keep(k) { + e.clone_from(old); + } + } + } + }); +} + +/// Make the raster effects of each of `leaf`'s fills and strokes from index `from` on follow +/// Transform effect `t`, listed after them, once `t` has moved the leaf +/// ([`crate::raster::follow_one`]). The fills and strokes are copies of one fill or stroke (those a +/// painted plug-in returns, [`vectorcraft_plugins::painted::items`]), with the same effects. `was` +/// holds those effects of the first one as they were before `t` was applied: each one that +/// follows takes the value [`crate::raster::followed`] gives it, in place of what Scale Strokes & +/// Effects made of it, and the others keep theirs. +fn follow_piece(leaf: &mut Node, was: &[Effect], from: usize, t: &Effect) { + let mut follow = was.to_vec(); + if !crate::raster::follow_one(&mut follow, t) { + return; + } + for item in &mut leaf.appearance.items { + for (k, (new, old)) in follow.iter().zip(was).enumerate() { + if new != old + && let Some(e) = item.effects_mut().get_mut(from + k) + { + *e = new.clone(); + } + } + } +} + /// The bounds of each group of type's outlines under `n` ([`outline_text`]), `n` included, in /// order. A group inside one of them is part of it. fn type_outline_bounds(n: &Node, out: &mut Vec<Option<Rect>>) { @@ -1445,17 +2660,25 @@ type GroupMark = (Vec<usize>, Option<Rect>, bool); /// The geometric bounds of `n` (as [`Node::geometric_bounds`] gives them) and whether a path or /// compound path below it that those bounds measure is in `kept`, measured in one walk. Each group below `n` that -/// [`GroupMark`] describes goes into `out`, reached from `n` through `at`. -fn group_marks(n: &Node, at: &mut Vec<usize>, kept: &HashSet<NodeId>, out: &mut Vec<GroupMark>) -> (Option<Rect>, bool) { +/// [`GroupMark`] describes goes into `out`, reached from `n` through `at`. An image that `images` +/// lists is measured by the pieces it will be cut into ([`WarpedImages::image_bounds`]). +fn group_marks( + n: &Node, + at: &mut Vec<usize>, + kept: &HashSet<NodeId>, + images: Option<&WarpedImages>, + out: &mut Vec<GroupMark>, +) -> (Option<Rect>, bool) { match &n.kind { NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => (n.geometric_bounds(), kept.contains(&n.id)), + NodeKind::Image(_) => (images.map_or_else(|| n.geometric_bounds(), |w| w.image_bounds(n)), false), NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. } if !n.extras().type_outlines => { let layer = matches!(n.kind, NodeKind::Layer { .. }); let skip = children.len().saturating_sub(n.editing_children().len()); let (mut bounds, mut held) = (None, false); for (i, c) in children.iter().enumerate() { at.push(i); - let (b, h) = group_marks(c, at, kept, out); + let (b, h) = group_marks(c, at, kept, images, out); if is_member_group(c) && (c.appearance.has_positioned_gradient() || c.appearance.has_unplaced_gradient()) { out.push((at.clone(), b, h)); } @@ -1577,17 +2800,239 @@ fn box_map(from: Rect, to: Rect) -> vectorcraft_geom::Affine { /// Apply the Transform effect's map `m` to every image and symbol instance under `n`, as /// [`for_each_leaf`] does to paths: the map goes into the object's placement, and `copies` more /// follow, each mapped once more than the last. Without copies the object itself takes the map, -/// as a path does. -fn transform_placed(n: &mut Node, m: Affine, copies: usize) { - transform_placed_within(n, m, copies, crate::distort::MAX_COPY_OBJECTS) +/// as a path does. The art of each one's linked opacity mask takes the map with `scaling`, as a +/// path's mask does. +fn transform_placed(n: &mut Node, m: Affine, copies: usize, scaling: vectorcraft_doc::Scaling) { + let mut room = crate::distort::MAX_COPY_OBJECTS.saturating_sub(placed_count(n)); + copy_placed(n, m, copies, scaling, &mut room); } /// [`transform_placed`] whose copies make at most `max` image and symbol instance nodes of the art, /// the originals included: each copy adds the object once more, and a Transform after this one /// copies the lot again, so copies stop where the result would pass `max` (#2042). +#[cfg(test)] pub(crate) fn transform_placed_within(n: &mut Node, m: Affine, copies: usize, max: usize) { let mut room = max.saturating_sub(placed_count(n)); - copy_placed(n, m, copies, &mut room); + copy_placed(n, m, copies, vectorcraft_doc::Scaling::default(), &mut room); +} + +/// Rows and columns of the pieces a Warp effect cuts an image into (VectorCraft's own number). +pub(crate) const WARP_IMAGE_CELLS: usize = 10; + +/// A Warp effect's point map, shared by the images it bends. +pub(crate) type WarpMap = Rc<dyn Fn(Point) -> Point>; + +/// One image a Warp effect bent: the image's own key, and each warp it took with the placement +/// the image had when it took it, in order. +type WarpedImage = (String, Vec<(WarpMap, Affine)>); + +/// The images Warp effects bend while [`reshape_leaves_apart`] runs the effects. Each such image's +/// key is replaced by a key of this table ([`WarpedImages::add`]), which a copy a later Transform +/// effect makes keeps. The images are cut into pieces once, after the last effect +/// ([`cut_warped_images`]): the effects after a Warp reshape the image's frame, not each piece, +/// and a later Warp or Transform moves the one set of pieces. +pub(crate) struct WarpedImages { + /// What this table's keys start with: no image key in the art starts with it + /// ([`WarpedImages::reserve`]). + prefix: String, + /// The prefix was checked against the art's image keys. + reserved: bool, + images: Vec<WarpedImage>, +} + +impl WarpedImages { + pub(crate) fn new() -> Self { + static TABLES: AtomicUsize = AtomicUsize::new(0); + Self { prefix: format!("\0warp{}:", TABLES.fetch_add(1, Ordering::Relaxed)), reserved: false, images: vec![] } + } + + /// Before the first image of `art` is marked: lengthen the prefix until no image key in `art` + /// starts with it, so no key from the document is read as one of this table's. + pub(crate) fn reserve(&mut self, art: &Node) { + if self.reserved { + return; + } + self.reserved = true; + let mut keys = vec![]; + art.walk(&mut |c| { + if let NodeKind::Image(im) = &c.kind { + keys.push(im.key.clone()); + } + }); + while keys.iter().any(|k| k.starts_with(self.prefix.as_str())) { + self.prefix.push(':'); + } + } + + /// What this table's keys start with. + #[cfg(test)] + pub(crate) fn prefix(&self) -> &str { + &self.prefix + } + + /// The image that `key`, a key of this table, stands for. + fn get(&self, key: &str) -> Option<&WarpedImage> { + self.images.get(key.strip_prefix(self.prefix.as_str())?.parse::<usize>().ok()?) + } + + /// Record that the image with key `key`, placed by `xf`, takes warp `f`; returns the image's + /// new key. + fn add(&mut self, key: &str, xf: Affine, f: &WarpMap) -> String { + let (own, mut warps) = self.get(key).cloned().unwrap_or_else(|| (key.to_string(), vec![])); + warps.push((f.clone(), xf)); + self.images.push((own, warps)); + format!("{}{}", self.prefix, self.images.len() - 1) + } + + /// Does the art `n` have room, within `max` nodes, for the pieces of every image under it that + /// this table lists? + fn fits(&self, n: &Node, max: usize) -> bool { + let mut count = 0usize; + n.walk(&mut |c| { + if let NodeKind::Image(im) = &c.kind + && self.get(&im.key).is_some() + { + count += 1; + } + }); + vectorcraft_doc::live::mesh_warp_cost(WARP_IMAGE_CELLS).saturating_mul(count) <= max.saturating_sub(n.count()) + } + + /// The geometric bounds of `art` as it draws after the effects so far: each image this table + /// lists measured by the pieces the warps and moves it took would cut it into, when the art + /// has room for them ([`cut_warped_images`]). + pub(crate) fn bounds(&self, art: &Node) -> Option<Rect> { + if self.images.is_empty() || !self.fits(art, crate::distort::MAX_COPY_OBJECTS) { + return art.geometric_bounds(); + } + // The pieces the images would be cut into now: each group of pieces is shown or hidden as + // its image is, and hidden objects are left out of a layer's bounds. + let mut probe = art.clone(); + restore_warped_images(&mut probe, self, true); + probe.geometric_bounds() + } + + /// The geometric bounds of image `n`: when this table lists it, measured by the pieces the + /// warps and moves it took would cut it into. + fn image_bounds(&self, n: &Node) -> Option<Rect> { + let NodeKind::Image(im) = &n.kind else { return n.geometric_bounds() }; + if self.get(&im.key).is_none() { + return n.geometric_bounds(); + } + let mut probe = Node::group(n.id, vec![Arc::new(n.clone())]); + restore_warped_images(&mut probe, self, true); + probe.geometric_bounds() + } + + /// This table when the art `art` has room for the pieces of the images it lists, so that a + /// measure of the art takes them bent ([`WarpedImages::bounds`]); `None` otherwise. + fn when_cut(&self, art: &Node) -> Option<&Self> { + (!self.images.is_empty() && self.fits(art, crate::distort::MAX_COPY_OBJECTS)).then_some(self) + } +} + +/// Record in `warped` that each image under `n` takes warp `f`, walking the groups and layers +/// [`for_each_leaf`] walks and counting the paths it passes in `at`. `kept` holds the places of +/// the paths that kept their shape (past the budget), in the order [`for_each_leaf`] visits the +/// paths of the art: an image in a clip group whose clipping art holds one (`held`) does not take +/// the warp. +pub(crate) fn mark_warped_images(n: &mut Node, f: &WarpMap, kept: &HashSet<usize>, held: bool, at: &mut usize, warped: &mut WarpedImages) { + let (NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. }) = &mut n.kind else { return }; + let mut held = held; + // A clip group's first member is its clipping art: when a path in it kept its shape, it and + // the members it clips keep theirs. + if *clip && let Some(first) = children.first() { + let start = *at; + held |= (start..start + leaf_count(first)).any(|p| kept.contains(&p)); + } + for c in children.iter_mut() { + match &c.kind { + NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => *at += 1, + NodeKind::Group { .. } | NodeKind::Layer { .. } => mark_warped_images(Arc::make_mut(c), f, kept, held, at, warped), + NodeKind::Image(_) if !held => { + if let NodeKind::Image(im) = &mut Arc::make_mut(c).kind { + im.key = warped.add(&im.key, im.xf, f); + } + } + _ => {} + } + } +} + +/// Give each image under `n` that `warped` lists its own key back, and cut it into the pieces of +/// a raster mesh warp ([`vectorcraft_doc::live::mesh_warp_image`], each piece drawn as the image +/// is, smoothed or not) through the warps it took and the moves between and after them +/// ([`warped_map`]). The art keeps to [`crate::distort::MAX_COPY_OBJECTS`] nodes: when the pieces +/// would pass it, no image is cut. An image whose placement has no inverse is not cut either. +fn cut_warped_images(n: &mut Node, warped: &WarpedImages) { + cut_warped_images_within(n, warped, crate::distort::MAX_COPY_OBJECTS); +} + +/// [`cut_warped_images`] with the art keeping to `max` nodes. +pub(crate) fn cut_warped_images_within(n: &mut Node, warped: &WarpedImages, max: usize) { + if warped.images.is_empty() { + return; + } + let cut = warped.fits(n, max); + restore_warped_images(n, warped, cut); +} + +/// The walk of [`cut_warped_images`]: each listed image gets its key back, and with `cut` is cut +/// into pieces. +fn restore_warped_images(n: &mut Node, warped: &WarpedImages, cut: bool) { + let Some(children) = n.children_mut() else { return }; + for c in children.iter_mut() { + let NodeKind::Image(im) = &c.kind else { + if c.children().is_some() { + restore_warped_images(Arc::make_mut(c), warped, cut); + } + continue; + }; + let Some((key, warps)) = warped.get(&im.key) else { continue }; + let mut image = (**c).clone(); + let NodeKind::Image(own) = &mut image.kind else { continue }; + own.key = key.clone(); + // The pieces start from the image as it was placed when it took its first warp. + let first = warps.first().map(|(_, at)| ImageObject { xf: *at, ..(**own).clone() }); + let map = warped_map(warps, own.xf); + *c = Arc::new(match (first, map) { + (Some(first), Some(map)) if cut => { + let pixelated = image.extras().pixelated; + vectorcraft_doc::live::mesh_warp_image(&image, &first, &*map, WARP_IMAGE_CELLS, pixelated, false) + } + _ => image, + }); + } +} + +/// The map that takes a point of an image placed by the first of `warps`' placements to where the +/// warps and the moves between them take it, for an image now placed by `placed`: each warp in +/// turn, then the move from the placement the image had when it took that warp to the one it had +/// at the next, or to `placed` after the last. `None` when a placement has no inverse. +fn warped_map(warps: &[(WarpMap, Affine)], placed: Affine) -> Option<Box<dyn Fn(Point) -> Point>> { + let mut steps: Vec<(WarpMap, Affine)> = Vec::with_capacity(warps.len()); + for (i, (f, at)) in warps.iter().enumerate() { + let det = at.determinant(); + if !det.is_finite() || det == 0.0 { + return None; + } + let next = warps.get(i + 1).map_or(placed, |(_, at)| *at); + let m = next * at.inverse(); + if !m.is_finite() { + return None; + } + steps.push((f.clone(), m)); + } + Some(Box::new(move |p| steps.iter().fold(p, |q, (f, m)| *m * f(q)))) +} + +/// How many paths [`for_each_leaf`] visits in `n`. +fn leaf_count(n: &Node) -> usize { + match &n.kind { + NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => 1, + NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => children.iter().map(|c| leaf_count(c)).sum(), + _ => 0, + } } /// An object that a Transform effect places through its transform rather than reshapes: an image @@ -1600,11 +3045,11 @@ fn is_placed(n: &Node) -> bool { /// document order, each copy taking one from `room` (what the art can still grow by), until the /// budget is full. As with a path, the copies stop before one reaches past /// [`crate::distort::within_reach`]. -fn copy_placed(n: &mut Node, m: Affine, copies: usize, room: &mut usize) { +fn copy_placed(n: &mut Node, m: Affine, copies: usize, scaling: vectorcraft_doc::Scaling, room: &mut usize) { let Some(children) = n.children_mut() else { return }; for c in children.iter_mut() { if !is_placed(c) { - copy_placed(Arc::make_mut(c), m, copies, room); + copy_placed(Arc::make_mut(c), m, copies, scaling, room); continue; } let src = (**c).clone(); @@ -1623,6 +3068,12 @@ fn copy_placed(n: &mut Node, m: Affine, copies: usize, room: &mut usize) { if xf != Affine::IDENTITY && one.appearance.has_positioned_gradient() { one.appearance.transform_gradients(xf); } + // So does the art of its linked opacity mask. + if xf != Affine::IDENTITY + && let Some(m) = one.extras_if_any().and_then(|x| x.mask.as_mut()).filter(|m| m.linked) + { + Arc::make_mut(&mut m.art).transform(xf, scaling); + } one }; if copies == 0 { diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index 43b339ccf4..9281a802bf 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -1,4 +1,5 @@ -//! Revolve as live, shaded vector art, shared by the canvas and every exporter. +//! Revolve and Revolve (Classic) as live, shaded vector art, shared by the canvas and every +//! exporter. use std::sync::Arc; use serde_json::Value; @@ -7,20 +8,39 @@ use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, L use vectorcraft_geom::{PathData, PathEl, Point, Rect, Vec2}; use vectorcraft_three_d::{Edge, Revolve}; -use crate::solids::{Profile, Scope, is_container, members, object_profile, profile, reshape_members, resolve_for, solid_paints, union_bounds}; +use crate::solids::{ + Profile, Scope, is_container, members, object_profile, past_effect, profile, reshape_members, resolve_for, solid_paints, union_bounds, +}; use crate::util::{flag, num, text}; use crate::{GeomContext, apply_geometry_with, is_geometry, merged_params}; pub const REVOLVE: &str = "threeD.revolve"; +mod classic; +pub use classic::CLASSIC_REVOLVE; + +/// Is `id` Revolve or Revolve (Classic), the effects this module draws? +pub fn is_revolve(id: &str) -> bool { + id == REVOLVE || id == CLASSIC_REVOLVE +} + /// Most bytes the copies of the object's paint in the faces may take together. Each face and the /// seam stroke around it gets a copy of the paint, so a gradient of many stops times tens of /// thousands of faces took gigabytes; past this the source path is drawn. -const MAX_PAINT_COPIES: usize = 256 << 20; +pub(crate) const MAX_PAINT_COPIES: usize = 256 << 20; + +/// The bytes of an object's paint copies so far: those of its surfaces' faces, and those of the parts +/// of its graphics, each within [`MAX_PAINT_COPIES`] of its own. Graphics past their budget are left +/// out without taking room the surfaces need. +#[derive(Default)] +struct Copies { + surfaces: usize, + graphics: usize, +} /// The most face and box tests a group's transparent members' faces take together to rejoin their /// members' last runs; past them each starts a run of its own. -const MAX_OVERLAP_TESTS: usize = 1 << 22; +pub(crate) const MAX_OVERLAP_TESTS: usize = 1 << 22; /// The width of the stroke around each face that covers the seams between faces. const SEAM_WIDTH: f64 = 0.75; @@ -55,7 +75,7 @@ pub(crate) fn paint_copies_add(used: &mut usize, copies: usize, paint: &Paint) - } fn visible(fx: &[Effect]) -> bool { - fx.iter().any(|e| e.visible && e.id == REVOLVE) + fx.iter().any(|e| e.visible && is_revolve(&e.id)) } pub fn has_revolve(n: &Node) -> bool { @@ -85,9 +105,25 @@ pub fn revolve_options(p: &Value) -> Revolve { smooth_shading: true, cap_ends: flag(p, "cap", true), curve_samples: None, + map_surface: false, } } +/// The options Revolve (`id` [`REVOLVE`]) or Revolve (Classic) ([`CLASSIC_REVOLVE`]) with +/// parameters `p` sweeps its surface with. A Revolve with graphics lays out its side for them. +fn options_of(id: &str, p: &Value) -> Revolve { + if id == CLASSIC_REVOLVE { + classic::options(p) + } else { + Revolve { map_surface: id == REVOLVE && !crate::solids::mapped_graphics(p).is_empty(), ..revolve_options(p) } + } +} + +/// The options effect `fx`, a Revolve or a Revolve (Classic), sweeps its surface with. +fn fx_options(fx: &Effect) -> Revolve { + options_of(&fx.id, &merged_params(&fx.id, &fx.params)) +} + /// Validate before a command mutates the document. Loading external files is still bounded /// by the evaluator; unsupported source kinds remain unchanged when rendered. pub fn validate_revolve(n: &Node, p: &Value) -> Result<(), String> { @@ -97,11 +133,16 @@ pub fn validate_revolve(n: &Node, p: &Value) -> Result<(), String> { /// [`validate_revolve`] with the symbols of `doc`: a symbol instance, a blend and a clipping group /// revolve the art they show ([`resolve_for`]), cut for Revolve whatever 3D effect `n` carries now. pub fn validate_revolve_in(doc: Option<&Document>, n: &Node, p: &Value) -> Result<(), String> { - validate_revolve_params(p)?; + validate_in(doc, n, REVOLVE, p) +} + +/// [`validate_revolve_in`] for Revolve or Revolve (Classic), `id`. +pub(crate) fn validate_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value) -> Result<(), String> { + validate_params_of(id, p)?; let n = &*resolve_for(doc, n, "Revolve", false)?; let effects = &n.appearance.effects; // The profile is measured before the object's one Revolve, hidden or shown. - let before = effects.iter().position(|e| e.id == REVOLVE).and_then(|i| effects.get(..i)).unwrap_or(effects); + let before = effects.iter().position(|e| is_revolve(&e.id)).and_then(|i| effects.get(..i)).unwrap_or(effects); if is_container(n) { const EMPTY: &str = "Revolve requires a group holding a shape with at least two anchors"; let mut shapes = members(n, "Revolve")?; @@ -110,9 +151,22 @@ pub fn validate_revolve_in(doc: Option<&Document>, n: &Node, p: &Value) -> Resul } reshape_members(n, before, &mut shapes); let b = union_bounds(&shapes).ok_or(EMPTY)?; - let options = shared_options(&shapes, revolve_options(p))?; + let options = shared_options(&shapes, options_of(id, p))?; let mut copies = 0; - return shapes.iter().try_for_each(|s| check_surface(&s.path, b, options, surface_item(&s.items), &mut copies)); + shapes.iter().try_for_each(|s| check_surface(&s.path, b, options, surface_item(&s.items), &mut copies))?; + // Without graphics, or without the document they draw from, no member is measured for them. + if let Some(doc) = doc.filter(|_| id == REVOLVE && !crate::solids::mapped_graphics(p).is_empty()) { + match graphics_member(&shapes, b, options).and_then(|k| shapes.get(k)) { + Some(s) => check_graphics(Some(doc), id, &s.path, b, options, p, &mut 0)?, + // With no member to carry them, the graphics' art must still fit its limits. + None => { + crate::solids::graphics::validate_symbols(doc, p)?; + crate::solids::graphics::validate_surface_symbols(doc, p)?; + } + } + } + let casting = shapes.iter().filter(|s| surface_item(&s.items).is_some_and(|i| paint_of(i).1 * s.opacity > 0.0)); + return check_shadow(p, casting.map(|s| &s.path), b, options); } let (path, _) = object_profile(n, "Revolve")?; if !has_two_anchors(&path) { @@ -121,18 +175,72 @@ pub fn validate_revolve_in(doc: Option<&Document>, n: &Node, p: &Value) -> Resul let path = geometry(&path, before, &GeomContext::of(n)); let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?; let paints = solid_paints(n); - check_surface(&path, b, revolve_options(p), surface_item(&paints), &mut 0) + check_surface(&path, b, options_of(id, p), surface_item(&paints), &mut 0)?; + check_graphics(doc, id, &path, b, options_of(id, p), p, &mut 0)?; + check_shadow(p, [&path], b, options_of(id, p)) +} + +/// An error when the graphics in Revolve (`id`) parameters `p`, with the symbols of `doc`, are past +/// their limits on the surface of `path` about the axis of `b`: their art, or the parts they draw +/// on its faces ([`crate::solids::graphics::surface_parts`]), whose paint copies count after +/// `copies`, the bytes of the copies of the object's graphics so far ([`Copies`]). The parts' +/// copies are added to `copies` when they fit, as drawing adds them. Without `doc` nothing is +/// drawn, and nothing is checked. +fn check_graphics(doc: Option<&Document>, id: &str, path: &PathData, b: Rect, options: Revolve, p: &Value, copies: &mut usize) -> Result<(), String> { + let graphics = crate::solids::mapped_graphics(p); + let Some(doc) = doc.filter(|_| id == REVOLVE && !graphics.is_empty()) else { return Ok(()) }; + crate::solids::graphics::validate_symbols(doc, p)?; + crate::solids::graphics::validate_surface_symbols(doc, p)?; + let faces = vectorcraft_three_d::revolve(path, b, options)?; + let mut used = *copies; + match crate::solids::graphics::surface_parts(Some(doc), NodeId(0), &graphics, &faces, &|_, c| Paint::solid(c), &mut used) { + Some(_) => { + *copies = used; + Ok(()) + } + None => Err("The graphics are too complex for this surface: simplify the symbols' art or reduce Segments".into()), + } +} + +/// The member of a group whose side takes the group's graphics: the first with the longest +/// profile among those with a fill or stroke. +fn graphics_member(shapes: &[Profile], b: Rect, options: Revolve) -> Option<usize> { + shapes + .iter() + .enumerate() + .filter(|(_, s)| surface_item(&s.items).is_some()) + .filter_map(|(k, s)| vectorcraft_three_d::revolve_surface_size(&s.path, b, options).map(|(_, h)| (k, h))) + .fold(None, |best: Option<(usize, f64)>, (k, h)| if best.is_some_and(|(_, top)| top >= h) { best } else { Some((k, h)) }) + .map(|(k, _)| k) +} + +/// With the shadow of Revolve parameters `p` on, an error when the surfaces of `paths` it is cast +/// from, about the axis of `b`, are past the limits together. +fn check_shadow<'a>(p: &Value, paths: impl IntoIterator<Item = &'a PathData>, b: Rect, options: Revolve) -> Result<(), String> { + if crate::solids::shadow::options(p).is_none() { + return Ok(()); + } + let mut caster = vectorcraft_three_d::ShadowCaster::new(); + paths.into_iter().try_for_each(|path| caster.revolve(path, vectorcraft_geom::FillRule::NonZero, b, options).map(|_| ())) } /// [`validate_revolve`] for a Revolve with parameters `p` at index `index` of the effects of -/// appearance item `target` of `n`. The surfaces of every fill and stroke that carries a Revolve, -/// `target`'s included, share one budget of paint copies, as in [`art`]. A visible object-level -/// Revolve draws in place of those surfaces. +/// appearance item `target` of `n` ([`validate_item_of`]). +#[cfg(test)] pub(crate) fn validate_item_revolve(n: &Node, p: &Value, target: usize, index: usize) -> Result<(), String> { + validate_item_of(None, n, REVOLVE, p, target, index) +} + +/// [`validate_revolve`] for a Revolve or Revolve (Classic), `id`, with parameters `p` at index +/// `index` of the effects of appearance item `target` of `n`. The surfaces of every fill and stroke +/// that carries one, `target`'s included, share one budget of paint copies, as in [`art`]. A visible +/// object-level Revolve draws in place of those surfaces. With `doc`, `target`'s graphics must fit +/// its surface ([`check_graphics`]). +pub(crate) fn validate_item_of(doc: Option<&Document>, n: &Node, id: &str, p: &Value, target: usize, index: usize) -> Result<(), String> { if is_container(n) || visible(&n.appearance.effects) || target >= n.appearance.items.len() { - return validate_revolve(n, p); + return validate_in(doc, n, id, p); } - validate_revolve_params(p)?; + validate_params_of(id, p)?; const EMPTY: &str = "Revolve requires a shape with at least two anchors"; let (path, _) = object_profile(n, "Revolve")?; if !has_two_anchors(&path) { @@ -140,18 +248,26 @@ pub(crate) fn validate_item_revolve(n: &Node, p: &Value, target: usize, index: u } let ctx = GeomContext::of(n); let path = geometry(&path, &n.appearance.effects, &ctx); - let mut copies = 0; + let (mut copies, mut graphic_copies) = (0, 0); for (i, item) in n.appearance.items.iter().enumerate() { let effects = item.effects(); - let at = if i == target { Some(index) } else { effects.iter().position(|e| e.visible && e.id == REVOLVE) }; - let options = match at.and_then(|at| effects.get(at)) { - _ if i == target => revolve_options(p), - Some(fx) if crate::paints(item) => revolve_options(&merged_params(REVOLVE, &fx.params)), + let at = if i == target { Some(index) } else { effects.iter().position(|e| e.visible && is_revolve(&e.id)) }; + let (kind, params) = match at.and_then(|at| effects.get(at)) { + _ if i == target => (id, p.clone()), + Some(fx) if crate::paints(item) => (fx.id.as_str(), merged_params(&fx.id, &fx.params)), _ => continue, }; + let options = options_of(kind, ¶ms); let path = geometry(&path, at.and_then(|at| effects.get(..at)).unwrap_or(effects), &ctx.item(item)); let b = path.bounds().ok_or(EMPTY)?; check_surface(&path, b, options, crate::paints(item).then_some(item), &mut copies)?; + // The graphics of every item add their paints' copies to the graphics' budget, as they + // are drawn; only the edited item's graphics are refused here. + let graphics = check_graphics(doc, kind, &path, b, options, ¶ms, &mut graphic_copies); + if i == target { + graphics?; + } + check_shadow(¶ms, [&path], b, options)?; } Ok(()) } @@ -185,13 +301,14 @@ fn shared_options(shapes: &[Profile], options: Revolve) -> Result<Revolve, Strin } /// The item whose paint an object's surface takes: its top fill, else its top stroke. -fn surface_item(items: &[AppearanceItem]) -> Option<&AppearanceItem> { +pub(crate) fn surface_item(items: &[AppearanceItem]) -> Option<&AppearanceItem> { items.iter().rev().find(|i| matches!(i, AppearanceItem::Fill(_))).or_else(|| items.last()) } -/// Check Revolve's parameter values `p` alone: its lights, `edge` and `cap`. +/// Check Revolve's parameter values `p` alone: its lights, shadow, `edge` and `cap`. pub(crate) fn validate_revolve_params(p: &Value) -> Result<(), String> { crate::lighting::validate(p)?; + crate::solids::shadow::validate(p)?; if p.get("edge").is_some_and(|v| v.as_str() != Some("left") && v.as_str() != Some("right")) { return Err("Revolve edge must be left or right".into()); } @@ -201,14 +318,66 @@ pub(crate) fn validate_revolve_params(p: &Value) -> Result<(), String> { Ok(()) } +/// [`validate_revolve_params`] for Revolve or Revolve (Classic), `id`; Revolve (Classic) also takes +/// only its own parameters, each in its range. +pub(crate) fn validate_params_of(id: &str, p: &Value) -> Result<(), String> { + validate_revolve_params(p)?; + crate::solids::graphics::validate(id, p)?; + if id == CLASSIC_REVOLVE { + classic::validate(p)?; + } + Ok(()) +} + fn geometry(path: &PathData, fx: &[Effect], ctx: &GeomContext) -> PathData { apply_geometry_with(fx, path, path.bounds().unwrap_or(Rect::ZERO), ctx) } +/// The shadow of Revolve `fx` cast by the surface of `path` in `item`'s paint about the axis of +/// `b`, revolved with `options`, as dark as `item` is opaque and in its blending mode; `None` with +/// the shadow off, when `item` is fully transparent or when it casts nothing, and an error when +/// the surface it is cast from is past the limits. +fn shadow_of(id: NodeId, fx: &Effect, path: &PathData, item: &AppearanceItem, b: Rect, options: Revolve) -> Result<Option<Node>, String> { + let Some(settings) = crate::solids::shadow::options(&merged_params(&fx.id, &fx.params)) else { return Ok(None) }; + let (_, opacity, blend) = paint_of(item); + if opacity <= 0.0 { + return Ok(None); + } + let mut caster = vectorcraft_three_d::ShadowCaster::new(); + caster.revolve(path, vectorcraft_geom::FillRule::NonZero, b, options)?; + Ok(crate::solids::shadow::art(id, &caster, settings, crate::solids::shadow::Ink { opacity, blend })) +} + +/// The shadow of group Revolve `fx` cast by the surfaces of the members `shapes` that have one, +/// about the axis of `b`, on one plane; each member's part is as dark as its surface is opaque, +/// in its paint's blending mode, and its opacity mask and blending mode apply to that part +/// ([`crate::solids::shadow::scoped_art`]). An error when the surfaces it is cast from are past the +/// limits. +fn group_shadow(id: NodeId, fx: &Effect, shapes: &[Profile], b: Rect, options: Revolve) -> Result<Vec<Arc<Node>>, String> { + let Some(settings) = crate::solids::shadow::options(&merged_params(&fx.id, &fx.params)) else { return Ok(vec![]) }; + let mut caster = vectorcraft_three_d::ShadowCaster::new(); + let mut cast = vec![]; + for s in shapes { + let Some((_, opacity, blend)) = surface_item(&s.items).map(paint_of) else { continue }; + // A member whose surface is fully transparent casts nothing. + let ink = crate::solids::shadow::Ink { opacity: opacity * s.opacity, blend }; + if ink.opacity <= 0.0 { + continue; + } + let faces = caster.revolve(&s.path, vectorcraft_geom::FillRule::NonZero, b, options)?; + cast.push((s.scopes.as_slice(), ink, faces)); + } + Ok(crate::solids::shadow::scoped_art(id, &caster, settings, cast, crate::solids::has_masks(shapes))) +} + /// One object's surface of revolution about the axis of `b`, and each face's depth. `copies` counts -/// the bytes of the paint copies of every surface of the object. +/// the bytes of the paint copies of every surface and graphic of the object. Revolve (Classic) draws every face +/// with its classic surface, as Extrude & Bevel (Classic) does. Revolve's graphics, with the +/// symbols of `doc`, are drawn on the faces of the side ([`crate::solids::graphics::surface_parts`]): +/// a face with a part of a graphic is a group of the face and that part. #[allow(clippy::too_many_arguments)] fn surface( + doc: Option<&Document>, n: &Node, path: &PathData, b: Rect, @@ -218,20 +387,49 @@ fn surface( opacity: f32, blend: vectorcraft_doc::color::BlendMode, expand: bool, - copies: &mut usize, + copies: &mut Copies, ) -> Option<(Vec<f64>, Node)> { // A loaded file or a profile edited past the limits keeps drawing its source path instead // of crashing the frame. Commands validate the same evaluator and report its errors. + if fx.id == CLASSIC_REVOLVE { + let facets = vectorcraft_three_d::revolve_facets(path, b, options).ok()?; + copies.surfaces = copies.surfaces.saturating_add(paint_copies(facets.len(), &paint)); + if copies.surfaces > MAX_PAINT_COPIES { + return None; + } + let depths = facets.iter().map(|f| f.depth).collect(); + let p = merged_params(&fx.id, &fx.params); + return Some((depths, crate::solids::classic::surface(n, facets, &paint, opacity, blend, &p))); + } let colored = options.light_color != [1.0; 3] || options.lights.is_some(); let faces = vectorcraft_three_d::revolve(path, b, options).ok()?; - *copies = copies.saturating_add(paint_copies(faces.len(), &paint)); - if *copies > MAX_PAINT_COPIES { + copies.surfaces = copies.surfaces.saturating_add(paint_copies(faces.len(), &paint)); + if copies.surfaces > MAX_PAINT_COPIES { return None; } + let graphics = crate::solids::mapped_graphics(&merged_params(&fx.id, &fx.params)); + let shade = |face: &vectorcraft_three_d::Face, c: Color| graphic_paint(face, c, colored); + // Graphics past the limits are left out, and the surface draws without them and their paints' + // copies. + let mut used = copies.graphics; + let mut parts = if graphics.is_empty() { + vec![] + } else { + match crate::solids::graphics::surface_parts(doc, n.id, &graphics, &faces, &shade, &mut used) { + Some(parts) => { + copies.graphics = used; + parts + } + None => vec![], + } + }; + let drawn = parts.iter().any(|p| !p.is_empty()); // Visibility is an expansion option, never a change to live geometry or export baking. // Keep all faces for paints whose coverage we cannot prove opaque. A bounded visibility - // failure also retains the complete surface rather than losing any of the user's art. + // failure also retains the complete surface rather than losing any of the user's art. With + // graphics drawn, every face stays, each with its part of the graphics. let visible = (expand + && !drawn && flag(&fx.params, "expandVisibleOnly", true) && paint.color().is_some() && opacity == 1.0 @@ -306,7 +504,16 @@ fn surface( .collect(); Arc::new(Node::path(n.id, face.path, Appearance { items, ..Default::default() })) }) - .collect(); + .collect::<Vec<_>>(); + let children = if drawn { + children + .into_iter() + .zip(parts.iter_mut().map(std::mem::take).chain(std::iter::repeat_with(Vec::new))) + .map(|(face, part)| if part.is_empty() { face } else { Arc::new(Node::group(n.id, std::iter::once(face).chain(part).collect())) }) + .collect() + } else { + children + }; let mut group = Node::group(n.id, children); group.opacity = opacity; group.blend = blend; @@ -314,12 +521,33 @@ fn surface( } /// A surface of one object about the bounds of `path`, built with options derived from `fx`. -/// `copies` is the count [`surface`] adds to. -fn object_surface(n: &Node, path: &PathData, fx: &Effect, item: &AppearanceItem, expand: bool, copies: &mut usize) -> Option<Node> { +/// `copies` is the count [`surface`] adds to; its graphics take the symbols of `doc`. +fn object_surface( + doc: Option<&Document>, + n: &Node, + path: &PathData, + fx: &Effect, + item: &AppearanceItem, + expand: bool, + copies: &mut Copies, +) -> Option<Node> { let b = path.bounds()?; let (paint, opacity, blend) = paint_of(item); - let options = revolve_options(&merged_params(REVOLVE, &fx.params)); - surface(n, path, b, options, fx, paint, opacity, blend, expand, copies).map(|(_, art)| art) + surface(doc, n, path, b, fx_options(fx), fx, paint, opacity, blend, expand, copies).map(|(_, art)| art) +} + +/// The paint of a graphic's solid color `c` on `face`, shaded as the face shades a solid fill of +/// that color: across the face with its smooth shading, under colored lights (`colored`) with +/// their color. +fn graphic_paint(face: &vectorcraft_three_d::Face, c: Color, colored: bool) -> Paint { + if colored { + return face + .light_gradient + .map_or_else(|| Paint::solid(crate::lighting::shade(c, face.illumination)), |g| crate::lighting::smooth_paint(g, c)); + } + let [r, g, b] = c.to_rgb(); + let color = |s: f64| Color::rgb(r * s as f32, g * s as f32, b * s as f32); + face.gradient.map_or_else(|| Paint::solid(color(face.brightness)), |g| shading_paint(g, color, |_| 1.0)) } fn shading_paint(g: vectorcraft_three_d::ShadeGradient, color: impl Fn(f64) -> Color, opacity: impl Fn(f64) -> f32) -> Paint { @@ -376,10 +604,10 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul let mesh = |path: &PathData, fx: &Effect, item: &AppearanceItem| -> Result<crate::SolidMesh, String> { let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?; let (paint, opacity, _) = paint_of(item); - let mesh = vectorcraft_three_d::revolve_mesh(path, rule, b, revolve_options(&merged_params(REVOLVE, &fx.params)))?; + let mesh = vectorcraft_three_d::revolve_mesh(path, rule, b, fx_options(fx))?; 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) { + if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id)) { let before = n.appearance.effects.get(..index).unwrap_or_default(); let Some(fx) = n.appearance.effects.get(index) else { return Ok(vec![]) }; let path = geometry(&path, before, &ctx); @@ -392,7 +620,7 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul 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) + if let Some(index) = item.effects().iter().position(|e| e.visible && is_revolve(&e.id)) && let Some(fx) = item.effects().get(index) { let p = geometry(&path, item.effects().get(..index).unwrap_or_default(), &ctx.item(item)); @@ -402,19 +630,73 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul Ok(out) } +/// The outline of every face [`revolve_art`] draws for `n`'s Revolve or Revolve (Classic) (its symbol +/// instances, blends and clipping groups already resolved), in document coordinates: with the +/// effect on the object, the surface in its top visible fill (else its stroke); with it on fills and strokes, one surface for each of +/// them, reshaped by the geometry effects after each one's Revolve; on a group or layer, one for +/// each member, about one shared axis. The swatches and patterns named by a live-effect plug-in +/// after a fill's or stroke's Revolve are looked up in `doc`. +pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result<Vec<PathData>, String> { + let faces = |path: &PathData, b: Rect, options: Revolve| -> Result<Vec<PathData>, String> { + Ok(vectorcraft_three_d::revolve(path, b, options)?.iter().map(vectorcraft_three_d::Face::path).collect()) + }; + if is_container(n) { + let index = n + .appearance + .effects + .iter() + .position(|e| e.visible && is_revolve(&e.id)) + .ok_or("a 3D effect on a group's fill or stroke draws nothing")?; + let Some(fx) = n.appearance.effects.get(index) else { return Ok(vec![]) }; + let mut shapes = members(n, "Revolve")?; + reshape_members(n, n.appearance.effects.get(..index).unwrap_or_default(), &mut shapes); + let b = union_bounds(&shapes).ok_or("Revolve requires a group holding a shape with at least two anchors")?; + let options = shared_options(&shapes, fx_options(fx))?; + let mut out = vec![]; + for s in shapes.iter().filter(|s| surface_item(&s.items).is_some()) { + out.extend(faces(&s.path, b, options)?); + } + return Ok(out); + } + let (path, _) = object_profile(n, "Revolve")?; + let ctx = GeomContext::of(n); + if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id)) { + let Some(fx) = n.appearance.effects.get(index) else { return Ok(vec![]) }; + let path = geometry(&path, n.appearance.effects.get(..index).unwrap_or_default(), &ctx); + if surface_item(&solid_paints(n)).is_none() { + return Err("the revolved object has no fill or stroke".into()); + } + let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?; + return faces(&path, b, fx_options(fx)); + } + 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 && is_revolve(&e.id)) + && let Some(fx) = item.effects().get(index) + { + let p = geometry(&path, item.effects().get(..index).unwrap_or_default(), &ctx.item(item)); + let b = p.bounds().ok_or("Revolve requires a shape with at least two anchors")?; + let surface = faces(&p, b, fx_options(fx))?; + out.extend(crate::solids::wireframe::reshaped(surface, item.effects().get(index + 1..).unwrap_or_default(), &GeomContext { doc, ..ctx })); + } + } + Ok(out) +} + /// [`revolve_meshes`] of group or layer `n`: one mesh for each member, about one shared axis. fn group_meshes(n: &Node, total: &mut usize, limit: usize) -> Result<Vec<crate::SolidMesh>, String> { let index = n .appearance .effects .iter() - .position(|e| e.visible && e.id == REVOLVE) + .position(|e| e.visible && is_revolve(&e.id)) .ok_or("a 3D effect on a group's fill or stroke draws nothing to export")?; let Some(fx) = n.appearance.effects.get(index) else { return Ok(vec![]) }; let mut shapes = members(n, "Revolve")?; reshape_members(n, n.appearance.effects.get(..index).unwrap_or_default(), &mut shapes); let b = union_bounds(&shapes).ok_or("Revolve requires a group holding a shape with at least two anchors")?; - let options = shared_options(&shapes, revolve_options(&merged_params(REVOLVE, &fx.params)))?; + let options = shared_options(&shapes, fx_options(fx))?; let mut out = vec![]; for s in &shapes { let Some(item) = surface_item(&s.items) else { continue }; @@ -431,45 +713,61 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> { } let n = &*resolve_for(doc, n, "Revolve", false).ok()?; if is_container(n) { - return group_art(n, expand); + return group_art(doc, n, expand); } - let (path, _) = profile(n)?; + let (path, rule) = profile(n)?; let ctx = GeomContext::of(n); let mut children = vec![]; - let mut copies = 0; + let mut copies = Copies::default(); let mut remaining = n.appearance.effects.clone(); - if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && e.id == REVOLVE) { + if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id)) { let fx = n.appearance.effects.get(index)?; let path = geometry(&path, n.appearance.effects.get(..index)?, &ctx); // An object's surface uses its top visible fill, falling back to its stroke. let paints = solid_paints(n); let item = surface_item(&paints)?; let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id)); - children.push(Arc::new(object_surface(n, &path, fx, item, expand, &mut copies)?)); + let surface = object_surface(doc, n, &path, fx, item, expand, &mut copies)?; + if let Some(b) = path.bounds() + && let Some(shadow) = shadow_of(n.id, fx, &path, item, b, fx_options(fx)).ok()? + { + children.push(Arc::new(shadow)); + } + children.push(Arc::new(surface)); // Later geometry acts on the projected art as a whole through container evaluation. - remaining = n - .appearance - .effects - .iter() - .enumerate() - .filter(|(i, e)| e.id != REVOLVE && (!is_geometry(&e.id) || *i > index)) - .map(|(_, e)| e.clone()) - .collect(); + remaining = past_effect(&n.appearance.effects, index); + remaining.retain(|e| !is_revolve(&e.id)); } else { let path = geometry(&path, &n.appearance.effects, &ctx); - remaining.retain(|e| !is_geometry(&e.id)); - 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) { + remaining = crate::without_geometry(&remaining); + // The object's Transform effects, applied to the path above, transform the items' raster + // effects too. Each copy keeps its item beside it, which plug-in effects are told they sit + // on. + let originals: Vec<&AppearanceItem> = n.appearance.items.iter().filter(|i| crate::paints(i)).collect(); + let mut items: Vec<AppearanceItem> = originals.iter().map(|i| (*i).clone()).collect(); + crate::raster::follow_paints(&mut items, &n.appearance.effects); + // Every item's shadow goes behind every item's art. + let mut shadows = vec![]; + for (original, item) in originals.into_iter().zip(&items) { + if let Some(index) = item.effects().iter().position(|e| e.visible && is_revolve(&e.id)) { let fx = item.effects().get(index)?; - let p = geometry(&path, item.effects().get(..index)?, &ctx.item(item)); + let p = geometry(&path, item.effects().get(..index)?, &ctx.item(original)); let expand = expand && !item.effects().iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id)); - let mut art = object_surface(n, &p, fx, item, expand, &mut copies)?; - art.appearance.effects = item.effects().iter().skip(index + 1).filter(|e| e.id != REVOLVE).cloned().collect(); + let mut art = object_surface(doc, n, &p, fx, item, expand, &mut copies)?; + art.appearance.effects = item.effects().iter().skip(index + 1).filter(|e| !is_revolve(&e.id)).cloned().collect(); + if let Some(b) = p.bounds() + && let Some(mut shadow) = shadow_of(n.id, fx, &p, item, b, fx_options(fx)).ok()? + { + shadow.appearance.effects = art.appearance.effects.clone(); + shadows.push(Arc::new(shadow)); + } children.push(Arc::new(art)); } else { - children.push(Arc::new(Node::path(n.id, path.clone(), Appearance { items: vec![item.clone()], ..Default::default() }))); + let flat = Appearance { items: vec![item.clone()], ..Default::default() }; + children.push(Arc::new(crate::group::shape_node(n.id, path.clone(), rule, flat))); } } + children.splice(0..0, shadows); } let mut art = n.clone(); art.kind = NodeKind::Group { children, clip: false }; @@ -508,14 +806,14 @@ pub(crate) fn scoped<'a>(id: NodeId, surfaces: Vec<(&'a [Scope], Arc<Node>)>, le /// What a face can paint, to tell whether two faces overlap: the convex hull of the points and /// control points of its outline, which holds the outline, and the hull's box grown by half the /// seam stroke. -struct Coverage { - bounds: Rect, +pub(crate) struct Coverage { + pub(crate) bounds: Rect, hull: Vec<Point>, } impl Coverage { /// `None` for a face with no outline and no box. - fn of(face: &Node) -> Option<Coverage> { + pub(crate) fn of(face: &Node) -> Option<Coverage> { let points: Vec<Point> = match face.path_data() { Some(path) => path .to_bezpath() @@ -543,7 +841,7 @@ impl Coverage { /// Do the two faces' hulls, each grown by half the seam stroke, overlap? A test of the /// separating axes of their edges and of the page's axes: `true` whenever they overlap, and /// sometimes near a corner when they don't. - fn meets(&self, other: &Coverage) -> bool { + pub(crate) fn meets(&self, other: &Coverage) -> bool { fn normals(hull: &[Point]) -> impl Iterator<Item = Vec2> + '_ { (0..hull.len()).filter_map(|i| { let (a, b) = (hull.get(i)?, hull.get((i + 1) % hull.len())?); @@ -590,38 +888,47 @@ fn convex_hull(mut points: Vec<Point>) -> Vec<Point> { } /// Do boxes `a` and `b` overlap with some area? -fn overlaps(a: Rect, b: Rect) -> bool { +pub(crate) fn overlaps(a: Rect, b: Rect) -> bool { a.x0 < b.x1 && b.x0 < a.x1 && a.y0 < b.y1 && b.y0 < a.y1 } /// [`art`] of group or layer `n`: every member swept about one axis on the bounds of all of them, /// each in its own paint. Every member's faces are drawn in one back-to-front order. `None` when /// the effect is only on the group's own fills or strokes or when its members can't be revolved. -fn group_art(n: &Node, expand: bool) -> Option<Node> { - let index = n.appearance.effects.iter().position(|e| e.visible && e.id == REVOLVE)?; +fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> { + let index = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id))?; let fx = n.appearance.effects.get(index)?; let mut shapes = members(n, "").ok()?; reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes); let b = union_bounds(&shapes)?; - let options = shared_options(&shapes, revolve_options(&merged_params(REVOLVE, &fx.params))).ok()?; + let options = shared_options(&shapes, fx_options(fx)).ok()?; let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id)); - let mut copies = 0; + let mut copies = Copies::default(); let mut surfaces = vec![]; let mut opaque = true; - for s in &shapes { + // The graphics go once, on the side of the member with the longest profile. Without graphics + // no member is measured for them. + let mapped = fx.id == REVOLVE && !crate::solids::mapped_graphics(&merged_params(&fx.id, &fx.params)).is_empty(); + let longest = if mapped { graphics_member(&shapes, b, options) } else { None }; + for (k, s) in shapes.iter().enumerate() { let Some(item) = surface_item(&s.items) else { continue }; // The opacity and blending of the member and the groups it is in apply through its scopes. let (paint, opacity, blend) = paint_of(item); opaque &= opacity >= 1.0 && blend == Default::default() && s.scopes.is_empty(); // A member with transparency of its own keeps every face, as a transparent object does. let expand = expand && s.scopes.is_empty(); - let (depths, art) = surface(n, &s.path, b, options, fx, paint, opacity, blend, expand, &mut copies)?; + let doc = doc.filter(|_| longest == Some(k)); + let (depths, art) = surface(doc, n, &s.path, b, options, fx, paint, opacity, blend, expand, &mut copies)?; surfaces.push((depths, art, s.scopes.as_slice())); } if surfaces.is_empty() { return None; } let plain = surfaces.iter().all(|(depths, s, _)| matches!(&s.kind, NodeKind::Group { children, clip: false } if children.len() == depths.len())); + // A classic surface whose gradient has transparent stops carries an opacity mask: its faces go + // in runs, as a transparent member's do, and each run carries the mask. + let masks: Vec<Option<Box<vectorcraft_doc::OpacityMask>>> = surfaces.iter().map(|(_, s, _)| s.extras().mask.clone()).collect(); + let opaque = opaque && masks.iter().all(Option::is_none); let children = if !plain { scoped(n.id, surfaces.into_iter().map(|(_, s, scopes)| (scopes, Arc::new(s))).collect(), 0) } else { @@ -663,7 +970,8 @@ fn group_art(n: &Node, expand: bool) -> Option<Node> { runs.push(Run { member: None, scopes, bounds: Rect::ZERO, faces: vec![face], cover: vec![], opacity, blend }); continue; }; - if opacity >= 1.0 && blend == Default::default() && scopes.is_empty() { + let masked = masks.get(member).is_some_and(Option::is_some); + if opacity >= 1.0 && blend == Default::default() && scopes.is_empty() && !masked { runs.push(Run { member: None, scopes, bounds: cover.bounds, faces: vec![face], cover: vec![cover], opacity, blend }); continue; } @@ -699,13 +1007,18 @@ fn group_art(n: &Node, expand: bool) -> Option<Node> { let mut group = Node::group(n.id, r.faces); group.opacity = r.opacity; group.blend = r.blend; + if let Some(mask) = r.member.and_then(|m| masks.get(m)).cloned().flatten() { + group.extras_mut().mask = Some(mask); + } Some((r.scopes, Arc::new(group))) }); scoped(n.id, runs.collect(), 0) } }; - let remaining = - n.appearance.effects.iter().enumerate().filter(|(i, e)| *i != index && (!is_geometry(&e.id) || *i > index)).map(|(_, e)| e.clone()).collect(); + // One shadow for every member's surface, behind them all. + let mut children = children; + children.splice(0..0, group_shadow(n.id, fx, &shapes, b, options).ok()?); + let remaining = past_effect(&n.appearance.effects, index); let mut art = n.clone(); art.kind = NodeKind::Group { children, clip: false }; art.appearance = Appearance { effects: remaining, ..Default::default() }.into(); @@ -838,6 +1151,52 @@ mod tests { assert!(surface.children().unwrap().iter().all(|c| c.opacity == 1.0 && !has_revolve(c))); } #[test] + fn a_fill_without_the_revolve_keeps_the_even_odd_hole() { + use vectorcraft_geom::FillRule; + use vectorcraft_geom::hit::fill_contains; + // Two nested squares drawn in the same direction: only the even-odd rule leaves a hole. + let [outer, inner] = [(100.0, 200.0), (130.0, 170.0)].map(|(lo, hi)| { + let mut b = BezPath::new(); + b.move_to((lo, lo)); + b.line_to((hi, lo)); + b.line_to((hi, hi)); + b.line_to((lo, hi)); + b.close_path(); + PathData::from_bezpath(&b) + }); + let flat = AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::rgb(0.1, 0.3, 0.9)))); + for id in [REVOLVE, CLASSIC_REVOLVE] { + let mut top = AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::rgb(0.8, 0.2, 0.1)))); + top.effects_mut().push(crate::new_effect(id, &json!({})).unwrap()); + let appearance = Appearance { items: vec![flat.clone(), top], ..Default::default() }; + let members = vec![ + Arc::new(Node::path(NodeId(2), outer.clone(), Appearance::default())), + Arc::new(Node::path(NodeId(3), inner.clone(), Appearance::default())), + ]; + let mut compound = Node::new(NodeId(1), NodeKind::Compound { children: members, rule: FillRule::EvenOdd }); + compound.appearance = appearance.clone().into(); + let both = PathData::new(outer.subpaths.iter().chain(&inner.subpaths).cloned().collect()); + let path = crate::group::shape_node(NodeId(1), both, FillRule::EvenOdd, appearance); + for (n, shape) in [(compound, "compound path"), (path, "path")] { + for (art, how) in [(revolve_art(&n), "live"), (expand_revolve_art(&n), "expanded")] { + let what = format!("{id} on the top fill of a {shape}, {how}"); + let art = art.unwrap_or_else(|| panic!("{what}")); + let children = art.children().unwrap(); + let plain: Vec<usize> = (0..children.len()) + .filter(|&i| children[i].appearance.items == [flat.clone()] && children[i].path_data().is_some()) + .collect(); + let [index] = plain[..] else { panic!("{what}: one flat child, got {plain:?}") }; + let NodeKind::Path { path, rule, .. } = &children[index].kind else { panic!("{what}: a path") }; + assert_eq!(*rule, FillRule::EvenOdd, "{what}"); + let bez = path.to_bezpath(); + assert!(fill_contains(&bez, *rule, Point::new(110.0, 150.0)), "{what}: the ring is filled"); + assert!(!fill_contains(&bez, *rule, Point::new(150.0, 150.0)), "{what}: the hole stays open"); + assert!(index + 1 < children.len(), "{what}: the revolved art is drawn above"); + } + } + } + } + #[test] fn export_bakes_faces_with_unique_ids_and_no_revolve_effects() { let mut d = Document::new(300.0, 300.0); let mut n = profile_node(); @@ -1118,7 +1477,7 @@ mod tests { group.appearance = Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0).into(); for id in [REVOLVE, crate::EXTRUDE] { assert!(crate::validate_three_d(&group, id, &json!({})).is_ok(), "{id} on the group itself"); - let refused = crate::validate_three_d_at(&group, id, &json!({}), Some((0, 0))).unwrap_err(); + let refused = crate::validate_three_d_at(&group, id, &json!({}), (Some(0), 0)).unwrap_err(); assert!(refused.contains("on the group itself"), "{id}: {refused}"); } } @@ -1284,3 +1643,7 @@ mod tests { assert_eq!(expand_revolve_art(&sample), revolve_art(&sample)); } } + +#[cfg(test)] +#[path = "revolve/tests_graphics.rs"] +mod tests_graphics; diff --git a/crates/effects/src/revolve/classic.rs b/crates/effects/src/revolve/classic.rs new file mode 100644 index 0000000000..1881381567 --- /dev/null +++ b/crates/effects/src/revolve/classic.rs @@ -0,0 +1,220 @@ +//! Revolve (Classic): the surface Revolve sweeps from a path, drawn with the classic surfaces of +//! Extrude & Bevel (Classic) (Wireframe, No Shading, Diffuse and Plastic), their highlight, blend +//! steps and shading color. +use serde_json::Value; +use vectorcraft_three_d::Revolve; + +pub const CLASSIC_REVOLVE: &str = "threeD.classicRevolve"; + +/// The numeric parameters: (key, lowest, highest, whole numbers only). +const RANGES: [(&str, f64, f64, bool); 13] = [ + ("angle", 0.0, 360.0, false), + ("offset", 0.0, 1000.0, false), + ("rotationX", -180.0, 180.0, false), + ("rotationY", -180.0, 180.0, false), + ("rotationZ", -180.0, 180.0, false), + ("perspectiveAngle", 0.0, 160.0, false), + ("lightRotation", -180.0, 180.0, false), + ("lightHeight", 0.0, 90.0, false), + ("lightIntensity", 0.0, 100.0, false), + ("ambient", 0.0, 100.0, false), + ("highlightIntensity", 0.0, 100.0, false), + ("highlightSize", 0.0, 100.0, false), + ("blendSteps", 1.0, 256.0, true), +]; + +const FLAGS: [&str; 2] = ["cap", "lightBehind"]; + +/// The surface Revolve (Classic)'s parameters `p` sweep: Revolve's angle, cap, offset, edge, +/// rotation and perspective, built unshaded, since the classic surfaces light its faces. +pub(crate) fn options(p: &Value) -> Revolve { + Revolve { shade: false, smooth_shading: false, lights: None, light_color: [1.0; 3], ..super::revolve_options(p) } +} + +/// Check Revolve (Classic)'s parameters `p` (its defaults filled in) beyond the checks it shares +/// with Revolve: every key is one of its parameters, numbers are in range, flags are true or false, +/// and the surface and shading color are named. +pub(crate) fn validate(p: &Value) -> Result<(), String> { + crate::solids::classic::validate_classic(CLASSIC_REVOLVE, p, &RANGES, &FLAGS) +} + +#[cfg(test)] +mod tests { + use serde_json::json; + use vectorcraft_doc::color::{Color, Paint}; + use vectorcraft_doc::{Appearance, AppearanceItem, Node, NodeId}; + use vectorcraft_geom::{BezPath, PathData}; + + use super::*; + + const BLUE: Color = Color::Rgb { r: 0.2, g: 0.4, b: 0.8 }; + + /// Half a vase's profile, open, filled blue. + fn profile() -> Node { + 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)); + Node::path(NodeId(1), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(BLUE), Paint::None, 0.0)) + } + + fn revolved(params: Value) -> Node { + let mut n = profile(); + n.appearance.effects.push(crate::new_effect(CLASSIC_REVOLVE, ¶ms).unwrap()); + crate::revolve_art(&n).unwrap() + } + + /// The faces of the surface of `art`, back to front. + fn faces(art: &Node) -> Vec<&Node> { + art.children().unwrap().iter().flat_map(|s| s.children().unwrap().iter().map(|f| &**f)).collect() + } + + fn fill(face: &Node) -> Option<Color> { + face.appearance.items.iter().find_map(|i| match i { + AppearanceItem::Fill(f) => f.paint.color(), + AppearanceItem::Stroke(_) => None, + }) + } + + fn facets(params: &Value) -> usize { + let n = profile(); + let path = n.path_data().unwrap(); + let p = crate::merged_params(CLASSIC_REVOLVE, params); + vectorcraft_three_d::revolve_facets(path, path.bounds().unwrap(), options(&p)).unwrap().len() + } + + #[test] + fn plastic_shades_every_face_of_the_swept_surface_in_the_fill() { + let art = revolved(json!({})); + let drawn = faces(&art); + assert_eq!(drawn.len(), facets(&json!({})), "one face for each facet of the surface"); + let colors: Vec<[f32; 3]> = drawn.iter().map(|f| fill(f).unwrap().to_rgb()).collect(); + // Lit from one side, the faces take more than one tone, and none is another hue: a face is + // the blue darkened toward black, lightened toward white, or both. + let distinct = colors.iter().filter(|c| colors.iter().any(|d| (c[0] - d[0]).abs() > 0.02)).count(); + assert!(distinct > 0, "{colors:?}"); + // Diffuse has no highlight, so every face is the blue darkened toward black. + let art = revolved(json!({"surface": "diffuse"})); + for face in faces(&art) { + let [r, g, b] = fill(face).unwrap().to_rgb(); + assert!(b <= 0.8 + 1e-6 && (g * 2.0 - b).abs() < 1e-4 && (r * 4.0 - b).abs() < 1e-4, "{r} {g} {b}"); + } + } + + #[test] + fn wireframe_strokes_the_edges_of_every_face_and_no_shading_keeps_the_paint() { + let art = revolved(json!({"surface": "wireframe"})); + let faces_drawn = faces(&art); + assert_eq!(faces_drawn.len(), facets(&json!({"surface": "wireframe"}))); + for face in faces_drawn { + match face.appearance.items.as_slice() { + [AppearanceItem::Stroke(s)] => assert_eq!((s.paint.color(), s.width), (Some(BLUE), 0.5)), + items => panic!("a wireframe face is one stroke: {items:?}"), + } + } + for face in faces(&revolved(json!({"surface": "none"}))) { + assert_eq!(fill(face), Some(BLUE)); + } + } + + #[test] + fn angle_offset_edge_and_cap_shape_the_surface() { + let full = revolved(json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0})).visual_bounds().unwrap(); + // Seen from the front, the full turn is twice the profile's width across, about its left edge. + assert!((full.width() - 60.0).abs() < 2.0, "{full:?}"); + let ring = revolved(json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "offset": 20})).visual_bounds().unwrap(); + assert!((ring.width() - 100.0).abs() < 2.0, "{ring:?}"); + // About its right edge the axis is at x 130, so the surface reaches x 160. + let right = revolved(json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "edge": "right"})).visual_bounds().unwrap(); + assert!((right.x1 - 160.0).abs() < 2.0, "{right:?}"); + assert!(facets(&json!({"angle": 90})) < facets(&json!({}))); + // The profile's ends lie on the axis, so they close nothing until an offset moves them off it. + assert!(facets(&json!({"cap": false, "offset": 10})) < facets(&json!({"offset": 10})), "hollow leaves out the end caps"); + } + + #[test] + fn a_group_revolves_its_members_about_one_shared_axis() { + let mut b = BezPath::new(); + b.move_to((150.0, 60.0)); + b.line_to((170.0, 60.0)); + b.line_to((170.0, 140.0)); + let outer = Node::path(NodeId(2), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + let mut g = Node::group(NodeId(3), vec![std::sync::Arc::new(profile()), std::sync::Arc::new(outer)]); + g.appearance.effects.push(crate::new_effect(CLASSIC_REVOLVE, &json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0})).unwrap()); + let art = crate::revolve_art(&g).unwrap(); + // The axis is at the left edge of both members together, x 100, so the outer one reaches 70 + // out on either side of it. + let bounds = art.visual_bounds().unwrap(); + assert!((bounds.x0 - 30.0).abs() < 2.0 && (bounds.x1 - 170.0).abs() < 2.0, "{bounds:?}"); + let mut colors = vec![]; + art.walk(&mut |n| colors.extend(fill(n).map(|c| c.to_rgb()))); + assert!(colors.iter().any(|c| c[2] > c[0]) && colors.iter().any(|c| c[0] == c[2]), "both members' paints are drawn"); + } + + /// A group member in a gradient with transparent stops keeps the shared back-to-front order of + /// every member's faces: its faces go in runs that carry its opacity mask, and the other + /// member's faces are drawn between them where they are in front of some and behind others. + #[test] + fn a_member_in_a_transparent_gradient_keeps_the_shared_face_order() { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let art = |end_opacity: f32| { + let mut end = GradientStop::new(1.0, Color::BLACK); + end.opacity = end_opacity; + let gradient = + Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, BLUE), end])))); + let mut b = BezPath::new(); + b.move_to((150.0, 60.0)); + b.line_to((170.0, 60.0)); + b.line_to((170.0, 140.0)); + let outer = Node::path(NodeId(2), PathData::from_bezpath(&b), Appearance::basic(gradient, Paint::None, 0.0)); + let mut g = Node::group(NodeId(3), vec![std::sync::Arc::new(outer), std::sync::Arc::new(profile())]); + g.appearance.effects.push(crate::new_effect(CLASSIC_REVOLVE, &json!({})).unwrap()); + crate::revolve_art(&g).unwrap() + }; + // The drawing order: `M` for a group with an opacity mask, `F` for a face outside one. + fn visit(n: &Node, order: &mut String) { + if n.extras().mask.is_some() { + order.push('M'); + return; + } + if n.path_data().is_some() { + order.push('F'); + } + for c in n.children().into_iter().flatten() { + visit(c, order); + } + } + let order = |art: &Node| { + let mut order = String::new(); + visit(art, &mut order); + order + }; + assert!(!order(&art(1.0)).contains('M'), "an opaque gradient needs no mask"); + let masked = order(&art(0.5)); + let (first, last) = (masked.find('M').unwrap(), masked.rfind('M').unwrap()); + assert!(masked.get(first..last).is_some_and(|between| between.contains('F')), "faces between the member's runs: {masked}"); + } + + #[test] + fn bad_parameters_are_refused() { + let check = |p: Value| crate::validate_three_d(&profile(), CLASSIC_REVOLVE, &crate::merged_params(CLASSIC_REVOLVE, &p)); + assert_eq!(check(json!({})), Ok(())); + for (p, error) in [ + (json!({"segments": 32}), "unknown parameter `segments`"), + (json!({"angle": 400}), "`angle` must be between 0 and 360"), + (json!({"offset": 1001}), "`offset` must be between 0 and 1000"), + (json!({"rotationY": -181}), "`rotationY` must be between -180 and 180"), + (json!({"blendSteps": 2.5}), "`blendSteps` must be a whole number"), + (json!({"lightBehind": 1}), "`lightBehind` must be true or false"), + (json!({"surface": "glossy"}), "`surface` must be one of"), + (json!({"shadingColor": "white"}), "`shadingColor` must be one of"), + (json!({"shadingCustom": "red"}), "`shadingCustom` must be a #rrggbb color"), + (json!({"edge": "middle"}), "Revolve edge must be left or right"), + (json!({"cap": "yes"}), "Revolve cap must be a boolean"), + ] { + let e = check(p.clone()).unwrap_err(); + assert!(e.contains(error), "{p}: {e}"); + } + } +} diff --git a/crates/effects/src/revolve/tests_graphics.rs b/crates/effects/src/revolve/tests_graphics.rs new file mode 100644 index 0000000000..5d9500628b --- /dev/null +++ b/crates/effects/src/revolve/tests_graphics.rs @@ -0,0 +1,576 @@ +use serde_json::json; +use vectorcraft_doc::Symbol; +use vectorcraft_doc::color::Color; +use vectorcraft_geom::{BezPath, shapes}; + +use super::*; +use crate::solids::three_d_params_as; + +fn bar(r: Rect, color: Color) -> Node { + Node::path(NodeId(0), shapes::rectangle(r), Appearance::basic(Paint::solid(color), Paint::None, 0.0)) +} + +/// A document with symbols "Red" and "Blue" (10 × 20 bars) and "Wide" (a red 300 × 10 bar). +fn document() -> Document { + let mut d = Document::new(1000.0, 1000.0); + for (name, r, color) in [ + ("Red", Rect::new(0.0, 0.0, 10.0, 20.0), Color::rgb(1.0, 0.0, 0.0)), + ("Blue", Rect::new(0.0, 0.0, 10.0, 20.0), Color::rgb(0.0, 0.0, 1.0)), + ("Wide", Rect::new(0.0, 0.0, 300.0, 10.0), Color::rgb(1.0, 0.0, 0.0)), + ("Flat", Rect::new(0.0, 0.0, 10.0, 2.0), Color::rgb(1.0, 0.0, 0.0)), + ] { + d.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(bar(r, color)) }); + } + d +} + +/// A gray open profile through `points` (its first and last on the axis at x 0), revolved with +/// `params` over a view straight on without shading. +fn revolved(points: &[(f64, f64)], params: Value) -> Node { + let mut b = BezPath::new(); + b.move_to(points[0]); + points[1..].iter().for_each(|p| b.line_to(*p)); + let mut p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": false}); + p.as_object_mut().unwrap().extend(params.as_object().unwrap().clone()); + let mut n = Node::path(NodeId(7), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(Color::rgb(0.5, 0.5, 0.5)), Paint::None, 0.0)); + n.appearance.effects.push(crate::new_effect(REVOLVE, &p).unwrap()); + n +} + +/// A cylinder of radius 50 about x 0, from y 0 to 200. +const CYLINDER: [(f64, f64); 4] = [(0.0, 0.0), (50.0, 0.0), (50.0, 200.0), (0.0, 200.0)]; + +/// A profile that narrows from 50 to 20 from the axis at y 100 and widens again. +const NECK: [(f64, f64); 5] = [(0.0, 0.0), (50.0, 0.0), (20.0, 100.0), (50.0, 200.0), (0.0, 200.0)]; + +/// The red channel of each color `paint` draws when it is a shade of pure red or pure blue (`blue`): +/// a solid color or the stops of a gradient. `None` for any other paint. +fn shade_of(paint: &Paint, blue: bool) -> Option<Vec<f32>> { + let hue = |c: &Color| { + let [r, g, b] = c.to_rgb(); + let (on, off) = if blue { (b, r) } else { (r, b) }; + (on > 0.02 && off < 0.01 && g < 0.01).then_some(on) + }; + match paint { + Paint::Solid { .. } => Some(vec![hue(&paint.color()?)?]), + Paint::Gradient(g) => g.gradient.stops.iter().map(|s| hue(&s.color)).collect(), + _ => None, + } +} + +/// The paths in `art` filled in a shade of red (or blue), with their shades. +fn parts(art: &Node, blue: bool) -> Vec<(PathData, Vec<f32>)> { + let mut out = vec![]; + art.walk(&mut |n| { + let Some(path) = n.path_data() else { return }; + let fill = n.appearance.items.iter().find_map(|i| match i { + AppearanceItem::Fill(f) => shade_of(&f.paint, blue), + AppearanceItem::Stroke(_) => None, + }); + if let Some(shades) = fill { + out.push((path.clone(), shades)); + } + }); + out +} + +fn reach(parts: &[(PathData, Vec<f32>)]) -> Rect { + parts.iter().filter_map(|(p, _)| p.bounds()).reduce(|a, b| a.union(b)).unwrap() +} + +fn near(a: f64, b: f64, tolerance: f64) -> bool { + (a - b).abs() <= tolerance +} + +#[test] +fn a_graphic_wraps_around_the_side_and_narrows_toward_the_silhouette() { + let d = document(); + let n = revolved(&CYLINDER, json!({"graphics": [{"symbol": "Red"}, {"symbol": "Blue", "x": 60.0}]})); + let art = revolve_art_in(Some(&d), &n).unwrap(); + // At the middle of the side, facing the viewer, the bar keeps its size: 10 wide at the axis's + // line, from 10 above the middle of the profile to 10 below. + let front = reach(&parts(&art, false)); + let half = 50.0 * (5.0f64 / 50.0).sin(); + assert!(near(front.x0, -half, 0.05) && near(front.x1, half, 0.05), "{front:?}"); + assert!(near(front.y0, 90.0, 1e-6) && near(front.y1, 110.0, 1e-6), "{front:?}"); + // 60 to its right the side has turned 1.1 to 1.3 radians away: the same bar draws less than + // half as wide, at the sine of those angles. + let turned = reach(&parts(&art, true)); + assert!(near(turned.x0, 50.0 * 1.1f64.sin(), 0.15) && near(turned.x1, 50.0 * 1.3f64.sin(), 0.15), "{turned:?}"); + assert!(turned.width() < front.width() / 2.0); +} + +#[test] +fn the_part_past_the_silhouette_and_on_the_back_is_not_drawn() { + let d = document(); + // A bar wider than the half of the side seen from the front reaches the silhouette and no + // further. + let n = revolved(&CYLINDER, json!({"graphics": [{"symbol": "Wide"}]})); + let wide = reach(&parts(&revolve_art_in(Some(&d), &n).unwrap(), false)); + assert!(wide.x0 > -50.0 - 1e-6 && wide.x1 < 50.0 + 1e-6, "{wide:?}"); + assert!(wide.x0 < -49.5 && wide.x1 > 49.5, "{wide:?}"); + // On the back, half a turn around the axis, nothing is drawn. + let n = revolved(&CYLINDER, json!({"graphics": [{"symbol": "Red", "x": 150.0}]})); + assert!(parts(&revolve_art_in(Some(&d), &n).unwrap(), false).is_empty()); + // Turned half a turn, the back faces the viewer. + let n = revolved(&CYLINDER, json!({"rotationY": 180.0, "graphics": [{"symbol": "Red", "x": 150.0}]})); + assert!(!parts(&revolve_art_in(Some(&d), &n).unwrap(), false).is_empty()); +} + +#[test] +fn a_graphic_follows_the_profile_and_keeps_its_size_where_it_comes_nearer_the_axis() { + let d = document(); + // A 10 wide bar keeps its length around the axis at every distance from it: at the neck, 20 + // from the axis, it spans 0.5 radians; half way up the slanted side (52.2 along it, 35 from + // the axis, at y 50), 2/7 of a radian. Straight on, both draw nearly 10 wide. + let slant = (30.0f64 * 30.0 + 100.0 * 100.0).sqrt(); + let n = revolved(&NECK, json!({"graphics": [{"symbol": "Flat"}, {"symbol": "Flat", "y": -slant / 2.0}]})); + let art = revolve_art_in(Some(&d), &n).unwrap(); + let all = parts(&art, false); + let neck: Vec<_> = all.iter().filter(|(p, _)| p.bounds().unwrap().center().y > 75.0).cloned().collect(); + let up: Vec<_> = all.iter().filter(|(p, _)| p.bounds().unwrap().center().y <= 75.0).cloned().collect(); + let (neck, up) = (reach(&neck), reach(&up)); + // Each bar is 2 tall, so its ends are up to 0.3 farther from the axis than its middle. + assert!(near(neck.width(), 2.0 * 20.0 * 0.25f64.sin(), 0.15), "{neck:?}"); + assert!(near(neck.center().y, 100.0, 0.05), "{neck:?}"); + assert!(near(up.width(), 2.0 * 35.0 * (5.0f64 / 35.0).sin(), 0.15), "{up:?}"); + assert!(near(up.center().y, 50.0, 0.05), "{up:?}"); + // At the neck a bar 25 to the right lies 1 to 1.5 radians around, near the silhouette; one 40 + // to the right lies 1.75 to 2.25 radians around, past the silhouette, and is not drawn. + let n = revolved(&NECK, json!({"graphics": [{"symbol": "Flat", "x": 25.0}]})); + let side = reach(&parts(&revolve_art_in(Some(&d), &n).unwrap(), false)); + assert!(near(side.x0, 20.0 * 1.0f64.sin(), 0.3) && near(side.x1, 20.0 * 1.5f64.sin(), 0.3), "{side:?}"); + let n = revolved(&NECK, json!({"graphics": [{"symbol": "Flat", "x": 40.0}]})); + assert!(parts(&revolve_art_in(Some(&d), &n).unwrap(), false).is_empty()); +} + +#[test] +fn with_the_axis_on_the_right_a_graphic_starts_on_the_front() { + let d = document(); + // The cylinder of radius 50 about x 0, swept from its right edge. + let profile = [(0.0, 0.0), (-50.0, 0.0), (-50.0, 200.0), (0.0, 200.0)]; + let n = revolved(&profile, json!({"edge": "right", "graphics": [{"symbol": "Red"}]})); + let front = reach(&parts(&revolve_art_in(Some(&d), &n).unwrap(), false)); + let half = 50.0 * (5.0f64 / 50.0).sin(); + assert!(near(front.x0, -half, 0.05) && near(front.x1, half, 0.05), "{front:?}"); + assert!(near(front.y0, 90.0, 1e-6) && near(front.y1, 110.0, 1e-6), "{front:?}"); + // x increases to the viewer's right here too. + let n = revolved(&profile, json!({"edge": "right", "graphics": [{"symbol": "Red", "x": 25.0}]})); + let right = reach(&parts(&revolve_art_in(Some(&d), &n).unwrap(), false)); + assert!(near(right.center().x, 50.0 * 0.5f64.sin(), 0.3), "{right:?}"); +} + +#[test] +fn a_graphic_is_shaded_with_the_surface() { + let d = document(); + // The light is on the left: the bar left of the middle is lighter than the one on its right, + // and neither keeps its unlit red. + let n = revolved(&CYLINDER, json!({"shade": true, "graphics": [{"symbol": "Red", "x": -30.0}, {"symbol": "Red", "x": 30.0}]})); + let all = parts(&revolve_art_in(Some(&d), &n).unwrap(), false); + let mean = |left: bool| { + let shades: Vec<f32> = + all.iter().filter(|(p, _)| (p.bounds().unwrap().center().x < 0.0) == left).flat_map(|(_, s)| s.iter().copied()).collect(); + shades.iter().sum::<f32>() / shades.len() as f32 + }; + assert!(mean(true) > mean(false) + 0.05, "{} {}", mean(true), mean(false)); + assert!(all.iter().all(|(_, s)| s.iter().all(|r| *r < 0.999))); +} + +#[test] +fn overlapping_graphics_keep_their_order_on_every_face() { + let d = document(); + // The wide red bar, listed second, reaches across the narrow blue one, listed first. Shaded, + // each face is one triangle. + let n = revolved(&CYLINDER, json!({"shade": true, "graphics": [{"symbol": "Blue", "x": 30.0}, {"symbol": "Wide"}]})); + let art = revolve_art_in(Some(&d), &n).unwrap(); + let mut both = 0; + art.walk(&mut |g| { + // A face with parts of graphics: the face's path, then the parts' paths. + let NodeKind::Group { children, clip: false } = &g.kind else { return }; + if !children.iter().all(|c| matches!(c.kind, NodeKind::Path { .. })) { + return; + } + let colors: Vec<bool> = children + .iter() + .filter_map(|c| { + let blue = !parts(c, true).is_empty(); + (blue || !parts(c, false).is_empty()).then_some(blue) + }) + .collect(); + if colors.contains(&true) && colors.contains(&false) { + both += 1; + assert!(colors.iter().position(|b| !b) > colors.iter().position(|b| *b), "{colors:?}"); + } + }); + assert!(both > 0); +} + +#[test] +fn a_graphic_past_the_end_reaches_the_curved_rim_and_no_further() { + let d = document(); + // A tube 50 from the axis with a cap at each end, in 10 segments, tilted to show its top: the + // bottom rim is an arc on the page whose lowest point, in front, lies between two corners of + // the faces. The wide bar runs 5 past the bottom of the profile. + for shade in [true, false] { + let mut b = BezPath::new(); + b.move_to((0.0, 0.0)); + b.line_to((0.0, 200.0)); + let p = json!({"offset": 50.0, "segments": 10, "rotationX": -30.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": shade, "graphics": [{"symbol": "Wide", "y": 100.0}]}); + let mut n = Node::path(NodeId(7), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(Color::rgb(0.5, 0.5, 0.5)), Paint::None, 0.0)); + n.appearance.effects.push(crate::new_effect(REVOLVE, &p).unwrap()); + let art = revolve_art_in(Some(&d), &n).unwrap(); + let mut lowest = f64::NEG_INFINITY; + art.walk(&mut |c| { + if let Some(b) = c.path_data().and_then(PathData::bounds) { + lowest = lowest.max(b.y1); + } + }); + let bar = reach(&parts(&art, false)); + assert!(near(bar.y1, lowest, 0.05), "shade {shade}: {bar:?} {lowest}"); + // A thin bar wholly past the end, 0.35 to 0.85 below it in front, lies between the faces' + // straight lower edge and the rim's arc there: it is drawn, inside the rim. + let mut thin = n.clone(); + let p = json!({"offset": 50.0, "segments": 10, "rotationX": -30.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": shade, "graphics": [{"symbol": "Flat", "y": 100.6, "scale": 25.0}]}); + thin.appearance.effects = vec![crate::new_effect(REVOLVE, &p).unwrap()]; + let past = parts(&revolve_art_in(Some(&d), &thin).unwrap(), false); + assert!(!past.is_empty(), "shade {shade}"); + assert!(reach(&past).y1 <= lowest + 1e-6, "shade {shade}: {:?} {lowest}", reach(&past)); + } +} + +#[test] +fn under_several_lights_a_graphic_takes_each_faces_own_lit_art() { + let d = document(); + let lights = json!([{"color": "#ff8080", "rotation": 120.0}, {"color": "#8080ff", "rotation": -30.0}]); + let clips = |n: &Node| { + let mut count = 0; + revolve_art_in(Some(&d), n).unwrap().walk(&mut |c| count += usize::from(matches!(c.kind, NodeKind::Group { clip: true, .. }))); + count + }; + let plain = revolved(&CYLINDER, json!({"shade": true, "lights": lights})); + let mapped = revolved(&CYLINDER, json!({"shade": true, "lights": lights, "graphics": [{"symbol": "Red"}]})); + // Each part of the bar is the face's lit art clipped to the part: one clip more for the + // part, one for the face's own art inside it. + assert!(clips(&mapped) > clips(&plain), "{} {}", clips(&mapped), clips(&plain)); + // A lit face draws its paint under the face's light: a layer of the light's three channels, + // multiplied over the paint. Every part of the bar takes such a layer of its own, so the bar + // is shaded with each face's colored light; a bar drawn in flat red would add none. + let lit = |n: &Node| { + let mut count = 0; + revolve_art_in(Some(&d), n).unwrap().walk(&mut |c| count += usize::from(c.blend == vectorcraft_doc::color::BlendMode::Multiply)); + count + }; + assert!(lit(&mapped) > lit(&plain), "{} {}", lit(&mapped), lit(&plain)); + // An opaque part also draws its lit art clipped to the band of its seam stroke; a translucent + // part, whose overlap would show, does not. + let mut d = d.clone(); + let mut clear = bar(Rect::new(0.0, 0.0, 10.0, 20.0), Color::rgb(1.0, 0.0, 0.0)); + if let Some(AppearanceItem::Fill(f)) = clear.appearance.items.first_mut() { + f.opacity = 0.5; + } + d.symbols.push(Symbol { dynamic: false, name: "Clear".into(), art: Arc::new(clear) }); + let clips = |n: &Node| { + let mut count = 0; + revolve_art_in(Some(&d), n).unwrap().walk(&mut |c| count += usize::from(matches!(c.kind, NodeKind::Group { clip: true, .. }))); + count + }; + let translucent = revolved(&CYLINDER, json!({"shade": true, "lights": lights, "graphics": [{"symbol": "Clear"}]})); + let (base, opaque, translucent) = (clips(&plain), clips(&mapped), clips(&translucent)); + assert!(translucent > base && opaque - base == 2 * (translucent - base), "{base} {opaque} {translucent}"); +} + +#[test] +fn graphics_past_the_point_limit_are_refused() { + let mut d = document(); + let dots: Vec<Arc<Node>> = (0..2000) + .map(|i| { + let c = Point::new(f64::from(i % 50) * 12.0, f64::from(i / 50) * 12.0); + Arc::new(Node::path( + NodeId(0), + shapes::ellipse(Rect::new(c.x, c.y, c.x + 10.0, c.y + 10.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + )) + }) + .collect(); + d.symbols.push(Symbol { dynamic: false, name: "Dots".into(), art: Arc::new(Node::group(NodeId(0), dots)) }); + let n = revolved(&CYLINDER, json!({})); + let p = |scale: f64| json!({"graphics": [{"symbol": "Dots", "scale": scale}]}); + assert!(validate_revolve_in(Some(&d), &n, &p(100.0)).is_ok()); + // At 100 times the size each dot is cut into hundreds of straight pieces. + let e = validate_revolve_in(Some(&d), &n, &p(10_000.0)).unwrap_err(); + assert!(e.contains("too complex"), "{e}"); +} + +#[test] +fn graphics_cut_into_too_many_parts_are_refused_on_the_object_and_on_a_fill() { + let mut d = document(); + // 4,000 thin bars across the side: few points each, but each is cut at every face it crosses. + let bars: Vec<Arc<Node>> = + (0..4000).map(|i| Arc::new(bar(Rect::new(0.0, f64::from(i) * 0.05, 300.0, f64::from(i) * 0.05 + 0.02), Color::BLACK))).collect(); + d.symbols.push(Symbol { dynamic: false, name: "Bars".into(), art: Arc::new(Node::group(NodeId(0), bars)) }); + let p = json!({"segments": 128, "graphics": [{"symbol": "Bars"}]}); + let n = revolved(&CYLINDER, json!({})); + let e = validate_revolve_in(Some(&d), &n, &p).unwrap_err(); + assert!(e.contains("too complex for this surface"), "{e}"); + assert!(validate_revolve_in(Some(&d), &n, &json!({"graphics": [{"symbol": "Red"}]})).is_ok()); + // The same on a Revolve on the object's fill. + let mut filled = n.clone(); + let fx = filled.appearance.effects.remove(0); + if let Some(AppearanceItem::Fill(f)) = filled.appearance.items.first_mut() { + f.effects.push(fx); + } + let e = crate::solids::validate_three_d_at_in(Some(&d), &filled, REVOLVE, &p, (Some(0), 0)).unwrap_err(); + assert!(e.contains("too complex for this surface"), "{e}"); +} + +#[test] +fn without_the_document_nothing_is_drawn_and_expand_keeps_the_graphics() { + let d = document(); + let n = revolved(&CYLINDER, json!({"graphics": [{"symbol": "Red"}]})); + assert!(parts(&revolve_art(&n).unwrap(), false).is_empty()); + let shown = parts(&revolve_art_in(Some(&d), &n).unwrap(), false); + let expanded = parts(&expand_revolve_art_in(Some(&d), &n).unwrap(), false); + assert!(!shown.is_empty()); + assert_eq!(shown, expanded); + // In a group the graphics go once, on the side of the member with the longest profile. + let mut member = n.clone(); + member.appearance.effects.clear(); + let mut short = member.clone(); + if let NodeKind::Path { path, .. } = &mut short.kind { + *path = PathData::from_bezpath(&{ + let mut b = BezPath::new(); + b.move_to((0.0, 80.0)); + b.line_to((30.0, 80.0)); + b.line_to((30.0, 120.0)); + b.line_to((0.0, 120.0)); + b + }); + } + let mut group = Node::group(NodeId(9), vec![Arc::new(short), Arc::new(member)]); + group.appearance.effects = n.appearance.effects.clone(); + assert_eq!(parts(&revolve_art_in(Some(&d), &group).unwrap(), false).len(), shown.len()); +} + +#[test] +fn revolve_takes_graphics_on_its_side_only() { + let front = json!({"graphics": [{"symbol": "Red"}]}); + let back = json!({"graphics": [{"symbol": "Red", "face": "back"}]}); + assert!(crate::solids::graphics::validate(REVOLVE, &front).is_ok()); + assert!(crate::solids::graphics::validate(REVOLVE, &back).unwrap_err().contains("side")); + assert!(crate::solids::graphics::validate(CLASSIC_REVOLVE, &front).is_err()); + let n = revolved(&CYLINDER, json!({})); + assert!(validate_revolve(&n, &back).is_err()); + // Changing the type keeps the front's graphics on Revolve's side and drops the back's. + let both = json!({"graphics": [{"symbol": "Red"}, {"symbol": "Blue", "face": "back"}]}); + let kept = three_d_params_as(crate::EXTRUDE, &both, REVOLVE); + assert_eq!(kept["graphics"].as_array().map(Vec::len), Some(1)); + assert_eq!(kept["graphics"][0]["symbol"], "Red"); + assert_eq!(three_d_params_as(REVOLVE, &front, crate::INFLATE).get("graphics"), None); +} + +#[test] +fn revolve_classic_draws_no_graphics_its_parameters_carry() { + let d = document(); + let mut n = revolved(&CYLINDER, json!({"graphics": [{"symbol": "Red"}]})); + assert!(!parts(&revolve_art_in(Some(&d), &n).unwrap(), false).is_empty()); + // A file can hold graphics on Revolve (Classic), which commands refuse: Revolve (Classic) + // draws its classic surface, without them. + if let Some(fx) = n.appearance.effects.first_mut() { + fx.id = CLASSIC_REVOLVE.into(); + } + assert!(parts(&revolve_art_in(Some(&d), &n).unwrap(), false).is_empty()); +} + +#[test] +fn a_group_with_no_member_to_carry_graphics_still_checks_their_art() { + let mut d = document(); + let dots: Vec<Arc<Node>> = (0..2000) + .map(|i| { + let c = Point::new(f64::from(i % 50) * 12.0, f64::from(i / 50) * 12.0); + Arc::new(Node::path( + NodeId(0), + shapes::ellipse(Rect::new(c.x, c.y, c.x + 10.0, c.y + 10.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + )) + }) + .collect(); + d.symbols.push(Symbol { dynamic: false, name: "Dots".into(), art: Arc::new(Node::group(NodeId(0), dots)) }); + let n = revolved(&CYLINDER, json!({})); + let mut member = n.clone(); + member.appearance.effects.clear(); + member.appearance.items.clear(); + let mut group = Node::group(NodeId(9), vec![Arc::new(member)]); + group.appearance.effects = n.appearance.effects.clone(); + // No member has a fill or stroke, so none carries the graphics, but art past the limits is + // refused as it is on a group whose member carries them. + let e = validate_in(Some(&d), &group, REVOLVE, &json!({"graphics": [{"symbol": "Dots", "scale": 10_000.0}]})).unwrap_err(); + assert!(e.contains("too complex"), "{e}"); + assert!(validate_in(Some(&d), &group, REVOLVE, &json!({"graphics": [{"symbol": "Red"}]})).is_ok()); +} + +#[test] +fn a_full_turn_draws_a_graphic_on_either_side_of_the_cut_at_the_back() { + let mut d = document(); + d.symbols.push(Symbol { dynamic: false, name: "Thin".into(), art: Arc::new(bar(Rect::new(0.0, 0.0, 2.0, 20.0), Color::rgb(1.0, 0.0, 0.0))) }); + // Half a turn around a radius of 50 is about 157 to each side of the middle: turned to face + // the viewer, a graphic just inside either end is drawn. + for x in [155.0, -155.0] { + let n = revolved(&CYLINDER, json!({"rotationY": 180.0, "graphics": [{"symbol": "Thin", "x": x}]})); + assert!(!parts(&revolve_art_in(Some(&d), &n).unwrap(), false).is_empty(), "x {x}"); + } +} + +/// A gray cylinder of radius 50 whose side is 200 edges along the profile, from y 0 to 200. +fn ribbed() -> Vec<(f64, f64)> { + let mut points = vec![(0.0, 0.0)]; + points.extend((0..=200).map(|k| (50.0, f64::from(k)))); + points.push((0.0, 200.0)); + points +} + +/// A symbol `name` of one red path whose contours are `contours`, each a polygon through its +/// points. +fn contours_symbol(name: &str, contours: &[Vec<Point>]) -> Symbol { + let mut b = BezPath::new(); + for contour in contours { + b.move_to(contour[0]); + contour[1..].iter().for_each(|p| b.line_to(*p)); + b.close_path(); + } + let art = Node::path(NodeId(0), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0)); + Symbol { dynamic: false, name: name.into(), art: Arc::new(art) } +} + +#[test] +fn contours_away_from_a_face_are_not_cut_at_it() { + // 2,000 small squares in two clusters on the back, at opposite corners of the side: the path's + // bounds reach across every face, but no square reaches a face that is drawn. + let squares: Vec<Vec<Point>> = (0..2000) + .map(|i| { + let (x, y) = if i < 1000 { (0.0, 0.0) } else { (290.0, 190.0) }; + let (x, y) = (x + f64::from(i % 10) * 0.1, y + f64::from(i % 1000 / 10) * 0.1); + vec![Point::new(x, y), Point::new(x + 0.05, y), Point::new(x + 0.05, y + 0.05), Point::new(x, y + 0.05)] + }) + .collect(); + let mut d = document(); + d.symbols.push(contours_symbol("Clusters", &squares)); + let n = revolved(&ribbed(), json!({})); + let p = json!({"graphics": [{"symbol": "Clusters"}]}); + assert_eq!(validate_revolve_in(Some(&d), &n, &p), Ok(())); +} + +#[test] +fn a_contour_that_reaches_every_face_and_draws_on_none_is_refused() { + // One contour of 10,000 points: a thin frame around the whole side, past its ends and on the + // back, so it is cut at every face and keeps nothing. + let edge = |from: Point, to: Point| (0..2500).map(move |k| from.lerp(to, f64::from(k) / 2500.0)); + let (outer, inner) = ([(0.0, 0.0), (400.0, 0.0), (400.0, 400.0), (0.0, 400.0)], [(1.0, 1.0), (1.0, 399.0), (399.0, 399.0), (399.0, 1.0)]); + let ring = |corners: [(f64, f64); 4]| (0..4).flat_map(move |k| edge(corners[k].into(), corners[(k + 1) % 4].into())).collect::<Vec<Point>>(); + let mut frame = ring(outer); + frame.extend(ring(inner)); + let mut d = document(); + d.symbols.push(contours_symbol("Frame", &[frame])); + let n = revolved(&ribbed(), json!({})); + let e = validate_revolve_in(Some(&d), &n, &json!({"graphics": [{"symbol": "Frame"}]})).unwrap_err(); + assert!(e.contains("too complex for this surface"), "{e}"); + assert!(parts(&revolve_art_in(Some(&d), &n).unwrap(), false).is_empty()); +} + +/// A red linear gradient of `stops` stops, each with `opacity`. +fn ramp(stops: usize, opacity: f32) -> Paint { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let stops = (0..stops) + .map(|i| { + let mut stop = GradientStop::new(i as f32 / stops as f32, Color::rgb(1.0, 0.0, 0.0)); + stop.opacity = opacity; + stop + }) + .collect(); + Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))) +} + +#[test] +fn the_copies_of_a_graphics_paint_have_a_budget_of_their_own() { + let mut d = document(); + for (name, opacity) in [("Ramp", 1.0), ("Clear ramp", 0.5)] { + let art = + Node::path(NodeId(0), shapes::rectangle(Rect::new(0.0, 0.0, 300.0, 10.0)), Appearance::basic(ramp(4096, opacity), Paint::None, 0.0)); + d.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(art) }); + } + let p = json!({"graphics": [{"symbol": "Ramp"}]}); + let n = revolved(&CYLINDER, json!({})); + let NodeKind::Path { path, .. } = &n.kind else { panic!("a path") }; + let faces = vectorcraft_three_d::revolve(path, path.bounds().unwrap(), options_of(REVOLVE, &p)).unwrap(); + let parts_of = |symbol: &str, copies: &mut usize| { + let graphics = crate::solids::mapped_graphics(&json!({"graphics": [{"symbol": symbol}]})); + crate::solids::graphics::surface_parts(Some(&d), NodeId(0), &graphics, &faces, &|_, c| Paint::solid(c), copies).map(|p| p.concat().len()) + }; + // Each opaque part copies the paint into its fill and its seam stroke; a part with + // transparent stops takes no seam stroke and copies it once. + let (opaque, clear) = (paint_bytes(&ramp(4096, 1.0)), paint_bytes(&ramp(4096, 0.5))); + let mut used = 0; + let count = parts_of("Ramp", &mut used).unwrap(); + assert!(count >= 2, "the graphic draws on several faces"); + assert_eq!(used, 2 * count * opaque); + let mut used = 0; + assert_eq!(parts_of("Clear ramp", &mut used), Some(count)); + assert_eq!(used, count * clear); + // Past the budget the graphic is refused. + assert_eq!(parts_of("Ramp", &mut (MAX_PAINT_COPIES - opaque)), None); + // A surface whose own gradient takes nearly the whole budget for surfaces still takes the + // graphic, on the object, on one fill of two and on a member of a group. + let stop = paint_bytes(&ramp(2, 1.0)) - paint_bytes(&ramp(1, 1.0)); + let base = paint_bytes(&ramp(1, 1.0)) - stop; + let gray = Paint::solid(Color::rgb(0.5, 0.5, 0.5)); + let full = ramp(((MAX_PAINT_COPIES - paint_copies(faces.len(), &gray)) / (faces.len() * 4) - base) / stop, 1.0); + assert!(MAX_PAINT_COPIES - paint_copies(faces.len(), &gray) - paint_copies(faces.len(), &full) < opaque); + let mut object = n.clone(); + if let Some(AppearanceItem::Fill(f)) = object.appearance.items.first_mut() { + f.paint = ramp(((MAX_PAINT_COPIES - opaque) / (faces.len() * 4) - base) / stop, 1.0); + } + assert_eq!(validate_revolve_in(Some(&d), &object, &p), Ok(())); + let fill = |paint: Paint, params: Value| { + let mut fill = FillLayer::new(paint); + fill.effects.push(crate::new_effect(REVOLVE, ¶ms).unwrap()); + AppearanceItem::Fill(fill) + }; + let mut two = n.clone(); + two.appearance = Appearance { items: vec![fill(gray.clone(), p.clone()), fill(full.clone(), json!({}))], ..Default::default() }.into(); + assert_eq!(crate::solids::validate_three_d_at_in(Some(&d), &two, REVOLVE, &json!({}), (Some(1), 0)), Ok(())); + let mut member = n.clone(); + member.appearance.effects.clear(); + let mut second = member.clone(); + if let Some(AppearanceItem::Fill(f)) = second.appearance.items.first_mut() { + f.paint = full; + } + let mut group = Node::group(NodeId(9), vec![Arc::new(member), Arc::new(second)]); + group.appearance.effects = n.appearance.effects.clone(); + assert_eq!(validate_in(Some(&d), &group, REVOLVE, &p), Ok(())); +} + +/// Whether each part of `art` filled with a gradient has a stroke over its seams. +fn gradient_seams(art: &Node) -> Vec<bool> { + let mut out = vec![]; + art.walk(&mut |n| { + let items = &n.appearance.items; + let red = |p: &Paint| matches!(p, Paint::Gradient(_)) && shade_of(p, false).is_some(); + if n.path_data().is_some() && matches!(items.first(), Some(AppearanceItem::Fill(f)) if red(&f.paint)) { + out.push(items.iter().any(|i| matches!(i, AppearanceItem::Stroke(_)))); + } + }); + out +} + +#[test] +fn a_gradient_with_transparent_stops_takes_no_stroke_over_its_seams() { + let mut d = document(); + for (name, opacity) in [("Opaque", 1.0), ("Clear", 0.5)] { + let art = Node::path(NodeId(0), shapes::rectangle(Rect::new(0.0, 0.0, 60.0, 10.0)), Appearance::basic(ramp(2, opacity), Paint::None, 0.0)); + d.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(art) }); + } + let seams = |symbol: &str| gradient_seams(&revolve_art_in(Some(&d), &revolved(&CYLINDER, json!({"graphics": [{"symbol": symbol}]}))).unwrap()); + let opaque = seams("Opaque"); + assert!(!opaque.is_empty() && opaque.iter().all(|s| *s), "{opaque:?}"); + let clear = seams("Clear"); + assert!(!clear.is_empty() && clear.iter().all(|s| !*s), "{clear:?}"); +} diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index be6c68ba74..9b364c3d3a 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -1,12 +1,13 @@ -//! Extrude & Bevel, Inflate, Rotate and Extrude & Bevel (Classic) as live, shaded vector art, +//! Extrude & Bevel, Inflate, Rotate, Extrude & Bevel (Classic) and Rotate (Classic) as live, shaded vector art, //! shared by the canvas and every exporter. Like Revolve, the source path stays editable and the effect draws its 3D faces. use std::sync::Arc; use serde_json::Value; use vectorcraft_doc::color::{BlendMode, Paint}; use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, Node, NodeId, NodeKind, OpacityMask, StrokeLayer}; -use vectorcraft_geom::{FillRule, PathData, Rect}; -use vectorcraft_three_d::{Bevel, BevelShape, Extrude, Facet, Inflate, Mesh, View}; +use vectorcraft_geom::{BezPath, FillRule, PathData, Point, Rect, Vec2}; +use vectorcraft_pathops::BoolOp; +use vectorcraft_three_d::{Bevel, BevelShape, DepthPlane, Extrude, Facet, Inflate, MAX_OBJECT_FACES, Mesh, PlanarFace, View}; #[cfg(test)] use vectorcraft_doc::color::Color; @@ -14,21 +15,47 @@ use vectorcraft_doc::color::Color; use crate::util::{flag, num, text}; use crate::{GeomContext, apply_geometry_with, is_geometry}; -mod classic; -pub use classic::{CLASSIC_EXTRUDE, SHADING_COLORS, classic_extrude_options, classic_shading}; +pub(crate) mod classic; +pub use classic::{CLASSIC_EXTRUDE, CLASSIC_ROTATE, ROTATE_SURFACES, SHADING_COLORS, classic_extrude_options, classic_shading}; mod source; pub(crate) use source::{resolve, resolve_for}; +pub(crate) mod graphics; +pub use graphics::{ + GRAPHICS, GraphicFrame, MAX_GRAPHICS, MappedGraphic, graphic_symbols, mapped_graphics, missing_symbol, names_graphic_symbol, + rename_graphic_symbol, rename_graphic_symbol_in, takes_graphics, with_graphic, +}; +pub use graphics::{ + MAX_OFFSET as GRAPHIC_MAX_OFFSET, NOT_TAKEN as GRAPHICS_NOT_TAKEN, SCALE_RANGE as GRAPHIC_SCALE_RANGE, appearance_graphic_symbols, + rename_appearance_graphic_symbol, +}; + +pub(crate) mod shadow; + +pub(crate) mod wireframe; +pub use wireframe::three_d_wireframe_in; + pub const EXTRUDE: &str = "threeD.extrude"; pub const INFLATE: &str = "threeD.inflate"; pub const ROTATE: &str = "threeD.rotate"; /// The 3D effects this module draws (Revolve has its own). -pub const SOLIDS: [&str; 4] = [EXTRUDE, INFLATE, ROTATE, CLASSIC_EXTRUDE]; +pub const SOLIDS: [&str; 5] = [EXTRUDE, INFLATE, ROTATE, CLASSIC_EXTRUDE, CLASSIC_ROTATE]; -/// Is `id` one of the 3D and Materials effects (Revolve included)? +/// Is `id` one of the 3D and Materials effects (Revolve and Revolve (Classic) included)? pub fn is_three_d(id: &str) -> bool { - id == crate::REVOLVE || SOLIDS.contains(&id) + crate::revolve::is_revolve(id) || SOLIDS.contains(&id) +} + +/// Is `id` one of the 3D (Classic) effects: Extrude & Bevel (Classic), Revolve (Classic) or Rotate +/// (Classic)? +pub fn is_classic_three_d(id: &str) -> bool { + id == CLASSIC_EXTRUDE || id == crate::CLASSIC_REVOLVE || id == CLASSIC_ROTATE +} + +/// Does 3D effect `id` turn the art as a flat plane: Rotate or Rotate (Classic)? +fn is_plane(id: &str) -> bool { + id == ROTATE || id == CLASSIC_ROTATE } /// The 3D and Materials panel's object types and the effect that draws each: (type, effect id). @@ -54,6 +81,13 @@ pub fn three_d_params_as(from: &str, params: &Value, to: &str) -> Value { } } } + // A plane has only a front, and Revolve's graphics go on its side, named the front, so graphics + // on the back cap are dropped. + if (to == ROTATE || to == crate::REVOLVE) + && let Some(Value::Array(list)) = out.get_mut(GRAPHICS) + { + list.retain(|g| g.get("face").and_then(Value::as_str) != Some(PlanarFace::Back.id())); + } Value::Object(out) } @@ -191,7 +225,12 @@ fn validate_solid_params(id: &str, p: &Value) -> Result<(), String> { if id == CLASSIC_EXTRUDE { classic::validate(p)?; } + if id == CLASSIC_ROTATE { + classic::validate_rotate(p)?; + } crate::lighting::validate(p)?; + shadow::validate(p)?; + graphics::validate(id, p)?; if let Some(v) = p.get("bevel") && !v.as_str().is_some_and(|s| s == "none" || BevelShape::parse(s).is_some()) { @@ -214,17 +253,62 @@ pub fn validate_solid(n: &Node, id: &str, p: &Value) -> Result<(), String> { /// [`validate_solid`] with the symbols of `doc`: a symbol instance, a blend and a clipping group /// build from the art they show ([`resolve`]). pub fn validate_solid_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value) -> Result<(), String> { + validate_solid_for(doc, n, id, p, (None, None)) +} + +/// [`validate_solid_in`] for the effect at `(item, index)`: index `index` of the effects of the +/// object (`item` `None`) or of its appearance item `item`, whose shadow is cast by that item's +/// solid alone. The index is the effects' length for a new effect. The solids are checked as +/// [`solid_art_in`] draws them: from the shapes after the geometry effects before the 3D effect. +/// On the object (or group) with `index` `None`, that effect is its first visible Extrude & Bevel, +/// Inflate or Rotate, as drawn, or a new one after its other effects when it has none. +fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at: (Option<usize>, Option<usize>)) -> Result<(), String> { validate_solid_params(id, p)?; + if let Some(doc) = doc { + graphics::validate_symbols(doc, p)?; + } let label = label_of(id); - let n = &*source::resolve_for(doc, n, label, id == ROTATE)?; + let n = &*source::resolve_for(doc, n, label, is_plane(id))?; + let effects = &n.appearance.effects; + let index = match at { + (None, Some(index)) => index, + _ => solid(effects).map_or(effects.len(), |(index, _)| index), + }; + let before = effects.get(..index).unwrap_or(effects); if is_container(n) { - let shapes = members(n, label)?; + let mut shapes = members(n, label)?; + reshape_members(n, before, &mut shapes); let b = union_bounds(&shapes).ok_or_else(|| format!("{label} requires a group holding a shape with at least two anchors"))?; - return shapes.iter().try_for_each(|s| facets(id, &s.path, s.rule, b, p).map(|_| ())); + shapes.iter().try_for_each(|s| facets(id, &s.path, s.rule, b, p).map(|_| ()))?; + check_solids(id, p, &shapes)?; + return cast_shadow(id, p, &shapes).map(|_| ()); } let (path, rule) = object_profile(n, label)?; - let b = path.bounds().ok_or_else(|| format!("{label} requires a shape with at least two anchors"))?; - facets(id, &path, rule, b, p).map(|_| ()) + let anchors = || format!("{label} requires a shape with at least two anchors"); + path.bounds().ok_or_else(anchors)?; + let ctx = GeomContext::of(n); + // With its shadow on, the shadow of the object's solids (or of the item's) must fit too. + let (path, items) = match at.0.and_then(|i| Some((n.appearance.items.get(i)?, at.1.unwrap_or(usize::MAX)))) { + Some((item, index)) => { + let path = geometry(&path, effects, &ctx); + (geometry(&path, item.effects().get(..index).unwrap_or(item.effects()), &ctx.item(item)), vec![item.clone()]) + } + None => (geometry(&path, before, &ctx), solid_paints(n)), + }; + let b = path.bounds().ok_or_else(anchors)?; + facets(id, &path, rule, b, p)?; + let shapes = [Profile { path, rule, items, opacity: 1.0, scopes: vec![] }]; + check_solids(id, p, &shapes)?; + cast_shadow(id, p, &shapes).map(|_| ()) +} + +/// Do the solids 3D effect `id` with parameters `p` builds from the fills and strokes of `shapes` +/// fit, each on its own and all of them together ([`built_solids`])? Rotate's planes are not +/// counted. +fn check_solids(id: &str, p: &Value, shapes: &[Profile]) -> Result<(), String> { + let Some(b) = union_bounds(shapes).filter(|_| !is_plane(id)) else { return Ok(()) }; + let (parts, bounds) = solid_parts(shapes, b); + built_solids(id, p, &parts, bounds, MAX_OBJECT_FACES).try_for_each(|r| r.map(|_| ())) } /// [`profile`], or the error a command reports for object `n`: type with no outlines to build from @@ -297,7 +381,7 @@ fn masked(id: NodeId, surfaces: Vec<(&[Scope], Arc<Node>)>) -> Vec<Arc<Node>> { } /// Does any of `shapes` sit in a scope with an opacity mask or a blending mode other than Normal? -fn has_masks(shapes: &[Profile]) -> bool { +pub(crate) fn has_masks(shapes: &[Profile]) -> bool { shapes.iter().any(|s| s.scopes.iter().any(composites)) } @@ -400,27 +484,32 @@ pub fn validate_three_d(n: &Node, id: &str, p: &Value) -> Result<(), String> { /// [`validate_three_d`] with the symbols of `doc` ([`validate_solid_in`]). pub fn validate_three_d_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value) -> Result<(), String> { - if id == crate::REVOLVE { crate::revolve::validate_revolve_in(doc, n, p) } else { validate_solid_in(doc, n, id, p) } + graphics::validate(id, p)?; + if crate::revolve::is_revolve(id) { crate::revolve::validate_in(doc, n, id, p) } else { validate_solid_in(doc, n, id, p) } } -/// [`validate_three_d`] for an effect at `(item, index)`, index `index` of the effects of -/// appearance item `item` of `n` (the effects' length for a new effect), or on the object itself -/// when `at` is `None`. A Revolve on a fill or stroke is checked in that item's paint, after the -/// item's geometry effects before it, together with the object's other items that carry a Revolve. -/// A group's or layer's fills and strokes take no 3D effect: only the group's own effect draws. -pub fn validate_three_d_at(n: &Node, id: &str, p: &Value, at: Option<(usize, usize)>) -> Result<(), String> { +/// [`validate_three_d`] for an effect at `(item, index)`: index `index` of the effects of +/// appearance item `item` of `n`, or of the object itself when `item` is `None` (the effects' +/// length for a new effect). An Extrude & Bevel, Inflate or Rotate is checked on the shapes after +/// the geometry effects before that index. A Revolve on a fill or stroke is checked in that item's +/// paint, after the item's geometry effects before it, together with the object's other items that +/// carry a Revolve. A group's or layer's fills and strokes take no 3D effect: only the group's own +/// effect draws. +pub fn validate_three_d_at(n: &Node, id: &str, p: &Value, at: (Option<usize>, usize)) -> Result<(), String> { validate_three_d_at_in(None, n, id, p, at) } /// [`validate_three_d_at`] with the symbols of `doc` ([`validate_solid_in`]). A symbol instance, a /// blend and a clipping group take a 3D effect as groups do: on the object itself. -pub fn validate_three_d_at_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at: Option<(usize, usize)>) -> Result<(), String> { +pub fn validate_three_d_at_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at: (Option<usize>, usize)) -> Result<(), String> { + graphics::validate(id, p)?; match at { - Some(_) if is_container(n) || source::resolves(n) => { + (Some(_), _) if is_container(n) || source::resolves(n) => { Err("A 3D effect on a group or layer goes on the group itself, not on its fill or stroke".into()) } - Some((item, index)) if id == crate::REVOLVE => crate::revolve::validate_item_revolve(n, p, item, index), - _ => validate_three_d_in(doc, n, id, p), + (Some(item), index) if crate::revolve::is_revolve(id) => crate::revolve::validate_item_of(doc, n, id, p, item, index), + (None, _) if crate::revolve::is_revolve(id) => crate::revolve::validate_in(doc, n, id, p), + (item, index) => validate_solid_for(doc, n, id, p, (item, Some(index))), } } @@ -428,7 +517,8 @@ pub fn validate_three_d_at_in(doc: Option<&Document>, n: &Node, id: &str, p: &Va /// build the art, for an edit that hides the effect: hidden, it draws nothing, so its object does /// not need to fit. pub fn validate_three_d_params(id: &str, p: &Value) -> Result<(), String> { - if id == crate::REVOLVE { crate::revolve::validate_revolve_params(p) } else { validate_solid_params(id, p) } + graphics::validate(id, p)?; + if crate::revolve::is_revolve(id) { crate::revolve::validate_params_of(id, p) } else { validate_solid_params(id, p) } } /// One surface: each facet a path shaded from `paint`, as a group with the paint's opacity and @@ -516,8 +606,8 @@ fn region(path: &PathData, rule: FillRule, item: &AppearanceItem) -> (PathData, } /// One part of [`solid_parts`]: a fill or stroke, its shape's opacity, the region it paints and its -/// fill rule, and its shape's scopes. -type Part<'a> = (&'a AppearanceItem, f32, PathData, FillRule, &'a [Scope]); +/// fill rule, its shape's scopes and the index of its shape. +type Part<'a> = (&'a AppearanceItem, f32, PathData, FillRule, &'a [Scope], usize); /// 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, the region it paints and its @@ -526,18 +616,626 @@ type Part<'a> = (&'a AppearanceItem, f32, PathData, FillRule, &'a [Scope]); fn solid_parts(shapes: &[Profile], fallback: Rect) -> (Vec<Part<'_>>, Rect) { let parts: Vec<Part> = shapes .iter() - .flat_map(|s| { + .enumerate() + .flat_map(|(member, 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)| { + s.items.iter().enumerate().filter(move |(k, i)| Some(*k) == top_fill || matches!(i, AppearanceItem::Stroke(_))).map(move |(_, i)| { let (area, rule) = region(&s.path, s.rule, i); - (i, s.opacity, area, rule, s.scopes.as_slice()) + (i, s.opacity, area, rule, s.scopes.as_slice(), member) }) }) .collect(); - let bounds = parts.iter().filter_map(|(_, _, area, _, _)| area.bounds()).reduce(|a, c| a.union(c)).unwrap_or(fallback); + let bounds = parts.iter().filter_map(|(_, _, area, _, _, _)| area.bounds()).reduce(|a, c| a.union(c)).unwrap_or(fallback); (parts, bounds) } +#[cfg(test)] +thread_local! { + /// How many solids [`built_solids`] has built on this thread, for the tests. + static SOLIDS_BUILT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; +} + +/// The solids Extrude & Bevel (Classic included) or Inflate `id` with parameters `p` builds from +/// `parts` ([`solid_parts`]) about `bounds`, one result for each part in order, each built only as +/// the iterator reaches it. A stroke's solid past its own limits is `None` (left out of the art, its +/// faces not counted); a fill's is an error. The faces of the solids kept count together: once they +/// pass `limit` ([`MAX_OBJECT_FACES`] for the art) the result is an error, and +/// no later part is built. An error ends the iterator. +fn built_solids<'a>( + id: &'a str, + p: &'a Value, + parts: &'a [Part<'a>], + bounds: Rect, + limit: usize, +) -> impl Iterator<Item = Result<Option<Vec<Facet>>, String>> + 'a { + // Inflate's eye is placed for every puff together, as far away as the highest needs. + let mut inflated = (id == INFLATE).then(|| { + let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule, _, _)| (area, *rule)).collect(); + vectorcraft_three_d::inflate_each(&shapes, bounds, inflate_options(p), view_options(p)) + }); + let mut kept = 0usize; + let mut ended = false; + parts.iter().map_while(move |(item, _, area, rule, _, _)| { + if ended { + return None; + } + #[cfg(test)] + SOLIDS_BUILT.with(|n| n.set(n.get() + 1)); + let built = match inflated.as_mut() { + Some(each) => each.next().unwrap_or_else(|| Ok(vec![])), + None => facets(id, area, *rule, bounds, p), + }; + let result = match built { + Ok(f) => { + kept = kept.saturating_add(f.len()); + if kept > limit { Err(vectorcraft_three_d::TOO_COMPLEX_SOLID.to_string()) } else { Ok(Some(f)) } + } + Err(_) if matches!(item, AppearanceItem::Stroke(_)) => Ok(None), + Err(e) => Err(e), + }; + ended = result.is_err(); + Some(result) + }) +} + +/// What a face of one of the solids [`art_for`] draws in one order was built from: the facet's +/// depth, whether it is a side face and whether it is turned away from the viewer, the bounds of +/// its polygon, the index of its shape, and whether its solid is that shape's fill or one of its +/// strokes that covers the fill's whole edge. A face that [`convex_face`] takes also keeps its +/// polygon and plane, for [`local_order`]; every other face has an empty `outline` and no `plane`. +struct Placed { + depth: f64, + side: bool, + away: bool, + bounds: Rect, + member: usize, + paints: Paints, + outline: Vec<Point>, + plane: Option<DepthPlane>, +} + +/// The part of its shape a face's solid is built from ([`Placed`]). +#[derive(Clone, Copy, PartialEq, Eq)] +enum Paints { + Fill, + /// A stroke whose solid holds the fill's whole edge and hides it: one with a width, without + /// dashes, a width profile or a brush, painted with a solid color or a gradient without + /// transparent stops, on a shape whose subpaths are all closed, extruded (an inflated fill can + /// rise in front of its stroke). + Stroke, + Other, +} + +/// Can a stroke's solid on a shape with outline `path` hold the fill's edge ([`Paints::Stroke`]) +/// under the effect `effect`? Only when the subpaths are all closed and the effect extrudes: an +/// inflated fill can rise in front of its stroke. +fn holds_edge(effect: &str, path: &PathData) -> bool { + effect != INFLATE && path.subpaths.iter().all(|p| p.closed) +} + +impl Paints { + /// What `item` of a shape is, its stroke's solid able to hold the fill's edge when `closed` + /// ([`holds_edge`]). + fn of(item: &AppearanceItem, closed: bool) -> Self { + match item { + AppearanceItem::Fill(_) => Paints::Fill, + AppearanceItem::Stroke(s) + if closed + && s.width > 0.0 + && s.width.is_finite() + && s.dash.is_none() + && s.profile.is_none() + && s.brush.is_none() + && match &s.paint { + Paint::Solid { .. } => true, + Paint::Gradient(_) => crate::lighting::opaque_paint(&s.paint).1.is_none(), + _ => false, + } => + { + Paints::Stroke + } + AppearanceItem::Stroke(_) => Paints::Other, + } + } +} + +impl Placed { + /// The face of `f`, of shape `member`'s part `paints`. + fn of(f: &Facet, member: usize, paints: Paints) -> Self { + let mut points = f.contours.iter().flatten(); + let bounds = points.next().map_or(Rect::ZERO, |p| points.fold(Rect::from_points(*p, *p), |r, q| r.union_pt(*q))); + let local = convex_face(f).is_some(); + let outline = f.contours.first().filter(|_| local).cloned().unwrap_or_default(); + let plane = f.plane.filter(|_| local); + Placed { depth: f.depth, side: f.side, away: f.away, bounds, member, paints, outline, plane } + } +} + +/// The most pairs of faces [`local_order`] compares, and the most [`cut_stroke_faces`] compares; +/// the pairs they have not reached by then keep the order of their depths. +const MAX_LOCAL_CHECKS: usize = 4_000_000; + +/// The polygon of `f` and the sign of its turns, when `f` is a face turned toward the viewer other +/// than a planar end, with a plane and one convex contour: a face [`local_order`] and +/// [`cut_stroke_faces`] work on. +fn convex_face(f: &Facet) -> Option<(&[Point], f64)> { + if f.away || f.end.is_some() || f.plane.is_none() || f.contours.len() != 1 { + return None; + } + let c = f.contours.first()?; + Some((c, convex(c)?)) +} + +/// The bounds of polygon `p` (`Rect::ZERO` when it has no points). +fn polygon_bounds(p: &[Point]) -> Rect { + let mut points = p.iter(); + points.next().map_or(Rect::ZERO, |q| points.fold(Rect::from_points(*q, *q), |r, q| r.union_pt(*q))) +} + +/// Do rectangles `a` and `b` overlap (more than along an edge)? +fn rects_overlap(a: Rect, b: Rect) -> bool { + a.x0 < b.x1 && b.x0 < a.x1 && a.y0 < b.y1 && b.y0 < a.y1 +} + +/// How many faces [`cut_stroke_faces`] may add to solids painted by `items` that hold `faces` faces +/// and whose paint copies take `paint_bytes` so far: as many as keep the faces within +/// [`MAX_OBJECT_FACES`] and the copies within the allowance, each added face counted as six copies +/// of the costliest stroke's paint. +fn cut_room<'a>(items: impl Iterator<Item = &'a AppearanceItem>, faces: usize, paint_bytes: usize) -> usize { + let per_face = items + .filter(|item| matches!(item, AppearanceItem::Stroke(_))) + .map(|item| { + let mut copies = 0usize; + crate::revolve::paint_copies_add(&mut copies, 6, paint_ref(item)); + copies + }) + .max() + .unwrap_or(0) + .max(1); + let affordable = crate::revolve::MAX_PAINT_COPIES.saturating_sub(paint_bytes) / per_face; + MAX_OBJECT_FACES.saturating_sub(faces).min(affordable) +} + +/// In `solids`, each solid's part ([`Paints`]), its shape's index and its faces, cut each face of a +/// stroke that does not cover the fill's edge ([`Paints::Other`]) that passes through the plane of a +/// face of the same shape's fill, or of a face of another of the shape's strokes, where the two +/// overlap on the drawing ([`cut_through`]). Of two such strokes, the later one's faces are cut +/// against the earlier one's; a covering stroke's faces ([`Paints::Stroke`]) are never cut, and an +/// other stroke's faces are cut against them. At most `room` pieces are added, the object's solids +/// together. +fn cut_stroke_faces(solids: &mut [(Paints, usize, &mut Vec<Facet>)], mut room: usize) { + let mut checks = 0usize; + for k in 0..solids.len() { + let Some((Paints::Other, shape)) = solids.get(k).map(|(p, s, _)| (*p, *s)) else { continue }; + let walls: Vec<usize> = (0..solids.len()) + .filter(|&j| { + solids.get(j).is_some_and(|(p, s, _)| { + *s == shape + && match p { + Paints::Fill | Paints::Stroke => true, + Paints::Other => j < k, + } + }) + }) + .collect(); + for j in walls { + let (wall, stroke) = if j < k { + let (before, from) = solids.split_at_mut(k); + (&**before[j].2, &mut *from[0].2) + } else { + let (before, from) = solids.split_at_mut(j); + (&**from[0].2, &mut *before[k].2) + }; + cut_through(wall, stroke, &mut room, &mut checks); + } + } +} + +/// Cut each face of `stroke` that passes through the plane of a face of `solid` (the fill's or +/// another stroke's) where their polygons overlap on the drawing, along the line where their depths +/// meet, so that each piece is wholly in front of or behind that face there ([`local_order`] can +/// then order them). A dash's end, which crosses the edge of the fill it is drawn on, is cut into its +/// part outside the fill, in front of the fill's wall, and its part inside, behind it. A piece keeps +/// the part of the face's curved outline on its side of the cut. The first piece of a face takes its +/// place, the others go at the end. Each cut adds a face out of `room`, and each pair compared counts +/// in `checks` ([`MAX_LOCAL_CHECKS`]); cutting stops when either runs out. +fn cut_through(solid: &[Facet], stroke: &mut Vec<Facet>, room: &mut usize, checks: &mut usize) { + // The faces from left to right: a face is compared with those that start left of its end. + let mut walls: Vec<(&Facet, &[Point], f64, Rect)> = + solid.iter().filter_map(|f| convex_face(f).map(|(c, turn)| (f, c, turn, polygon_bounds(c)))).collect(); + if walls.is_empty() { + return; + } + walls.sort_by(|a, b| a.3.x0.total_cmp(&b.3.x0)); + let mut k = 0; + while k < stroke.len() { + let mut extent = stroke.get(k).and_then(convex_face).map(|(c, _)| polygon_bounds(c)); + for &(wall, outline, turn, bounds) in &walls { + let Some(at) = extent.filter(|e| bounds.x0 < e.x1) else { break }; + if *checks >= MAX_LOCAL_CHECKS || *room == 0 { + return; + } + *checks += 1; + if !rects_overlap(at, bounds) { + continue; + } + let Some(s) = stroke.get(k) else { break }; + let Some((c, _)) = convex_face(s) else { break }; + if let Some((near, far)) = cut(s, c, wall, outline, turn) { + *room -= 1; + extent = convex_face(&near).map(|(c, _)| polygon_bounds(c)); + stroke[k] = near; + stroke.push(far); + } + } + k += 1; + } +} + +/// Face `s` (polygon `c`) cut where its depth meets that of face `wall` (convex polygon `outline`, +/// turning with sign `turn`): its piece nearer the viewer than the wall's plane and its piece +/// farther. `None` when the two do not overlap on the drawing or `s` is on one side of the wall's +/// plane wherever they do. +fn cut(s: &Facet, c: &[Point], wall: &Facet, outline: &[Point], turn: f64) -> Option<(Facet, Facet)> { + let ahead = |p: Point| Some(s.depth_at(p)? - wall.depth_at(p)?); + let overlap = clip_convex(c, outline, turn); + centroid(&overlap)?; + let tolerance = 1e-6; + let (mut nearer, mut farther) = (false, false); + for p in &overlap { + let d = ahead(*p)?; + nearer |= d > tolerance; + farther |= d < -tolerance; + } + if !(nearer && farther) { + return None; + } + let (a, b) = (s.plane?, wall.plane?); + let values: Vec<f64> = match (a.eye, b.eye) { + (Some(e), Some(f)) if e == f && a.center == b.center => { + // With perspective the depths themselves are not linear on the drawing, but where they + // meet is a line: (dA - aA e)(nzB - aB) = (dB - aB e)(nzA - aA), with aX = (nX · p) / e, + // whose difference is linear. Its sign is that of the depths' difference over the + // product of the two denominators, taken at the middle of the face. + let at = |p: Point| { + let (x, y) = (p.x - a.center.x, p.y - a.center.y); + let (aa, ab) = ((a.normal[0] * x + a.normal[1] * y) / e, (b.normal[0] * x + b.normal[1] * y) / e); + let (da, db) = (a.normal[2] - aa, b.normal[2] - ab); + ((a.offset - aa * e) * db - (b.offset - ab * e) * da, da * db) + }; + let sign = at(centroid(c)?).1.signum(); + c.iter().map(|p| at(*p).0 * sign).collect() + } + _ => c.iter().map(|p| ahead(*p)).collect::<Option<_>>()?, + }; + let piece = |sign: f64| { + let points = half(c, &values, sign); + let mid = centroid(&points)?; + let mut f = s.clone(); + f.depth = s.depth_at(mid).unwrap_or(s.depth); + f.contours = vec![points]; + f.outline = s.outline.as_ref().and_then(|o| clip_to_side(o, c, &values, sign)); + Some(f) + }; + Some((piece(1.0)?, piece(-1.0)?)) +} + +/// Curved outline `outline` of a face with polygon `c`, cut along the line where `values` (one per +/// point of `c`, varying linearly along each edge) is 0, keeping the side where `sign` times them is +/// at least 0. `None` when the line does not cross `c` at two points or nothing is left. +fn clip_to_side(outline: &PathData, c: &[Point], values: &[f64], sign: f64) -> Option<PathData> { + let mut crossings = vec![]; + for (j, (&a, &va)) in c.iter().zip(values).enumerate() { + let k = (j + 1) % c.len(); + let (Some(&b), Some(&vb)) = (c.get(k), values.get(k)) else { continue }; + if (va >= 0.0) != (vb >= 0.0) { + crossings.push(a.lerp(b, va / (va - vb))); + } + } + let &[q0, q1] = crossings.as_slice() else { return None }; + let along = q1 - q0; + let length = along.hypot(); + if length.is_nan() || length <= 1e-9 { + return None; + } + let along = along / length; + let (inside, _) = c.iter().zip(values).find(|(_, v)| **v * sign > 0.0)?; + let mut across = Vec2::new(-along.y, along.x); + if (*inside - q0).dot(across) < 0.0 { + across = -across; + } + let bounds = outline.bounds()?.union(polygon_bounds(c)); + let reach = 2.0 * (bounds.width() + bounds.height() + (q0 - bounds.center()).hypot()) + 1.0; + let mut side = BezPath::new(); + side.move_to(q0 - along * reach); + side.line_to(q0 + along * reach); + side.line_to(q0 + along * reach + across * reach); + side.line_to(q0 - along * reach + across * reach); + side.close_path(); + let kept = vectorcraft_pathops::boolean(outline, FillRule::NonZero, &PathData::from_bezpath(&side), FillRule::NonZero, BoolOp::Intersect); + kept.bounds().is_some().then_some(kept) +} + +/// The part of polygon `p` where `sign` times `values` (one per point, varying linearly along each +/// edge) is at least 0. +fn half(p: &[Point], values: &[f64], sign: f64) -> Vec<Point> { + let mut out = vec![]; + for (j, (&a, &va)) in p.iter().zip(values).enumerate() { + let k = (j + 1) % p.len(); + let (Some(&b), Some(&vb)) = (p.get(k), values.get(k)) else { continue }; + let (sa, sb) = (va * sign, vb * sign); + if sa >= 0.0 { + out.push(a); + } + if (sa >= 0.0) != (sb >= 0.0) { + out.push(a.lerp(b, sa / (sa - sb))); + } + } + out +} + +/// `order` (back to front), when it draws a face of one of a shape's strokes and an overlapping face +/// of the same shape's fill or strokes the wrong way round for their depths where they overlap on +/// the drawing, with every pair of overlapping faces that keep a polygon and a plane +/// ([`convex_face`]: turned toward the viewer, not a planar end), of any shape, put in the order of +/// their depths where they overlap: the face nearer the viewer there goes after the other. A fill +/// wall and a face of the same shape's covering stroke ([`Paints::Stroke`]) keep their order. Each +/// face otherwise keeps its place in `order`, so a fill wall in the gap between two dashes stays +/// where its depth puts it. A cycle of such pairs is broken at the face that comes first in `order`. +/// A face drawn last (a planar end turned toward the viewer, at depth `f64::MAX`) keeps its place: +/// no face moves across it. Otherwise `order` as it is. +fn local_order(faces: &[Placed], order: Vec<usize>) -> Vec<usize> { + use std::cmp::Reverse; + // The faces of each shape that take part, from left to right for a sweep along x. + let mut shapes: Vec<Vec<usize>> = vec![]; + for (k, f) in faces.iter().enumerate() { + if f.outline.len() < 3 || f.plane.is_none() { + continue; + } + if shapes.len() <= f.member { + shapes.resize_with(f.member + 1, Vec::new); + } + shapes[f.member].push(k); + } + if !shapes.iter().any(|list| list.iter().any(|&k| faces[k].paints != Paints::Fill)) { + return order; + } + for list in &mut shapes { + list.sort_by(|&a, &b| faces[a].bounds.x0.total_cmp(&faces[b].bounds.x0)); + } + // A fill wall and a face of the same shape's covering stroke keep the order [`draw_order`] gave + // them: the stroke's solid holds the wall, which never shows. + let covered = |f: &Placed, s: &Placed| f.paints == Paints::Fill && f.side && s.paints == Paints::Stroke && f.member == s.member; + // Is there a face of a shape's strokes and a face of the same shape's fill or strokes that the + // order of their depths draws the wrong way round where they overlap? + let mut position = vec![0usize; faces.len()]; + for (at, &k) in order.iter().enumerate() { + position[k] = at; + } + let mut checks = 0usize; + let mut misordered = false; + 'shapes: for list in &shapes { + for (i, &f) in list.iter().enumerate() { + let a = &faces[f]; + for &s in list.iter().skip(i + 1).take_while(|&&s| faces[s].bounds.x0 < a.bounds.x1) { + if checks >= MAX_LOCAL_CHECKS { + break 'shapes; + } + checks += 1; + let b = &faces[s]; + if (a.paints == Paints::Fill && b.paints == Paints::Fill) || covered(a, b) || covered(b, a) || !rects_overlap(a.bounds, b.bounds) { + continue; + } + if nearer_where_overlapping(a, b).is_some_and(|a_nearer| a_nearer != (position[f] > position[s])) { + misordered = true; + break 'shapes; + } + } + } + } + if !misordered { + return order; + } + // Moving those faces must not carry them past any other face they overlap, so every pair of + // faces with a polygon and a plane that overlap goes in the order of their depths there. + let mut sweep: Vec<usize> = (0..faces.len()).filter(|&k| faces[k].outline.len() >= 3 && faces[k].plane.is_some()).collect(); + sweep.sort_by(|&a, &b| faces[a].bounds.x0.total_cmp(&faces[b].bounds.x0)); + // For each face, the faces drawn after it, and for each, how many go before it. + let mut after: Vec<Vec<usize>> = vec![vec![]; faces.len()]; + let mut waits = vec![0usize; faces.len()]; + 'pairs: for (i, &k) in sweep.iter().enumerate() { + let a = &faces[k]; + for &j in sweep.iter().skip(i + 1).take_while(|&&j| faces[j].bounds.x0 < a.bounds.x1) { + if checks >= MAX_LOCAL_CHECKS { + break 'pairs; + } + checks += 1; + let b = &faces[j]; + if !rects_overlap(a.bounds, b.bounds) { + continue; + } + let a_later = if covered(a, b) || covered(b, a) { + position[k] > position[j] + } else { + let Some(a_nearer) = nearer_where_overlapping(a, b) else { continue }; + a_nearer + }; + let (back, front) = if a_later { (j, k) } else { (k, j) }; + after[back].push(front); + waits[front] += 1; + } + } + // Each step draws the face that comes first in `order` of those whose faces before are drawn. + let mut ready: std::collections::BinaryHeap<Reverse<(usize, usize)>> = + (0..faces.len()).filter(|&k| waits[k] == 0).map(|k| Reverse((position[k], k))).collect(); + // The faces drawn last, in `order`: each goes only after every face before it in `order`. + let last: Vec<usize> = order.iter().copied().filter(|&k| faces[k].depth >= f64::MAX).collect(); + let mut next_last = 0usize; + let mut drawn = vec![false; faces.len()]; + let mut out = Vec::with_capacity(order.len()); + let mut first = 0usize; + while out.len() < order.len() { + while last.get(next_last).is_some_and(|&k| drawn[k]) { + next_last += 1; + } + let limit = last.get(next_last).map_or(usize::MAX, |&k| position[k]); + let k = match ready.peek() { + Some(&Reverse((at, k))) if at < limit => { + ready.pop(); + k + } + _ => { + // A cycle, or the faces left to draw before a face drawn last wait for faces after + // it: the first face in `order` not drawn yet goes next. + while order.get(first).is_some_and(|&k| drawn[k]) { + first += 1; + } + let Some(&k) = order.get(first) else { break }; + k + } + }; + if drawn[k] { + continue; + } + drawn[k] = true; + out.push(k); + for &j in &after[k] { + waits[j] = waits[j].saturating_sub(1); + if waits[j] == 0 && !drawn[j] { + ready.push(Reverse((position[j], j))); + } + } + } + out +} + +/// Whether face `a` is nearer the viewer than face `b` where their polygons overlap on the drawing, +/// measured at the middle of the overlap. `None` when they do not overlap, when either polygon is +/// not convex, or when they are at the same depth there. +fn nearer_where_overlapping(a: &Placed, b: &Placed) -> Option<bool> { + let (pa, pb) = (a.plane?, b.plane?); + let turn = convex(&b.outline)?; + convex(&a.outline)?; + let overlap = clip_convex(&a.outline, &b.outline, turn); + let mid = centroid(&overlap)?; + let (da, db) = (pa.depth_at(mid)?, pb.depth_at(mid)?); + let tolerance = 1e-6 * (1.0 + da.abs().max(db.abs())); + ((da - db).abs() > tolerance).then_some(da > db) +} + +/// The sign of the turns of convex polygon `p` (`None` when it is not convex or has no area). +fn convex(p: &[Point]) -> Option<f64> { + let n = p.len(); + let mut sign = 0.0; + for i in 0..n { + let (a, b, c) = (p[i], p[(i + 1) % n], p[(i + 2) % n]); + let cross = (b - a).cross(c - b); + if cross.abs() <= 1e-12 { + continue; + } + if sign == 0.0 { + sign = cross.signum(); + } else if cross.signum() != sign { + return None; + } + } + (sign != 0.0).then_some(sign) +} + +/// The part of polygon `subject` inside convex polygon `clip`, whose turns have sign `turn` +/// (Sutherland–Hodgman). +fn clip_convex(subject: &[Point], clip: &[Point], turn: f64) -> Vec<Point> { + let mut out = subject.to_vec(); + for i in 0..clip.len() { + if out.is_empty() { + break; + } + let (e0, e1) = (clip[i], clip[(i + 1) % clip.len()]); + let side = |p: Point| (e1 - e0).cross(p - e0) * turn; + let input = std::mem::take(&mut out); + for j in 0..input.len() { + let (p, q) = (input[j], input[(j + 1) % input.len()]); + let (sp, sq) = (side(p), side(q)); + if sp >= 0.0 { + out.push(p); + } + if (sp >= 0.0) != (sq >= 0.0) { + let t = sp / (sp - sq); + out.push(p.lerp(q, t)); + } + } + } + out +} + +/// The centroid of polygon `p`, `None` when it has (almost) no area. It is measured from the +/// polygon's first point, so a small polygon far from the origin keeps its area. +fn centroid(p: &[Point]) -> Option<Point> { + let origin = *p.first()?; + let n = p.len(); + let (mut area, mut cx, mut cy) = (0.0, 0.0, 0.0); + for i in 0..n { + let (a, b) = (p[i] - origin, p[(i + 1) % n] - origin); + let cross = a.x * b.y - b.x * a.y; + area += cross; + cx += (a.x + b.x) * cross; + cy += (a.y + b.y) * cross; + } + (area.abs() > 1e-9).then(|| origin + Vec2::new(cx / (3.0 * area), cy / (3.0 * area))) +} + +/// The most bounds comparisons [`draw_order`] makes; the fill walls it has not reached by then keep +/// their depths. +const MAX_OVERLAP_CHECKS: usize = 4_000_000; + +/// The order faces `faces` are drawn in, back to front, as indices into `faces`: by depth (faces +/// at the same depth in the order given), except that with `sealed` (solids with caps) a side face +/// of a shape's fill turned toward the viewer is drawn before each face of the same shape's +/// covering strokes ([`Paints::Stroke`]), turned toward the viewer, whose bounds overlap its own. +/// Such a stroke's closed solid holds the fill's walls, so they never show and can be drawn under +/// any other face. A shape's fill faces and the faces of its other strokes then go in the order of +/// their depths where they overlap ([`local_order`]). +fn draw_order(faces: &[Placed], sealed: bool) -> Vec<usize> { + // Each face's depth to sort by, and whether it was moved before a stroke face at that depth. + let mut keys: Vec<(f64, bool)> = faces.iter().map(|f| (f.depth, false)).collect(); + if sealed { + // The stroke faces turned toward the viewer of each shape, nearest last. + let mut strokes: Vec<Vec<&Placed>> = vec![]; + for f in faces.iter().filter(|f| f.paints == Paints::Stroke && !f.away) { + if strokes.len() <= f.member { + strokes.resize_with(f.member + 1, Vec::new); + } + strokes[f.member].push(f); + } + for list in &mut strokes { + list.sort_by(|a, b| a.depth.total_cmp(&b.depth)); + } + let overlap = |a: &Rect, b: &Rect| a.x0 < b.x1 && b.x0 < a.x1 && a.y0 < b.y1 && b.y0 < a.y1; + let mut checks = 0usize; + for (f, key) in faces.iter().zip(&mut keys) { + if f.paints != Paints::Fill || !f.side || f.away { + continue; + } + let Some(list) = strokes.get(f.member).filter(|l| !l.is_empty()) else { continue }; + for s in list.iter().take_while(|s| s.depth <= f.depth) { + if checks >= MAX_OVERLAP_CHECKS { + break; + } + checks += 1; + if overlap(&s.bounds, &f.bounds) { + *key = (s.depth, true); + break; + } + } + } + } + let mut order: Vec<usize> = (0..faces.len()).collect(); + // A stable sort: faces at the same depth keep the order of the appearance, and a fill's side + // face moved to a stroke face's depth goes before it. + order.sort_by(|&a, &b| keys[a].0.total_cmp(&keys[b].0).then(keys[b].1.cmp(&keys[a].1))); + local_order(faces, order) +} + /// `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. pub(crate) fn reshape_members(n: &Node, before: &[Effect], shapes: &mut [Profile]) { @@ -551,28 +1249,255 @@ pub(crate) fn reshape_members(n: &Node, before: &[Effect], shapes: &mut [Profile } } +/// A 3D effect's shadow and its surfaces ([`art_for`]). +type ShadowAndSurfaces = (Vec<Arc<Node>>, Vec<Arc<Node>>); + /// 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, /// each in its own paint. When every one is opaque with normal blending and no colored light makes -/// a surface one composite or masks it, their faces are drawn in one back-to-front order (where -/// depths tie, as for the caps turned toward the viewer, in the order of the appearance); +/// a surface one composite, their faces are drawn in one back-to-front order (where depths tie, as +/// for the caps turned toward the viewer, in the order of the appearance, and with caps, a shape's +/// fill walls before the faces of its covering strokes that overlap them, and its fill's faces and +/// its other strokes' faces, cut where they pass through each other ([`cut_stroke_faces`]), in the +/// order of their depths where they overlap: [`draw_order`]), the +/// faces of a solid in a gradient with transparent stops in runs that carry its opacity mask +/// ([`in_runs`]); /// otherwise each solid is a surface of its own, in that order. A member's opacity mask and /// blending mode, and those of a group it is in, apply to the surfaces of the members it holds -/// ([`masked`]). -fn art_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Node>>> { +/// ([`masked`]). The art comes in two parts: the effect's shadow ([`cast_shadow`], none with it +/// off), to be drawn behind every surface of the object, and the surfaces. +fn art_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<ShadowAndSurfaces> { + let art = surfaces_for(doc, n, fx, shapes)?; + // A shadow past the limits draws the source path, as a solid past them does; commands report + // the error ([`validate_solid_in`]). + let shadow = match cast_shadow(&fx.id, &crate::merged_params(&fx.id, &fx.params), shapes).ok()? { + Some((caster, settings, cast)) => shadow::scoped_art(n.id, &caster, settings, cast, has_masks(shapes)), + None => vec![], + }; + Some((shadow, art)) +} + +/// What the shadow of the solids [`surfaces_for`] builds for effect `id` with parameters `p` on +/// `shapes` is cast from, on one plane: the faces of every solid, the shadow's settings and the +/// faces of each solid of visible art with its member's scopes and ink. `None` with the shadow +/// off, for Extrude & Bevel (Classic) and Rotate (Classic) or with no shapes. A stroke's solid that is not built (past +/// the limits) casts nothing, as it draws nothing; any other solid that is not built is an error. +/// When a member's opacity mask or blending mode applies to its solids ([`masked`]), it applies to +/// the part of the shadow they cast too ([`shadow::scoped_art`]). +fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result<Option<Cast<'a>>, String> { + if id == CLASSIC_EXTRUDE || id == CLASSIC_ROTATE { + return Ok(None); + } + let (Some(settings), Some(b)) = (shadow::options(p), union_bounds(shapes)) else { return Ok(None) }; + let view = view_options(p); + let mut caster = vectorcraft_three_d::ShadowCaster::new(); + // The faces each solid of visible art added, with its member's scopes and its ink (opacity + // and blending mode), in order. A fully transparent fill or stroke (or member) casts nothing + // and does not place the plane. + let mut cast: Vec<shadow::Cast> = vec![]; + let ink = |item: &AppearanceItem, member: f32| { + let (_, opacity, blend) = paint_of(item, member); + shadow::Ink { opacity, blend } + }; + if id == ROTATE { + for s in shapes { + for item in s.items.iter().filter(|i| ink(i, s.opacity).opacity > 0.0) { + let (area, rule) = region(&s.path, s.rule, item); + let faces = caster.plane(&area, rule, b, view)?; + cast.push((s.scopes.as_slice(), ink(item, s.opacity), faces)); + } + } + } else { + let (parts, bounds) = solid_parts(shapes, b); + let inks: Vec<shadow::Ink> = parts.iter().map(|(item, member, ..)| ink(item, *member)).collect(); + // Inflate's eye is placed for every shape together, as the solids are. + let added: Vec<Result<std::ops::Range<usize>, String>> = if id == INFLATE { + let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule, _, _)| (area, *rule)).collect(); + let casts: Vec<bool> = inks.iter().map(|i| i.opacity > 0.0).collect(); + caster.inflate(&shapes, &casts, bounds, inflate_options(p), view) + } else { + let mut added = vec![]; + for ((_, _, area, rule, _, _), ink) in parts.iter().zip(&inks) { + added.push(if ink.opacity > 0.0 { caster.extrude(area, *rule, bounds, extrude_options(p), view) } else { Ok(0..0) }); + } + added + }; + for (((item, _, _, _, scopes, _), ink), faces) in parts.iter().zip(inks).zip(added) { + if ink.opacity <= 0.0 { + continue; + } + // A stroke whose own solid is past the limits is left out; past the shadow's limit for + // all the solids together, the shadow is refused. + let faces = match faces { + Ok(faces) => faces, + Err(e) if matches!(item, AppearanceItem::Stroke(_)) && e != vectorcraft_three_d::TOO_COMPLEX_SHADOW => continue, + Err(e) => return Err(e), + }; + cast.push((*scopes, ink, faces)); + } + } + Ok(Some((caster, settings, cast))) +} + +/// The faces a shadow is cast from, its settings, and the faces of each solid of visible art with +/// its member's scopes and ink ([`cast_shadow`]). +type Cast<'a> = (vectorcraft_three_d::ShadowCaster, vectorcraft_three_d::Shadow, Vec<shadow::Cast<'a>>); + +/// The graphics of a 3D effect with parameters `p`, drawn on its faces ([`graphics::face_art`]): +/// for each planar face with a graphic, the art and the face. `caps` are the faces the viewer sees +/// of the ends of the object's solids, each with its end; `bounds` are the bounds the solids were +/// built with; `opacity` is the opacity of the fill or stroke those solids are painted with, which +/// the graphics take too. `elements` is the effect's count of drawn path elements, shared by every +/// call for one effect ([`graphics::face_art`]). +fn graphic_art( + doc: Option<&Document>, + id: NodeId, + (effect, p): (&str, &Value), + bounds: Rect, + caps: &[&Facet], + opacity: f32, + elements: &mut usize, +) -> Vec<(PlanarFace, Arc<Node>)> { + let list = graphics::mapped_graphics(p); + if list.is_empty() || !takes_graphics(effect) { + return vec![]; + } + let view = view_options(p); + PlanarFace::ALL + .into_iter() + .filter_map(|face| { + let on: Vec<&Facet> = caps.iter().copied().filter(|f| f.end == Some(face)).collect(); + let map = if effect == ROTATE { + vectorcraft_three_d::plane_face_map(bounds, view) + } else { + vectorcraft_three_d::extrude_face_map(bounds, extrude_options(p), view, face) + }?; + graphics::face_art(doc, id, &list, (face, &map), bounds.center(), &on, elements).map(|mut art| { + art.opacity *= opacity; + (face, Arc::new(art)) + }) + }) + .collect() +} + +/// A solid (a fill's or a stroke's) with ends the viewer sees: the index of its surface, its +/// member, the ends, the opacity and blending mode of its fill or stroke, and whether its surface +/// carries an opacity mask (a gradient's transparency under a colored light, [`surface`]). +struct Filled { + at: usize, + member: usize, + caps: Vec<Facet>, + opacity: f32, + blend: BlendMode, + masked: bool, +} + +/// Does a surface in `paint` carry an opacity mask ([`surface`])? +fn masks_surface(paint: &Paint, colored: bool) -> bool { + colored && crate::lighting::opaque_paint(paint).1.is_some() +} + +/// The graphics of the solids `filled` ([`graphic_art`]), each with the index of the surface it is +/// drawn right after (the last of those solids holding its face) and its face. Solids in a run +/// with the same opacity and blending mode share their graphics. With `per_member` +/// (a member's opacity mask or blending mode applies to its surfaces) each member's solids get +/// graphics of their own, clipped to that member's caps, so they stay in that member's scopes. +/// All the groups share one limit on the path elements drawn: once it is reached, later groups +/// draw no graphics. +fn placed_graphics( + doc: Option<&Document>, + id: NodeId, + effect: (&str, &Value), + bounds: Rect, + filled: &[Filled], + per_member: bool, +) -> Vec<(usize, PlanarFace, Arc<Node>)> { + let mut groups: Vec<Vec<&Filled>> = vec![]; + for f in filled { + // Solids whose fills or strokes differ in opacity or blending mode get graphics of their + // own, each drawn as its fill or stroke is. A solid whose surface carries an opacity mask + // gets its own too, which takes that mask ([`with_graphics`]). A solid joins only the + // group of the solid before it, so a graphic is never drawn past a solid painted between. + let joins = |first: &Filled| { + (!per_member || first.member == f.member) && first.opacity == f.opacity && first.blend == f.blend && !first.masked && !f.masked + }; + match groups.last_mut().filter(|g| g.first().is_some_and(|first| joins(first))) { + Some(g) => g.push(f), + None => groups.push(vec![f]), + } + } + let mut out = vec![]; + let mut elements = 0usize; + for group in groups { + let caps: Vec<&Facet> = group.iter().flat_map(|f| &f.caps).collect(); + let opacity = group.first().map_or(1.0, |f| f.opacity); + let blend = group.first().map_or(BlendMode::Normal, |f| f.blend); + for (face, mut art) in graphic_art(doc, id, effect, bounds, &caps, opacity, &mut elements) { + if let Some(f) = group.iter().rev().find(|f| f.caps.iter().any(|c| c.end == Some(face))) { + Arc::make_mut(&mut art).blend = blend; + out.push((f.at, face, art)); + } + } + } + out +} + +/// One solid's surface as [`surfaces_for`] builds it: its faces' depths, its art, its member's +/// scopes, and for each face the end of a solid it is, when the viewer sees it. +type BuiltSurface<'s> = (Vec<Placed>, Node, &'s [Scope], Vec<Option<PlanarFace>>); + +/// [`with_graphics`] of built surfaces, each drawn whole. +fn whole_surfaces<'s>(surfaces: Vec<BuiltSurface<'s>>, arts: &[(usize, PlanarFace, Arc<Node>)]) -> Vec<(&'s [Scope], Arc<Node>)> { + with_graphics(surfaces.into_iter().map(|(_, s, scopes, _)| (scopes, Arc::new(s))).collect(), 0, arts) +} + +/// `surfaces` (those from index `first`) drawn whole, each with its scopes, and the graphics `arts` +/// ([`placed_graphics`]) of those surfaces each right after its surface, with that surface's scopes +/// and its opacity mask (a gradient's transparency), so a graphic is hidden where its cap is. +fn with_graphics<'s>( + surfaces: Vec<(&'s [Scope], Arc<Node>)>, + first: usize, + arts: &[(usize, PlanarFace, Arc<Node>)], +) -> Vec<(&'s [Scope], Arc<Node>)> { + let mut out = Vec::with_capacity(surfaces.len() + arts.len()); + for (k, (scopes, s)) in surfaces.into_iter().enumerate() { + let mask = s.extras().mask.clone(); + out.push((scopes, s)); + out.extend(arts.iter().filter(|(at, ..)| *at == first + k).map(|(.., art)| { + let mut art = art.clone(); + if let Some(mask) = &mask { + Arc::make_mut(&mut art).extras_mut().mask = Some(mask.clone()); + } + (scopes, art) + })); + } + out +} + +/// The ends of `f` the viewer sees, for a fill's solid or a stroke's: where its graphics go. +fn seen_ends(f: &[Facet]) -> impl Iterator<Item = &Facet> { + f.iter().filter(|f| f.end.is_some() && !f.away) +} + +/// [`art_for`] without the shadow: the solids' surfaces, with the graphics mapped onto their planar +/// faces drawn right after the last of the solids' surfaces that holds that face. +fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Node>>> { let b = union_bounds(shapes)?; let p = crate::merged_params(&fx.id, &fx.params); - let classic = fx.id == CLASSIC_EXTRUDE; + let classic = fx.id == CLASSIC_EXTRUDE || fx.id == CLASSIC_ROTATE; let colored = !classic && view_options(&p).has_colored_lights(); let masks = has_masks(shapes); // The paint copies of every solid together: past the allowance the source path is drawn. let mut paint_bytes = 0usize; - if fx.id == ROTATE { + // The caps are copied only when the effect has graphics to draw on them. + let graphics_on = !classic && takes_graphics(&fx.id) && !mapped_graphics(&p).is_empty(); + if is_plane(&fx.id) { // Every part turns about the centre of the object's own bounds (a group's members about // the centre of theirs), so they stay together. let mut out = vec![]; - for s in shapes { + let mut filled = vec![]; + for (member, s) in shapes.iter().enumerate() { for item in &s.items { let (paint, opacity, blend) = paint_of(item, s.opacity); let (area, rule) = region(&s.path, s.rule, item); @@ -580,70 +1505,248 @@ fn art_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Node>>> if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, &paint, colored), &paint) { return None; } - out.push((s.scopes.as_slice(), Arc::new(surface(n, f, &paint, opacity, blend, colored)))); + if graphics_on { + let caps: Vec<Facet> = seen_ends(&f).cloned().collect(); + if !caps.is_empty() { + filled.push(Filled { at: out.len(), member, caps, opacity, blend, masked: masks_surface(&paint, colored) }); + } + } + let art = if classic { classic::surface(n, f, &paint, opacity, blend, &p) } else { surface(n, f, &paint, opacity, blend, colored) }; + out.push((s.scopes.as_slice(), Arc::new(art))); } } + let arts = placed_graphics(doc, n.id, (ROTATE, &p), b, &filled, masks); + let out = with_graphics(out, 0, &arts); return Some(if masks { masked(n.id, out) } else { out.into_iter().map(|(_, s)| s).collect() }); } 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(); - vectorcraft_three_d::inflate_together(&shapes, bounds, inflate_options(&p), view_options(&p)) - } else { - parts.iter().map(|(_, _, area, rule, _)| facets(&fx.id, area, *rule, bounds, &p)).collect() - }; let mut solids = vec![]; - for ((item, opacity, _, _, scopes), f) in parts.iter().zip(built) { + for ((item, opacity, _, _, scopes, member), f) in parts.iter().zip(built_solids(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES)) { let item: &AppearanceItem = item; match f { - Ok(f) if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, paint_ref(item), colored), paint_ref(item)) => return None, - Ok(f) => solids.push((item, *opacity, *scopes, f)), + Ok(Some(f)) if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, paint_ref(item), colored), paint_ref(item)) => { + return None; + } + Ok(Some(f)) => solids.push((item, *opacity, *scopes, f, *member)), // A stroke's outline past the limits is left out; the fill's solid still draws. - Err(_) if matches!(item, AppearanceItem::Stroke(_)) => {} - // A loaded file or a shape edited past the limits keeps drawing its source path - // instead of failing the frame; commands validate the same evaluator and report its - // errors. + Ok(None) => {} + // A loaded file or a shape edited past the limits (its own, or those of the object's + // solids together) keeps drawing its source path instead of failing the frame; + // commands validate the same evaluator and report its errors. Err(_) => return None, } } if solids.is_empty() { return None; } - let opaque = solids.iter().all(|(item, member, _, _)| { + let opaque = solids.iter().all(|(item, member, _, _, _)| { let (_, opacity, blend) = paint_of(item, *member); opacity >= 1.0 && blend == BlendMode::Normal }); - let surfaces: Vec<(Vec<f64>, Node, &[Scope])> = solids - .into_iter() - .map(|(item, member, scopes, f)| { - let depths: Vec<f64> = f.iter().map(|f| f.depth).collect(); - let (paint, opacity, blend) = paint_of(item, member); - let art = if classic { classic::surface(n, f, &paint, opacity, blend, &p) } else { surface(n, f, &paint, opacity, blend, colored) }; - (depths, art, scopes) + let closed = |shape: usize| shapes.get(shape).is_some_and(|s| holds_edge(&fx.id, &s.path)); + // A solid whose surface is one composite of all its facets ([`surface`]: a solid color under + // colored lights with smooth shading) has no faces to order. + let composite = |item: &AppearanceItem, f: &[Facet]| colored && paint_ref(item).color().is_some() && f.iter().any(|f| f.rgb_gradient.is_some()); + // The faces are drawn in one order (below) unless a composite draws the surfaces whole. Under + // a member's opacity mask or blending, each member's faces go in one order of their own when its + // fills and strokes are opaque, blend normally, carry no opacity mask and are not composites. + let one_order = opaque && !solids.iter().any(|(item, _, _, f, _)| composite(item, f)); + let shape_order: Vec<bool> = (0..shapes.len()) + .map(|shape| { + solids.iter().filter(|s| s.4 == shape).all(|(item, member, _, f, _)| { + let (paint, opacity, blend) = paint_of(item, *member); + opacity >= 1.0 && blend == BlendMode::Normal && !masks_surface(&paint, colored) && !composite(item, f) + }) }) .collect(); - if masks { - return Some(masked(n.id, surfaces.into_iter().map(|(_, s, scopes)| (scopes, Arc::new(s))).collect())); - } - // One order takes a plain group of faces from each solid, one face for each facet. With - // colored lights a surface can instead be one clipped composite of all its facets, or carry an - // opacity mask, and then it stays whole. - let plain = surfaces.iter().all(|(depths, s, _)| { - s.extras().mask.is_none() && matches!(&s.kind, NodeKind::Group { children, clip: false } if children.len() == depths.len()) - }); - if !opaque || !plain { - return Some(surfaces.into_iter().map(|(_, s, _)| Arc::new(s)).collect()); - } - let mut faces = vec![]; - for (depths, s, _) in surfaces { - if let NodeKind::Group { children, .. } = s.kind { - faces.extend(depths.into_iter().zip(children)); + let ordered = |shape: usize| if masks { shape_order.get(shape).copied().unwrap_or(false) } else { one_order }; + if solids.iter().any(|s| ordered(s.4)) { + // A stroke face that passes through a fill wall or another stroke's face is cut where it + // does. The pieces count against the limits as the faces did: cutting stops before the + // faces pass MAX_OBJECT_FACES or their paint copies pass the allowance, so an effect that + // draws uncut still draws. + let counts: Vec<usize> = solids.iter().map(|(.., f, _)| f.len()).collect(); + let room = cut_room(solids.iter().map(|(item, ..)| *item), counts.iter().sum(), paint_bytes); + let mut cuts: Vec<(Paints, usize, &mut Vec<Facet>)> = solids + .iter_mut() + .filter(|(.., shape)| ordered(*shape)) + .map(|(item, _, _, f, shape)| (Paints::of(item, closed(*shape)), *shape, f)) + .collect(); + cut_stroke_faces(&mut cuts, room); + for ((item, _, _, f, _), before) in solids.iter().zip(counts) { + let added = f.get(before..).unwrap_or_default(); + if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(added, paint_ref(item), colored), paint_ref(item)) { + return None; + } } } - // A stable sort: faces at the same depth keep the order of the appearance. - faces.sort_by(|a, b| a.0.total_cmp(&b.0)); - Some(vec![Arc::new(Node::group(n.id, faces.into_iter().map(|(_, face)| face).collect()))]) + let arts = if !graphics_on { + vec![] + } else { + let filled: Vec<Filled> = solids + .iter() + .enumerate() + .filter_map(|(at, (item, member, _, f, shape))| { + let caps: Vec<Facet> = seen_ends(f).cloned().collect(); + let (paint, opacity, blend) = paint_of(item, *member); + let masked = masks_surface(&paint, colored); + (!caps.is_empty()).then_some(Filled { at, member: *shape, caps, opacity, blend, masked }) + }) + .collect(); + placed_graphics(doc, n.id, (&fx.id, &p), bounds, &filled, masks) + }; + let members: Vec<usize> = solids.iter().map(|s| s.4).collect(); + let surfaces: Vec<BuiltSurface> = solids + .into_iter() + .map(|(item, member, scopes, f, shape)| { + let paints = Paints::of(item, closed(shape)); + let depths: Vec<Placed> = f.iter().map(|f| Placed::of(f, shape, paints)).collect(); + let ends = f.iter().map(|f| f.end.filter(|_| !f.away)).collect(); + let (paint, opacity, blend) = paint_of(item, member); + let art = if classic { classic::surface(n, f, &paint, opacity, blend, &p) } else { surface(n, f, &paint, opacity, blend, colored) }; + (depths, art, scopes, ends) + }) + .collect(); + let sealed = match fx.id.as_str() { + INFLATE => inflate_options(&p).cap, + CLASSIC_EXTRUDE => classic_extrude_options(&p).cap, + _ => extrude_options(&p).cap, + }; + // One order takes a plain group of faces from each solid, one face for each facet. With + // colored lights a surface can instead be one clipped composite of all its facets. A composite + // has no faces to order, so it draws whole. + let plain = |(depths, s, _, _): &BuiltSurface| matches!(&s.kind, NodeKind::Group { children, clip: false } if children.len() == depths.len()); + if masks { + // Each member's surfaces, in the scopes of its opacity mask or blending: its faces in one + // order when it is opaque and plain, otherwise each surface whole. + let mut out = vec![]; + let mut surfaces = surfaces.into_iter().zip(members).enumerate().peekable(); + while let Some((first, (s, member))) = surfaces.next() { + let mut run = vec![s]; + while let Some((_, (s, _))) = surfaces.next_if(|(_, (_, m))| *m == member) { + run.push(s); + } + let flat = run.iter().all(|s| plain(s) && s.1.opacity >= 1.0 && s.1.blend == BlendMode::Normal && s.1.extras().mask.is_none()); + if ordered(member) && flat { + let scopes = run.first().map_or(&[][..], |s| s.2); + out.push((scopes, Arc::new(Node::group(n.id, in_one_order(n.id, run, first, &arts, sealed))))); + } else { + out.extend(with_graphics(run.into_iter().map(|(_, s, scopes, _)| (scopes, Arc::new(s))).collect(), first, &arts)); + } + } + return Some(masked(n.id, out)); + } + if !opaque || !surfaces.iter().all(plain) { + return Some(whole_surfaces(surfaces, &arts).into_iter().map(|(_, s)| s).collect()); + } + Some(vec![Arc::new(Node::group(n.id, in_one_order(n.id, surfaces, 0, &arts, sealed)))]) +} + +/// The faces of `surfaces` (plain groups of their faces, [`surfaces_for`]'s from index `first`) in +/// one order ([`draw_order`], `sealed` for solids with caps), each of the graphics `arts` of those +/// surfaces right after the last face it is drawn on, of the surfaces that share it. A surface in a gradient with transparent stops +/// carries an opacity mask: its faces go in runs ([`in_runs`]), each carrying the mask, and each of +/// its graphics carries the mask too ([`with_graphics`]), so a graphic is hidden where its cap is. +fn in_one_order(id: NodeId, surfaces: Vec<BuiltSurface<'_>>, first: usize, arts: &[(usize, PlanarFace, Arc<Node>)], sealed: bool) -> Vec<Arc<Node>> { + let masks: Vec<Option<Box<OpacityMask>>> = surfaces.iter().map(|(_, s, _, _)| s.extras().mask.clone()).collect(); + let arts: Vec<&(usize, PlanarFace, Arc<Node>)> = arts.iter().filter(|(at, ..)| (first..first + surfaces.len()).contains(at)).collect(); + let (mut placed, mut faces, mut ends) = (vec![], vec![], vec![]); + for (surface, (depths, s, _, e)) in surfaces.into_iter().enumerate() { + if let NodeKind::Group { children, .. } = s.kind { + placed.extend(depths); + faces.extend(children.into_iter().map(|face| Some((surface, face)))); + ends.extend(e.into_iter().map(|end| end.map(|end| (surface, end)))); + } + } + let order = draw_order(&placed, sealed); + // Each graphic goes right after the last of the faces it is drawn on, among the surfaces that + // share it ([`placed_graphics`]): a masked surface's own, or else the run of surfaces without a + // mask that ends at its surface. + let last: Vec<Option<usize>> = arts + .iter() + .map(|(at, face, _)| { + let at = at - first; + let from = if masks.get(at).is_some_and(Option::is_some) { + at + } else { + masks.get(..at).and_then(|before| before.iter().rposition(Option::is_some)).map_or(0, |k| k + 1) + }; + order.iter().rposition(|k| ends.get(*k).copied().flatten().is_some_and(|(surface, end)| end == *face && (from..=at).contains(&surface))) + }) + .collect(); + let mut drawn: Vec<(usize, Arc<Node>)> = Vec::with_capacity(order.len() + arts.len()); + for (at, k) in order.into_iter().enumerate() { + drawn.extend(faces.get_mut(k).and_then(Option::take)); + drawn.extend(last.iter().zip(&arts).filter(|(l, _)| **l == Some(at)).map(|(_, (surface, .., art))| { + let mut art = art.clone(); + if let Some(mask) = masks.get(surface - first).cloned().flatten() { + Arc::make_mut(&mut art).extras_mut().mask = Some(mask); + } + // An index past the surfaces: the graphic goes in a run of its own, with its own mask. + (masks.len(), art) + })); + } + if masks.iter().any(Option::is_some) { in_runs(id, drawn, &masks) } else { drawn.into_iter().map(|(_, face)| face).collect() } +} + +/// `faces` in their back-to-front order, each with the index of its surface, where some surfaces +/// carry an opacity mask (`masks`, by surface). A face of a surface without one goes in the order +/// on its own. The faces of a masked surface share a run, one group with the surface's mask. Such a +/// face joins its surface's last run unless a face drawn after that run overlaps it: only then does +/// the surface split, where one group can't be both behind and in front of another face. +fn in_runs(id: NodeId, faces: Vec<(usize, Arc<Node>)>, masks: &[Option<Box<OpacityMask>>]) -> Vec<Arc<Node>> { + use crate::revolve::{Coverage, overlaps}; + struct Run { + surface: Option<usize>, + bounds: Rect, + faces: Vec<Arc<Node>>, + cover: Vec<Coverage>, + } + let mut runs: Vec<Run> = vec![]; + let mut last_run = vec![None; masks.len()]; + // Past this many tests a face starts a run of its own, which never draws out of order. + let mut budget = crate::revolve::MAX_OVERLAP_TESTS; + for (surface, face) in faces { + let Some(cover) = Coverage::of(&face) else { + // A face with no outline and no box overlaps nothing. + runs.push(Run { surface: None, bounds: Rect::ZERO, faces: vec![face], cover: vec![] }); + continue; + }; + if masks.get(surface).is_none_or(Option::is_none) { + runs.push(Run { surface: None, bounds: cover.bounds, faces: vec![face], cover: vec![cover] }); + continue; + } + let mut clear = |r: &Run| { + budget = budget.saturating_sub(1); + if !overlaps(r.bounds, cover.bounds) { + return budget > 0; + } + budget = budget.saturating_sub(r.cover.len()); + budget > 0 && r.cover.iter().all(|c| !overlaps(c.bounds, cover.bounds) || !c.meets(&cover)) + }; + let joins = last_run.get(surface).copied().flatten().filter(|&i: &usize| runs.get(i + 1..).is_some_and(|later| later.iter().all(&mut clear))); + match joins.and_then(|i| runs.get_mut(i)) { + Some(run) => { + run.bounds = run.bounds.union(cover.bounds); + run.faces.push(face); + run.cover.push(cover); + } + None => { + if let Some(last) = last_run.get_mut(surface) { + *last = Some(runs.len()); + } + runs.push(Run { surface: Some(surface), bounds: cover.bounds, faces: vec![face], cover: vec![cover] }); + } + } + } + runs.into_iter() + .filter_map(|mut r| { + let Some(mask) = r.surface.and_then(|s| masks.get(s)).cloned().flatten() else { return r.faces.pop() }; + let mut group = Node::group(id, r.faces); + group.extras_mut().mask = Some(mask); + Some(Arc::new(group)) + }) + .collect() } fn geometry(path: &PathData, fx: &[Effect], ctx: &GeomContext) -> PathData { @@ -667,7 +1770,7 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> { } let n = &*resolve(doc, n, "").ok()?; if is_container(n) { - return group_solid_art(n); + return group_solid_art(doc, n); } let (path, rule) = profile(n)?; let ctx = GeomContext::of(n); @@ -676,31 +1779,36 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> { let remaining: Vec<Effect>; if let Some((index, fx)) = solid(&n.appearance.effects) { let path = geometry(&path, n.appearance.effects.get(..index)?, &ctx); - children.extend(art_for(n, fx, &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }])?); + let (shadow, surfaces) = art_for(doc, n, fx, &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }])?; + children.extend(shadow.into_iter().chain(surfaces)); // Later geometry effects act on the projected art as a whole. - remaining = n - .appearance - .effects - .iter() - .enumerate() - .filter(|(i, e)| *i != index && (!is_geometry(&e.id) || *i > index)) - .map(|(_, e)| e.clone()) - .collect(); + remaining = past_effect(&n.appearance.effects, index); } else { let path = geometry(&path, &n.appearance.effects, &ctx); - remaining = n.appearance.effects.iter().filter(|e| !is_geometry(&e.id)).cloned().collect(); + remaining = crate::without_geometry(&n.appearance.effects); + // The object's Transform effects, applied to the path above, transform the items' raster + // effects too. + let mut paints = paints; + crate::raster::follow_paints(&mut paints, &n.appearance.effects); + // Every item's shadow goes behind every item's art. + let mut shadows = vec![]; for item in &paints { if let Some((index, fx)) = solid(item.effects()) { let p = geometry(&path, item.effects().get(..index)?, &ctx.item(item)); - for mut art in art_for(n, fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }])? { - Arc::make_mut(&mut art).appearance.effects = - item.effects().iter().skip(index + 1).filter(|e| !is_three_d(&e.id)).cloned().collect(); - children.push(art); - } + let (shadow, surfaces) = art_for(doc, n, fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }])?; + let later: Vec<Effect> = item.effects().iter().skip(index + 1).filter(|e| !is_three_d(&e.id)).cloned().collect(); + let with_later = |mut art: Arc<Node>| { + Arc::make_mut(&mut art).appearance.effects = later.clone(); + art + }; + shadows.extend(shadow.into_iter().map(with_later)); + children.extend(surfaces.into_iter().map(with_later)); } else { - children.push(Arc::new(Node::path(n.id, path.clone(), Appearance { items: vec![item.clone()], ..Default::default() }))); + let flat = Appearance { items: vec![item.clone()], ..Default::default() }; + children.push(Arc::new(crate::group::shape_node(n.id, path.clone(), rule, flat))); } } + children.splice(0..0, shadows); } let mut art = n.clone(); art.kind = NodeKind::Group { children, clip: false }; @@ -712,19 +1820,121 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> { /// geometry effects before it reshape the members, those after it bend the result as a whole; the /// group's own fills and strokes are not drawn. `None` when the effect is only on one of the /// group's own fills or strokes, or when its members can't become solids. -fn group_solid_art(n: &Node) -> Option<Node> { +fn group_solid_art(doc: Option<&Document>, n: &Node) -> Option<Node> { let (index, fx) = solid(&n.appearance.effects)?; let mut shapes = members(n, "").ok()?; 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(); + let (shadow, surfaces) = art_for(doc, n, fx, &shapes)?; + let children = shadow.into_iter().chain(surfaces).collect(); + let remaining = past_effect(&n.appearance.effects, index); let mut art = n.clone(); art.kind = NodeKind::Group { children, clip: false }; art.appearance = Appearance { effects: remaining, ..Default::default() }.into(); Some(art) } +/// Where the graphics of the 3D effect of `n` (on the object itself with `item` `None`, else on its +/// fill or stroke `item`) are drawn: the bounds its solids are built with and the maps of their +/// planar faces ([`graphics::GraphicFrame`]). `None` when `n` has no visible Extrude & Bevel or +/// Rotate there, or its art can't be built. +pub fn graphic_frame(doc: Option<&Document>, n: &Node, item: Option<usize>) -> Option<graphics::GraphicFrame> { + frame_of(doc, n, item, &solid) +} + +/// [`graphic_frame`] of the 3D effect at `index` in that list, which must be a visible Extrude & +/// Bevel, Rotate or Revolve. Revolve's frame is its unrolled side seen from the front, centered on +/// the origin, with no face maps: it sizes a new graphic and places no handles. +pub fn graphic_frame_at(doc: Option<&Document>, n: &Node, item: Option<usize>, index: usize) -> Option<graphics::GraphicFrame> { + frame_of(doc, n, item, &|fx: &[Effect]| fx.get(index).filter(|e| e.visible && is_three_d(&e.id)).map(|e| (index, e))) +} + +/// Does a visible geometry effect come after the 3D effect at `index` in the effects of `n` (on the +/// object itself with `item` `None`, else on its fill or stroke `item`)? Such an effect moves or +/// bends the drawn art, graphics included, while [`graphic_frame_at`] places the graphics on the +/// art before it. +pub fn graphics_reshaped_after(n: &Node, item: Option<usize>, index: usize) -> bool { + n.appearance.effects_at(item).and_then(|fx| fx.get(index + 1..)).is_some_and(crate::has_geometry) +} + +/// Finds a 3D effect in a list of effects, with its index there. +type Pick<'p> = dyn for<'e> Fn(&'e [Effect]) -> Option<(usize, &'e Effect)> + 'p; + +/// [`graphic_frame`] of the 3D effect `pick` finds in the effects of `n` or its `item`. +fn frame_of(doc: Option<&Document>, n: &Node, item: Option<usize>, pick: &Pick<'_>) -> Option<graphics::GraphicFrame> { + let n = &*resolve(doc, n, "").ok()?; + let (fx, shapes) = if is_container(n) { + let (index, fx) = pick(&n.appearance.effects).filter(|_| item.is_none())?; + let mut shapes = members(n, "").ok()?; + reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes); + (fx, shapes) + } else { + let (path, rule) = profile(n)?; + let ctx = GeomContext::of(n); + match item { + None => { + let (index, fx) = pick(&n.appearance.effects)?; + let path = geometry(&path, n.appearance.effects.get(..index)?, &ctx); + (fx, vec![Profile { path, rule, items: solid_paints(n), opacity: 1.0, scopes: vec![] }]) + } + Some(k) => { + let it = n.appearance.items.get(k)?; + let (index, fx) = pick(it.effects())?; + let path = geometry(&geometry(&path, &n.appearance.effects, &ctx), it.effects().get(..index)?, &ctx.item(it)); + (fx, vec![Profile { path, rule, items: vec![it.clone()], opacity: 1.0, scopes: vec![] }]) + } + } + }; + if !takes_graphics(&fx.id) { + return None; + } + let p = crate::merged_params(&fx.id, &fx.params); + let b = union_bounds(&shapes)?; + if fx.id == crate::REVOLVE { + // Revolve's graphics lie on its unrolled side (in a group, the side of the member with the + // longest profile): the frame is the part of it seen from the front, with no planar face + // to place a handle on. + let options = crate::revolve::revolve_options(&p); + let (w, h) = shapes + .iter() + .filter(|s| crate::revolve::surface_item(&s.items).is_some()) + .filter_map(|s| vectorcraft_three_d::revolve_surface_size(&s.path, b, options)) + .fold((0.0f64, 0.0f64), |best, size| if size.1 > best.1 { size } else { best }); + if w <= 0.0 || h <= 0.0 { + return None; + } + return Some(graphics::GraphicFrame::new(Rect::new(-w / 2.0, -h / 2.0, w / 2.0, h / 2.0), None, None)); + } + let view = view_options(&p); + if fx.id == ROTATE { + let plane = vectorcraft_three_d::plane_face_map(b, view); + return Some(graphics::GraphicFrame::new(b, plane, None)); + } + let (_, bounds) = solid_parts(&shapes, b); + let options = extrude_options(&p); + let map = |face| vectorcraft_three_d::extrude_face_map(bounds, options, view, face); + Some(graphics::GraphicFrame::new(bounds, map(PlanarFace::Front), map(PlanarFace::Back))) +} + +/// The bounds of the art symbol `name` of `doc` draws as a graphic, in the symbol's coordinates. +pub fn graphic_bounds(doc: &Document, name: &str) -> Option<Rect> { + graphics::art_bounds(doc, name) +} + +/// `effects` without the 3D effect at `index` and the geometry effects before it, which shape the +/// art it projects. Each raster effect before it follows the Transform effects among those +/// ([`crate::without_geometry`]), unless a Transform effect after it makes copies or moves at +/// random ([`crate::raster::holds_back`]); the effects after it stay as they are. +pub(crate) fn past_effect(effects: &[Effect], index: usize) -> Vec<Effect> { + let (before, after) = effects.split_at(index.min(effects.len())); + let after = after.get(1..).unwrap_or_default(); + let kept: Vec<Effect> = if after.iter().any(crate::raster::holds_back) { + before.iter().filter(|e| !is_geometry(&e.id)).cloned().collect() + } else { + crate::without_geometry(before) + }; + kept.into_iter().chain(after.iter().cloned()).collect() +} + /// One solid of a 3D object as a mesh, with the color it is painted. #[derive(Clone, Debug, PartialEq)] pub struct SolidMesh { @@ -774,7 +1984,7 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize) 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 }, limit); - if fx.id == ROTATE { + if is_plane(&fx.id) { for s in shapes { for item in &s.items { let (paint, opacity, _) = paint_of(item, s.opacity); @@ -785,15 +1995,26 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize) return Ok(out); } let (parts, bounds) = solid_parts(shapes, b); + // The solids the art draws, past the limits of the object's solids together as it is + // ([`built_solids`]), each built and its faces counted as the loop reaches it, then dropped. + let drawn = built_solids(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES).map(|r| r.map(|f| f.is_some())); // Inflate lays out every puff at once (they share one eye); each Inflate and Extrude & Bevel // solid and its mesh are built as the loop reaches them. let mut inflated = (fx.id == INFLATE).then(|| { - let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule, _)| (area, *rule)).collect(); + 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 extrude = if fx.id == CLASSIC_EXTRUDE { classic_extrude_options(&p) } else { extrude_options(&p) }; + for ((item, member, area, rule, _, _), drawn) in parts.iter().zip(drawn) { let item: &AppearanceItem = item; + if !drawn? { + // A stroke the art leaves out is left out of the meshes too; Inflate's next puff + // still belongs to the next part. + if let Some(built) = inflated.as_mut() { + built.next(); + } + continue; + } 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), @@ -906,3 +2127,6 @@ mod tests_mesh; #[cfg(test)] mod tests_sources; + +#[cfg(test)] +mod tests_shadow; diff --git a/crates/effects/src/solids/classic.rs b/crates/effects/src/solids/classic.rs index 730fb8e53b..919de831ce 100644 --- a/crates/effects/src/solids/classic.rs +++ b/crates/effects/src/solids/classic.rs @@ -1,6 +1,6 @@ //! Extrude & Bevel (Classic): the solid Extrude & Bevel builds from a path, drawn with the classic //! surfaces (Wireframe, No Shading, Diffuse and Plastic), their highlight, blend steps and shading -//! color. +//! color. Rotate (Classic): the plane Rotate turns, drawn with the No Shading and Diffuse surfaces. use std::sync::Arc; use serde_json::Value; @@ -12,6 +12,10 @@ use vectorcraft_three_d::{Bevel, BevelShape, ClassicShading, ClassicSurface, Ext use crate::util::{flag, num, text}; pub const CLASSIC_EXTRUDE: &str = "threeD.classicExtrude"; +pub const CLASSIC_ROTATE: &str = "threeD.classicRotate"; + +/// The surfaces Rotate (Classic) takes: No Shading and Diffuse. +pub const ROTATE_SURFACES: [&str; 2] = ["none", "diffuse"]; /// The width of a Wireframe edge, in points. const WIRE: f64 = 0.5; @@ -104,8 +108,39 @@ const FLAGS: [&str; 4] = ["cap", "bevelInside", "lightBehind", "drawHiddenFaces" /// its parameters, numbers are in range, flags are true or false, and `surface`, `shadingColor` and /// `shadingCustom` name a surface, a shading color and a #rrggbb color. pub fn validate(p: &Value) -> Result<(), String> { + validate_classic(CLASSIC_EXTRUDE, p, &RANGES, &FLAGS) +} + +/// Rotate (Classic)'s numeric parameters: (key, lowest, highest, whole numbers only). +const ROTATE_RANGES: [(&str, f64, f64, bool); 9] = [ + ("rotationX", -180.0, 180.0, false), + ("rotationY", -180.0, 180.0, false), + ("rotationZ", -180.0, 180.0, false), + ("perspectiveAngle", 0.0, 160.0, false), + ("lightRotation", -180.0, 180.0, false), + ("lightHeight", 0.0, 90.0, false), + ("lightIntensity", 0.0, 100.0, false), + ("ambient", 0.0, 100.0, false), + ("blendSteps", 1.0, 256.0, true), +]; + +/// Check Rotate (Classic)'s parameters `p` (its defaults filled in) as [`validate`] checks Extrude & +/// Bevel (Classic)'s, with `surface` No Shading or Diffuse only. +pub fn validate_rotate(p: &Value) -> Result<(), String> { + validate_classic(CLASSIC_ROTATE, p, &ROTATE_RANGES, &["lightBehind"])?; + if p.get("surface").is_some_and(|v| !v.as_str().is_some_and(|s| ROTATE_SURFACES.contains(&s))) { + return Err(format!("`surface` must be one of {}", ROTATE_SURFACES.join(", "))); + } + Ok(()) +} + +/// Check the parameters `p` of classic 3D effect `id` (its defaults filled in): every key is one of +/// its parameters, the numbers `ranges` lists, as (key, lowest, highest, whole numbers only), are in +/// range, the `flags` are true or false, and `surface`, `shadingColor` and `shadingCustom` name a +/// surface, a shading color and a #rrggbb color. +pub(crate) fn validate_classic(id: &str, p: &Value, ranges: &[(&str, f64, f64, bool)], flags: &[&str]) -> Result<(), String> { let Some(map) = p.as_object() else { return Ok(()) }; - let defaults = crate::default_params(CLASSIC_EXTRUDE).unwrap_or(Value::Null); + let defaults = crate::default_params(id).unwrap_or(Value::Null); let known: Vec<&str> = defaults.as_object().map(|m| m.keys().map(String::as_str).collect()).unwrap_or_default(); for key in map.keys() { if !known.contains(&key.as_str()) { @@ -113,7 +148,7 @@ pub fn validate(p: &Value) -> Result<(), String> { return Err(format!("unknown parameter `{key}`; the command takes: {keys}")); } } - for (key, min, max, whole) in RANGES { + for &(key, min, max, whole) in ranges { let Some(v) = map.get(key) else { continue }; let Some(x) = v.as_f64() else { return Err(format!("`{key}` must be a number")) }; if whole && (x.fract() != 0.0 || !(min..=max).contains(&x)) { @@ -123,7 +158,7 @@ pub fn validate(p: &Value) -> Result<(), String> { return Err(format!("`{key}` must be between {min} and {max} (got {x})")); } } - for key in FLAGS { + for &key in flags { if map.get(key).is_some_and(|v| !v.is_boolean()) { return Err(format!("`{key}` must be true or false")); } @@ -161,7 +196,7 @@ fn shaded(c: Color, tone: f64, spec: f64, shade: Option<Color>) -> Color { /// for each facet: the edges of the faces on Wireframe, else each face filled in its paint shaded by /// its tone and highlight. A gradient with transparent stops is shaded opaque and then masked by /// its own transparency, so the shading follows the gradient's coverage. -pub(super) fn surface(n: &Node, facets: Vec<Facet>, source: &Paint, opacity: f32, blend: BlendMode, p: &Value) -> Node { +pub(crate) fn surface(n: &Node, facets: Vec<Facet>, source: &Paint, opacity: f32, blend: BlendMode, p: &Value) -> Node { let shading = classic_shading(p); let lights = lights(p); let shade = shading_color(p); diff --git a/crates/effects/src/solids/graphics.rs b/crates/effects/src/solids/graphics.rs new file mode 100644 index 0000000000..7c0087e15b --- /dev/null +++ b/crates/effects/src/solids/graphics.rs @@ -0,0 +1,1072 @@ +//! Graphics mapped onto a 3D object's planar faces (Window › 3D and Materials › Materials › +//! Graphics): the art of a document symbol drawn on Extrude & Bevel's front or back cap, or on a +//! plane, turned, foreshortened and shaded with that face and clipped to it. +//! +//! The effect keeps its graphics in its `graphics` parameter, each `{symbol, face, x, y, scale, +//! rotation}`: the symbol's name, the face, the offset of the graphic's center from the center of +//! the object's bounds in the face's own plane (points, x to the right and y down as the face is +//! seen from the front of that face), its size as a share of the symbol's own, and its turn +//! (degrees, counterclockwise). On the back cap, x runs to the right as the back is seen from +//! behind, so the graphic reads the right way round there. +//! +//! On Revolve the graphics lie on the swept side surface, unrolled flat +//! ([`vectorcraft_three_d::SurfaceCell`]): x and y are the offset of the graphic's center from the +//! middle of that surface, x around the axis and y along the profile, and each face of the side +//! draws the part of the graphics that falls on it ([`surface_parts`]). + +use std::sync::Arc; + +use serde_json::{Map, Value, json}; +use vectorcraft_doc::color::{BlendMode, Paint}; +use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeId, NodeKind, Symbol}; +use vectorcraft_geom::kurbo::{CubicBez, ParamCurve, PathEl, Shape}; +use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, SubPath, Vec2}; +use vectorcraft_three_d::{FaceMap, Facet, PlanarFace}; + +/// The effect parameter that holds the graphics. +pub const GRAPHICS: &str = "graphics"; + +/// The most graphics one 3D effect maps. +pub const MAX_GRAPHICS: usize = 64; + +/// The most fills and stroke outlines the art of one symbol draws as a graphic. +const MAX_PIECES: usize = 4096; + +/// The most path elements the graphics of one 3D effect draw together, after a perspective cuts +/// their curves. +const MAX_ELEMENTS: usize = 400_000; + +/// The pieces each curve of a graphic is cut into under a perspective map, which bends it. +const PERSPECTIVE_PIECES: usize = 8; + +/// How deep symbol instances in a graphic's art may nest. +const MAX_NESTING: usize = 8; + +/// How deep the objects of a graphic's art may be, counting groups and the art of the symbols it +/// places: as deep as an object may be drawn. +const MAX_LEVELS: usize = 4 * vectorcraft_doc::MAX_DEPTH; + +/// The error for graphics on a 3D effect that takes none. +pub const NOT_TAKEN: &str = "Graphics map onto the Plane, Extrude and Revolve object types"; + +/// The buckets around the unrolled side surface that the pieces of Revolve's graphics are sorted +/// into, so each face looks only at the pieces near it. +const SURFACE_BUCKETS: usize = 256; + +/// How closely the curves of a graphic on Revolve's side follow their shape when they are cut into +/// straight pieces, in points of the unrolled surface. +const SURFACE_TOLERANCE: f64 = 0.05; + +/// How far from the middle of Revolve's unrolled side a curve of a graphic may reach, in points: +/// as far as a Revolve profile's coordinates may. +const SURFACE_REACH: f64 = 1e8; + +/// The most points the parts of Revolve's graphics draw on its faces together, a graphic's area cut +/// at every face it crosses. Past it no graphic is drawn on that surface. +const MAX_SURFACE_POINTS: usize = 2_000_000; + +/// The most points of Revolve's graphics cut at its faces together, counted before each cut whether +/// or not it keeps any of them. Past it no graphic is drawn on that surface. +const MAX_SURFACE_CUTS: usize = 32 * MAX_SURFACE_POINTS; + +/// The width of the stroke of the same paint around each opaque part of a graphic on Revolve's +/// side, which covers the seams between the parts on neighboring faces. +const SURFACE_SEAM: f64 = 0.3; + +/// The size range of a graphic, as a percentage of its symbol's own size. +pub const SCALE_RANGE: (f64, f64) = (1.0, 10_000.0); + +/// How far a graphic's center may be from the center of its object, in points. +pub const MAX_OFFSET: f64 = 1e6; + +/// One graphic mapped onto a face of a 3D object. +#[derive(Clone, Debug, PartialEq)] +pub struct MappedGraphic { + pub symbol: String, + pub face: PlanarFace, + pub x: f64, + pub y: f64, + /// Percent of the symbol's own size. + pub scale: f64, + /// Degrees, counterclockwise. + pub rotation: f64, +} + +impl MappedGraphic { + pub fn to_value(&self) -> Value { + json!({"symbol": self.symbol, "face": self.face.id(), "x": self.x, "y": self.y, "scale": self.scale, "rotation": self.rotation}) + } + + /// The graphic `v` describes. Only `symbol` is required: `face` defaults to front, the offsets + /// and the rotation to 0 and the scale to 100. + pub fn from_value(v: &Value) -> Result<Self, String> { + let Value::Object(m) = v else { return Err(format!("each of `{GRAPHICS}` must be an object")) }; + if let Some(k) = m.keys().find(|k| !matches!(k.as_str(), "symbol" | "face" | "x" | "y" | "scale" | "rotation")) { + return Err(format!("`{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}`")); + } + let symbol = match m.get("symbol") { + Some(Value::String(s)) if !s.trim().is_empty() => s.clone(), + _ => return Err(format!("each of `{GRAPHICS}` needs `symbol`, the name of a symbol")), + }; + let face = match m.get("face") { + None => PlanarFace::Front, + Some(v) => v.as_str().and_then(PlanarFace::parse).ok_or_else(|| format!("`{GRAPHICS}` face must be front or back"))?, + }; + let number = |key: &str, default: f64, (lo, hi): (f64, f64)| -> Result<f64, String> { + match m.get(key) { + None => Ok(default), + Some(v) => v + .as_f64() + .filter(|n| n.is_finite() && (lo..=hi).contains(n)) + .ok_or_else(|| format!("`{GRAPHICS}` {key} must be a number from {lo} to {hi}")), + } + }; + Ok(Self { + symbol, + face, + x: number("x", 0.0, (-MAX_OFFSET, MAX_OFFSET))?, + y: number("y", 0.0, (-MAX_OFFSET, MAX_OFFSET))?, + scale: number("scale", 100.0, SCALE_RANGE)?, + rotation: number("rotation", 0.0, (-360.0, 360.0))?, + }) + } + + /// Where the graphic's art goes in the face's plane, for symbol art whose bounds are `art` on an + /// object whose bounds have center `center`. + fn placement(&self, art: Rect, center: Point) -> Affine { + let place = Affine::translate((center.x + self.x, center.y + self.y)) + * Affine::rotate(-self.rotation.to_radians()) + * Affine::scale(self.scale / 100.0) + * Affine::translate(-art.center().to_vec2()); + match self.face { + PlanarFace::Front => place, + // Seen from behind, the back's right is the front's left. + PlanarFace::Back => { + Affine::translate(center.to_vec2()) * Affine::scale_non_uniform(-1.0, 1.0) * Affine::translate(-center.to_vec2()) * place + } + } + } +} + +/// The 3D effects that take graphics: Extrude & Bevel (its caps), Rotate (the plane) and Revolve +/// (its swept side). +pub fn takes_graphics(id: &str) -> bool { + id == super::EXTRUDE || id == super::ROTATE || id == crate::REVOLVE +} + +/// The graphics in parameters `p`, leaving out entries that are not valid (a file may hold +/// anything; commands check every entry with [`validate`]). +pub fn mapped_graphics(p: &Value) -> Vec<MappedGraphic> { + match p.get(GRAPHICS) { + Some(Value::Array(list)) => list.iter().take(MAX_GRAPHICS).filter_map(|v| MappedGraphic::from_value(v).ok()).collect(), + _ => vec![], + } +} + +/// Are the graphics in parameters `p` of 3D effect `id` valid? Only Extrude & Bevel, Rotate and +/// Revolve take graphics; a plane has only a front, and Revolve's graphics go on its side, named +/// the front. +pub fn validate(id: &str, p: &Value) -> Result<(), String> { + let list = match p.get(GRAPHICS) { + None => return Ok(()), + Some(Value::Array(list)) => list, + Some(_) => return Err(format!("`{GRAPHICS}` must be an array")), + }; + if list.is_empty() { + return Ok(()); + } + if !takes_graphics(id) { + return Err(NOT_TAKEN.into()); + } + if list.len() > MAX_GRAPHICS { + return Err(format!("`{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics")); + } + for v in list { + let g = MappedGraphic::from_value(v)?; + if id == super::ROTATE && g.face == PlanarFace::Back { + return Err("A plane has one face: map its graphics onto the front".into()); + } + if id == crate::REVOLVE && g.face == PlanarFace::Back { + return Err("Revolve maps graphics onto its side: map them onto the front".into()); + } + } + Ok(()) +} + +/// The first symbol the graphics in `p` name that `doc` does not have, leaving out the symbols the +/// graphics in `old` (the effect's parameters before an edit) already name: a graphic whose symbol +/// was deleted may stay. +pub fn missing_symbol(doc: &Document, p: &Value, old: Option<&Value>) -> Option<String> { + let kept = old.map(mapped_graphics).unwrap_or_default(); + mapped_graphics(p) + .into_iter() + .map(|g| g.symbol) + .find(|name| !doc.symbols.iter().any(|s| s.name == *name) && !kept.iter().any(|g| g.symbol == *name)) +} + +/// Does the art of the symbols the graphics in `p` name fit the limits? A graphic whose symbol +/// `doc` does not have draws nothing and is not counted. With a perspective, each curve counts as +/// the [`PERSPECTIVE_PIECES`] pieces it is cut into; without one, it counts once. +pub fn validate_symbols(doc: &Document, p: &Value) -> Result<(), String> { + let curve = if super::view_options(p).perspective > 0.0 { PERSPECTIVE_PIECES } else { 1 }; + let mut elements = 0usize; + for g in mapped_graphics(p) { + let Some(symbol) = doc.symbols.iter().find(|s| s.name == g.symbol) else { continue }; + let pieces = pieces_of(doc, symbol)?; + elements = elements.saturating_add(pieces.iter().map(|p| drawn_elements(&p.path, curve)).sum()); + if elements > MAX_ELEMENTS { + return Err("The graphics are too complex: simplify the symbols' art".into()); + } + } + Ok(()) +} + +/// The path elements `path` draws when each curve draws `curve` elements, before curves near the +/// eye are split further: one for each straight line, move and close. +fn drawn_elements(path: &PathData, curve: usize) -> usize { + let segments = |s: &SubPath| (0..s.segment_count()).map(|i| if s.segment_is_line(i) { 1 } else { curve }).sum::<usize>(); + path.subpaths.iter().map(|s| 1 + usize::from(s.closed) + segments(s)).sum() +} + +/// One area of a graphic's art, drawn with one paint: a fill, or a stroke's outline. +struct Piece { + path: PathData, + rule: FillRule, + paint: Paint, + opacity: f32, + blend: BlendMode, +} + +/// The areas the art of `symbol` paints, back to front, at the symbol's natural size: the fills of +/// its paths, compound paths and type (as outlines), and its strokes' outlines, through the symbol +/// instances it holds (with their changes to dynamic symbols, and through 9-slice guides). Hidden objects, guides, clipping paths and images are left out, and clipping +/// groups draw their art unclipped. +fn pieces_of(doc: &Document, symbol: &Symbol) -> Result<Vec<Piece>, String> { + fn walk(doc: &Document, n: &Node, outer: f32, xf: Affine, (depth, level): (usize, usize), out: &mut Vec<Piece>) -> Result<(), String> { + if !n.visible || n.is_guide() { + return Ok(()); + } + if level > MAX_LEVELS { + return Err(format!("A graphic's art may be nested at most {MAX_LEVELS} levels deep: simplify the symbol's art")); + } + let opacity = outer * n.opacity; + let shape = match &n.kind { + NodeKind::Path { path, rule, clipping: false, .. } => Some((path.clone(), *rule)), + NodeKind::Compound { children, rule } => { + Some((PathData::new(children.iter().filter_map(|c| c.path_data()).flat_map(|p| p.subpaths.iter().cloned()).collect()), *rule)) + } + NodeKind::Text(_) => { + if let Some(mut outlined) = crate::outline_text(n) { + // The outlines take the type's place, with its opacity. + outlined.visible = true; + outlined.opacity = n.opacity; + walk(doc, &outlined, outer, xf, (depth, level + 1), out)?; + } + None + } + NodeKind::SymbolInstance { symbol, xf: at } => { + if let Some(s) = doc.symbols.iter().find(|s| s.name == *symbol) { + if depth >= MAX_NESTING { + return Err(format!("A graphic's art may nest symbols at most {MAX_NESTING} levels deep: simplify the symbol's art")); + } + // The instance shows its own changes to a dynamic symbol's art, and a symbol + // with 9-slice guides is placed through them, as the canvas draws it. The + // pieces are not clipped, so paths that cross a guide are cut at it. + let art = vectorcraft_doc::symbol_overrides::dynamic_art(&s.art, n); + if doc.symbol_slice_map(symbol, *at).is_some() { + let Some(placed) = doc.place_symbol_art_unclipped(symbol, &art, *at) else { + return Err("A graphic's art holds too many objects: simplify the symbol's art".into()); + }; + walk(doc, &placed, opacity, xf, (depth + 1, level + 1), out)?; + } else { + walk(doc, &art, opacity, xf * *at, (depth + 1, level + 1), out)?; + } + } + None + } + _ => { + for c in n.children().into_iter().flatten() { + walk(doc, c, opacity, xf, (depth, level + 1), out)?; + } + None + } + }; + let Some((path, rule)) = shape else { return Ok(()) }; + // Symbol art keeps its strokes' widths as drawn while its geometry is scaled to the + // symbol's square, so a stroke is outlined after the art takes its size. + let path = path.transformed(xf); + for item in n.appearance.items.iter().filter(|i| i.visible()) { + let (area, rule, paint, item_opacity, blend) = match item { + AppearanceItem::Fill(f) => (path.clone(), rule, f.paint.clone(), f.opacity, f.blend), + AppearanceItem::Stroke(s) if s.width > 0.0 && s.width.is_finite() => { + (crate::stroke::outline_region(&path, rule, s), FillRule::EvenOdd, s.paint.clone(), s.opacity, s.blend) + } + AppearanceItem::Stroke(_) => continue, + }; + if matches!(paint, Paint::None) || area.bounds().is_none() { + continue; + } + if out.len() >= MAX_PIECES { + return Err(format!("A graphic draws at most {MAX_PIECES} fills and strokes: simplify the symbol's art")); + } + // A placed gradient or pattern takes the same size and place as its path. + let mut paint = paint; + match &mut paint { + Paint::Gradient(g) => g.transform(xf), + Paint::Pattern { xf: placed, .. } => *placed = xf * *placed, + Paint::None | Paint::Solid { .. } => {} + } + out.push(Piece { path: area, rule, paint, opacity: opacity * item_opacity, blend }); + } + Ok(()) + } + let mut out = vec![]; + walk(doc, &symbol.art, 1.0, doc.symbol_natural_xf(&symbol.name), (0, 1), &mut out)?; + Ok(out) +} + +/// `path` through `map`: exactly for an affine map, otherwise with each curve cut into +/// [`PERSPECTIVE_PIECES`] pieces whose control points go through it (straight lines stay straight +/// under a perspective). Fails when part of it has no page point, or when it takes more than `room` +/// elements. +fn map_path(path: &PathData, map: &FaceMap, affine: Option<Affine>, room: usize) -> Result<BezPath, NotMapped> { + let bp = path.to_bezpath(); + if let Some(a) = affine { + return if bp.elements().len() <= room { Ok(a * bp) } else { Err(NotMapped::Full) }; + } + let to = |p: Point| map.to_page(p).ok_or(NotMapped::Behind); + let mut out = BezPath::new(); + let mut at = Point::ZERO; + for el in bp.elements() { + if out.elements().len() > room { + return Err(NotMapped::Full); + } + match *el { + PathEl::MoveTo(p) => { + out.move_to(to(p)?); + at = p; + } + PathEl::LineTo(p) => { + out.line_to(to(p)?); + at = p; + } + PathEl::QuadTo(c, p) => { + cubic_to(&mut out, vectorcraft_geom::kurbo::QuadBez::new(at, c, p).raise(), map).ok_or(NotMapped::Behind)?; + at = p; + } + PathEl::CurveTo(c1, c2, p) => { + cubic_to(&mut out, CubicBez::new(at, c1, c2, p), map).ok_or(NotMapped::Behind)?; + at = p; + } + PathEl::ClosePath => out.close_path(), + } + } + if out.elements().len() <= room { Ok(out) } else { Err(NotMapped::Full) } +} + +/// Why [`map_path`] drew nothing. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum NotMapped { + /// Part of the path has no page point: it is at or behind the eye. + Behind, + /// The path takes more elements than it has room for. + Full, +} + +/// Curve `c` through `map`, cut into [`PERSPECTIVE_PIECES`] pieces. A piece that lies in front of +/// the eye while a control point does not is split further ([`piece_to`]). `None` when part of a +/// piece has no page point. +fn cubic_to(out: &mut BezPath, c: CubicBez, map: &FaceMap) -> Option<()> { + for k in 0..PERSPECTIVE_PIECES { + let (t0, t1) = (k as f64 / PERSPECTIVE_PIECES as f64, (k + 1) as f64 / PERSPECTIVE_PIECES as f64); + let s = c.subsegment(t0..t1); + if !map.maps_curve([s.p0, s.p1, s.p2, s.p3]) { + return None; + } + piece_to(out, s, map, MAX_SPLITS)?; + } + Some(()) +} + +/// How many times [`piece_to`] halves a piece whose control points are behind the eye. +const MAX_SPLITS: usize = 4; + +/// Piece `s`, which lies in front of the eye, through `map`: halved until the control points of +/// each half have page points, at most `splits` times, and drawn straight past that. +fn piece_to(out: &mut BezPath, s: CubicBez, map: &FaceMap, splits: usize) -> Option<()> { + let end = map.to_page(s.p3)?; + match (map.to_page(s.p1), map.to_page(s.p2)) { + (Some(c1), Some(c2)) => out.curve_to(c1, c2, end), + _ if splits == 0 => out.line_to(end), + _ => { + let (a, b) = s.subdivide(); + piece_to(out, a, map, splits - 1)?; + piece_to(out, b, map, splits - 1)?; + } + } + Some(()) +} + +/// The graphics `graphics` lists for `face`, drawn on caps `caps` (the faces of that end of the +/// object's solids that the viewer sees) through `map`, for an object whose bounds have +/// center `center`: one clipping group of every such graphic, shaded with the first cap's light. +/// Pattern tiles keep their colors: the document's pattern draws them. A graphic whose symbol +/// `doc` does not have draws nothing. `elements` counts the path elements +/// the effect's graphics have drawn so far, after a perspective cuts their curves, and is shared by +/// every call for one effect. `None` when there is nothing to draw or that count passes +/// [`MAX_ELEMENTS`]. +pub(super) fn face_art( + doc: Option<&Document>, + id: NodeId, + graphics: &[MappedGraphic], + (face, map): (PlanarFace, &FaceMap), + center: Point, + caps: &[&Facet], + elements: &mut usize, +) -> Option<Node> { + let doc = doc?; + let light = caps.first()?.illumination; + let affine = map.local_affine(center).filter(|_| map.is_affine()); + let mut children = vec![]; + for g in graphics.iter().filter(|g| g.face == face) { + let Some(symbol) = doc.symbols.iter().find(|s| s.name == g.symbol) else { continue }; + // A symbol past the limits is left out; the other graphics still draw. + let Ok(pieces) = pieces_of(doc, symbol) else { continue }; + let Some(bounds) = pieces.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b)) else { continue }; + let place = g.placement(bounds, center); + // Gradients follow the face's map as it is near the graphic's center. + let middle = place * bounds.center(); + // When the center is at or behind the eye, they follow it near the middle of the part that + // is in front; a graphic with no part in front is left out. + let local = map.local_affine(middle).or_else(|| { + let part = map.mapped_part(place.transform_rect_bbox(bounds))?; + let sum = part.iter().fold(Point::ZERO, |s, p| s + p.to_vec2()); + map.local_affine(Point::new(sum.x / part.len() as f64, sum.y / part.len() as f64)) + }); + let Some(local) = local else { continue }; + let gradient_map = local * place; + for piece in pieces { + let placed = piece.path.transformed(place); + // Each anchor draws at least one element. A perspective cuts curves into more, and + // straight lines stay one each: the path may take what is left of the limit, and is + // counted as it is drawn. Past the limit, the face draws nothing. + let least: usize = placed.subpaths.iter().map(|s| s.anchors.len()).sum(); + let before = *elements; + if before.saturating_add(least) > MAX_ELEMENTS { + return None; + } + let room = MAX_ELEMENTS - before; + let mut rule = piece.rule; + let mapped = match map_path(&placed, map, affine, room) { + Err(NotMapped::Behind) => { + // Part of it is at or behind the eye: the part in front is drawn. + let Some(part) = placed.bounds().and_then(|b| map.mapped_part(b)) else { continue }; + let Some(&first) = part.first() else { continue }; + let mut front = BezPath::new(); + front.move_to(first); + part.iter().skip(1).for_each(|p| front.line_to(*p)); + front.close_path(); + let cut = vectorcraft_pathops::boolean( + &placed, + piece.rule, + &PathData::from_bezpath(&front), + FillRule::NonZero, + vectorcraft_pathops::BoolOp::Intersect, + ); + rule = FillRule::NonZero; + map_path(&cut, map, affine, room) + } + done => done, + }; + let mapped = match mapped { + Ok(mapped) => mapped, + Err(NotMapped::Full) => return None, + Err(NotMapped::Behind) => continue, + }; + *elements = before.saturating_add(mapped.elements().len()); + let mut paint = piece.paint; + vectorcraft_doc::recolor::map_paint(&mut paint, &|c| crate::lighting::shade(c, light)); + // A pattern's tiles follow the graphic onto the face, as its gradients do below. + if let Paint::Pattern { xf, .. } = &mut paint { + *xf = gradient_map * *xf; + } + let mut fill = FillLayer::new(paint); + fill.opacity = piece.opacity; + fill.blend = piece.blend; + let mut appearance = Appearance { items: vec![AppearanceItem::Fill(fill)], ..Default::default() }; + appearance.transform_gradients(gradient_map); + let mut node = Node::path(id, PathData::from_bezpath(&mapped), appearance); + if let NodeKind::Path { rule: r, .. } = &mut node.kind { + *r = rule; + } + children.push(Arc::new(node)); + } + } + if children.is_empty() { + return None; + } + let mut clip = BezPath::new(); + for cap in caps { + // A cap's holes are contours of the same path wound against its outline, so turning the + // whole path keeps them holes under the nonzero rule. + let mut outline = cap.path().to_bezpath(); + if outline.area() < 0.0 { + outline = outline.reverse_subpaths(); + } + clip.extend(outline.iter()); + } + let clip = Node::path(id, PathData::from_bezpath(&clip), Appearance::default()); + Some(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, children))], clip: true })) +} + +/// One area of a graphic placed on Revolve's unrolled side surface, cut into straight pieces. +struct Unrolled { + polygons: Vec<Vec<Point>>, + /// The bounds of each of `polygons`. + boxes: Vec<Rect>, + bounds: Rect, + rule: FillRule, + paint: Paint, + opacity: f32, + blend: BlendMode, + /// Where the graphic's art goes on the surface: its gradients and patterns are placed with it. + place: Affine, +} + +/// The areas of `graphics` (those of the front: Revolve's side) placed on the unrolled side +/// surface, cut into straight pieces. A graphic whose symbol `doc` does not have, or whose art is +/// past the limits of [`pieces_of`], is left out. `None` when the pieces take more than +/// [`MAX_ELEMENTS`] points together. +fn unrolled(doc: &Document, graphics: &[MappedGraphic]) -> Option<Vec<Unrolled>> { + let mut pieces = vec![]; + let mut points = 0usize; + for g in graphics.iter().filter(|g| g.face == PlanarFace::Front) { + let Some(symbol) = doc.symbols.iter().find(|s| s.name == g.symbol) else { continue }; + let Ok(art) = pieces_of(doc, symbol) else { continue }; + let Some(bounds) = art.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b)) else { continue }; + let place = g.placement(bounds, Point::ZERO); + for piece in art { + let placed = place * piece.path.to_bezpath(); + let mut polygons = straight_pieces(&placed, &mut points)?; + polygons.retain(|p| p.len() >= 3 && p.iter().all(|q| q.is_finite())); + let boxes: Vec<Rect> = + polygons.iter().filter_map(|polygon| polygon.iter().map(|p| Rect::from_points(*p, *p)).reduce(|a, b| a.union(b))).collect(); + let Some(bounds) = boxes.iter().copied().reduce(|a, b| a.union(b)) else { continue }; + pieces.push(Unrolled { + polygons, + boxes, + bounds, + rule: piece.rule, + paint: piece.paint, + opacity: piece.opacity, + blend: piece.blend, + place, + }); + } + } + Some(pieces) +} + +/// The contours of `path` cut into straight pieces within [`SURFACE_TOLERANCE`], adding the points +/// made to `points`. Each curve is cut on its own and the count is checked before the next one, so +/// the work stops at the first curve past [`MAX_ELEMENTS`] points: `None` then, and for a path with +/// a coordinate of a line or a curve farther than [`SURFACE_REACH`] from the origin, which bounds +/// the pieces of one curve and the arithmetic of the cuts at the faces. +fn straight_pieces(path: &BezPath, points: &mut usize) -> Option<Vec<Vec<Point>>> { + let near = |p: &Point| p.x.abs() <= SURFACE_REACH && p.y.abs() <= SURFACE_REACH; + let mut polygons: Vec<Vec<Point>> = vec![]; + let mut current: Vec<Point> = vec![]; + let (mut start, mut last) = (Point::ZERO, Point::ZERO); + for el in path.elements() { + if *points > MAX_ELEMENTS { + return None; + } + match *el { + PathEl::MoveTo(p) | PathEl::LineTo(p) if !near(&p) => return None, + PathEl::MoveTo(p) => { + polygons.push(std::mem::take(&mut current)); + current.push(p); + *points += 1; + (start, last) = (p, p); + } + PathEl::LineTo(p) => { + current.push(p); + *points += 1; + last = p; + } + PathEl::ClosePath => { + polygons.push(std::mem::take(&mut current)); + last = start; + } + PathEl::QuadTo(a, p) | PathEl::CurveTo(_, a, p) => { + let first = if let PathEl::CurveTo(b, ..) = *el { b } else { a }; + if ![last, first, a, p].iter().all(near) { + return None; + } + vectorcraft_geom::kurbo::flatten([PathEl::MoveTo(last), *el], SURFACE_TOLERANCE, |cut| { + if let PathEl::LineTo(q) = cut { + current.push(q); + *points += 1; + } + }); + last = p; + } + } + } + polygons.push(current); + (*points <= MAX_ELEMENTS).then_some(polygons) +} + +/// Do the graphics in Revolve parameters `p` fit the limits with the symbols of `doc`? Their art, +/// cut into straight pieces on the side surface, may take up to [`MAX_ELEMENTS`] points together. +pub(crate) fn validate_surface_symbols(doc: &Document, p: &Value) -> Result<(), String> { + let list = mapped_graphics(p); + if list.is_empty() || unrolled(doc, &list).is_some() { + return Ok(()); + } + Err("The graphics are too complex: simplify the symbols' art".into()) +} + +/// The parts of `graphics` that fall on each of `faces`, a revolved surface's faces in drawing +/// order, for an object with id `id`: for each face, the nodes to draw right after it. Only faces +/// of the swept side that show their outside to the viewer carry a part, so a graphic narrows +/// toward the silhouette, is hidden past it and is covered by the nearer faces drawn after it. +/// `shade` gives the paint of a solid color on a face, as the surface under it is shaded; the +/// colors of gradients and patterns are multiplied by the face's light. A graphic whose symbol +/// `doc` does not have, or that is past the limits of its art, draws nothing. `None` past +/// [`MAX_ELEMENTS`] points together before they are cut at the faces, [`MAX_SURFACE_POINTS`] +/// after, [`MAX_SURFACE_CUTS`] points cut, or when the copies of their paints in the parts take +/// `copies`, the bytes of the copies of the object's graphics so far, past Revolve's budget for +/// them: commands refuse such graphics, and a loaded file draws the surface without them. +pub(crate) fn surface_parts( + doc: Option<&Document>, + id: NodeId, + graphics: &[MappedGraphic], + faces: &[vectorcraft_three_d::Face], + shade: &dyn Fn(&vectorcraft_three_d::Face, vectorcraft_doc::color::Color) -> Paint, + copies: &mut usize, +) -> Option<Vec<Vec<Arc<Node>>>> { + let mut out: Vec<Vec<Arc<Node>>> = vec![vec![]; faces.len()]; + let Some(doc) = doc else { return Some(out) }; + let pieces = unrolled(doc, graphics)?; + let Some(all) = pieces.iter().map(|p| p.bounds).reduce(|a, b| a.union(b)) else { return Some(out) }; + // Each piece listed in the buckets of the surface's x its bounds reach across. + let width = (all.width() / SURFACE_BUCKETS as f64).max(1e-9); + let bucket = |x: f64| (((x - all.x0) / width).floor().max(0.0) as usize).min(SURFACE_BUCKETS - 1); + let mut buckets: Vec<Vec<usize>> = vec![vec![]; SURFACE_BUCKETS]; + for (k, p) in pieces.iter().enumerate() { + for b in buckets.get_mut(bucket(p.bounds.x0)..=bucket(p.bounds.x1)).into_iter().flatten() { + b.push(k); + } + } + let mut seen = vec![usize::MAX; pieces.len()]; + let mut drawn = 0usize; + let mut cut_points = 0usize; + let mut triangle_id = 0usize; + for (face, parts) in faces.iter().zip(out.iter_mut()) { + let Some(cell) = face.surface.as_ref().filter(|c| c.outward && !face.cap) else { continue }; + if cell.uv.len() != cell.page.len() || !(3..=4).contains(&cell.uv.len()) { + continue; + } + let triangles: &[[usize; 3]] = if cell.uv.len() == 3 { &[[0, 1, 2]] } else { &[[0, 1, 2], [0, 2, 3]] }; + for corners in triangles { + triangle_id += 1; + let pick = |of: &[Point]| corners.iter().map(|k| of.get(*k).copied()).collect::<Option<Vec<Point>>>(); + let (Some(uv), Some(page)) = (pick(&cell.uv), pick(&cell.page)) else { continue }; + let (Some(map), Some(window)) = (triangle_map(&uv, &page), counterclockwise(&uv)) else { continue }; + // A face along an end cap's ring has that edge curved on the page: its parts are cut + // from a larger triangle and then to the face's own outline, so they reach the curve + // where the graphic runs past the end of the profile. A four-cornered face is cut into + // two triangles along its diagonal from corner 0 to corner 2: each takes the part of + // the outline on its own side of it. + let window = if face.outline.is_some() { grown(window, 3.0) } else { window }; + // The pieces are looked up over the whole of the window they are cut to. + let Some(reach) = window.iter().map(|p| Rect::from_points(*p, *p)).reduce(|a, b| a.union(b)) else { continue }; + if reach.x1 < all.x0 || reach.x0 > all.x1 || reach.y1 < all.y0 || reach.y0 > all.y1 { + continue; + } + // The pieces near the triangle, each once, in the graphics' drawing order. + let mut near = vec![]; + for b in buckets.get(bucket(reach.x0)..=bucket(reach.x1)).into_iter().flatten() { + for &k in b { + let Some(slot) = seen.get_mut(k) else { continue }; + if *slot != triangle_id { + *slot = triangle_id; + near.push(k); + } + } + } + near.retain(|k| { + pieces + .get(*k) + .is_some_and(|p| p.bounds.x1 >= reach.x0 && p.bounds.x0 <= reach.x1 && p.bounds.y1 >= reach.y0 && p.bounds.y0 <= reach.y1) + }); + if near.is_empty() { + continue; + } + near.sort_unstable(); + let own = corners.iter().find(|k| **k != 0 && **k != 2).and_then(|k| cell.page.get(*k)).filter(|_| triangles.len() == 2); + let rim = face.outline.as_ref().map(|outline| match (own, cell.page.first(), cell.page.get(2)) { + (Some(&toward), Some(&a), Some(&b)) => { + let side = side_of(a, b, toward); + vectorcraft_pathops::boolean(outline, FillRule::NonZero, &side, FillRule::NonZero, vectorcraft_pathops::BoolOp::Intersect) + } + _ => outline.clone(), + }); + let rim = rim.as_ref(); + for k in near { + let Some(piece) = pieces.get(k) else { continue }; + let mut path = BezPath::new(); + // Each contour is cut only where its own bounds reach the triangle. + for (polygon, b) in piece.polygons.iter().zip(&piece.boxes) { + if b.x1 < reach.x0 || b.x0 > reach.x1 || b.y1 < reach.y0 || b.y0 > reach.y1 { + continue; + } + cut_points = cut_points.saturating_add(polygon.len()); + if cut_points > MAX_SURFACE_CUTS { + return None; + } + let cut = clip_to(polygon, &window); + let Some((first, rest)) = cut.split_first() else { continue }; + path.move_to(map * *first); + rest.iter().for_each(|q| path.line_to(map * *q)); + path.close_path(); + drawn = drawn.saturating_add(cut.len()); + } + if drawn > MAX_SURFACE_POINTS { + return None; + } + if path.elements().is_empty() { + continue; + } + let (path, rule) = match rim { + Some(outline) => { + let cut = vectorcraft_pathops::boolean( + &PathData::from_bezpath(&path), + piece.rule, + outline, + FillRule::NonZero, + vectorcraft_pathops::BoolOp::Intersect, + ); + (cut.to_bezpath(), FillRule::NonZero) + } + None => (path, piece.rule), + }; + if path.elements().is_empty() { + continue; + } + // Each part copies its paint into its fill, and into the stroke over its seams when + // it takes one. + if !crate::revolve::paint_copies_add(copies, 1 + usize::from(takes_seam(piece)), &piece.paint) { + return None; + } + parts.push(Arc::new(surface_piece(id, piece, (path, rule), map, face, shade))); + } + } + } + Some(out) +} + +/// The node of the part `path` (on the page, filled under `rule`) of `piece`, which `map` takes +/// from the unrolled surface onto `face`. +fn surface_piece( + id: NodeId, + piece: &Unrolled, + (path, rule): (BezPath, FillRule), + map: Affine, + face: &vectorcraft_three_d::Face, + shade: &dyn Fn(&vectorcraft_three_d::Face, vectorcraft_doc::color::Color) -> Paint, +) -> Node { + let gradient_map = map * piece.place; + // Under several lights a face's light varies across it in each channel: a solid color draws + // as the face's own lit art in that color, clipped to the part. An opaque part also draws that + // art clipped to a band of the seam stroke's width around its edges, as the other parts take + // a stroke over their seams. + if let (Some(c), Some(light)) = (piece.paint.color().filter(|_| matches!(piece.paint, Paint::Solid { .. })), face.rgb_gradient) { + let lit = Arc::new(crate::lighting::rgb_gradient_art(id, &face.path(), &Paint::solid(c), light)); + let clipped = |area: &BezPath, rule: FillRule| { + let mut clip = Node::path(id, PathData::from_bezpath(area), Appearance::default()); + if let NodeKind::Path { rule: r, .. } = &mut clip.kind { + *r = rule; + } + Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), lit.clone()], clip: true }) + }; + let mut group = clipped(&path, rule); + if takes_seam(piece) { + let style = vectorcraft_geom::kurbo::Stroke::new(SURFACE_SEAM).with_join(vectorcraft_geom::kurbo::Join::Round); + let band = vectorcraft_geom::kurbo::stroke(path.iter(), &style, &vectorcraft_geom::kurbo::StrokeOpts::default(), SURFACE_TOLERANCE); + group = Node::group(id, vec![Arc::new(group), Arc::new(clipped(&band, FillRule::NonZero))]); + } + group.opacity = piece.opacity; + group.blend = piece.blend; + return group; + } + let mut paint = piece.paint.clone(); + if let Paint::Pattern { xf, .. } = &mut paint { + *xf = gradient_map * *xf; + } + let solid = paint.color().filter(|_| matches!(paint, Paint::Solid { .. })); + let mut fill = FillLayer::new(paint); + fill.opacity = piece.opacity; + fill.blend = piece.blend; + let mut appearance = Appearance { items: vec![AppearanceItem::Fill(fill)], ..Default::default() }; + appearance.transform_gradients(gradient_map); + for item in appearance.items.iter_mut() { + if let AppearanceItem::Fill(f) = item { + match solid { + Some(c) => f.paint = shade(face, c), + None => { + vectorcraft_doc::recolor::map_paint(&mut f.paint, &|c| crate::lighting::shade(c, face.illumination)); + } + } + } + } + // Parts on neighboring faces meet edge to edge: an opaque part takes a narrow stroke of its + // paint over the seam, as the faces do. + if takes_seam(piece) + && let Some(AppearanceItem::Fill(f)) = appearance.items.first() + { + let mut seam = vectorcraft_doc::StrokeLayer::new(f.paint.clone(), SURFACE_SEAM); + seam.join = vectorcraft_doc::LineJoin::Round; + appearance.items.push(AppearanceItem::Stroke(seam)); + } + let mut node = Node::path(id, PathData::from_bezpath(&path), appearance); + if let NodeKind::Path { rule: r, .. } = &mut node.kind { + *r = rule; + } + node +} + +/// Does each part of `piece` take a stroke of its paint over its seams? Only an opaque part does: +/// the overlap of a transparent one, of one whose gradient has a stop or a freeform point that is +/// not fully opaque, or of a pattern, whose tile may hold transparent art, would show. +fn takes_seam(piece: &Unrolled) -> bool { + let clear = match &piece.paint { + Paint::Gradient(g) => { + g.gradient.stops.iter().any(|s| s.opacity < 1.0) || g.freeform.as_ref().is_some_and(|f| f.points.iter().any(|p| p.opacity < 1.0)) + } + Paint::Pattern { .. } => true, + _ => false, + }; + piece.opacity >= 1.0 && piece.blend == BlendMode::Normal && !clear +} + +/// A region far larger than the face on the side of the line through `a` and `b` that `toward` is +/// on: a rectangle with one edge along the line, reaching a thousand times the line's length past +/// its ends and away from it. +fn side_of(a: Point, b: Point, toward: Point) -> PathData { + let along = b - a; + let mut across = Vec2::new(-along.y, along.x); + if across.dot(toward - a) < 0.0 { + across = -across; + } + let (far, wide) = (across * 1000.0, along * 1000.0); + let mut out = BezPath::new(); + out.move_to(a - wide); + out.line_to(b + wide); + out.line_to(b + wide + far); + out.line_to(a - wide + far); + out.close_path(); + PathData::from_bezpath(&out) +} + +/// Triangle `t` scaled by `factor` about its centroid, wound as it was. +fn grown(t: [Point; 3], factor: f64) -> [Point; 3] { + let c = Point::new((t[0].x + t[1].x + t[2].x) / 3.0, (t[0].y + t[1].y + t[2].y) / 3.0); + t.map(|p| c + (p - c) * factor) +} + +/// The affine map that takes the corners `from` of a triangle onto `to`. `None` for a triangle +/// with no area or a map that is not finite. +fn triangle_map(from: &[Point], to: &[Point]) -> Option<Affine> { + let ([u0, u1, u2], [p0, p1, p2]) = (<[Point; 3]>::try_from(from).ok()?, <[Point; 3]>::try_from(to).ok()?); + let (a, b) = (u1 - u0, u2 - u0); + let det = a.x * b.y - b.x * a.y; + if det.abs() <= 1e-12 * (a.hypot2() + b.hypot2()).max(1e-300) { + return None; + } + let (c, d) = (p1 - p0, p2 - p0); + let m = [(c.x * b.y - d.x * a.y) / det, (c.y * b.y - d.y * a.y) / det, (d.x * a.x - c.x * b.x) / det, (d.y * a.x - c.y * b.x) / det]; + let xf = Affine::new([m[0], m[1], m[2], m[3], p0.x - m[0] * u0.x - m[2] * u0.y, p0.y - m[1] * u0.x - m[3] * u0.y]); + xf.as_coeffs().iter().all(|v| v.is_finite()).then_some(xf) +} + +/// Triangle `t` wound counterclockwise (y up), as [`clip_to`] reads its window. `None` without +/// three corners. +fn counterclockwise(t: &[Point]) -> Option<[Point; 3]> { + let [a, b, c] = <[Point; 3]>::try_from(t).ok()?; + Some(if (b - a).cross(c - a) < 0.0 { [a, c, b] } else { [a, b, c] }) +} + +/// The part of `polygon` inside the convex `window` (one step of Sutherland and Hodgman's clip for +/// each of its edges). A polygon that is not convex keeps its area, with edges along the window's +/// sides where it leaves and comes back. +fn clip_to(polygon: &[Point], window: &[Point; 3]) -> Vec<Point> { + let mut out = polygon.to_vec(); + for k in 0..3 { + let (a, b) = (window[k], window[(k + 1) % 3]); + let side = |p: Point| (b - a).cross(p - a); + let input = std::mem::take(&mut out); + for (i, &p) in input.iter().enumerate() { + let q = input[(i + 1) % input.len()]; + let (sp, sq) = (side(p), side(q)); + if sp >= 0.0 { + out.push(p); + } + if (sp >= 0.0) != (sq >= 0.0) { + out.push(p.lerp(q, sp / (sp - sq))); + } + } + if out.len() < 3 { + return vec![]; + } + } + out +} + +/// The bounds of the art symbol `name` of `doc` draws as a graphic, in the symbol's coordinates. +pub(super) fn art_bounds(doc: &Document, name: &str) -> Option<Rect> { + let symbol = doc.symbols.iter().find(|s| s.name == name)?; + pieces_of(doc, symbol).ok()?.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b)) +} + +/// Where a 3D object's graphics are drawn: the bounds its solids are built with (the graphics' +/// offsets are from their center) and the maps of its front and back faces, when it has them. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct GraphicFrame { + pub bounds: Rect, + front: Option<FaceMap>, + back: Option<FaceMap>, +} + +impl GraphicFrame { + pub(super) fn new(bounds: Rect, front: Option<FaceMap>, back: Option<FaceMap>) -> Self { + Self { bounds, front, back } + } + + pub fn map(&self, face: PlanarFace) -> Option<&FaceMap> { + match face { + PlanarFace::Front => self.front.as_ref(), + PlanarFace::Back => self.back.as_ref(), + } + } + + /// The point of `face`'s plane that offset `(x, y)` names, as [`MappedGraphic`] places a + /// graphic's center. + fn art_point(&self, face: PlanarFace, (x, y): (f64, f64)) -> Point { + let c = self.bounds.center(); + match face { + PlanarFace::Front => Point::new(c.x + x, c.y + y), + PlanarFace::Back => Point::new(c.x - x, c.y + y), + } + } + + /// Where graphic `g`'s center lands on the page, and whether its face is turned toward the + /// viewer. `None` when the object has no such face or the point has no page point. + pub fn handle(&self, g: &MappedGraphic) -> Option<(Point, bool)> { + let map = self.map(g.face)?; + Some((map.to_page(self.art_point(g.face, (g.x, g.y)))?, map.visible)) + } + + /// The offset of a graphic on `face` whose center lands on page point `page`. + pub fn offset_at(&self, face: PlanarFace, page: Point) -> Option<(f64, f64)> { + let art = self.map(face)?.to_art(page)?; + let c = self.bounds.center(); + let (x, y) = match face { + PlanarFace::Front => (art.x - c.x, art.y - c.y), + PlanarFace::Back => (c.x - art.x, art.y - c.y), + }; + (x.abs() <= MAX_OFFSET && y.abs() <= MAX_OFFSET).then_some((x, y)) + } + + /// The scale (percent) at which art with bounds `art` fits inside the object's bounds, at most + /// 100: where a newly mapped graphic starts. + pub fn fitting_scale(&self, art: Rect) -> f64 { + let fit = (self.bounds.width() / art.width().max(1e-9)).min(self.bounds.height() / art.height().max(1e-9)); + (fit * 100.0).clamp(SCALE_RANGE.0, 100.0) + } +} + +/// The symbols the graphics of `n`'s 3D effects name (its own effects and its fills' and strokes'). +pub fn graphic_symbols(n: &Node) -> Vec<String> { + appearance_graphic_symbols(&n.appearance) +} + +/// The symbols the graphics of the 3D effects in `appearance` name, as [`graphic_symbols`]: for a +/// graphic style's appearance. +pub fn appearance_graphic_symbols(appearance: &Appearance) -> Vec<String> { + std::iter::once(&appearance.effects) + .chain(appearance.items.iter().map(AppearanceItem::effects)) + .flatten() + .filter(|e| takes_graphics(&e.id)) + .flat_map(|e| mapped_graphics(&e.params)) + .map(|g| g.symbol) + .collect() +} + +/// Makes the graphics of `n`'s 3D effects that name symbol `from` name `to` instead. Returns +/// whether any changed. +pub fn rename_graphic_symbol(n: &mut Node, from: &str, to: &str) -> bool { + // Checked first, so an appearance that names another symbol is not copied. + graphic_symbols(n).iter().any(|s| s == from) && rename_appearance_graphic_symbol(&mut n.appearance, from, to) +} + +/// [`rename_graphic_symbol`] for the 3D effects in `appearance`: for a graphic style's appearance. +pub fn rename_appearance_graphic_symbol(appearance: &mut Appearance, from: &str, to: &str) -> bool { + if !appearance_graphic_symbols(appearance).iter().any(|s| s == from) { + return false; + } + let mut lists: Vec<&mut Vec<vectorcraft_doc::Effect>> = vec![]; + let (effects, items) = (&mut appearance.effects, &mut appearance.items); + lists.push(effects); + lists.extend(items.iter_mut().map(AppearanceItem::effects_mut)); + for e in lists.into_iter().flatten().filter(|e| takes_graphics(&e.id)) { + if let Some(Value::Array(list)) = e.params.get_mut(GRAPHICS) { + for g in list.iter_mut() { + if g.get("symbol").and_then(Value::as_str) == Some(from) { + g["symbol"] = json!(to); + } + } + } + } + true +} + +/// Does `n` or any object in it, opacity masks included, have a graphic that names symbol `from`? +pub fn names_graphic_symbol(n: &Node, from: &str) -> bool { + let mut found = false; + vectorcraft_doc::swatches::walk_with_masks(n, &mut |c| found |= graphic_symbols(c).iter().any(|s| s == from)); + found +} + +/// [`rename_graphic_symbol`] for `n` and every object in it, at any depth, opacity masks included. +/// Only the parts that name `from` are copied. Returns whether any changed. +pub fn rename_graphic_symbol_in(n: &mut Node, from: &str, to: &str) -> bool { + let names = names_graphic_symbol; + let mut changed = rename_graphic_symbol(n, from, to); + if let Some(mask) = n.extras_if_any().and_then(|x| x.mask.as_deref_mut()).filter(|m| names(&m.art, from)) { + changed |= rename_graphic_symbol_in(Arc::make_mut(&mut mask.art), from, to); + } + if let Some(children) = n.children_mut() { + for c in children.iter_mut().filter(|c| names(c, from)) { + changed |= rename_graphic_symbol_in(Arc::make_mut(c), from, to); + } + } + changed +} + +/// `p` with graphic `g` added at the end of its list. +pub fn with_graphic(p: &Value, g: &MappedGraphic) -> Value { + let mut out = p.as_object().cloned().unwrap_or_else(Map::new); + let mut list = match out.get(GRAPHICS) { + Some(Value::Array(list)) => list.clone(), + _ => vec![], + }; + list.push(g.to_value()); + out.insert(GRAPHICS.into(), Value::Array(list)); + Value::Object(out) +} + +#[cfg(test)] +#[path = "tests_graphics.rs"] +mod tests; diff --git a/crates/effects/src/solids/shadow.rs b/crates/effects/src/solids/shadow.rs new file mode 100644 index 0000000000..3906ac2d3c --- /dev/null +++ b/crates/effects/src/solids/shadow.rs @@ -0,0 +1,101 @@ +//! The shadow of the 3D and Materials effects (Extrude & Bevel, Inflate, Rotate and Revolve): the +//! `shadow` switch with `shadowPosition`, `shadowDistance` and `shadowBounds`, and the shape it +//! draws behind the solids. +use std::ops::Range; +use std::sync::Arc; + +use serde_json::Value; +use vectorcraft_doc::color::{BlendMode, Color, Paint}; +use vectorcraft_doc::{Appearance, AppearanceItem, FillLayer, Node, NodeId}; +use vectorcraft_three_d::{Shadow, ShadowCaster, ShadowPlane, ShadowPosition}; + +use super::Scope; +use crate::util::{flag, num, text}; + +/// The shadow's paint: black at this opacity. VectorCraft's own values. +const SHADOW_OPACITY: f32 = 0.5; + +/// The shadow `p` asks for, or `None` with the switch off or when the first light lights nothing +/// (Shading is off or its intensity is 0), so that no shadow is built. +pub(crate) fn options(p: &Value) -> Option<Shadow> { + let intensity = crate::lighting::lights(p).and_then(|l| l.iter().next().map(|l| l.intensity)).unwrap_or_else(|| num(p, "lightIntensity", 80.0)); + let lit = flag(p, "shade", true) && intensity > 0.0; + (lit && flag(p, "shadow", false)).then(|| Shadow { + position: ShadowPosition::parse(text(p, "shadowPosition", "behind")).unwrap_or_default(), + distance: num(p, "shadowDistance", 0.0) / 100.0, + bounds: num(p, "shadowBounds", 100.0) / 100.0, + }) +} + +/// Check the shadow settings in `p`: an error for a value out of its range or of the wrong kind. +pub(crate) fn validate(p: &Value) -> Result<(), String> { + if p.get("shadow").is_some_and(|v| !v.is_boolean()) { + return Err("shadow must be true or false".into()); + } + if p.get("shadowPosition").is_some_and(|v| v.as_str().and_then(ShadowPosition::parse).is_none()) { + return Err("shadowPosition must be behind or below".into()); + } + for (key, min, max) in [("shadowDistance", 0.0, 100.0), ("shadowBounds", 10.0, 400.0)] { + if p.get(key).is_some_and(|v| !v.as_f64().is_some_and(|n| n.is_finite() && (min..=max).contains(&n))) { + return Err(format!("{key} must be a number from {min} to {max}")); + } + } + Ok(()) +} + +/// The opacity and blending mode of the fill or stroke (and member) that casts part of a shadow. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Ink { + pub(crate) opacity: f32, + pub(crate) blend: BlendMode, +} + +/// The shadow of the faces in `caster` as a path of object `id`, cast by art in `ink`: filled +/// black at [`SHADOW_OPACITY`] times its opacity, in its blending mode, with the nonzero rule; +/// `None` when it casts nothing. +pub(crate) fn art(id: NodeId, caster: &ShadowCaster, shadow: Shadow, ink: Ink) -> Option<Node> { + let all = 0..caster.len(); + let all = std::slice::from_ref(&all); + piece(id, caster, &caster.shadow_plane(shadow, all)?, all, ink) +} + +/// [`art`] of the faces in the ranges `faces` of `caster` only, on `plane`. +fn piece(id: NodeId, caster: &ShadowCaster, plane: &ShadowPlane, faces: &[Range<usize>], ink: Ink) -> Option<Node> { + let path = caster.path_on(plane, faces)?; + let mut fill = FillLayer::new(Paint::solid(Color::BLACK)); + fill.opacity = SHADOW_OPACITY * ink.opacity.clamp(0.0, 1.0); + fill.blend = ink.blend; + Some(Node::path(id, path, Appearance { items: vec![AppearanceItem::Fill(fill)], ..Default::default() })) +} + +/// Whether `a` and `b` are the same objects' scopes (each member holds its own copies). +fn same_scopes(a: &[Scope], b: &[Scope]) -> bool { + a.len() == b.len() && a.iter().zip(b).all(|(a, b)| a.key == b.key) +} + +/// The faces one solid added to a caster, with the scopes of its member and the ink of its art. +pub(crate) type Cast<'a> = (&'a [Scope], Ink, Range<usize>); + +/// The faces of the solids that cast one piece of a shadow, with their scopes and ink. +type Run<'a> = (&'a [Scope], Ink, Vec<Range<usize>>); + +/// The shadow `cast` casts on one plane: the faces of `caster` that the solids of visible art +/// added, each range with the scopes of the member that cast it and the ink of the art, in order. +/// Each run of solids in the same ink casts a piece in that ink ([`art`]); with `masks` (a member's +/// opacity mask or blending mode applies to its solids) the solids of a run also share their scopes, +/// and each piece is drawn in their opacity masks and blending modes ([`super::masked`]). +pub(crate) fn scoped_art(id: NodeId, caster: &ShadowCaster, shadow: Shadow, cast: Vec<Cast<'_>>, masks: bool) -> Vec<Arc<Node>> { + let placing: Vec<Range<usize>> = cast.iter().map(|(.., faces)| faces.clone()).collect(); + let Some(plane) = caster.shadow_plane(shadow, &placing) else { return vec![] }; + // Consecutive solids in the same ink (and with masks, the same scopes) share a piece; the pieces + // keep the solids' order. + let mut runs: Vec<Run> = vec![]; + for (scopes, ink, faces) in cast { + match runs.last_mut() { + Some(run) if run.1 == ink && (!masks || same_scopes(run.0, scopes)) => run.2.push(faces), + _ => runs.push((scopes, ink, vec![faces])), + } + } + let pieces = runs.into_iter().filter_map(|(scopes, ink, faces)| Some((scopes, Arc::new(piece(id, caster, &plane, &faces, ink)?)))); + if masks { super::masked(id, pieces.collect()) } else { pieces.map(|(_, piece)| piece).collect() } +} diff --git a/crates/effects/src/solids/source.rs b/crates/effects/src/solids/source.rs index 66ca2c1d72..d71b2993af 100644 --- a/crates/effects/src/solids/source.rs +++ b/crates/effects/src/solids/source.rs @@ -8,7 +8,7 @@ use std::borrow::Cow; use std::sync::Arc; use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeKind}; -use vectorcraft_geom::{FillRule, PathData, Rect}; +use vectorcraft_geom::{FillRule, PathData, Point, Rect, SubPath}; use vectorcraft_pathops as po; use super::{MAX_MEMBERS, Scope, geometry, is_container, members, profile, region, reshape_members, solid_paints}; @@ -24,6 +24,19 @@ const MAX_DEPTH: usize = 64; /// many steps. pub(super) const MAX_WORK: usize = 1 << 18; +/// The most times resolving one 3D effect's art may cut an image's frame to a clipping path to +/// learn whether the clip shows any of it ([`Resolver::hidden`]). +pub(super) const MAX_IMAGE_CUTS: usize = 1024; + +/// The area, in square points, under which what a clip shows of an image's frame counts as nothing: +/// the sliver left where the frame only touches the clipping path. +const SHOWN_AREA: f64 = 1e-9; + +/// The precision an image's frame is cut to a clipping path with: the cut drops pieces narrower +/// than this, so it is far below [`po::DEFAULT_PRECISION`], and a strip of the image much +/// narrower than a hundredth of a point still counts as shown. +const CUT_PRECISION: f64 = 1e-6; + /// The error for an image a 3D effect is asked to build from. pub(crate) fn image_refusal(label: &str) -> String { format!("{label} can't build a solid from an image: trace it first with Object › Image Trace › Make.") @@ -55,7 +68,7 @@ fn needs(n: &Node) -> bool { /// a clipping path too complex to cut the art with. `label` is the effect's name. The art is cut /// for the solid effect `n` carries ([`resolve_for`]). pub(crate) fn resolve<'a>(doc: Option<&Document>, n: &'a Node, label: &str) -> Result<Cow<'a, Node>, String> { - let every_fill = super::solid(&n.appearance.effects).is_some_and(|(_, fx)| fx.id == super::ROTATE); + let every_fill = super::solid(&n.appearance.effects).is_some_and(|(_, fx)| super::is_plane(&fx.id)); resolve_for(doc, n, label, every_fill) } @@ -66,7 +79,7 @@ pub(crate) fn resolve_for<'a>(doc: Option<&Document>, n: &'a Node, label: &str, if !needs(n) { return Ok(Cow::Borrowed(n)); } - let mut r = Resolver { doc, label, every_fill, leaves: 0, work: 0, shown: None }; + let mut r = Resolver { doc, label, every_fill, leaves: 0, work: 0, cuts: 0, shown: None }; let children = r.content(n, 0); #[cfg(test)] WORK.with(|w| w.set(r.work)); @@ -90,8 +103,18 @@ struct Resolver<'a> { leaves: usize, /// The objects visited or made so far, counted against [`MAX_WORK`]. work: usize, - /// Inside clipping groups, the box of what their clipping paths show together. - shown: Option<Rect>, + /// The image frames cut to clipping paths so far, counted against [`MAX_IMAGE_CUTS`]. + cuts: usize, + /// Inside clipping groups, what their clipping paths show together. + shown: Option<Shown>, +} + +/// The clipping paths around the art being listed, outermost first, with the box of what they +/// show together. +#[derive(Clone)] +struct Shown { + bounds: Rect, + clips: Vec<Arc<(PathData, FillRule)>>, } impl Resolver<'_> { @@ -111,15 +134,52 @@ impl Resolver<'_> { /// `f` run on the art of `c`. The effects of an object or group can move its art into a clip, /// so inside one with effects no image is left out for lying outside the clip ([`Self::shown`]). fn inside<T>(&mut self, c: &Node, f: impl FnOnce(&mut Self) -> Result<T, String>) -> Result<T, String> { - let outer = self.shown; - if has_effects(c) { - self.shown = None; + if !has_effects(c) { + return f(self); } + let outer = self.shown.take(); let out = f(self); self.shown = outer; out } + /// Does the plain image `c` lie wholly outside what the clips around it show together, each + /// clipping path with its own fill rule? Its frame, the pixel rectangle as its transform places + /// it, is cut to each clip in turn until nothing is left. An error when a cut fails or the cuts + /// pass [`MAX_IMAGE_CUTS`]: the image may show, so it can't be left out. + fn hidden(&mut self, c: &Node) -> Result<bool, String> { + let Some(shown) = &self.shown else { return Ok(false) }; + let NodeKind::Image(im) = &c.kind else { return Ok(false) }; + let Some(b) = c.visual_bounds() else { return Ok(true) }; + if b.intersect(shown.bounds).area() <= 0.0 { + return Ok(true); + } + let (w, h) = (f64::from(im.width), f64::from(im.height)); + let corners = [(0.0, 0.0), (w, 0.0), (w, h), (0.0, h)].map(|(x, y)| im.xf * Point::new(x, y)); + if corners.iter().any(|p| !p.x.is_finite() || !p.y.is_finite()) { + return Err(image_refusal(self.label)); + } + let clips = shown.clips.clone(); + let mut left = PathData::single(SubPath::polyline(&corners, true)); + for clip in clips { + let Some(here) = clip.0.bounds() else { return Ok(true) }; + if left.bounds().is_none_or(|l| l.intersect(here).area() <= 0.0) { + return Ok(true); + } + self.cuts += 1; + if self.cuts > MAX_IMAGE_CUTS { + return Err(self.too_much_work()); + } + self.spend(1)?; + left = + po::try_boolean(&left, FillRule::NonZero, &clip.0, clip.1, po::BoolOp::Intersect, CUT_PRECISION).map_err(|_| self.too_complex())?; + if left.subpaths.iter().all(|s| s.area().abs() <= SHOWN_AREA) { + return Ok(true); + } + } + Ok(false) + } + /// The art `n`, a symbol instance, a blend, a clipping group or layer, or a group holding one, /// shows, as the members of a plain group. fn content(&mut self, n: &Node, depth: usize) -> Result<Vec<Arc<Node>>, String> { @@ -162,11 +222,15 @@ impl Resolver<'_> { if clip_nested_past(first, MAX_DEPTH.saturating_sub(depth)) { return Err(self.too_deep()); } - let clip = clip_area(first); - // An image wholly outside every clip around it shows nothing and is left out. - let outer = self.shown; + let clip = Arc::new(clip_area(first)); + // An image wholly outside what the clips around it show together draws nothing and + // is left out. let here = clip.0.bounds().unwrap_or(Rect::ZERO); - self.shown = Some(outer.map_or(here, |o| o.intersect(here))); + let outer = self.shown.take(); + let mut inner_shown = outer.clone().unwrap_or(Shown { bounds: here, clips: vec![] }); + inner_shown.bounds = inner_shown.bounds.intersect(here); + inner_shown.clips.push(clip.clone()); + self.shown = Some(inner_shown); let listed = self.list(rest, depth + 1); self.shown = outer; let (inner, _) = listed?; @@ -198,8 +262,7 @@ impl Resolver<'_> { // Only an image with no effects or fills and strokes of its own is measured by its // frame; any other one may draw inside the clip. let plain = !has_effects(c) && c.appearance.items.iter().all(|i| !i.visible()); - let hidden = plain && self.shown.is_some_and(|k| c.visual_bounds().is_none_or(|b| b.intersect(k).area() <= 0.0)); - if hidden { + if plain && self.hidden(c)? { changed = true; continue; } diff --git a/crates/effects/src/solids/tests.rs b/crates/effects/src/solids/tests.rs index 7273a44b22..5126b76660 100644 --- a/crates/effects/src/solids/tests.rs +++ b/crates/effects/src/solids/tests.rs @@ -180,6 +180,604 @@ fn the_front_caps_are_drawn_last_in_the_order_of_the_appearance() { } } +/// A C, open to the right: two concave corners where its walls meet the walls of the notch. +fn letter_c() -> BezPath { + let mut b = BezPath::new(); + b.move_to((100.0, 100.0)); + b.line_to((200.0, 100.0)); + b.line_to((200.0, 130.0)); + b.line_to((130.0, 130.0)); + b.line_to((130.0, 170.0)); + b.line_to((200.0, 170.0)); + b.line_to((200.0, 200.0)); + b.line_to((100.0, 200.0)); + b.close_path(); + b +} + +/// The pairs (blue, red) of `walls`, by index, where the blue face is drawn first and the two +/// faces' bounds overlap. +fn red_after_blue(walls: &[&Node]) -> Vec<(usize, usize)> { + let bounds: Vec<Rect> = walls.iter().map(|f| f.path_data().and_then(PathData::bounds).unwrap()).collect(); + let overlap = |a: &Rect, b: &Rect| a.x0 < b.x1 && b.x0 < a.x1 && a.y0 < b.y1 && b.y0 < a.y1; + let mut out = vec![]; + for (i, a) in walls.iter().enumerate() { + for (j, b) in walls.iter().enumerate().skip(i + 1) { + if blue(a) && !blue(b) && overlap(&bounds[i], &bounds[j]) { + out.push((i, j)); + } + } + } + out +} + +/// An opaque stroke's solid holds the fill's edge, so the fill's walls are drawn before every +/// face of the stroke they overlap, and the stroke's walls cover them at the concave corners of a +/// turned C, in Extrude & Bevel and Extrude & Bevel (Classic). The front caps stay last, the +/// fill's below the stroke's. +#[test] +fn a_fills_walls_are_drawn_before_the_stroke_faces_over_them() { + let views = [json!({}), json!({"rotationX": -20, "rotationY": -40, "rotationZ": 0}), json!({"rotationX": 25, "rotationY": -55, "rotationZ": 10})]; + for id in [EXTRUDE, CLASSIC_EXTRUDE] { + for view in &views { + let mut params = view.clone(); + params["depth"] = json!(60); + let mut n = stroked(&letter_c()); + n.appearance.effects.push(fx(id, params)); + let art = solid_art(&n).unwrap(); + let faces = faces(&art); + let [walls @ .., fill_cap, stroke_cap] = faces.as_slice() else { panic!("{id} {view}: the caps") }; + assert!(!blue(fill_cap) && blue(stroke_cap), "{id} {view}: the caps last"); + assert!(walls.iter().any(|f| !blue(f)) && walls.iter().any(|f| blue(f)), "{id} {view}: walls of both"); + let wrong = red_after_blue(walls); + assert!(wrong.is_empty(), "{id} {view}: fill walls after the stroke faces over them: {wrong:?} of {}", walls.len()); + } + } + // Strokes aligned inside or outside keep the fill's walls, in that order. A dashed stroke + // leaves the fill's walls in the gaps between its dashes, and they keep their depths. + use vectorcraft_doc::StrokeAlign; + for (dash, align) in [(true, StrokeAlign::Center), (false, StrokeAlign::Inside), (false, StrokeAlign::Outside)] { + let mut n = stroked(&letter_c()); + if let Some(AppearanceItem::Stroke(s)) = n.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Stroke(_))) { + s.dash = dash.then(|| vectorcraft_doc::Dash { pattern: vec![12.0, 12.0], offset: 0.0, align_corners: false }); + s.align = align; + } + n.appearance.effects.push(fx(EXTRUDE, views[1].clone())); + let art = solid_art(&n).unwrap(); + let faces = faces(&art); + let [walls @ .., _, _] = faces.as_slice() else { panic!("{align:?}: the caps") }; + assert!(walls.iter().any(|f| !blue(f)), "{align:?}: the fill's walls"); + if !dash { + assert!(red_after_blue(walls).is_empty(), "{align:?}"); + } + } +} + +/// The faces of the solids effect `id` with `params` builds for `n`, in the order they are drawn, +/// as [`surfaces_for`] orders them, each with the index of the part ([`solid_parts`]) it was built +/// from and whether it is a stroke's. +fn drawn_parts(n: &Node, id: &str, params: &Value) -> Vec<(Facet, usize, bool)> { + let (path, rule) = profile(n).unwrap(); + let shapes = [Profile { path, rule, items: solid_paints(n), opacity: 1.0, scopes: vec![] }]; + let p = crate::merged_params(id, params); + let (parts, bounds) = solid_parts(&shapes, union_bounds(&shapes).unwrap()); + let mut solids = vec![]; + for (part, ((item, _, _, _, _, member), f)) in parts.iter().zip(built_solids(id, &p, &parts, bounds, MAX_OBJECT_FACES)).enumerate() { + let Some(f) = f.unwrap() else { continue }; + let closed = holds_edge(id, &shapes[*member].path); + solids.push((Paints::of(item, closed), *member, f, part, matches!(item, AppearanceItem::Stroke(_)))); + } + let mut cuts: Vec<(Paints, usize, &mut Vec<Facet>)> = solids.iter_mut().map(|(paints, member, f, _, _)| (*paints, *member, f)).collect(); + cut_stroke_faces(&mut cuts, MAX_OBJECT_FACES); + let (mut placed, mut all) = (vec![], vec![]); + for (paints, member, f, part, stroke) in solids { + for facet in f { + placed.push(Placed::of(&facet, member, paints)); + all.push((facet, part, stroke)); + } + } + let sealed = match id { + INFLATE => inflate_options(&p).cap, + CLASSIC_EXTRUDE => classic_extrude_options(&p).cap, + _ => extrude_options(&p).cap, + }; + draw_order(&placed, sealed).into_iter().map(|k| all[k].clone()).collect() +} + +/// Is `p` inside the polygon of `f` (nonzero winding)? +fn facet_contains(f: &Facet, p: Point) -> bool { + let mut winding = 0i32; + for c in &f.contours { + for (a, b) in c.iter().zip(c.iter().cycle().skip(1)).take(c.len()) { + let cross = (b.x - a.x) * (p.y - a.y) - (p.x - a.x) * (b.y - a.y); + if a.y <= p.y && b.y > p.y && cross > 0.0 { + winding += 1; + } else if a.y > p.y && b.y <= p.y && cross < 0.0 { + winding -= 1; + } + } + } + winding != 0 +} + +/// The points of a 1 pt grid over `faces` (drawn in that order, each with whether it is a stroke's) +/// where the face drawn on top is the fill's while a face of the stroke turned toward the viewer is +/// nearer the viewer there by more than 0.5 pt, or the other way round. Points within 0.3 pt of an +/// edge are left out. +fn wrong_on_top(faces: &[(Facet, bool)]) -> Vec<Point> { + let polygons: Vec<&Facet> = faces.iter().map(|(f, _)| f).collect(); + let extent = + polygons.iter().flat_map(|f| f.contours.iter().flatten()).fold(Rect::new(f64::MAX, f64::MAX, f64::MIN, f64::MIN), |r, p| r.union_pt(*p)); + let mut wrong = vec![]; + let mut y = extent.y0.floor() + 0.5; + while y < extent.y1 { + let mut x = extent.x0.floor() + 0.5; + while x < extent.x1 { + let p = Point::new(x, y); + let well_inside = |f: &Facet| { + [(-0.3, -0.3), (0.3, -0.3), (-0.3, 0.3), (0.3, 0.3), (0.0, 0.0)].iter().all(|(dx, dy)| facet_contains(f, Point::new(x + dx, y + dy))) + }; + let top = faces.iter().rposition(|(f, _)| facet_contains(f, p)); + if let Some((f, stroke)) = top.and_then(|k| faces.get(k)).filter(|(f, _)| !f.away && well_inside(f)) { + let nearest = |of_stroke: bool| { + faces.iter().filter(|(g, s)| *s == of_stroke && !g.away && well_inside(g)).filter_map(|(g, _)| g.depth_at(p)).reduce(f64::max) + }; + if let (Some(ds), Some(df)) = (nearest(true), nearest(false)) + && (ds - df).abs() > 0.5 + && (ds > df) != *stroke + && f.depth_at(p).is_some() + { + wrong.push(p); + } + } + x += 1.0; + } + y += 1.0; + } + wrong +} + +/// The points of a 1 pt grid over `faces` (drawn in that order) where the face drawn on top is +/// farther from the viewer than another face turned toward the viewer, of any part, by more than +/// 0.5 pt. Points within 0.3 pt of an edge, and faces without a plane, are left out. +fn misdrawn(faces: &[(Facet, usize, bool)]) -> Vec<Point> { + let extent = + faces.iter().flat_map(|(f, ..)| f.contours.iter().flatten()).fold(Rect::new(f64::MAX, f64::MAX, f64::MIN, f64::MIN), |r, p| r.union_pt(*p)); + let mut wrong = vec![]; + let mut y = extent.y0.floor() + 0.5; + while y < extent.y1 { + let mut x = extent.x0.floor() + 0.5; + while x < extent.x1 { + let p = Point::new(x, y); + let well_inside = |f: &Facet| { + [(-0.3, -0.3), (0.3, -0.3), (-0.3, 0.3), (0.3, 0.3), (0.0, 0.0)].iter().all(|(dx, dy)| facet_contains(f, Point::new(x + dx, y + dy))) + }; + let top = faces.iter().rposition(|(f, ..)| facet_contains(f, p)).and_then(|k| faces.get(k)).filter(|(f, ..)| !f.away && well_inside(f)); + if let Some(on_top) = top.and_then(|(f, ..)| f.depth_at(p)) { + let nearest = faces.iter().filter(|(g, ..)| !g.away && well_inside(g)).filter_map(|(g, ..)| g.depth_at(p)).reduce(f64::max); + if nearest.is_some_and(|d| d - on_top > 0.5) { + wrong.push(p); + } + } + x += 1.0; + } + y += 1.0; + } + wrong +} + +/// The faces of a shape's fill and strokes are drawn in the order of their depths where they +/// overlap: on a turned C, with or without perspective, under a stroke that does not cover the +/// fill's whole edge (dashed, with a width profile, or with a brush), under a plain stroke and +/// under two strokes whose faces pass through each other, no point shows a face farther from the +/// viewer than another, in Extrude & Bevel and Extrude & Bevel (Classic), and only a few in +/// Inflate, where curved puffs cross. +#[test] +fn fill_walls_and_strokes_that_leave_gaps_draw_in_the_order_of_their_depths_where_they_overlap() { + use vectorcraft_doc::{Dash, WidthProfile}; + let views = [ + json!({"rotationX": -20, "rotationY": -40, "rotationZ": 0}), + json!({"rotationX": 25, "rotationY": -55, "rotationZ": 10}), + json!({"rotationX": -30, "rotationY": 50, "rotationZ": 5, "perspectiveAngle": 40}), + json!({"rotationX": -30, "rotationY": 20, "rotationZ": 5, "perspectiveAngle": 40}), + ]; + type Style<'a> = (&'a str, &'a dyn Fn(&mut Node)); + let first = |n: &mut Node, set: &dyn Fn(&mut StrokeLayer)| { + if let Some(AppearanceItem::Stroke(s)) = n.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Stroke(_))) { + set(s); + } + }; + let dash = |pattern: Vec<f64>, offset: f64| Some(Dash { pattern, offset, align_corners: false }); + let styles: [Style; 6] = [ + ("plain", &|_| {}), + ("dashed", &|n| first(n, &|s| s.dash = dash(vec![12.0, 12.0], 0.0))), + ("profiled", &|n| first(n, &|s| s.profile = Some(WidthProfile::lens()))), + ("brushed", &|n| first(n, &|s| s.brush = Some("brush".into()))), + ("dashed with perspective", &|n| first(n, &|s| s.dash = dash(vec![20.0, 6.0], 3.0))), + ("two strokes", &|n| { + first(n, &|s| s.dash = dash(vec![12.0, 12.0], 0.0)); + let mut wide = StrokeLayer::new(Paint::solid(RED), 14.0); + wide.profile = Some(WidthProfile::lens()); + n.appearance.items.push(AppearanceItem::Stroke(wide)); + }), + ]; + for id in [EXTRUDE, CLASSIC_EXTRUDE, INFLATE] { + for (v, view) in views.iter().enumerate() { + for (style, set) in &styles { + // The last two views, for the plain and the two strokes only. + if v >= 2 && !["plain", "two strokes"].contains(style) { + continue; + } + let mut params = view.clone(); + params["depth"] = json!(60); + if style.contains("perspective") { + params["perspectiveAngle"] = json!(40); + } + let mut n = stroked(&letter_c()); + set(&mut n); + let parts = drawn_parts(&n, id, ¶ms); + let faces: Vec<(Facet, bool)> = parts.iter().map(|(f, _, s)| (f.clone(), *s)).collect(); + assert!(faces.iter().any(|(_, s)| *s) && faces.iter().any(|(_, s)| !*s), "{id} {view} {style}: faces of both"); + // Inflate's curved puffs cross each other along curves its flat facets only follow + // roughly: a few points next to those crossings may still show the farther face. + let allowed = if id == INFLATE { 5 } else { 0 }; + let wrong = wrong_on_top(&faces); + assert!(wrong.len() <= allowed, "{id} {view} {style}: {} points drawn in the wrong paint, first {:?}", wrong.len(), wrong.first()); + let wrong = misdrawn(&parts); + assert!(wrong.len() <= allowed, "{id} {view} {style}: {} points show a farther face, first {:?}", wrong.len(), wrong.first()); + } + } + } +} + +/// The paths of `art`'s faces in drawing order, leaving out the graphics (clip groups). +fn face_paths(art: &Node) -> Vec<PathData> { + fn walk(n: &Node, out: &mut Vec<PathData>) { + match &n.kind { + NodeKind::Group { clip: true, .. } => {} + NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, out)), + _ => out.extend(n.path_data().cloned()), + } + } + let mut out = vec![]; + walk(art, &mut out); + out +} + +/// A member of a 3D group with an opacity mask or a blending mode of its own draws its fill's and +/// its strokes' faces in one order inside that mask, the order the same member draws them in +/// without it, its dashes cut where they pass through the fill's walls. A member whose stroke is +/// translucent still draws each surface whole. +#[test] +fn a_masked_members_fill_and_stroke_faces_go_in_one_order() { + let mut member = stroked(&letter_c()); + if let Some(AppearanceItem::Stroke(s)) = member.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Stroke(_))) { + s.dash = Some(vectorcraft_doc::Dash { pattern: vec![12.0, 12.0], offset: 0.0, align_corners: false }); + } + let solid = |member: Node| { + let mut g = Node::group(NodeId(2), vec![Arc::new(member)]); + g.appearance.effects.push(fx(EXTRUDE, json!({"rotationX": -20, "rotationY": -40, "rotationZ": 0, "depth": 60}))); + solid_art(&g).unwrap() + }; + let cover = Node::path( + NodeId(900), + vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 400.0, 400.0)), + Appearance::basic(Paint::solid(Color::WHITE), Paint::None, 0.0), + ); + let mut masked = member.clone(); + masked.extras_mut().mask = Some(Box::new(OpacityMask::new(cover, true))); + let mut multiplied = member.clone(); + multiplied.blend = BlendMode::Multiply; + let unmasked = face_paths(&solid(member.clone())); + for (what, scoped) in [("masked", masked.clone()), ("multiplied", multiplied)] { + let art = solid(scoped); + let mut scopes = 0; + art.walk(&mut |n| scopes += usize::from(n.extras().mask.is_some() || n.blend == BlendMode::Multiply)); + assert!(scopes > 0, "{what}: drawn in its scope"); + assert_eq!(face_paths(&art), unmasked, "{what}: the faces in the member's one order"); + } + // A translucent stroke keeps its surface whole: the fill's faces, then the stroke's. + if let Some(AppearanceItem::Stroke(s)) = masked.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Stroke(_))) { + s.opacity = 0.5; + } + let art = solid(masked); + let mut groups = vec![]; + art.walk(&mut |n| { + if n.opacity == 0.5 { + groups.push(n.children().map_or(0, Vec::len)); + } + }); + assert_eq!(groups.len(), 1, "the stroke's surface is one translucent group"); +} + +/// Under a light that is not white, Inflate in gradients, whose faces are drawn one by one, draws the +/// fill's and the dashed stroke's faces in one order, as it does under a white light. A solid color, +/// drawn as one composite of each surface's facets, still draws each surface whole. +#[test] +fn a_colored_inflate_in_gradients_draws_its_faces_in_one_order() { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let gradient = |c: Color| { + Paint::Gradient(Box::new(GradientPaint::new(Gradient::new( + GradientKind::Linear, + vec![GradientStop::new(0.0, c), GradientStop::new(1.0, Color::WHITE)], + )))) + }; + let mut n = stroked(&letter_c()); + for item in &mut n.appearance.items { + match item { + AppearanceItem::Fill(f) => f.paint = gradient(RED), + AppearanceItem::Stroke(s) => { + s.paint = gradient(BLUE); + s.dash = Some(vectorcraft_doc::Dash { pattern: vec![12.0, 12.0], offset: 0.0, align_corners: false }); + } + } + } + // How many surfaces the art draws, and how many faces the first holds. + let drawn = |n: &Node, lights: Option<Value>| { + let mut n = n.clone(); + let mut p = json!({"rotationX": -20, "rotationY": -40, "rotationZ": 0, "depth": 60}); + if let Some(lights) = lights { + p["lights"] = lights; + } + n.appearance.effects.push(fx(INFLATE, p)); + let art = solid_art(&n).unwrap(); + let surfaces = art.children().unwrap(); + (surfaces.len(), surfaces[0].children().map_or(0, Vec::len)) + }; + let colored = json!([{"color": "#ff8080"}]); + let white = drawn(&n, None); + assert_eq!(white.0, 1, "one order"); + let cut = drawn_parts(&n, INFLATE, &json!({"rotationX": -20, "rotationY": -40, "rotationZ": 0, "depth": 60})).len(); + assert_eq!(white.1, cut, "the white light's faces, cut"); + assert_eq!(drawn(&n, Some(colored.clone())).0, 1, "one order under the colored light"); + // A solid color under the colored light: a composite for each of the fill and the stroke. + let solid = stroked(&letter_c()); + assert_eq!(drawn(&solid, Some(colored)).0, 2); +} + +/// A face of a stroke that leaves gaps passing through the plane of its fill's wall where they +/// overlap is cut along the line where their depths meet, into the piece in front of the wall and +/// the piece behind it; a face on one side of the wall, another shape's stroke, a covering stroke +/// and a cut past the room left are left whole. +#[test] +fn a_stroke_face_through_a_fill_wall_is_cut_where_their_depths_meet() { + let facet = |x: f64, normal: [f64; 3], offset: f64| Facet { + contours: vec![vec![Point::new(x, 0.0), Point::new(x + 10.0, 0.0), Point::new(x + 10.0, 10.0), Point::new(x, 10.0)]], + depth: 0.0, + brightness: 1.0, + illumination: [1.0; 3], + normal, + rgb_gradient: None, + outline: None, + side: true, + away: false, + end: None, + plane: Some(DepthPlane { normal, offset, center: Point::ZERO, eye: None }), + }; + let wall = facet(0.0, [0.0, 0.0, 1.0], 0.0); + // z = x - 8: behind the wall left of x = 8, in front of it right of it. + let r = std::f64::consts::FRAC_1_SQRT_2; + let mut through = facet(5.0, [-r, 0.0, r], -8.0 * r); + // Its curved outline: the top edge bows up to y = -2. + let mut curved = BezPath::new(); + curved.move_to((5.0, 0.0)); + curved.curve_to((8.0, -8.0 / 3.0), (12.0, -8.0 / 3.0), (15.0, 0.0)); + curved.line_to((15.0, 10.0)); + curved.line_to((5.0, 10.0)); + curved.close_path(); + through.outline = Some(PathData::from_bezpath(&curved)); + let extent = |f: &Facet| polygon_bounds(&f.contours[0]); + let cut_with = |paints: Paints, member: usize, room: usize| { + let (mut fill, mut stroke) = (vec![wall.clone()], vec![through.clone()]); + let mut solids: Vec<(Paints, usize, &mut Vec<Facet>)> = vec![(Paints::Fill, 0, &mut fill), (paints, member, &mut stroke)]; + cut_stroke_faces(&mut solids, room); + stroke + }; + let pieces = cut_with(Paints::Other, 0, 10); + assert_eq!(pieces.len(), 2); + let (near, far) = (extent(&pieces[0]), extent(&pieces[1])); + assert!((near.x0 - 8.0).abs() < 1e-9 && near.x1 == 15.0 && far.x0 == 5.0 && (far.x1 - 8.0).abs() < 1e-9, "{near:?} {far:?}"); + assert!(pieces[0].depth > 0.0 && pieces[1].depth < 0.0); + // Each piece keeps its side of the curved outline, the bowed edge included. + let curve = |f: &Facet| f.outline.as_ref().and_then(PathData::bounds).unwrap(); + let (near, far) = (curve(&pieces[0]), curve(&pieces[1])); + assert!((near.x0 - 8.0).abs() < 1e-6 && (near.x1 - 15.0).abs() < 1e-6 && near.y0 < -1.5, "{near:?}"); + assert!((far.x0 - 5.0).abs() < 1e-6 && (far.x1 - 8.0).abs() < 1e-6 && far.y0 < -1.5, "{far:?}"); + let whole = std::slice::from_ref(&through); + assert_eq!(cut_with(Paints::Other, 1, 10), whole, "another shape's stroke"); + assert_eq!(cut_with(Paints::Stroke, 0, 10), whole, "a covering stroke"); + assert_eq!(cut_with(Paints::Other, 0, 0), whole, "no room"); + let (mut fill, mut stroke) = (vec![wall.clone()], vec![facet(5.0, [0.0, 0.0, 1.0], 1.0)]); + cut_stroke_faces(&mut [(Paints::Fill, 0, &mut fill), (Paints::Other, 0, &mut stroke)], 10); + assert_eq!(stroke.len(), 1, "in front of the wall wherever they overlap"); + // Of two of a shape's strokes whose faces pass through each other, the later stroke's face is + // cut against the earlier one's; a covering stroke's face is never cut, and the other stroke's + // face is cut against it. Two shapes' strokes are left whole. + for (case, (first, second, cut_first)) in + [(Paints::Other, Paints::Other, false), (Paints::Stroke, Paints::Other, false), (Paints::Other, Paints::Stroke, true)].into_iter().enumerate() + { + let (mut a, mut b) = (vec![wall.clone()], vec![through.clone()]); + cut_stroke_faces(&mut [(first, 0, &mut a), (second, 0, &mut b)], 10); + assert_eq!((a.len(), b.len()), if cut_first { (2, 1) } else { (1, 2) }, "case {case}"); + } + let (mut a, mut b) = (vec![wall.clone()], vec![through.clone()]); + cut_stroke_faces(&mut [(Paints::Other, 0, &mut a), (Paints::Other, 1, &mut b)], 10); + assert_eq!((a.len(), b.len()), (1, 1), "two shapes"); +} + +/// A small polygon far from the origin keeps its area and centroid. +#[test] +fn a_small_polygon_far_away_has_a_centroid() { + let far = 100_000_000.0; + let square = [Point::new(far, far), Point::new(far + 1.0, far), Point::new(far + 1.0, far + 1.0), Point::new(far, far + 1.0)]; + let c = centroid(&square).unwrap(); + assert!((c.x - far - 0.5).abs() < 1e-6 && (c.y - far - 0.5).abs() < 1e-6, "{c:?}"); + assert!(centroid(&[]).is_none() && centroid(&square[..2]).is_none()); +} + +/// Cutting adds no more faces than the object's face limit and the paint-copy allowance leave room +/// for, so an effect that draws with its faces uncut still draws. +#[test] +fn cutting_stays_within_the_face_limit_and_the_paint_allowance() { + let items = stroked(&letter_c()).appearance.items.clone(); + let stroke = items.iter().find(|i| matches!(i, AppearanceItem::Stroke(_))).unwrap(); + let mut one = 0usize; + crate::revolve::paint_copies_add(&mut one, 6, paint_ref(stroke)); + let max = crate::revolve::MAX_PAINT_COPIES; + assert_eq!(cut_room(items.iter(), 10, 0), (MAX_OBJECT_FACES - 10).min(max / one)); + assert_eq!(cut_room(items.iter(), MAX_OBJECT_FACES + 5, 0), 0); + assert_eq!(cut_room(items.iter(), 10, max - 3 * one), 3); + assert_eq!(cut_room(items.iter(), 10, max + 1), 0); +} + +/// Where a shape's fill wall and a face of its stroke that leaves gaps overlap, the one nearer the +/// viewer there is drawn after the other, whichever their depths put first; a stroke face that +/// overlaps no fill wall keeps its place. +#[test] +fn local_order_puts_overlapping_fill_walls_and_stroke_faces_in_depth_order() { + let square = |x: f64| vec![Point::new(x, 0.0), Point::new(x + 10.0, 0.0), Point::new(x + 10.0, 10.0), Point::new(x, 10.0)]; + let at = |depth: f64, x: f64, z: f64, paints: Paints| Placed { + depth, + side: true, + away: false, + bounds: Rect::new(x, 0.0, x + 10.0, 10.0), + member: 0, + paints, + outline: square(x), + plane: Some(DepthPlane { normal: [0.0, 0.0, 1.0], offset: z, center: Point::ZERO, eye: None }), + }; + // 0 a fill wall at z 0; 1 a stroke face over half of it, nearer, sorted before it; 2 a stroke + // face elsewhere; 3 a stroke face over it, farther, sorted after it. + let faces = + [at(5.0, 0.0, 0.0, Paints::Fill), at(2.0, 5.0, 1.0, Paints::Other), at(1.0, 20.0, 1.0, Paints::Other), at(6.0, 2.0, -1.0, Paints::Other)]; + assert_eq!(draw_order(&faces, true), [2, 3, 0, 1]); + assert_eq!(draw_order(&faces, false), [2, 3, 0, 1]); + // A covering stroke's faces keep the wall's own rule. + let covering: Vec<Placed> = faces + .iter() + .map(|f| Placed { paints: if f.paints == Paints::Other { Paints::Stroke } else { f.paints }, outline: vec![], plane: None, ..*f }) + .collect(); + assert_eq!(draw_order(&covering, false), [2, 1, 0, 3]); + // Another shape's stroke, and a stroke face at the same depth where they overlap, move nothing. + let other_shape: Vec<Placed> = + faces[..3].iter().map(|f| Placed { member: usize::from(f.paints == Paints::Other), outline: f.outline.clone(), ..*f }).collect(); + assert_eq!(draw_order(&other_shape, true), [2, 1, 0]); + let level = [at(5.0, 0.0, 0.0, Paints::Fill), at(2.0, 5.0, 0.0, Paints::Other)]; + assert_eq!(draw_order(&level, true), [1, 0]); + // A stroke face moved after its fill's wall does not pass a nearer face of another shape that + // it overlaps: 0 a stroke face, 1 another shape's face in front of both, 2 the fill's wall. + let in_front = Placed { member: 1, ..at(2.0, 5.0, 2.0, Paints::Fill) }; + let shapes = [at(1.0, 5.0, 1.0, Paints::Other), in_front, at(3.0, 0.0, 0.0, Paints::Fill)]; + assert_eq!(draw_order(&shapes, true), [2, 0, 1]); + // A shape with a covering stroke as well keeps its fill wall before the covering stroke's face, + // even where that face is the farther: 0 the fill's wall, 1 the covering stroke's face behind + // it, 2 the other stroke's face in front. + let both = [at(3.0, 0.0, 0.0, Paints::Fill), at(3.0, 0.0, -1.0, Paints::Stroke), at(2.0, 5.0, 1.0, Paints::Other)]; + assert_eq!(draw_order(&both, true), [0, 1, 2]); + // Faces of a shape's strokes go in the order of their depths where they overlap too, with no + // fill face among them: 1 is nearer than 0 there, though sorted before it. + for (case, (back, front)) in + [(Paints::Other, Paints::Other), (Paints::Stroke, Paints::Other), (Paints::Stroke, Paints::Stroke)].into_iter().enumerate() + { + let strokes = [at(5.0, 0.0, 0.0, back), at(2.0, 5.0, 1.0, front)]; + assert_eq!(draw_order(&strokes, true), [0, 1], "case {case}"); + } +} + +/// A cycle of overlapping stroke faces is broken at the face that comes first by depth, and a cap +/// drawn last stays after every wall: 0 at x 0 to 10, flat at z 0; 1 at x 4 to 14, z = x - 8; 2 at +/// x 8 to 18, flat at z 1. Where they overlap, 0 is nearer than 1, 1 nearer than 2 and 2 nearer +/// than 0. 3 is the cap. +#[test] +fn a_depth_cycle_keeps_the_cap_last() { + let square = |x: f64| vec![Point::new(x, 0.0), Point::new(x + 10.0, 0.0), Point::new(x + 10.0, 10.0), Point::new(x, 10.0)]; + let at = |depth: f64, x: f64, normal: [f64; 3], offset: f64| Placed { + depth, + side: true, + away: false, + bounds: Rect::new(x, 0.0, x + 10.0, 10.0), + member: 0, + paints: Paints::Other, + outline: square(x), + plane: Some(DepthPlane { normal, offset, center: Point::ZERO, eye: None }), + }; + let cap = Placed { + depth: f64::MAX, + side: false, + away: false, + bounds: Rect::new(0.0, 0.0, 18.0, 10.0), + member: 0, + paints: Paints::Other, + outline: vec![], + plane: None, + }; + let faces = [at(1.0, 0.0, [0.0, 0.0, 1.0], 0.0), at(2.0, 4.0, [-1.0, 0.0, 1.0], -8.0), at(3.0, 8.0, [0.0, 0.0, 1.0], 1.0), cap]; + assert_eq!(draw_order(&faces, true), [0, 2, 1, 3]); +} + +/// The order keeps depths except where a shape's fill wall turned toward the viewer overlaps a +/// face of the same shape's stroke drawn before it: the wall then goes just before that face. A +/// cap, a face turned away, another shape's stroke, a stroke face the wall does not overlap and an +/// effect without caps keep the order of the depths. +#[test] +fn the_draw_order_moves_a_fill_wall_before_the_stroke_faces_it_overlaps() { + let at = |depth: f64, x: f64, member: usize, paints: Paints, side: bool, away: bool| Placed { + depth, + side, + away, + bounds: Rect::new(x, 0.0, x + 10.0, 10.0), + member, + paints, + outline: vec![], + plane: None, + }; + // 0 the fill's wall; 1 the stroke's wall over it; 2 another shape's stroke over it; 3 a stroke + // wall elsewhere; 4 a stroke face turned away; 5 a fill cap; 6 the stroke's cap, nearer; 7 a + // fill wall at the stroke wall's depth. + let faces = [ + at(5.0, 0.0, 0, Paints::Fill, true, false), + at(3.0, 5.0, 0, Paints::Stroke, true, false), + at(2.0, 5.0, 1, Paints::Stroke, true, false), + at(1.0, 50.0, 0, Paints::Stroke, true, false), + at(0.0, 0.0, 0, Paints::Stroke, true, true), + at(4.0, 0.0, 0, Paints::Fill, false, false), + at(6.0, 0.0, 0, Paints::Stroke, false, false), + at(3.0, 0.0, 0, Paints::Fill, true, false), + ]; + assert_eq!(draw_order(&faces, true), [4, 3, 2, 0, 7, 1, 5, 6]); + assert_eq!(draw_order(&faces, false), [4, 3, 2, 1, 7, 5, 0, 6]); + // A shape with no stroke, and a stroke without a width, move nothing. + // Only a stroke whose solid hides the fill's whole edge counts: an opaque, plain stroke with a + // width on a closed shape. + let stroke = |f: &dyn Fn(&mut StrokeLayer)| { + let mut s = StrokeLayer::new(Paint::solid(BLUE), 6.0); + f(&mut s); + AppearanceItem::Stroke(s) + }; + assert!(Paints::of(&stroke(&|_| {}), true) == Paints::Stroke); + assert!(Paints::of(&stroke(&|_| {}), false) == Paints::Other, "an open shape"); + let closed = profile(&stroked(&letter_c())).unwrap().0; + assert!(holds_edge(EXTRUDE, &closed) && holds_edge(CLASSIC_EXTRUDE, &closed)); + assert!(!holds_edge(INFLATE, &closed), "an inflated fill can rise in front of its stroke"); + assert!(Paints::of(&stroke(&|s| s.width = 0.0), true) == Paints::Other, "no width"); + let dash = vectorcraft_doc::Dash { pattern: vec![4.0, 4.0], offset: 0.0, align_corners: false }; + assert!(Paints::of(&stroke(&|s| s.dash = Some(dash.clone())), true) == Paints::Other, "dashes"); + assert!(Paints::of(&stroke(&|s| s.brush = Some("brush".into())), true) == Paints::Other); + assert!(Paints::of(&stroke(&|s| s.paint = Paint::None), true) == Paints::Other); + assert!(Paints::of(&stroke(&|s| s.paint = Paint::Pattern { pattern: "p".into(), xf: Affine::IDENTITY }), true) == Paints::Other, "a pattern"); + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let gradient = |opacity: f32| { + let mut end = GradientStop::new(1.0, RED); + end.opacity = opacity; + Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, BLUE), end])))) + }; + assert!(Paints::of(&stroke(&|s| s.paint = gradient(1.0)), true) == Paints::Stroke, "an opaque gradient"); + assert!(Paints::of(&stroke(&|s| s.paint = gradient(0.5)), true) == Paints::Other, "a gradient with a transparent stop"); + let other = |p: Paints| if p == Paints::Stroke { Paints::Other } else { p }; + let unstroked: Vec<Placed> = faces.iter().map(|f| at(f.depth, f.bounds.x0, f.member, other(f.paints), f.side, f.away)).collect(); + assert_eq!(draw_order(&unstroked, true), draw_order(&faces, false)); +} + /// A stroked open path builds a ribbon, the stroke's outline, not the area the path would enclose /// if it were closed: for an L of two 100 pt legs, a 6 pt band with butt ends and a mitered corner. #[test] @@ -222,6 +820,142 @@ fn a_stroke_past_the_limits_is_left_out() { } } +/// Each solid [`built_solids`] gives for effect `id` on `n` within `limit` faces together, as its +/// face count (`None` for a stroke left out) or the error, every result the iterator gives. +fn solid_faces(id: &str, n: &Node, limit: usize) -> Vec<Result<Option<usize>, String>> { + let shapes = [Profile { path: profile(n).unwrap().0, rule: FillRule::NonZero, items: solid_paints(n), opacity: 1.0, scopes: vec![] }]; + let p = crate::merged_params(id, &json!({})); + let (parts, bounds) = solid_parts(&shapes, union_bounds(&shapes).unwrap()); + built_solids(id, &p, &parts, bounds, limit).map(|r| r.map(|f| f.map(|f| f.len()))).collect() +} + +/// The solids of one object count their faces together: at the limit they all build, one face past +/// it is an error, and the solids after the one that passes it are never built. +#[test] +fn an_objects_solids_count_their_faces_together() { + for id in [EXTRUDE, CLASSIC_EXTRUDE, INFLATE] { + let mut n = square_node(); + // A second stroke, so a solid follows the one that passes the limit. + let stroke = n.appearance.items[1].clone(); + n.appearance.items.push(stroke); + let counts: Vec<usize> = solid_faces(id, &n, MAX_OBJECT_FACES).into_iter().map(|c| c.unwrap().unwrap()).collect(); + assert!(counts.len() == 3 && counts.iter().all(|c| *c > 0), "{id}: {counts:?}"); + let total: usize = counts.iter().sum(); + assert!(solid_faces(id, &n, total).iter().all(Result::is_ok), "{id}: at the limit"); + let past = solid_faces(id, &n, total - 1); + assert_eq!(past.last(), Some(&Err(vectorcraft_three_d::TOO_COMPLEX_SOLID.to_string())), "{id}"); + SOLIDS_BUILT.with(|b| b.set(0)); + let past = solid_faces(id, &n, counts[0] + counts[1] - 1); + assert!(past.len() == 2 && past[1].is_err(), "{id}: {past:?}"); + assert_eq!(SOLIDS_BUILT.with(std::cell::Cell::get), 2, "{id}: the second stroke's solid is never built"); + } +} + +/// A convex polygon of `corners` corners about (20,000, 20,000), filled red, with no stroke. +fn polygon_node(id: u64, corners: usize) -> Node { + let points: Vec<Point> = (0..corners) + .map(|k| { + let (s, c) = (k as f64 * std::f64::consts::TAU / corners as f64).sin_cos(); + Point::new(20_000.0 + 10_000.0 * c, 20_000.0 + 10_000.0 * s) + }) + .collect(); + let path = PathData::single(vectorcraft_geom::SubPath::polyline(&points, true)); + Node::path(NodeId(id), path, Appearance::basic(Paint::solid(RED), Paint::None, 0.0)) +} + +/// A group whose members' solids each fit, but not all of them together, draws its source art, and +/// the commands that check the effect report the error, as do its mesh and its wireframe; one +/// member fewer, within the limit, draws. +#[test] +fn a_groups_solids_together_past_the_limit_draw_the_source() { + let member = polygon_node(1, 16_384); + let mut alone = member.clone(); + alone.appearance.effects.push(fx(EXTRUDE, json!({}))); + let [Ok(Some(each))] = solid_faces(EXTRUDE, &alone, MAX_OBJECT_FACES)[..] else { panic!("one solid") }; + // Members stacked in one place each build the same solid. + let fits = MAX_OBJECT_FACES / each; + let group = |count: usize| { + let members = (0..count) + .map(|k| { + let mut m = member.clone(); + m.id = NodeId(k as u64 + 1); + Arc::new(m) + }) + .collect(); + let mut g = Node::group(NodeId(9999), members); + g.appearance.effects.push(fx(EXTRUDE, json!({}))); + g + }; + let within = group(fits); + assert!(validate_solid(&within, EXTRUDE, &json!({})).is_ok(), "{fits} × {each} faces"); + assert!(solid_art(&within).is_some()); + let past = group(fits + 1); + assert_eq!(validate_solid(&past, EXTRUDE, &json!({})), Err(vectorcraft_three_d::TOO_COMPLEX_SOLID.to_string())); + assert!(solid_art(&past).is_none(), "the source art draws"); + assert_eq!(three_d_meshes(&past), Err(vectorcraft_three_d::TOO_COMPLEX_SOLID.to_string())); + assert_eq!(three_d_wireframe_in(None, &past), Err(vectorcraft_three_d::TOO_COMPLEX_SOLID.to_string())); +} + +/// A fill and strokes whose solids each fit, but not all of them together, draw the source art, +/// and the strokes after the one past the limit are not left out to make room. +#[test] +fn a_fill_and_strokes_together_past_the_limit_draw_the_source() { + let mut n = polygon_node(1, 16_384); + n.appearance.effects.push(fx(EXTRUDE, json!({}))); + let stroke = AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(BLUE), 20.0)); + n.appearance.items.push(stroke.clone()); + // Strokes alike each build the same solid. + let [Ok(Some(fill)), Ok(Some(each))] = solid_faces(EXTRUDE, &n, MAX_OBJECT_FACES)[..] else { panic!("a fill's solid and a stroke's") }; + let fits = (MAX_OBJECT_FACES - fill) / each; + assert!(fits >= 2, "{fill} + {fits} × {each}"); + n.appearance.items.extend(std::iter::repeat_n(stroke, fits - 1)); + assert!(validate_solid(&n, EXTRUDE, &json!({})).is_ok(), "{fill} + {fits} × {each}"); + let art = solid_art(&n).unwrap(); + assert!(faces(&art).iter().any(|f| blue(f))); + n.appearance.items.push(AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(BLUE), 20.0))); + assert_eq!(validate_solid(&n, EXTRUDE, &json!({})), Err(vectorcraft_three_d::TOO_COMPLEX_SOLID.to_string())); + assert!(solid_art(&n).is_none(), "the source art draws"); +} + +/// The check builds the solids from the shapes the art draws them from: after the geometry effects +/// before the 3D effect, on an object, on its fill and on a group. Copies a Transform effect before +/// it makes that take the solids past the limit fail the check, as the art then draws the source. +#[test] +fn the_check_counts_the_faces_after_the_geometry_effects_before() { + let mut alone = polygon_node(1, 16_384); + alone.appearance.effects.push(fx(EXTRUDE, json!({}))); + let [Ok(Some(each))] = solid_faces(EXTRUDE, &alone, MAX_OBJECT_FACES)[..] else { panic!("one solid") }; + // Side by side, each copy builds the same solid. + let copies = |k: usize| fx("distort.transform", json!({"moveH": 30_000.0, "copies": k})); + for (k, fits) in [(1, true), (MAX_OBJECT_FACES / each, false)] { + let mut n = polygon_node(1, 16_384); + n.appearance.effects = vec![copies(k), fx(EXTRUDE, json!({}))]; + assert_eq!(validate_solid(&n, EXTRUDE, &json!({})).is_ok(), fits, "on the object, {k} copies"); + assert_eq!(solid_art(&n).is_some(), fits, "on the object, {k} copies"); + let mut f = polygon_node(1, 16_384); + f.appearance.items[0].effects_mut().extend([copies(k), fx(EXTRUDE, json!({}))]); + assert_eq!(validate_three_d_at(&f, EXTRUDE, &json!({}), (Some(0), 1)).is_ok(), fits, "on the fill, {k} copies"); + assert_eq!(solid_art(&f).is_some(), fits, "on the fill, {k} copies"); + let mut g = Node::group(NodeId(9999), vec![Arc::new(polygon_node(1, 16_384))]); + g.appearance.effects = vec![copies(k), fx(EXTRUDE, json!({}))]; + assert_eq!(validate_solid(&g, EXTRUDE, &json!({})).is_ok(), fits, "on a group, {k} copies"); + assert_eq!(solid_art(&g).is_some(), fits, "on a group, {k} copies"); + // A new effect goes after the copies. + let mut new = polygon_node(1, 16_384); + new.appearance.effects = vec![copies(k)]; + assert_eq!(validate_three_d_at(&new, EXTRUDE, &json!({}), (None, 1)).is_ok(), fits, "a new effect, {k} copies"); + } + // A hidden effect checked at its own index counts only the effects before it: copies after it + // copy the drawn art once it is shown again. + let mut hidden = polygon_node(1, 16_384); + let mut extrude = fx(EXTRUDE, json!({})); + extrude.visible = false; + hidden.appearance.effects = vec![extrude, copies(MAX_OBJECT_FACES / each)]; + assert!(validate_three_d_at(&hidden, EXTRUDE, &json!({}), (None, 0)).is_ok()); + hidden.appearance.effects[0].visible = true; + assert!(solid_art(&hidden).is_some()); +} + /// At no volume Inflate's front is flat: turned, the fill's cells are all drawn before the stroke's, /// whatever their depths, as the extrusion's caps are. When the fill puffs, a stroke too narrow to /// puff on the grid stays flat and keeps its depths: the fill's puff is drawn over its far side. @@ -284,15 +1018,16 @@ fn a_translucent_stroke_is_a_surface_of_its_own() { } /// With a light that is not white, a fill in a gradient with transparent stops is drawn with an -/// opacity mask over its whole surface: the fill's solid and the stroke's stay surfaces of their -/// own, and the mask stays on the fill's. Under a white light the same object is one surface. +/// opacity mask: its faces still take their places in the one order of the fill's and the +/// stroke's faces, in runs that each carry the mask. Under a white light the faces carry the +/// gradient itself and no mask. #[test] -fn a_masked_surface_under_a_colored_light_stays_whole() { +fn a_masked_surface_under_a_colored_light_keeps_the_shared_face_order() { use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; let mut half = GradientStop::new(1.0, RED); half.opacity = 0.5; let gradient = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, RED), half])); - for (lights, surfaces) in [(json!({"lights": [{"color": "#ff8080"}]}), 2), (json!({}), 1)] { + for (lights, masked) in [(json!({"lights": [{"color": "#ff8080"}]}), true), (json!({}), false)] { let mut n = stroked_rect(100.0); if let Some(AppearanceItem::Fill(f)) = n.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Fill(_))) { f.paint = Paint::Gradient(Box::new(gradient.clone())); @@ -300,8 +1035,10 @@ fn a_masked_surface_under_a_colored_light_stays_whole() { n.appearance.effects.push(fx(EXTRUDE, lights.clone())); let art = solid_art(&n).unwrap(); let drawn = art.children().unwrap(); - assert_eq!(drawn.len(), surfaces, "{lights}"); - assert_eq!(drawn[0].extras().mask.is_some(), surfaces == 2, "{lights}"); + assert_eq!(drawn.len(), 1, "{lights}: one order of faces"); + let runs: Vec<&Arc<Node>> = drawn[0].children().unwrap().iter().filter(|c| c.extras().mask.is_some()).collect(); + assert_eq!(!runs.is_empty(), masked, "{lights}"); + assert!(runs.iter().all(|r| r.children().unwrap().iter().all(|f| !blue(f))), "{lights}: the mask stays on the fill's faces"); } } @@ -323,6 +1060,68 @@ fn transparency_stays_on_the_whole_surface_and_items_take_their_own_effect() { assert!(matches!(surfaces[1].kind, NodeKind::Path { .. })); } +/// Two nested squares drawn in the same direction, so only the even-odd rule leaves a hole. +fn nested_squares() -> [PathData; 2] { + [(100.0, 200.0), (130.0, 170.0)].map(|(lo, hi)| { + let mut b = BezPath::new(); + b.move_to((lo, lo)); + b.line_to((hi, lo)); + b.line_to((hi, hi)); + b.line_to((lo, hi)); + b.close_path(); + PathData::from_bezpath(&b) + }) +} + +/// The nested squares as an even-odd compound path and as one even-odd path, painted by `items`. +fn even_odd_shapes(items: Vec<AppearanceItem>) -> [Node; 2] { + let [outer, inner] = nested_squares(); + let appearance = Appearance { items, ..Default::default() }; + let children = vec![ + Arc::new(Node::path(NodeId(2), outer.clone(), Appearance::default())), + Arc::new(Node::path(NodeId(3), inner.clone(), Appearance::default())), + ]; + let mut compound = Node::new(NodeId(1), NodeKind::Compound { children, rule: FillRule::EvenOdd }); + compound.appearance = appearance.clone().into(); + let both = PathData::new(outer.subpaths.into_iter().chain(inner.subpaths).collect()); + [compound, crate::group::shape_node(NodeId(1), both, FillRule::EvenOdd, appearance)] +} + +/// Check that `art` draws `item` as one flat child: an even-odd path with a hole in the middle, +/// below the 3D art after it. +fn assert_flat_item_keeps_the_hole(art: &Node, item: &AppearanceItem, what: &str) { + use vectorcraft_geom::hit::fill_contains; + let children = art.children().unwrap(); + let flat: Vec<usize> = + (0..children.len()).filter(|&i| children[i].appearance.items == [item.clone()] && children[i].path_data().is_some()).collect(); + let [index] = flat[..] else { panic!("{what}: one flat child, got {flat:?}") }; + let NodeKind::Path { path, rule, .. } = &children[index].kind else { panic!("{what}: a path") }; + assert_eq!(*rule, FillRule::EvenOdd, "{what}"); + let bez = path.to_bezpath(); + assert!(fill_contains(&bez, *rule, Point::new(110.0, 150.0)), "{what}: the ring is filled"); + assert!(!fill_contains(&bez, *rule, Point::new(150.0, 150.0)), "{what}: the hole stays open"); + assert!(index + 1 < children.len(), "{what}: the 3D art is drawn above"); +} + +#[test] +fn a_fill_or_stroke_without_the_effect_keeps_the_even_odd_hole() { + let red = AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::solid(RED))); + let blue = AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::solid(BLUE))); + let stroke = AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::BLACK), 4.0)); + for id in SOLIDS { + // The top fill and then the top stroke take the effect; the fill below stays flat. + for (top, on) in [(&red, "fill"), (&stroke, "stroke")] { + let mut lifted = top.clone(); + lifted.effects_mut().push(fx(id, json!({}))); + for (n, shape) in even_odd_shapes(vec![blue.clone(), lifted]).into_iter().zip(["compound path", "path"]) { + let what = format!("{id} on the top {on} of a {shape}"); + let art = solid_art(&n).unwrap_or_else(|| panic!("{what}")); + assert_flat_item_keeps_the_hole(&art, &blue, &what); + } + } + } +} + #[test] fn export_and_expand_bake_faces_with_their_own_ids() { for id in SOLIDS { @@ -716,7 +1515,9 @@ fn classic_shading_keeps_a_gradients_transparency() { } let art = solid_art(&n).unwrap(); let surface = &art.children().unwrap()[0]; - assert_eq!(surface.extras().mask.is_some(), masked, "{end}"); + let mut has_mask = false; + surface.walk(&mut |c| has_mask |= c.extras().mask.is_some()); + assert_eq!(has_mask, masked, "{end}"); let mut opaque = true; surface.walk(&mut |c| { for item in &c.appearance.items { @@ -731,6 +1532,67 @@ fn classic_shading_keeps_a_gradients_transparency() { } } +/// A group member in a gradient with transparent stops keeps the shared back-to-front order of +/// every member's faces: its faces go in runs that carry its opacity mask, and the other member's +/// faces are drawn between them where they are in front of some and behind others. Here a square +/// frame in the gradient holds a square in its hole: the frame's inner walls are behind the square +/// and its front cap is in front of the square's walls. +#[test] +fn a_member_in_a_transparent_gradient_keeps_the_shared_face_order() { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let square = |b: &mut BezPath, x0: f64, x1: f64, clockwise: bool| { + let corners = [(x0, x0), (x1, x0), (x1, x1), (x0, x1)]; + let mut points = corners.to_vec(); + if !clockwise { + points.reverse(); + } + b.move_to(points[0]); + for p in &points[1..] { + b.line_to(*p); + } + b.close_path(); + }; + let art = |id: &str, params: &Value, end_opacity: f32| { + let mut end = GradientStop::new(1.0, Color::BLACK); + end.opacity = end_opacity; + let gradient = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, RED), end])))); + let mut b = BezPath::new(); + square(&mut b, 100.0, 300.0, true); + square(&mut b, 150.0, 250.0, false); + let frame = Node::path(NodeId(1), PathData::from_bezpath(&b), Appearance::basic(gradient, Paint::None, 0.0)); + let mut b = BezPath::new(); + square(&mut b, 185.0, 215.0, true); + let inner = Node::path(NodeId(2), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(BLUE), Paint::None, 0.0)); + let mut g = Node::group(NodeId(3), vec![Arc::new(frame), Arc::new(inner)]); + g.appearance.effects.push(fx(id, params.clone())); + solid_art(&g).unwrap_or_else(|| panic!("{id}")) + }; + // The drawing order: `M` for a group with an opacity mask, `F` for a face outside one. + fn visit(n: &Node, order: &mut String) { + if n.extras().mask.is_some() { + order.push('M'); + return; + } + if n.path_data().is_some() { + order.push('F'); + } + for c in n.children().into_iter().flatten() { + visit(c, order); + } + } + let order = |art: &Node| { + let mut order = String::new(); + visit(art, &mut order); + order + }; + for (id, params) in [(CLASSIC_EXTRUDE, json!({})), (EXTRUDE, json!({"lights": [{"color": "#ff8080"}]}))] { + assert!(!order(&art(id, ¶ms, 1.0)).contains('M'), "{id}: an opaque gradient needs no mask"); + let masked = order(&art(id, ¶ms, 0.5)); + let (first, last) = (masked.find('M').unwrap(), masked.rfind('M').unwrap()); + assert!(masked.get(first..last).is_some_and(|between| between.contains('F')), "{id}: faces between the member's runs: {masked}"); + } +} + #[test] fn classic_parameters_are_checked() { let n = classic(json!({})); @@ -758,3 +1620,80 @@ fn classic_parameters_are_checked() { assert!(err.starts_with(says), "{p}: {err}"); } } + +/// The red square, stroked black, with Rotate (Classic) and `params`: its surfaces, the fill's +/// plane first, then the stroke's outline. +fn classic_rotate(params: Value) -> Vec<Node> { + let mut n = square_node(); + n.appearance.effects.push(fx(CLASSIC_ROTATE, params)); + solid_art(&n).unwrap().children().unwrap().iter().map(|s| (**s).clone()).collect() +} + +#[test] +fn classic_rotate_turns_every_fill_and_stroke_as_one_plane() { + let front = json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0}); + let surfaces = classic_rotate(front.clone()); + assert_eq!(surfaces.len(), 2, "the fill's plane and the stroke's outline"); + assert!(surfaces.iter().all(|s| s.children().unwrap().len() == 1), "each is one flat face"); + let fill = surfaces[0].visual_bounds().unwrap(); + assert!((fill.width() - 100.0).abs() < 1.0 && (fill.height() - 100.0).abs() < 1.0, "{fill:?}"); + // Turned 60° about the vertical axis, the square shows half its width and all its height, + // about the center of its bounds. + let turned = classic_rotate(json!({"rotationX": 0, "rotationY": 60, "rotationZ": 0}))[0].visual_bounds().unwrap(); + assert!((turned.width() - 50.0).abs() < 1.0 && (turned.height() - 100.0).abs() < 1.0, "{turned:?}"); + assert!((turned.center().x - 150.0).abs() < 1.0, "{turned:?}"); + // Turned past 90°, the back of the plane is drawn. + let back = classic_rotate(json!({"rotationX": 0, "rotationY": 150, "rotationZ": 0})); + assert!(back[0].visual_bounds().is_some_and(|b| (b.width() - 100.0 * 30f64.to_radians().cos()).abs() < 1.0)); +} + +#[test] +fn classic_rotate_shades_with_no_shading_or_diffuse() { + let rgb = |p: Value| fill_rgb(&classic_rotate(p)[0].children().unwrap()[0]); + // No Shading keeps the paint, the color itself kept. + let mut n = square_node(); + n.appearance.effects.push(fx(CLASSIC_ROTATE, json!({"surface": "none"}))); + let art = solid_art(&n).unwrap(); + let AppearanceItem::Fill(f) = &faces(&art)[0].appearance.items[0] else { panic!("a fill first") }; + assert_eq!(f.paint, Paint::solid(RED)); + // Diffuse: straight on with the light in front, the face is fully lit; turned away from the + // light, it is the red darkened toward black. + let lit = json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "lightHeight": 90}); + assert!(close3(rgb(lit), RED.to_rgb())); + let [r, g, b] = rgb(json!({"rotationX": 0, "rotationY": 70, "rotationZ": 0, "lightHeight": 90})); + assert!(r < 0.8 - 0.05 && (g * 4.0 - r).abs() < 1e-4 && (b * 8.0 - r).abs() < 1e-4, "{r} {g} {b}"); + // No light: the ambient share of the red. A custom shading color darkens toward that color; + // None keeps the paint. + let dark = rgb(json!({"lightIntensity": 0, "ambient": 20, "blendSteps": 256})); + assert!((dark[0] - 0.8 * 0.2).abs() < 0.01, "{dark:?}"); + let blue = rgb(json!({"lightIntensity": 0, "ambient": 20, "shadingColor": "custom", "shadingCustom": "#0000ff"})); + assert!(blue[2] > blue[0] / 8.0 + 0.01, "{blue:?}"); + assert!(close3(rgb(json!({"lightIntensity": 0, "shadingColor": "none"})), RED.to_rgb())); +} + +#[test] +fn classic_rotate_parameters_are_checked() { + let n = square_node(); + let check = |p: Value| validate_solid(&n, CLASSIC_ROTATE, &crate::merged_params(CLASSIC_ROTATE, &p)); + assert!(check(json!({})).is_ok()); + assert!(check(json!({"surface": "none", "shadingColor": "custom", "shadingCustom": "#12aBcd", "blendSteps": 1})).is_ok()); + for (p, says) in [ + (json!({"surface": "plastic"}), "`surface` must be one of none, diffuse"), + (json!({"surface": "wireframe"}), "`surface` must be one of none, diffuse"), + (json!({"surface": 2}), "`surface` must be one of"), + (json!({"shadingColor": "red"}), "`shadingColor` must be one of black, custom, none"), + (json!({"shadingCustom": "#fff"}), "`shadingCustom` must be a #rrggbb color"), + (json!({"rotationX": 181}), "`rotationX` must be between -180 and 180 (got 181)"), + (json!({"perspectiveAngle": 161}), "`perspectiveAngle` must be between 0 and 160 (got 161)"), + (json!({"lightIntensity": 101}), "`lightIntensity` must be between 0 and 100 (got 101)"), + (json!({"blendSteps": 0}), "`blendSteps` must be a whole number between 1 and 256 (got 0)"), + (json!({"lightBehind": 1}), "`lightBehind` must be true or false"), + (json!({"highlightSize": 50}), "unknown parameter `highlightSize`"), + (json!({"drawHiddenFaces": true}), "unknown parameter `drawHiddenFaces`"), + (json!({"shadow": true}), "unknown parameter `shadow`"), + (json!({"lights": []}), "lights must contain one to ten lights"), + ] { + let err = check(p.clone()).unwrap_err(); + assert!(err.starts_with(says), "{p}: {err}"); + } +} diff --git a/crates/effects/src/solids/tests_graphics.rs b/crates/effects/src/solids/tests_graphics.rs new file mode 100644 index 0000000000..e0935a43e7 --- /dev/null +++ b/crates/effects/src/solids/tests_graphics.rs @@ -0,0 +1,870 @@ +use serde_json::json; +use vectorcraft_doc::color::Color; +use vectorcraft_doc::{StrokeLayer, Symbol}; +use vectorcraft_geom::shapes; + +use super::super::{EXTRUDE, INFLATE, ROTATE, graphic_frame, solid_art_in, three_d_params_as, validate_three_d_in, validate_three_d_params}; +use super::*; + +fn red() -> Color { + Color::rgb(1.0, 0.0, 0.0) +} + +fn square(id: u64, r: Rect, paint: Paint) -> Node { + Node::path(NodeId(id), shapes::rectangle(r), Appearance::basic(paint, Paint::None, 0.0)) +} + +/// A document with symbol "Mark": a red 10 × 10 square. +fn document() -> Document { + let mut d = Document::new(1000.0, 1000.0); + d.symbols.push(Symbol { + dynamic: false, + name: "Mark".into(), + art: Arc::new(square(0, Rect::new(500.0, 500.0, 510.0, 510.0), Paint::solid(red()))), + }); + d +} + +/// A gray 100 × 100 square at (0, 0) with effect `id`, its parameters `params` over a view +/// straight on. +fn object(id: &str, params: Value) -> Node { + let mut p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": false}); + if let (Some(p), Some(extra)) = (p.as_object_mut(), params.as_object()) { + p.extend(extra.clone()); + } + let mut n = square(7, Rect::new(0.0, 0.0, 100.0, 100.0), Paint::solid(Color::rgb(0.5, 0.5, 0.5))); + n.appearance.effects.push(crate::new_effect(id, &p).unwrap()); + n +} + +/// The graphics clip groups in `art`, in drawing order: each one's mapped paths. +fn graphics_in(art: &Node) -> Vec<Vec<(PathData, Paint)>> { + let mut out = vec![]; + art.walk(&mut |n| { + if let NodeKind::Group { children, clip: true } = &n.kind + && let [_, inner] = children.as_slice() + && let NodeKind::Group { children: paths, clip: false } = &inner.kind + { + let paths: Vec<(PathData, Paint)> = paths + .iter() + .filter_map(|p| { + let fill = p.appearance.items.iter().find_map(|i| match i { + AppearanceItem::Fill(f) => Some(f.paint.clone()), + AppearanceItem::Stroke(_) => None, + })?; + Some((p.path_data()?.clone(), fill)) + }) + .collect(); + if paths.iter().any(|(_, p)| p.color().is_some_and(|c| c.to_rgb()[1] < 0.1 && c.to_rgb()[0] > 0.3)) { + out.push(paths); + } + } + }); + out +} + +fn bounds_of(paths: &[(PathData, Paint)]) -> Rect { + paths.iter().filter_map(|(p, _)| p.bounds()).reduce(|a, b| a.union(b)).unwrap() +} + +fn close(a: Rect, b: Rect) -> bool { + [(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(p, q)| (p - q).abs() < 1e-6) +} + +#[test] +fn a_graphic_is_drawn_on_the_front_cap_at_its_offset_size_and_turn() { + let d = document(); + let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Mark", "x": 20.0, "y": -10.0, "scale": 200.0}]})); + let art = solid_art_in(Some(&d), &n).unwrap(); + let found = graphics_in(&art); + assert_eq!(found.len(), 1); + // Straight on, the front cap is the art: a 20 × 20 square centered 20 right of and 10 above (50, 50). + assert!(close(bounds_of(&found[0]), Rect::new(60.0, 30.0, 80.0, 50.0)), "{:?}", bounds_of(&found[0])); + // Turned 45°, the square's corners reach out to its half diagonal. + let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Mark", "rotation": 45.0}]})); + let b = bounds_of(&graphics_in(&solid_art_in(Some(&d), &n).unwrap())[0]); + assert!((b.width() - 10.0 * 2f64.sqrt()).abs() < 1e-6); +} + +#[test] +fn without_the_document_or_its_symbol_nothing_is_drawn() { + let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Mark"}]})); + let art = solid_art_in(None, &n).unwrap(); + assert!(graphics_in(&art).is_empty()); + let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Gone"}]})); + assert!(graphics_in(&solid_art_in(Some(&document()), &n).unwrap()).is_empty()); + // Without graphics, the art is the same as before they existed. + let plain = object(EXTRUDE, json!({})); + assert_eq!(solid_art_in(Some(&document()), &plain), solid_art_in(None, &plain)); +} + +#[test] +fn the_graphic_is_shaded_with_its_face() { + let d = document(); + let n = object(EXTRUDE, json!({"shade": true, "lightIntensity": 0.0, "ambient": 50.0, "graphics": [{"symbol": "Mark"}]})); + let found = graphics_in(&solid_art_in(Some(&d), &n).unwrap()); + let c = found[0][0].1.color().unwrap().to_rgb(); + assert!((c[0] - 0.5).abs() < 1e-3 && c[1].abs() < 1e-6 && c[2].abs() < 1e-6, "{c:?}"); +} + +#[test] +fn the_graphic_goes_right_after_its_cap_and_is_clipped_to_it() { + let d = document(); + let n = object(EXTRUDE, json!({"rotationX": -20.0, "rotationY": 25.0, "graphics": [{"symbol": "Mark", "scale": 2000.0}]})); + let art = solid_art_in(Some(&d), &n).unwrap(); + let NodeKind::Group { children, .. } = &art.kind else { panic!("a group") }; + let NodeKind::Group { children: faces, .. } = &children.last().unwrap().kind else { panic!("the ordered faces") }; + let last = faces.last().unwrap(); + assert!(matches!(&last.kind, NodeKind::Group { clip: true, .. }), "the graphic is drawn last, over the front cap"); + let NodeKind::Group { children: parts, .. } = &last.kind else { panic!() }; + let clip = parts[0].path_data().unwrap().bounds().unwrap(); + let cap = faces[faces.len() - 2].path_data().unwrap().bounds().unwrap(); + assert!(close(clip, cap), "clipped to the cap: {clip:?} against {cap:?}"); +} + +#[test] +fn the_back_cap_reads_the_right_way_round_from_behind() { + let d = document(); + let behind = json!({"rotationY": 180.0, "graphics": [{"symbol": "Mark", "face": "back", "x": 20.0}]}); + let n = object(EXTRUDE, behind); + let found = graphics_in(&solid_art_in(Some(&d), &n).unwrap()); + assert_eq!(found.len(), 1); + let b = bounds_of(&found[0]); + // Seen from behind, x runs to the right on the page too. + assert!((b.center().x - 70.0).abs() < 1e-6, "{b:?}"); + let frame = graphic_frame(Some(&d), &n, None).unwrap(); + let g = MappedGraphic::from_value(&json!({"symbol": "Mark", "face": "back", "x": 20.0})).unwrap(); + let (at, visible) = frame.handle(&g).unwrap(); + assert!(visible && (at.x - 70.0).abs() < 1e-6); + let (x, y) = frame.offset_at(PlanarFace::Back, Point::new(40.0, 55.0)).unwrap(); + assert!((x + 10.0).abs() < 1e-6 && (y - 5.0).abs() < 1e-6); + // From the front the back cap is hidden, and so is its graphic. + let front = object(EXTRUDE, json!({"graphics": [{"symbol": "Mark", "face": "back"}]})); + assert!(graphics_in(&solid_art_in(Some(&d), &front).unwrap()).is_empty()); +} + +#[test] +fn a_perspective_foreshortens_the_graphic_with_its_face() { + let d = document(); + let params = json!({"rotationX": -30.0, "rotationY": 35.0, "perspectiveAngle": 100.0, "graphics": [{"symbol": "Mark", "scale": 400.0}]}); + let n = object(EXTRUDE, params); + let found = graphics_in(&solid_art_in(Some(&d), &n).unwrap()); + let frame = graphic_frame(Some(&d), &n, None).unwrap(); + let map = frame.map(PlanarFace::Front).unwrap(); + // The corners of the 40 × 40 square centered on the object land where the face's map takes them. + let path = &found[0][0].0; + let corners: Vec<Point> = [(30.0, 30.0), (70.0, 30.0), (70.0, 70.0), (30.0, 70.0)].map(|(x, y)| map.to_page(Point::new(x, y)).unwrap()).into(); + for c in corners { + let near = path.subpaths.iter().flat_map(|s| &s.anchors).map(|a| a.p.distance(c)).fold(f64::INFINITY, f64::min); + assert!(near < 1e-6, "{c:?} is {near} from the drawn graphic"); + } +} + +#[test] +fn a_graphic_behind_the_eye_leaves_the_others_drawn() { + let d = document(); + let view = json!({"rotationX": -60.0, "rotationY": 0.0, "perspectiveAngle": 160.0}); + let n = object(EXTRUDE, view.clone()); + let frame = graphic_frame(Some(&d), &n, None).unwrap(); + let map = frame.map(PlanarFace::Front).unwrap(); + let c = frame.bounds.center(); + // An offset whose point of the front's plane is at or behind the eye. + let y = [1.0, -1.0] + .into_iter() + .flat_map(|s| (1..60).map(move |k| s * 10f64.powf(f64::from(k) / 10.0))) + .find(|y| map.local_affine(Point::new(c.x, c.y + y)).is_none()) + .expect("an offset behind the eye"); + let mut params = view; + params["graphics"] = json!([{"symbol": "Mark"}, {"symbol": "Mark", "y": y}]); + let found = graphics_in(&solid_art_in(Some(&d), &object(EXTRUDE, params)).unwrap()); + assert_eq!(found.len(), 1, "the graphic that projects is still drawn"); + // A graphic centered there but large enough to reach over the cap draws the part in front. + let mut params = json!({"rotationX": -60.0, "rotationY": 0.0, "perspectiveAngle": 160.0}); + params["graphics"] = json!([{"symbol": "Mark", "y": y, "scale": (20.0 * (y.abs() + 50.0)).clamp(1.0, 10_000.0)}]); + let found = graphics_in(&solid_art_in(Some(&d), &object(EXTRUDE, params)).unwrap()); + assert_eq!(found.len(), 1, "the part in front is drawn (offset {y})"); + assert!(!found[0].is_empty()); +} + +#[test] +fn the_graphic_takes_the_opacity_of_its_fill() { + let d = document(); + for id in [EXTRUDE, ROTATE] { + let mut n = object(id, json!({"graphics": [{"symbol": "Mark"}]})); + if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() { + f.opacity = 0.25; + } + let art = solid_art_in(Some(&d), &n).unwrap(); + let mut opacities = vec![]; + art.walk(&mut |c| { + if matches!(c.kind, NodeKind::Group { clip: true, .. }) { + opacities.push(c.opacity); + } + }); + assert_eq!(opacities, vec![0.25], "{id}"); + } +} + +#[test] +fn the_graphic_takes_the_blending_mode_of_its_fill() { + let d = document(); + for id in [EXTRUDE, ROTATE] { + let mut n = object(id, json!({"graphics": [{"symbol": "Mark"}]})); + if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() { + f.blend = BlendMode::Multiply; + } + let art = solid_art_in(Some(&d), &n).unwrap(); + let mut blends = vec![]; + art.walk(&mut |c| { + if matches!(c.kind, NodeKind::Group { clip: true, .. }) { + blends.push(c.blend); + } + }); + assert_eq!(blends, vec![BlendMode::Multiply], "{id}"); + } +} + +#[test] +fn each_fill_of_a_plane_gives_its_graphic_its_own_opacity() { + let d = document(); + let mut n = object(ROTATE, json!({"graphics": [{"symbol": "Mark"}]})); + if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() { + f.opacity = 0.25; + } + let mut second = FillLayer::new(Paint::solid(Color::rgb(0.2, 0.2, 0.2))); + second.opacity = 0.75; + n.appearance.items.push(AppearanceItem::Fill(second)); + let art = solid_art_in(Some(&d), &n).unwrap(); + let mut opacities = vec![]; + art.walk(&mut |c| { + if matches!(c.kind, NodeKind::Group { clip: true, .. }) { + opacities.push(c.opacity); + } + }); + opacities.sort_by(f32::total_cmp); + assert_eq!(opacities, vec![0.25, 0.75]); +} + +#[test] +fn a_symbols_gradient_takes_the_size_of_its_art() { + use vectorcraft_doc::color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop}; + let mut d = document(); + // Symbol art kept in its 20 × 20 square, drawn 40 × 20. + let mut g = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red()), GradientStop::new(1.0, Color::BLACK)])); + g.geom = Some(GradientGeom { start: Point::new(-10.0, 0.0), end: Point::new(10.0, 0.0), aspect: 1.0, focal: None }); + let art = square(0, Rect::new(-10.0, -10.0, 10.0, 10.0), Paint::Gradient(Box::new(g))); + d.symbols.push(Symbol { dynamic: false, name: "Ramp".into(), art: Arc::new(art) }); + d.unknown.insert(vectorcraft_doc::SYMBOL_SIZES.into(), json!({"Ramp": [40.0, 20.0]})); + let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Ramp"}]})); + let out = solid_art_in(Some(&d), &n).unwrap(); + let mut found = None; + out.walk(&mut |c| { + if let (Some(p), Some(AppearanceItem::Fill(f))) = (c.path_data(), c.appearance.items.first()) + && let Paint::Gradient(g) = &f.paint + { + found = Some((p.bounds().unwrap(), g.geom.unwrap())); + } + }); + let (bounds, geom) = found.unwrap(); + assert!(close(bounds, Rect::new(30.0, 40.0, 70.0, 60.0)), "{bounds:?}"); + assert!(geom.start.distance(Point::new(30.0, 50.0)) < 1e-6 && geom.end.distance(Point::new(70.0, 50.0)) < 1e-6, "{geom:?}"); +} + +#[test] +fn a_symbols_pattern_follows_the_graphic() { + let mut d = document(); + let tiles = Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY }; + d.symbols.push(Symbol { dynamic: false, name: "Tiles".into(), art: Arc::new(square(0, Rect::new(-10.0, -10.0, 10.0, 10.0), tiles)) }); + let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Tiles", "scale": 200.0}]})); + let out = solid_art_in(Some(&d), &n).unwrap(); + let mut found = None; + out.walk(&mut |c| { + if let Some(AppearanceItem::Fill(f)) = c.appearance.items.first() + && let Paint::Pattern { xf, .. } = &f.paint + { + found = Some((c.path_data().unwrap().bounds().unwrap(), *xf)); + } + }); + let (bounds, xf) = found.unwrap(); + // The 20 × 20 art drawn 40 × 40 on the middle of the front: its tiles go with it. + assert!(close(bounds, Rect::new(30.0, 30.0, 70.0, 70.0)), "{bounds:?}"); + assert!((xf * Point::new(-10.0, -10.0)).distance(Point::new(30.0, 30.0)) < 1e-6, "{xf:?}"); + assert!((xf * Point::new(10.0, 10.0)).distance(Point::new(70.0, 70.0)) < 1e-6, "{xf:?}"); +} + +#[test] +fn a_curve_in_front_of_the_eye_maps_though_its_control_points_do_not() { + let bounds = Rect::new(10.0, 20.0, 70.0, 60.0); + let view = vectorcraft_three_d::View { rotation_x: -89.0, rotation_y: 40.0, rotation_z: 10.0, perspective: 160.0, ..Default::default() }; + let map = vectorcraft_three_d::plane_face_map(bounds, view).unwrap(); + // Where the page map stops along the line x = `x`, between the center and a point it does not map. + let edge = |x: f64| { + let inside = Point::new(x, bounds.center().y); + let far = [Point::new(x, -1e6), Point::new(x, 1e6)].into_iter().find(|p| map.to_page(*p).is_none()).unwrap(); + let (mut a, mut b) = (inside, far); + for _ in 0..200 { + let m = a.midpoint(b); + if map.to_page(m).is_some() { a = m } else { b = m } + } + a + }; + let (b1, b2) = (edge(40.0), edge(60.0)); + let u = (b2 - b1).normalize(); + let mut n = vectorcraft_geom::Vec2::new(-u.y, u.x); + if map.to_page(b1 + n * 10.0).is_none() { + n = -n; + } + // Ends 219.17 in front of that line and control points 100 and 42 past it: the curve stays + // about 1 in front, while a control point of one of the pieces it is cut into falls behind. + let at = |s: f64, t: f64| b1 + n * s + u * t; + let mut curve = BezPath::new(); + curve.move_to(at(219.17, 0.0)); + curve.curve_to(at(-100.0, 5.0), at(-42.0, 15.0), at(219.17, 20.0)); + let c = CubicBez::new(at(219.17, 0.0), at(-100.0, 5.0), at(-42.0, 15.0), at(219.17, 20.0)); + assert!((0..=1000).all(|k| map.to_page(c.eval(k as f64 / 1000.0)).is_some()), "the curve itself is in front"); + let pieces = (0..PERSPECTIVE_PIECES).map(|k| c.subsegment(k as f64 / 8.0..(k + 1) as f64 / 8.0)); + assert!(pieces.flat_map(|s| [s.p1, s.p2]).any(|p| map.to_page(p).is_none()), "a piece's control point is behind"); + let mapped = map_path(&PathData::from_bezpath(&curve), &map, None, usize::MAX).expect("the curve maps"); + // The split pieces count toward the room the path is given: without room, the path is full, + // not behind the eye, so it is not clipped. + assert!(mapped.elements().len() > 1 + PERSPECTIVE_PIECES); + assert_eq!(map_path(&PathData::from_bezpath(&curve), &map, None, PERSPECTIVE_PIECES + 1).err(), Some(NotMapped::Full)); + assert!(mapped.elements().iter().all(|e| e.end_point().is_none_or(|p| p.x.is_finite() && p.y.is_finite()))); + // That piece is split until its halves' control points map, so it stays a curve. + assert!(mapped.elements().iter().all(|e| !matches!(e, PathEl::LineTo(_))), "{mapped:?}"); + // With its ends at 214.25 instead, the curve dips about 0.24 behind the line between the ends + // of two pieces, which still map: it has no page point there, and is left to the clipping. + let c = CubicBez::new(at(214.25, 0.0), at(-100.0, 5.0), at(-42.0, 15.0), at(214.25, 20.0)); + assert!((0..=PERSPECTIVE_PIECES).all(|k| map.to_page(c.eval(k as f64 / 8.0)).is_some())); + assert!((0..=1000).any(|k| map.to_page(c.eval(k as f64 / 1000.0)).is_none())); + let mut dips = BezPath::new(); + dips.move_to(c.p0); + dips.curve_to(c.p1, c.p2, c.p3); + assert_eq!(map_path(&PathData::from_bezpath(&dips), &map, None, usize::MAX).err(), Some(NotMapped::Behind)); +} + +#[test] +fn members_with_their_own_blending_get_graphics_of_their_own() { + let d = document(); + let a = square(1, Rect::new(0.0, 0.0, 50.0, 100.0), Paint::solid(Color::rgb(0.5, 0.5, 0.5))); + let mut b = square(2, Rect::new(50.0, 0.0, 100.0, 100.0), Paint::solid(Color::rgb(0.5, 0.5, 0.5))); + b.blend = BlendMode::Multiply; + let mut group = Node::group(NodeId(3), vec![Arc::new(a), Arc::new(b)]); + let p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": false, "graphics": [{"symbol": "Mark", "scale": 1000.0}]}); + group.appearance.effects.push(crate::new_effect(EXTRUDE, &p).unwrap()); + let art = solid_art_in(Some(&d), &group).unwrap(); + let found = graphics_in(&art); + // One graphic clipped to each member's cap: the second stays inside the member's Multiply group. + assert_eq!(found.len(), 2); + let mut blended = 0; + art.walk(&mut |c| { + if c.blend == BlendMode::Multiply { + blended += graphics_in(c).len(); + } + }); + assert_eq!(blended, 1); +} + +#[test] +fn a_graphic_stays_under_a_solid_painted_after_its_own() { + let d = document(); + let member = |id: u64, r: Rect, color: Color, opacity: f32| { + let mut n = square(id, r, Paint::solid(color)); + if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() { + f.opacity = opacity; + } + Arc::new(n) + }; + let gray = Color::rgb(0.5, 0.5, 0.5); + // A and C share their fill's opacity; B, painted between them, has its own and covers part of A. + let a = member(1, Rect::new(0.0, 0.0, 60.0, 100.0), gray, 1.0); + let b = member(2, Rect::new(40.0, 0.0, 100.0, 100.0), Color::rgb(0.0, 0.0, 1.0), 0.5); + let c = member(4, Rect::new(200.0, 0.0, 260.0, 100.0), gray, 1.0); + let mut group = Node::group(NodeId(3), vec![a, b, c]); + let p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": false, "graphics": [{"symbol": "Mark", "scale": 3000.0}]}); + group.appearance.effects.push(crate::new_effect(EXTRUDE, &p).unwrap()); + let art = solid_art_in(Some(&d), &group).unwrap(); + // In drawing order: 'G' for a graphic, 'B' for a face of B's solid. + let mut order = String::new(); + art.walk(&mut |n| { + if matches!(n.kind, NodeKind::Group { clip: true, .. }) && !graphics_in(n).is_empty() { + order.push('G'); + } else if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first() + && f.paint.color().is_some_and(|c| c.to_rgb()[2] > 0.9 && c.to_rgb()[0] < 0.1) + { + order.push('B'); + } + }); + // A's graphic is drawn right after A, under B; C's is drawn after B. + assert_eq!(graphics_in(&art).len(), 3, "{order}"); + assert!(order.starts_with('G'), "{order}"); +} + +/// [`document`] with symbol "Dense" too: a red polygon of 30,000 sides, straight or `curved`. +fn dense_document(curved: bool) -> Document { + let mut d = document(); + let mut poly = BezPath::new(); + let mut last = Point::ZERO; + for k in 0..30_000 { + let a = k as f64 / 30_000.0 * std::f64::consts::TAU; + let p = Point::new(5.0 + 5.0 * a.cos(), 5.0 + 5.0 * a.sin()); + if k == 0 { + poly.move_to(p); + } else if curved { + poly.curve_to(last.lerp(p, 1.0 / 3.0), last.lerp(p, 2.0 / 3.0), p); + } else { + poly.line_to(p); + } + last = p; + } + poly.close_path(); + let art = Node::path(NodeId(0), PathData::from_bezpath(&poly), Appearance::basic(Paint::solid(red()), Paint::None, 0.0)); + d.symbols.push(Symbol { dynamic: false, name: "Dense".into(), art: Arc::new(art) }); + d +} + +/// The graphics drawn on a group of two members, each with its own graphic of symbol "Dense" +/// ([`dense_document`]), seen under a perspective. +fn dense_graphics_drawn(curved: bool) -> usize { + let d = dense_document(curved); + let a = square(1, Rect::new(0.0, 0.0, 50.0, 100.0), Paint::solid(Color::rgb(0.5, 0.5, 0.5))); + let mut b = square(2, Rect::new(50.0, 0.0, 100.0, 100.0), Paint::solid(Color::rgb(0.5, 0.5, 0.5))); + b.blend = BlendMode::Multiply; + let mut group = Node::group(NodeId(3), vec![Arc::new(a), Arc::new(b)]); + let p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "perspectiveAngle": 60.0, "shade": false, "graphics": [{"symbol": "Dense", "scale": 1000.0}]}); + group.appearance.effects.push(crate::new_effect(EXTRUDE, &p).unwrap()); + graphics_in(&solid_art_in(Some(&d), &group).unwrap()).len() +} + +#[test] +fn members_with_graphics_of_their_own_share_one_element_limit() { + // A perspective cuts each of the 30,000 curves into 8: one copy fits the limit, two do not. + // The first member's graphic is drawn; the second would pass the limit, so it draws none. + assert_eq!(dense_graphics_drawn(true), 1); +} + +#[test] +fn straight_sides_count_once_under_a_perspective() { + // A perspective keeps each of the 30,000 straight sides one element: both copies fit the limit. + assert_eq!(dense_graphics_drawn(false), 2); +} + +#[test] +fn the_symbol_check_counts_what_the_view_draws() { + // Two graphics of the 30,000-sided polygon under a perspective: straight, they fit the limit; + // curved, they do not. + let two = json!({"perspectiveAngle": 60.0, "graphics": [{"symbol": "Dense"}, {"symbol": "Dense", "face": "back"}]}); + let n = object(EXTRUDE, two.clone()); + assert!(validate_three_d_in(Some(&dense_document(false)), &n, EXTRUDE, &two).is_ok()); + let e = validate_three_d_in(Some(&dense_document(true)), &n, EXTRUDE, &two).unwrap_err(); + assert!(e.contains("too complex"), "{e}"); + // Without a perspective each curve draws once: curved, they fit too. + let flat = json!({"perspectiveAngle": 0.0, "graphics": two["graphics"].clone()}); + assert!(validate_three_d_in(Some(&dense_document(true)), &n, EXTRUDE, &flat).is_ok()); +} + +#[test] +fn a_plane_and_a_hollow_solid() { + let d = document(); + let plane = object(ROTATE, json!({"rotationY": 30.0, "graphics": [{"symbol": "Mark"}]})); + assert_eq!(graphics_in(&solid_art_in(Some(&d), &plane).unwrap()).len(), 1); + let hollow = object(EXTRUDE, json!({"cap": false, "graphics": [{"symbol": "Mark"}]})); + assert!(graphics_in(&solid_art_in(Some(&d), &hollow).unwrap()).is_empty()); +} + +#[test] +fn a_stroked_graphic_draws_its_stroke_as_an_outline() { + let mut d = document(); + let mut ring = square(0, Rect::new(0.0, 0.0, 10.0, 10.0), Paint::None); + ring.appearance = Appearance { items: vec![AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(red()), 2.0))], ..Default::default() }.into(); + d.symbols.push(Symbol { dynamic: false, name: "Ring".into(), art: Arc::new(ring) }); + let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Ring"}]})); + let found = graphics_in(&solid_art_in(Some(&d), &n).unwrap()); + // The 10 × 10 square's 2 pt stroke reaches 1 pt outside it. + assert!(close(bounds_of(&found[0]), Rect::new(44.0, 44.0, 56.0, 56.0)), "{:?}", bounds_of(&found[0])); +} + +#[test] +fn graphics_are_checked() { + let n = object(EXTRUDE, json!({})); + let check = |id: &str, graphics: Value| validate_three_d_in(None, &n, id, &json!({"graphics": graphics})); + assert!(check(EXTRUDE, json!([{"symbol": "Mark", "face": "back", "x": 3.0, "scale": 50.0, "rotation": -90.0}])).is_ok()); + assert!(check(EXTRUDE, json!([])).is_ok()); + for bad in [ + json!("Mark"), + json!([{"face": "front"}]), + json!([{"symbol": ""}]), + json!([{"symbol": "Mark", "face": "side"}]), + json!([{"symbol": "Mark", "scale": 0.0}]), + json!([{"symbol": "Mark", "rotation": 400.0}]), + json!([{"symbol": "Mark", "x": "1"}]), + json!([{"symbol": "Mark", "repeat": true}]), + json!(vec![json!({"symbol": "Mark"}); MAX_GRAPHICS + 1]), + ] { + assert!(check(EXTRUDE, bad.clone()).is_err(), "{bad}"); + } + assert!(check(ROTATE, json!([{"symbol": "Mark", "face": "back"}])).is_err()); + assert!(check(INFLATE, json!([{"symbol": "Mark"}])).is_err()); + // Revolve takes graphics on its side, named the front; Revolve (Classic) takes none. + assert!(validate_three_d_params(crate::REVOLVE, &json!({"graphics": [{"symbol": "Mark"}]})).is_ok()); + assert!(validate_three_d_params(crate::REVOLVE, &json!({"graphics": [{"symbol": "Mark", "face": "back"}]})).is_err()); + assert!(validate_three_d_params(crate::CLASSIC_REVOLVE, &json!({"graphics": [{"symbol": "Mark"}]})).is_err()); + // A loaded file's invalid entries are left out when drawn. + assert_eq!(mapped_graphics(&json!({"graphics": [{"symbol": "Mark"}, {"face": "back"}, 3]})).len(), 1); +} + +#[test] +fn the_frame_at_an_index_is_that_effects() { + let d = document(); + let mut n = object(EXTRUDE, json!({})); + n.appearance.effects.push(crate::new_effect(ROTATE, &json!({})).unwrap()); + // The first 3D effect is the Extrude & Bevel, with a back cap; the second is a plane, without. + assert!(graphic_frame(Some(&d), &n, None).unwrap().map(PlanarFace::Back).is_some()); + assert!(super::super::graphic_frame_at(Some(&d), &n, None, 0).unwrap().map(PlanarFace::Back).is_some()); + assert!(super::super::graphic_frame_at(Some(&d), &n, None, 1).unwrap().map(PlanarFace::Back).is_none()); + assert!(super::super::graphic_frame_at(Some(&d), &n, None, 2).is_none()); +} + +#[test] +fn a_change_to_a_plane_drops_the_back_caps_graphics() { + let p = json!({"graphics": [{"symbol": "Mark", "face": "front"}, {"symbol": "Mark", "face": "back"}]}); + let plane = three_d_params_as(EXTRUDE, &p, ROTATE); + assert_eq!(plane["graphics"], json!([{"symbol": "Mark", "face": "front"}])); + assert!(validate_three_d_params(ROTATE, &plane).is_ok()); + // Back to Extrude & Bevel, the front's graphic stays. + assert_eq!(three_d_params_as(ROTATE, &plane, EXTRUDE)["graphics"], plane["graphics"]); +} + +#[test] +fn a_stroked_solid_carries_its_graphic_too() { + let d = document(); + let mut n = Node::path( + NodeId(7), + shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), + Appearance::basic(Paint::None, Paint::solid(Color::rgb(0.5, 0.5, 0.5)), 20.0), + ); + let p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": false, "graphics": [{"symbol": "Mark", "scale": 2000.0}]}); + n.appearance.effects.push(crate::new_effect(EXTRUDE, &p).unwrap()); + assert_eq!(graphics_in(&solid_art_in(Some(&d), &n).unwrap()).len(), 1); +} + +#[test] +fn art_nested_too_deep_is_refused_and_not_drawn() { + let mut d = document(); + let mut art = square(0, Rect::new(0.0, 0.0, 10.0, 10.0), Paint::solid(red())); + for k in 0..=MAX_LEVELS { + art = Node::group(NodeId(k as u64 + 1), vec![Arc::new(art)]); + } + d.symbols.push(Symbol { dynamic: false, name: "Deep".into(), art: Arc::new(art) }); + let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Deep"}]})); + let e = validate_three_d_in(Some(&d), &n, EXTRUDE, &json!({"graphics": [{"symbol": "Deep"}]})).unwrap_err(); + assert!(e.contains("nested"), "{e}"); + assert!(graphics_in(&solid_art_in(Some(&d), &n).unwrap()).is_empty()); + // A loaded file draws its other graphics. + let both = object(EXTRUDE, json!({"graphics": [{"symbol": "Deep"}, {"symbol": "Mark"}]})); + assert_eq!(graphics_in(&solid_art_in(Some(&d), &both).unwrap()).len(), 1); +} + +#[test] +fn symbols_nested_too_deep_are_refused_and_not_drawn() { + let mut d = document(); + // Symbol `N{k}` holds an instance of `N{k-1}`, and `N0` is a square. + d.symbols.push(Symbol { dynamic: false, name: "N0".into(), art: Arc::new(square(0, Rect::new(0.0, 0.0, 10.0, 10.0), Paint::solid(red()))) }); + for k in 1..=MAX_NESTING + 1 { + let instance = Node::new(NodeId(k as u64), NodeKind::SymbolInstance { symbol: format!("N{}", k - 1), xf: Affine::IDENTITY }); + d.symbols.push(Symbol { dynamic: false, name: format!("N{k}"), art: Arc::new(instance) }); + } + let deepest = format!("N{MAX_NESTING}"); + let p = json!({"graphics": [{"symbol": deepest}]}); + assert!(validate_three_d_in(Some(&d), &object(EXTRUDE, p.clone()), EXTRUDE, &p).is_ok()); + assert_eq!(graphics_in(&solid_art_in(Some(&d), &object(EXTRUDE, p)).unwrap()).len(), 1); + let past = format!("N{}", MAX_NESTING + 1); + let p = json!({"graphics": [{"symbol": past}]}); + let e = validate_three_d_in(Some(&d), &object(EXTRUDE, p.clone()), EXTRUDE, &p).unwrap_err(); + assert!(e.contains("nest"), "{e}"); + assert!(graphics_in(&solid_art_in(Some(&d), &object(EXTRUDE, p)).unwrap()).is_empty()); +} + +#[test] +fn a_solid_in_a_transparent_gradient_keeps_its_graphic() { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let d = document(); + let mut stop = GradientStop::new(1.0, red()); + stop.opacity = 0.25; + let gradient = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red()), stop])); + // Under a colored light the faces are drawn opaque and masked by the gradient's transparency. + let mut n = object(EXTRUDE, json!({"shade": true, "lights": [{"color": "#ff8080"}], "graphics": [{"symbol": "Mark"}]})); + if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() { + f.paint = Paint::Gradient(Box::new(gradient)); + } + let art = solid_art_in(Some(&d), &n).unwrap(); + let mut masked = false; + art.walk(&mut |c| masked |= c.extras().mask.is_some()); + assert!(masked); + assert_eq!(graphics_in(&art).len(), 1); + // Each graphic clip group in `art`, in drawing order: whether it carries an opacity mask. + let masks = |art: &Node| { + let mut out = vec![]; + art.walk(&mut |c| { + if let NodeKind::Group { children, clip: true } = &c.kind + && let [_, inner] = children.as_slice() + && matches!(inner.kind, NodeKind::Group { clip: false, .. }) + { + out.push(c.extras().mask.is_some()); + } + }); + out + }; + // The graphic carries the cap's mask, so it is hidden where the gradient is transparent. + assert_eq!(masks(&art), vec![true]); + // With an opaque stroke drawn after the fill, the fill's cap keeps a masked graphic of its own + // and the stroke's outline gets an unmasked one. + n.appearance.items.push(AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 4.0))); + assert_eq!(masks(&solid_art_in(Some(&d), &n).unwrap()), vec![true, false]); +} + +/// The paths of `art`'s faces in drawing order (a face lit by a colored light is a clip group: its +/// clipping path), leaving out the graphics (clip groups of solid-color paths). +fn face_paths(art: &Node) -> Vec<PathData> { + fn walk(n: &Node, out: &mut Vec<PathData>) { + match &n.kind { + NodeKind::Group { children, clip: true } => { + let graphic = children.get(1).is_some_and(|inner| match &inner.kind { + NodeKind::Group { children: paths, clip: false } => paths.iter().all(|p| { + p.path_data().is_some() + && p.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if f.paint.color().is_some())) + }), + _ => false, + }); + if !graphic { + out.extend(children.first().and_then(|c| c.path_data()).cloned()); + } + } + NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, out)), + _ => out.extend(n.path_data().cloned()), + } + } + let mut out = vec![]; + walk(art, &mut out); + out +} + +/// A turned solid in a gradient with transparent stops under a colored light, with a dashed stroke +/// and a graphic, draws its fill's and its stroke's faces in the one order it draws them in without +/// the graphic, and the graphic keeps the cap's mask and goes after the fill's cap, not the stroke's. +#[test] +fn a_transparent_gradient_with_a_graphic_keeps_the_shared_face_order() { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let d = document(); + let mut stop = GradientStop::new(1.0, red()); + stop.opacity = 0.25; + let gradient = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red()), stop])); + let solid = |graphics: Value| { + let mut n = object( + EXTRUDE, + json!({"rotationX": -20.0, "rotationY": -40.0, "depth": 60.0, "shade": true, "lights": [{"color": "#ff8080"}], "graphics": graphics}), + ); + if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() { + f.paint = Paint::Gradient(Box::new(gradient.clone())); + } + // A gradient stroke: a solid color under the colored light would be one composite. + let blues = Gradient::new( + GradientKind::Linear, + vec![GradientStop::new(0.0, Color::rgb(0.0, 0.0, 1.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 0.5))], + ); + let mut stroke = StrokeLayer::new(Paint::Gradient(Box::new(GradientPaint::new(blues))), 6.0); + stroke.dash = Some(vectorcraft_doc::Dash { pattern: vec![12.0, 12.0], offset: 0.0, align_corners: false }); + n.appearance.items.push(AppearanceItem::Stroke(stroke)); + solid_art_in(Some(&d), &n).unwrap() + }; + let with = solid(json!([{"symbol": "Mark"}])); + let without = solid(json!([])); + assert!(face_paths(&without).len() > 20, "the faces are found"); + assert_eq!(face_paths(&with), face_paths(&without), "the faces in one order"); + // The graphic is drawn on the fill's cap and on the stroke's (the clip groups holding the + // symbol's red square); the fill's, whose surface carries the mask, carries it too. + let mut masked = vec![]; + with.walk(&mut |c| { + if let NodeKind::Group { children, clip: true } = &c.kind + && let [_, inner] = children.as_slice() + && let NodeKind::Group { children: paths, clip: false } = &inner.kind + && paths.iter().any(|p| { + p.appearance.items.iter().any(|i| match i { + AppearanceItem::Fill(f) => f.paint.color().is_some_and(|c| c.to_rgb()[1] < 0.1 && c.to_rgb()[0] > 0.3), + AppearanceItem::Stroke(_) => false, + }) + }) + { + masked.push(c.extras().mask.is_some()); + } + }); + masked.sort_unstable(); + assert_eq!(masked, [false, true], "the fill's graphic carries the cap's mask"); + // The fill's graphic goes right after the fill's cap, so the dashes on the cap's edge, drawn + // after it, cover it. Drawn in order: the fill's graphic (the masked clip group), and each face, + // the fill's or the stroke's by its gradient's first stop (red or blue), with its bounds. + let mut drawn: Vec<(&str, Rect)> = vec![]; + with.walk(&mut |c| { + if let NodeKind::Group { children, clip: true } = &c.kind + && c.extras().mask.is_some() + && let Some(bounds) = children.first().and_then(|clip| clip.path_data()).and_then(PathData::bounds) + { + drawn.push(("graphic", bounds)); + } + let first_stop = c.appearance.items.iter().find_map(|i| match i { + AppearanceItem::Fill(f) => match &f.paint { + Paint::Gradient(g) => g.gradient.stops.first().map(|s| s.color.to_rgb()), + _ => None, + }, + AppearanceItem::Stroke(_) => None, + }); + if let (Some(rgb), Some(bounds)) = (first_stop, c.path_data().and_then(PathData::bounds)) { + drawn.push((if rgb[0] > rgb[2] { "fill" } else { "stroke" }, bounds)); + } + }); + let graphic = drawn.iter().position(|(kind, _)| *kind == "graphic").unwrap(); + let covering = |(kind, b): &(&str, Rect)| *kind == "stroke" && b.intersect(drawn[graphic].1).area() > 0.0; + assert!(drawn[graphic..].iter().any(covering), "a dash on the cap's edge is drawn over the fill's graphic"); +} + +#[test] +fn a_cap_with_a_hole_keeps_the_hole_out_of_the_graphic() { + let d = document(); + let outer = shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)).to_bezpath(); + let hole = shapes::rectangle(Rect::new(30.0, 30.0, 70.0, 70.0)).to_bezpath().reverse_subpaths(); + let mut ring = outer; + ring.extend(hole.iter()); + for flip in [false, true] { + let ring = if flip { ring.reverse_subpaths() } else { ring.clone() }; + let mut n = + Node::path(NodeId(7), PathData::from_bezpath(&ring), Appearance::basic(Paint::solid(Color::rgb(0.5, 0.5, 0.5)), Paint::None, 0.0)); + let p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": false, "graphics": [{"symbol": "Mark", "scale": 2000.0}]}); + n.appearance.effects.push(crate::new_effect(EXTRUDE, &p).unwrap()); + let art = solid_art_in(Some(&d), &n).unwrap(); + let mut clips = vec![]; + art.walk(&mut |c| { + if let NodeKind::Group { children, clip: true } = &c.kind { + clips.push(children[0].path_data().unwrap().to_bezpath()); + } + }); + assert_eq!(clips.len(), 1, "flip {flip}"); + assert_ne!(clips[0].winding(Point::new(10.0, 10.0)), 0, "flip {flip}: the ring is inside the clip"); + assert_eq!(clips[0].winding(Point::new(50.0, 50.0)), 0, "flip {flip}: the hole is outside it"); + } +} + +#[test] +fn a_graphic_starts_inside_its_object() { + let d = document(); + let frame = graphic_frame(Some(&d), &object(EXTRUDE, json!({})), None).unwrap(); + assert_eq!(frame.fitting_scale(Rect::new(0.0, 0.0, 10.0, 10.0)), 100.0); + assert!((frame.fitting_scale(Rect::new(0.0, 0.0, 400.0, 200.0)) - 25.0).abs() < 1e-9); + assert_eq!(super::super::graphic_bounds(&d, "Mark"), Some(Rect::new(500.0, 500.0, 510.0, 510.0))); +} + +#[test] +fn a_symbol_instance_in_a_graphic_draws_as_the_canvas_shows_it() { + let mut d = document(); + let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0)); + // A dynamic symbol whose instance in "Changed" fills its square blue instead of red. + d.symbols.push(Symbol { dynamic: true, name: "Dynamic".into(), art: Arc::new(square(0, Rect::new(0.0, 0.0, 10.0, 10.0), Paint::solid(red()))) }); + let mut changed = Node::new(NodeId(1), NodeKind::SymbolInstance { symbol: "Dynamic".into(), xf: Affine::IDENTITY }); + changed.extras_mut().symbol_overrides = + vec![vectorcraft_doc::symbol_overrides::SymbolOverride { fill: Some(blue.clone()), ..Default::default() }]; + d.symbols.push(Symbol { dynamic: false, name: "Changed".into(), art: Arc::new(changed) }); + let pieces = pieces_of(&d, d.symbols.iter().find(|s| s.name == "Changed").unwrap()).unwrap(); + assert_eq!(pieces.iter().map(|p| p.paint.clone()).collect::<Vec<_>>(), [blue]); + // A symbol with 9-slice guides, a 100 × 100 square with a 10 × 10 one in its corner, placed + // three times as wide: the corner keeps its width while the rest stretches. + let corner = square(2, Rect::new(0.0, 0.0, 10.0, 10.0), Paint::solid(red())); + let whole = square(3, Rect::new(0.0, 0.0, 100.0, 100.0), Paint::solid(red())); + d.symbols.push(Symbol { dynamic: false, name: "Sliced".into(), art: Arc::new(Node::group(NodeId(4), vec![Arc::new(whole), Arc::new(corner)])) }); + d.set_symbol_nine_slice("Sliced", Some(vectorcraft_doc::SymbolNineSlice::default())); + let wide = Node::new(NodeId(5), NodeKind::SymbolInstance { symbol: "Sliced".into(), xf: Affine::scale_non_uniform(3.0, 1.0) }); + d.symbols.push(Symbol { dynamic: false, name: "Wide".into(), art: Arc::new(wide) }); + let pieces = pieces_of(&d, d.symbols.iter().find(|s| s.name == "Wide").unwrap()).unwrap(); + let widths: Vec<f64> = pieces.iter().map(|p| p.path.bounds().unwrap().width()).collect(); + assert_eq!(widths.len(), 2); + assert!((widths[1] / widths[0] - 1.0 / 30.0).abs() < 1e-6, "{widths:?}"); + // With a gradient, the square crossing the guides is cut at them: its pieces cover the + // placed 300 × 100 once, not one whole copy for each cell. + use vectorcraft_doc::color::{Gradient, GradientPaint}; + let gradient = Paint::Gradient(Box::new(GradientPaint::new(Gradient::default()))); + let shaded = square(6, Rect::new(0.0, 0.0, 100.0, 100.0), gradient); + d.symbols.push(Symbol { dynamic: false, name: "Shaded".into(), art: Arc::new(Node::group(NodeId(7), vec![Arc::new(shaded)])) }); + d.set_symbol_nine_slice("Shaded", Some(vectorcraft_doc::SymbolNineSlice::default())); + let wide = Node::new(NodeId(8), NodeKind::SymbolInstance { symbol: "Shaded".into(), xf: Affine::scale_non_uniform(3.0, 1.0) }); + d.symbols.push(Symbol { dynamic: false, name: "WideShaded".into(), art: Arc::new(wide) }); + let pieces = pieces_of(&d, d.symbols.iter().find(|s| s.name == "WideShaded").unwrap()).unwrap(); + let area: f64 = pieces.iter().map(|p| p.path.to_bezpath().area().abs()).sum(); + assert!((area - 30_000.0).abs() < 1e-3, "{area}"); +} + +#[test] +fn curves_are_cut_one_at_a_time_and_the_work_stops_at_the_limit() { + let ellipse = shapes::ellipse(Rect::new(0.0, 0.0, 10.0, 6.0)).to_bezpath(); + // Cut curve by curve, a path gives the points it gives cut whole. + for scale in [1.0, 100.0, 10_000.0] { + let placed = Affine::scale(scale) * ellipse.clone(); + let mut whole = vec![]; + vectorcraft_geom::kurbo::flatten(placed.iter(), SURFACE_TOLERANCE, |el| { + if let PathEl::MoveTo(p) | PathEl::LineTo(p) = el { + whole.push(p); + } + }); + let mut points = 0; + let cut: Vec<Point> = straight_pieces(&placed, &mut points).unwrap().into_iter().flatten().collect(); + assert_eq!(points, cut.len()); + assert_eq!(cut.len(), whole.len(), "{scale}"); + assert!(cut.iter().zip(&whole).all(|(a, b)| a.distance(*b) < 1e-9), "{scale}"); + } + // Past the limit no further curve is cut: of 1,000 ellipses that each take more than 3,000 + // points, the count stops within one curve of the limit. + let mut many = BezPath::new(); + (0..1000).for_each(|_| many.extend(Affine::scale(10_000.0) * ellipse.clone())); + let mut points = 0; + assert!(straight_pieces(&many, &mut points).is_none()); + assert!(points > MAX_ELEMENTS && points < MAX_ELEMENTS + 2000, "{points}"); + // A curve that reaches farther than any surface, or to no finite point, is not cut at all. + for scale in [1e12, f64::INFINITY] { + let mut points = 0; + assert!(straight_pieces(&(Affine::scale(scale) * ellipse.clone()), &mut points).is_none()); + assert!(points <= 1, "{scale}: {points}"); + } +} + +#[test] +fn a_line_that_reaches_farther_than_any_surface_is_not_cut() { + let triangle = |far: f64| { + let mut b = BezPath::new(); + b.move_to((0.0, 0.0)); + b.line_to((far, 0.0)); + b.line_to((0.0, 1.0)); + b.close_path(); + b + }; + assert!(straight_pieces(&triangle(1e7), &mut 0).is_some()); + for far in [1e12, 1e300] { + assert!(straight_pieces(&triangle(far), &mut 0).is_none(), "{far}"); + assert!(straight_pieces(&(Affine::translate((far, 0.0)) * triangle(1.0)), &mut 0).is_none(), "{far}"); + } +} + +#[test] +fn only_an_opaque_part_on_revolve_takes_a_seam_stroke() { + let piece = |paint: Paint, opacity: f32, blend: BlendMode| Unrolled { + polygons: vec![], + boxes: vec![], + bounds: Rect::ZERO, + rule: FillRule::NonZero, + paint, + opacity, + blend, + place: Affine::IDENTITY, + }; + assert!(takes_seam(&piece(Paint::solid(red()), 1.0, BlendMode::Normal))); + assert!(!takes_seam(&piece(Paint::solid(red()), 0.5, BlendMode::Normal))); + assert!(!takes_seam(&piece(Paint::solid(red()), 1.0, BlendMode::Multiply))); + // A pattern's tile may hold transparent art, which the overlap would show. + assert!(!takes_seam(&piece(Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY }, 1.0, BlendMode::Normal))); +} diff --git a/crates/effects/src/solids/tests_mesh.rs b/crates/effects/src/solids/tests_mesh.rs index 1ae347c978..aeefafbc77 100644 --- a/crates/effects/src/solids/tests_mesh.rs +++ b/crates/effects/src/solids/tests_mesh.rs @@ -59,6 +59,20 @@ fn the_meshes_of_one_object_share_one_triangle_budget() { assert!(meshes_for(effect, &shapes, &mut total, MAX_MESH_TRIANGLES).is_err_and(|e| e.contains("too complex"))); } +/// A mesh past the budget stops the export before the solids after it are built. +#[test] +fn the_solids_after_a_mesh_past_the_budget_are_not_built() { + let mut n = square_node(1, 100.0); + n.appearance.effects.push(fx(EXTRUDE, json!({}))); + let first = three_d_meshes(&n).unwrap()[0].mesh.triangles.len(); + let shapes = [Profile { path: profile(&n).unwrap().0, rule: FillRule::NonZero, items: solid_paints(&n), opacity: 1.0, scopes: vec![] }]; + let Some(effect) = n.appearance.effects.first() else { panic!("no effect") }; + let mut total = MAX_MESH_TRIANGLES - first + 1; + SOLIDS_BUILT.with(|b| b.set(0)); + assert!(meshes_for(effect, &shapes, &mut total, MAX_MESH_TRIANGLES).is_err_and(|e| e.contains("too complex"))); + assert_eq!(SOLIDS_BUILT.with(std::cell::Cell::get), 1, "the stroke's solid is never built"); +} + #[test] fn revolve_stops_at_the_first_mesh_past_the_budget() { // The fill revolves into a mesh; the stroke's profile, copied 1000 times, is too complex to @@ -109,6 +123,22 @@ fn an_extruded_mesh_is_as_deep_as_the_effect() { assert!((hi[2] - lo[2] - 30.0).abs() < 1e-9 && (hi[0] - lo[0] - 100.0).abs() < 1e-9, "{lo:?} {hi:?}"); } +/// Extrude & Bevel (Classic) exports the solid it draws: its bevel as wide as it is high. +#[test] +fn a_classic_extrusion_exports_its_own_bevel() { + let mut n = square_node(1, 100.0); + n.appearance.items.truncate(1); + let params = json!({ "bevel": "classic", "bevelHeight": 10.0 }); + n.appearance.effects.push(fx(CLASSIC_EXTRUDE, params.clone())); + let meshes = three_d_meshes(&n).unwrap(); + let p = crate::merged_params(CLASSIC_EXTRUDE, ¶ms); + let path = profile(&n).unwrap().0; + let bounds = path.bounds().unwrap(); + let own = vectorcraft_three_d::extrude_mesh(&path, FillRule::NonZero, bounds, classic_extrude_options(&p), view_options(&p)).unwrap(); + assert_eq!(meshes.len(), 1); + assert_eq!(meshes[0].mesh, own); +} + #[test] fn revolve_gives_a_mesh_in_the_top_fill() { let mut b = BezPath::new(); diff --git a/crates/effects/src/solids/tests_shadow.rs b/crates/effects/src/solids/tests_shadow.rs new file mode 100644 index 0000000000..4400555d2b --- /dev/null +++ b/crates/effects/src/solids/tests_shadow.rs @@ -0,0 +1,225 @@ +use serde_json::json; +use vectorcraft_doc::color::Color; +use vectorcraft_doc::{Document, NodeId}; +use vectorcraft_geom::{Affine, BezPath}; + +use super::*; + +const RED: Color = Color::Rgb { r: 0.8, g: 0.2, b: 0.1 }; + +/// The 3D and Materials effects that cast shadows. +const CASTING: [&str; 4] = [EXTRUDE, INFLATE, ROTATE, crate::REVOLVE]; + +fn square_node(id: u64, dx: f64) -> Node { + let mut b = BezPath::new(); + b.move_to((100.0 + dx, 100.0)); + b.line_to((200.0 + dx, 100.0)); + b.line_to((200.0 + dx, 200.0)); + b.line_to((100.0 + dx, 200.0)); + b.close_path(); + Node::path(NodeId(id), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(RED), Paint::None, 0.0)) +} + +fn art(n: &Node, id: &str) -> Option<Node> { + if id == crate::REVOLVE { crate::revolve_art(n) } else { solid_art(n) } +} + +/// The opacity of shadow `n`: a path filled black and nothing else; `None` for any other node. +fn shadow_opacity(n: &Node) -> Option<f32> { + let [AppearanceItem::Fill(fill)] = n.appearance.items.as_slice() else { return None }; + (matches!(n.kind, NodeKind::Path { .. }) && fill.paint.color() == Some(Color::BLACK)).then_some(fill.opacity) +} + +/// Whether `n` is the shadow of opaque art: a path filled black at 50 %, nothing else. +fn is_shadow(n: &Node) -> bool { + shadow_opacity(n) == Some(0.5) +} + +fn shadows(n: &Node) -> usize { + let mut count = 0; + n.walk(&mut |c| count += usize::from(is_shadow(c))); + count +} + +#[test] +fn each_3d_effect_draws_its_shadow_behind_its_solid_when_shadows_are_on() { + for id in CASTING { + let mut n = square_node(1, 0.0); + n.appearance.effects.push(crate::new_effect(id, &json!({})).unwrap()); + let plain = art(&n, id).unwrap_or_else(|| panic!("{id}")); + assert_eq!(shadows(&plain), 0, "{id}: off by default"); + n.appearance.effects[0].params = json!({"shadow": true, "shadowDistance": 50}); + let lit = art(&n, id).unwrap_or_else(|| panic!("{id}")); + let children = lit.children().unwrap(); + assert!(is_shadow(&children[0]), "{id}: the shadow is drawn first"); + assert_eq!(shadows(&lit), 1, "{id}"); + // The default light is up and to the left: the shadow on a plane away from the object + // reaches past the solid down and right. + let shadow = children[0].visual_bounds().unwrap(); + let solid = children[1..].iter().filter_map(|c| c.visual_bounds()).reduce(|a, b| a.union(b)).unwrap(); + assert!(shadow.x1 > solid.x1 && shadow.y1 > solid.y1, "{id}: {shadow:?} {solid:?}"); + // The art's bounds take the shadow in. + assert!(lit.visual_bounds().unwrap().contains_rect(shadow), "{id}"); + } +} + +#[test] +fn the_shadow_moves_with_its_settings() { + for id in CASTING { + let bounds = |params: Value| { + let mut n = square_node(1, 0.0); + n.appearance.effects.push(crate::new_effect(id, ¶ms).unwrap()); + let lit = art(&n, id).unwrap(); + let shadow = &lit.children().unwrap()[0]; + assert!(is_shadow(shadow), "{id} {params}"); + shadow.visual_bounds().unwrap() + }; + let near = bounds(json!({"shadow": true})); + let far = bounds(json!({"shadow": true, "shadowDistance": 100})); + assert!(far.x1 > near.x1 + 1.0, "{id}: {near:?} {far:?}"); + // With the light straight in front, the outline falls about the plane's center; at 10 % + // the plane cuts it to a square 0.4 times the object's size across. + let tight = bounds(json!({"shadow": true, "shadowBounds": 10, "lightHeight": 90})); + let wide = bounds(json!({"shadow": true, "shadowBounds": 400, "lightHeight": 90})); + assert!(wide.width() > tight.width() * 2.0, "{id}: {tight:?} {wide:?}"); + let below = bounds(json!({"shadow": true, "shadowPosition": "below", "rotationX": -30})); + assert_ne!(below, near, "{id}"); + } +} + +#[test] +fn shadow_settings_out_of_range_or_of_the_wrong_kind_are_refused() { + for id in CASTING { + for (params, error) in [ + (json!({"shadow": "yes"}), "shadow must be true or false"), + (json!({"shadowPosition": "under"}), "shadowPosition must be behind or below"), + (json!({"shadowPosition": 1}), "shadowPosition must be behind or below"), + (json!({"shadowDistance": 101}), "shadowDistance must be a number from 0 to 100"), + (json!({"shadowDistance": -1}), "shadowDistance must be a number from 0 to 100"), + (json!({"shadowBounds": 5}), "shadowBounds must be a number from 10 to 400"), + (json!({"shadowBounds": "wide"}), "shadowBounds must be a number from 10 to 400"), + ] { + let err = validate_three_d_params(id, ¶ms).unwrap_err(); + assert!(err.contains(error), "{id} {params}: {err}"); + } + let ok = json!({"shadow": true, "shadowPosition": "below", "shadowDistance": 100, "shadowBounds": 10}); + assert!(validate_three_d_params(id, &ok).is_ok(), "{id}"); + } +} + +#[test] +fn a_group_casts_one_shadow_for_all_its_members() { + for id in CASTING { + let mut g = Node::group(NodeId(9), vec![Arc::new(square_node(1, 0.0)), Arc::new(square_node(2, 200.0))]); + g.appearance.effects.push(crate::new_effect(id, &json!({"shadow": true, "lightHeight": 90})).unwrap()); + let lit = art(&g, id).unwrap_or_else(|| panic!("{id}")); + assert_eq!(shadows(&lit), 1, "{id}"); + let shadow = lit.children().unwrap()[0].clone(); + assert!(is_shadow(&shadow), "{id}"); + // With the light straight in front, the shadow behind spans both members. + let b = shadow.visual_bounds().unwrap(); + assert!(b.x0 < 200.0 && b.x1 > 300.0, "{id}: {b:?}"); + } +} + +/// A member's opacity mask applies to the part of the shadow it casts, as to its solid: that part +/// is drawn in the mask, the other member's outside it, both on one plane. +#[test] +fn a_masked_member_casts_its_part_of_the_shadow_in_its_mask() { + for id in CASTING { + let mut masked = square_node(2, 200.0); + let mut cover = square_node(3, 200.0); + cover.appearance.items = Appearance::basic(Paint::solid(Color::WHITE), Paint::None, 0.0).items; + masked.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(cover, true))); + let mut g = Node::group(NodeId(9), vec![Arc::new(square_node(1, 0.0)), Arc::new(masked)]); + g.appearance.effects.push(crate::new_effect(id, &json!({"shadow": true})).unwrap()); + let lit = art(&g, id).unwrap_or_else(|| panic!("{id}")); + assert_eq!(shadows(&lit), 2, "{id}: one piece for each member"); + let mut in_mask = 0; + lit.walk(&mut |c| { + if c.extras().mask.is_some() { + c.walk(&mut |s| in_mask += usize::from(is_shadow(s))); + } + }); + assert_eq!(in_mask, 1, "{id}"); + } +} + +#[test] +fn transparent_art_and_a_light_that_lights_nothing_cast_no_shadow() { + for id in CASTING { + let mut n = square_node(1, 0.0); + n.appearance.effects.push(crate::new_effect(id, &json!({"shadow": true, "shade": false})).unwrap()); + assert_eq!(shadows(&art(&n, id).unwrap()), 0, "{id}: Shading off"); + n.appearance.effects[0].params = json!({"shadow": true, "lightIntensity": 0}); + assert_eq!(shadows(&art(&n, id).unwrap()), 0, "{id}: no intensity"); + // A member at 0 % opacity casts nothing; the other member still casts its shadow. + let mut clear = square_node(2, 200.0); + clear.opacity = 0.0; + let mut g = Node::group(NodeId(9), vec![Arc::new(square_node(1, 0.0)), Arc::new(clear)]); + g.appearance.effects.push(crate::new_effect(id, &json!({"shadow": true, "lightHeight": 90})).unwrap()); + let lit = art(&g, id).unwrap_or_else(|| panic!("{id}")); + let shadow = lit.children().unwrap()[0].clone(); + assert!(is_shadow(&shadow), "{id}"); + let b = shadow.visual_bounds().unwrap(); + assert!(b.x1 < 300.0, "{id}: only the visible member casts: {b:?}"); + // Art at 50 % casts a shadow half as dark. + let mut half = square_node(1, 0.0); + for item in &mut half.appearance.items { + if let AppearanceItem::Fill(fill) = item { + fill.opacity = 0.5; + } + } + half.appearance.effects.push(crate::new_effect(id, &json!({"shadow": true})).unwrap()); + let lit = art(&half, id).unwrap(); + assert_eq!(shadow_opacity(&lit.children().unwrap()[0]), Some(0.25), "{id}"); + // Art in a blending mode casts its shadow in that mode. + for item in &mut half.appearance.items { + if let AppearanceItem::Fill(fill) = item { + fill.blend = BlendMode::Screen; + } + } + let lit = art(&half, id).unwrap(); + let AppearanceItem::Fill(fill) = &lit.children().unwrap()[0].appearance.items[0] else { panic!("{id}: a fill") }; + assert_eq!(fill.blend, BlendMode::Screen, "{id}"); + } +} + +/// With a 3D effect on each of two fills, both fills' shadows are drawn behind both fills' solids. +#[test] +fn the_shadows_of_every_fill_go_behind_every_fill_s_solid() { + for id in CASTING { + let mut n = square_node(1, 0.0); + let fill = n.appearance.items.iter().find(|i| matches!(i, AppearanceItem::Fill(_))).unwrap().clone(); + n.appearance.items = vec![fill.clone(), fill]; + for item in &mut n.appearance.items { + item.effects_mut().push(crate::new_effect(id, &json!({"shadow": true})).unwrap()); + } + let lit = art(&n, id).unwrap_or_else(|| panic!("{id}")); + let children = lit.children().unwrap(); + assert!(children.len() >= 4, "{id}"); + assert!(is_shadow(&children[0]) && is_shadow(&children[1]), "{id}: both shadows first"); + assert!(children[2..].iter().all(|c| !is_shadow(c)), "{id}"); + } +} + +#[test] +fn expand_appearance_keeps_the_shadow_as_a_path() { + for id in CASTING { + let mut d = Document::new(400.0, 400.0); + let mut n = square_node(1, 0.0); + n.id = d.alloc_id(); + n.appearance.effects.push(crate::new_effect(id, &json!({"shadow": true})).unwrap()); + let mut stroke = |_: &mut Document, _: &PathData, _: FillRule, _: &StrokeLayer| None; + let expanded = crate::expand_leaf(&mut d, &n, &mut stroke).unwrap_or_else(|| panic!("{id}")); + assert_eq!(shadows(&expanded), 1, "{id}"); + let mut effects = 0; + expanded.walk(&mut |c| effects += c.appearance.effects.len()); + assert_eq!(effects, 0, "{id}"); + // It moves with the object, as the solid does. + let before = art(&n, id).unwrap().children().unwrap()[0].visual_bounds().unwrap(); + n.transform(Affine::translate((40.0, 0.0)), false); + let after = art(&n, id).unwrap().children().unwrap()[0].visual_bounds().unwrap(); + assert!((after.x0 - before.x0 - 40.0).abs() < 1e-6, "{id}: {before:?} {after:?}"); + } +} diff --git a/crates/effects/src/solids/tests_sources.rs b/crates/effects/src/solids/tests_sources.rs index b2f6daf1c6..b7a9429fd9 100644 --- a/crates/effects/src/solids/tests_sources.rs +++ b/crates/effects/src/solids/tests_sources.rs @@ -317,6 +317,86 @@ fn images_are_refused_alone_and_in_a_group_with_image_trace_named() { } } +/// A clipping group: `art` inside a clipping path of `path` filled under `rule`. +fn shaped_clip_group(id: u64, path: PathData, rule: FillRule, art: Vec<Node>) -> Node { + let mut clipping = Node::path(NodeId(id + 1), path, Appearance::default()); + if let NodeKind::Path { clipping: c, rule: r, .. } = &mut clipping.kind { + *c = true; + *r = rule; + } + let children = std::iter::once(clipping).chain(art).map(Arc::new).collect(); + Node::new(NodeId(id), NodeKind::Group { children, clip: true }) +} + +/// An image `width` by `height` pixels placed by `xf`. +fn placed(id: u64, width: u32, height: u32, xf: Affine) -> Node { + let mut img = image(id); + if let NodeKind::Image(i) = &mut img.kind { + i.width = width; + i.height = height; + i.xf = xf; + } + img +} + +#[test] +fn an_image_inside_a_clips_box_but_outside_its_shape_is_left_out() { + let d = document(); + let circle = || shapes::ellipse(Rect::new(100.0, 100.0, 200.0, 200.0)); + let square = || shapes::rectangle(Rect::new(100.0, 100.0, 150.0, 150.0)); + let at = |x: f64, y: f64| Affine::translate((x, y)); + // Two circles inside each other's clips: they show together only the lens between them. + let lens = |art: Vec<Node>| { + let inner = shaped_clip_group(70, shapes::ellipse(Rect::new(120.0, 100.0, 220.0, 200.0)), FillRule::NonZero, art); + shaped_clip_group(80, shapes::ellipse(Rect::new(80.0, 100.0, 180.0, 200.0)), FillRule::NonZero, vec![inner]) + }; + let mut ring = shapes::rectangle(Rect::new(100.0, 100.0, 200.0, 200.0)); + ring.subpaths.extend(shapes::rectangle(Rect::new(130.0, 130.0, 170.0, 170.0)).subpaths); + // Turned 45° about its center at (156, 156): its box reaches into the square's corner, and its + // frame does not. + let turned = at(156.0, 156.0) * Affine::rotate(std::f64::consts::FRAC_PI_4) * at(-5.0, -5.0); + // A shown rectangle and an image `w` by `h` at `xf` inside the clipping path `path`. + let clipped = |path: PathData, rule: FillRule, shown: Rect, (w, h, xf): (u32, u32, Affine)| { + shaped_clip_group(60, path, rule, vec![rect(62, shown.x0, shown.y0, shown.x1, shown.y1, 0.0), placed(63, w, h, xf)]) + }; + let middle = Rect::new(140.0, 140.0, 160.0, 160.0); + let band = Rect::new(100.0, 100.0, 110.0, 200.0); + let left_out = [ + // In the corner of the circle's box, outside the circle. + ("a circle's corner", clipped(circle(), FillRule::NonZero, middle, (10, 10, at(100.0, 100.0)))), + ("a turned frame", clipped(square(), FillRule::NonZero, Rect::new(110.0, 110.0, 140.0, 140.0), (10, 10, turned))), + // Above the lens: inside each circle, outside both at once. + ("two clips' shared area", lens(vec![rect(62, 145.0, 140.0, 155.0, 160.0, 0.0), placed(63, 8, 3, at(146.0, 100.0))])), + ("an even-odd hole", clipped(ring.clone(), FillRule::EvenOdd, band, (10, 10, at(140.0, 140.0)))), + ]; + let shown = [ + ("part of the circle", clipped(circle(), FillRule::NonZero, middle, (10, 10, at(145.0, 145.0)))), + ("a non-zero hole", clipped(ring, FillRule::NonZero, band, (10, 10, at(140.0, 140.0)))), + // A strip 0.005 pt wide inside the square still shows. + ("a narrow strip", clipped(square(), FillRule::NonZero, Rect::new(110.0, 110.0, 140.0, 140.0), (10, 10, at(149.995, 120.0)))), + ("the lens", lens(vec![rect(62, 145.0, 140.0, 155.0, 160.0, 0.0), placed(63, 8, 3, at(146.0, 108.0))])), + ]; + for id in TYPES { + for (what, g) in &left_out { + let n = with(g.clone(), id, json!({})); + assert_eq!(validate_three_d_in(Some(&d), &n, id, &json!({})), Ok(()), "{id}: {what}"); + assert!(art(&d, &n, id).is_some(), "{id}: {what} draws"); + assert!(three_d_meshes_in(Some(&d), &n).is_ok_and(|m| !m.is_empty()), "{id}: {what} exports"); + } + for (what, g) in &shown { + let n = with(g.clone(), id, json!({})); + assert!(validate_three_d_in(Some(&d), &n, id, &json!({})).is_err_and(|e| e.contains("Image Trace")), "{id}: {what}"); + assert!(art(&d, &n, id).is_none(), "{id}: {what}"); + } + } + // Each frame cut to a clip counts: past the limit the art is refused, never left out unchecked. + let many: Vec<Node> = std::iter::once(rect(62, 140.0, 140.0, 160.0, 160.0, 0.0)) + .chain((0..=source::MAX_IMAGE_CUTS as u64).map(|i| placed(100 + i, 10, 10, at(100.0, 100.0)))) + .collect(); + let n = with(shaped_clip_group(60, circle(), FillRule::NonZero, many), ROTATE, front()); + assert!(validate_three_d_in(Some(&d), &n, ROTATE, &json!({})).is_err_and(|e| e.contains("too many objects"))); +} + /// Symbols `L0` to `L{levels}`: `L0` holds `leaf`, each later one `fan` instances of the one /// before it. fn nested_symbols(levels: usize, fan: usize, leaf: Node) -> Document { diff --git a/crates/effects/src/solids/wireframe.rs b/crates/effects/src/solids/wireframe.rs new file mode 100644 index 0000000000..00e741bfe6 --- /dev/null +++ b/crates/effects/src/solids/wireframe.rs @@ -0,0 +1,268 @@ +//! Expand as Wireframes: the edges of the faces a 3D effect draws, as open and closed paths that +//! can be edited on their own. +use std::collections::{HashMap, HashSet, VecDeque}; +use std::sync::Arc; + +use vectorcraft_doc::color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Document, Effect, Node, NodeId}; +use vectorcraft_geom::{Anchor, CubicBez, PathData, Point, SubPath}; +use vectorcraft_three_d::Facet; + +use super::{ + Profile, ROTATE, built_solids, facets, geometry, has_solid, is_container, is_plane, is_three_d, label_of, members, object_profile, region, + reshape_members, resolve, resolve_for, solid, solid_paints, solid_parts, union_bounds, +}; +use crate::{GeomContext, is_geometry}; + +/// The most distinct edges one object's wireframe may have. +pub(crate) const MAX_WIRE_EDGES: usize = 1_000_000; + +/// The grid points are rounded to before edges are compared, in points: two faces that share an +/// edge give it once. +const GRID: f64 = 1.0 / 1024.0; + +const NO_EFFECT: &str = "the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate)"; + +/// The wireframe of `n`'s 3D effect (Extrude & Bevel, Revolve, Inflate, Rotate or one of their 3D +/// (Classic) forms), in document coordinates: the edges of every face the effect draws for the object as +/// it is turned and projected, each edge once. Edges that meet end to end are joined into one path; +/// a run that comes back to where it started is closed. A curved edge stays a curve. The geometry +/// effects after the object's 3D effect reshape the wireframe as they reshape the drawn art. On a +/// group or layer, the edges of the solids of all its members. An error when `n` has no visible 3D +/// effect, when its solids can't be built, when the canvas draws the source art in their place, when +/// they draw no face, or past [`MAX_WIRE_EDGES`] edges. +pub fn three_d_wireframe_in(doc: Option<&Document>, n: &Node) -> Result<Vec<PathData>, String> { + if !crate::has_revolve(n) && !has_solid(n) { + return Err(NO_EFFECT.into()); + } + let label = n.appearance.effects.iter().find(|e| e.visible && is_three_d(&e.id)).map_or("This effect", |e| label_of(&e.id)); + // The faces come from the effect whose art the canvas draws (Revolve first, as the canvas tries + // it first). When neither draws, past their limits, the canvas shows the source art and there + // is no surface to expand. + let revolve = crate::has_revolve(n) && crate::revolve_art_in(doc, n).is_some(); + if !revolve && !(has_solid(n) && super::solid_art_in(doc, n).is_some()) { + // The builders' own error says why, when there is one. Revolve's art is cut for Revolve, + // as the canvas cuts it. + if crate::has_revolve(n) { + crate::revolve::revolve_face_paths(doc, &*resolve_for(doc, n, label, false)?)?; + } else { + solid_face_paths(doc, &*resolve(doc, n, label)?)?; + } + return Err(format!("{label} draws the source art for this object instead of its 3D surface")); + } + // Revolve's art is cut for Revolve whatever other 3D effect the object carries, as the canvas + // cuts it ([`crate::revolve_art_in`]). + let n = &*if revolve { resolve_for(doc, n, label, false)? } else { resolve(doc, n, label)? }; + let faces = if revolve { crate::revolve::revolve_face_paths(doc, n)? } else { solid_face_paths(doc, n)? }; + let faces = after_geometry(doc, n, faces, revolve); + let wire = edges(&faces)?; + if wire.is_empty() { + return Err(format!("{label} draws no faces for this object")); + } + Ok(wire) +} + +/// `faces` reshaped by the visible geometry effects after the 3D effect of `n`'s own that drew them +/// ([`reshaped`]): its first visible Revolve when `revolve` is set, else its first visible Extrude & +/// Bevel, Inflate or Rotate. +fn after_geometry(doc: Option<&Document>, n: &Node, faces: Vec<PathData>, revolve: bool) -> Vec<PathData> { + let fx = &n.appearance.effects; + let drawn = if revolve { fx.iter().position(|e| e.visible && crate::revolve::is_revolve(&e.id)) } else { solid(fx).map(|(i, _)| i) }; + let Some(index) = drawn else { return faces }; + reshaped(faces, fx.get(index + 1..).unwrap_or_default(), &GeomContext { doc, ..GeomContext::of(n) }) +} + +/// `faces` reshaped by the visible geometry effects in `later` (the effects after a 3D effect), as +/// they reshape the faces of the drawn surface ([`crate::reshape::reshape_leaves`]): each effect +/// reshapes each face on its own, about the bounds all the faces have before it, and the faces keep +/// to one budget of anchors together. `ctx` gives the object's id, the seed of a random Transform, +/// and the document. +pub(crate) fn reshaped(faces: Vec<PathData>, later: &[Effect], ctx: &GeomContext) -> Vec<PathData> { + let after: Vec<&Effect> = later.iter().filter(|e| e.visible && is_geometry(&e.id)).collect(); + if after.is_empty() { + return faces; + } + let id = NodeId(ctx.seed); + let fill = Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0); + let mut art = Node::group(id, faces.into_iter().map(|f| Arc::new(Node::path(id, f, fill.clone()))).collect()); + crate::reshape::reshape_leaves(&mut art, &after, later, ctx.doc); + let mut out = vec![]; + art.walk(&mut |c| out.extend(c.path_data().cloned())); + out +} + +/// The outline of every face [`super::solid_art`] draws for `n` (already resolved): with the effect +/// on the object, its solids; with it on fills and strokes, the solid of each; on a group or layer, +/// the solids of its members, about one shared axis. The swatches and patterns named by a live-effect +/// plug-in after a fill's or stroke's 3D effect are looked up in `doc`. +fn solid_face_paths(doc: Option<&Document>, n: &Node) -> Result<Vec<PathData>, String> { + 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")?; + let mut shapes = members(n, label_of(&fx.id))?; + reshape_members(n, n.appearance.effects.get(..index).unwrap_or_default(), &mut shapes); + return facet_paths(fx, &shapes); + } + let label = n.appearance.effects.iter().find(|e| e.visible && is_three_d(&e.id)).map_or("This effect", |e| label_of(&e.id)); + let (path, rule) = object_profile(n, label)?; + 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); + return facet_paths(fx, &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }]); + } + 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)); + let faces = facet_paths(fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }])?; + out.extend(reshaped(faces, item.effects().get(index + 1..).unwrap_or_default(), &GeomContext { doc, ..ctx })); + } + } + Ok(out) +} + +/// The outlines of the facets effect `fx` builds from `shapes`, as `art_for` builds them: Rotate and +/// Rotate (Classic) turn every fill and stroke; Extrude & Bevel and Inflate build a solid from each shape's +/// top fill and from the outline of each stroke. A stroke whose solid is past the limits is left out, +/// as it is left out of the drawn art; past the limits of the object's solids together, the result +/// is an error, as the canvas draws the source art. +fn facet_paths(fx: &Effect, shapes: &[Profile]) -> Result<Vec<PathData>, String> { + let label = label_of(&fx.id); + 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 mut out = vec![]; + if is_plane(&fx.id) { + for s in shapes { + for item in &s.items { + let (area, rule) = region(&s.path, s.rule, item); + out.extend(facets(ROTATE, &area, rule, b, &p)?.iter().map(Facet::path)); + } + } + return Ok(out); + } + let (parts, bounds) = solid_parts(shapes, b); + // The solids the art draws, each past the limits of the object's solids together as it is. + for f in built_solids(&fx.id, &p, &parts, bounds, vectorcraft_three_d::MAX_OBJECT_FACES) { + out.extend(f?.iter().flatten().map(Facet::path)); + } + Ok(out) +} + +/// A point on the [`GRID`]. +type Snap = (i64, i64); + +fn snap(p: Point) -> Snap { + ((p.x / GRID).round() as i64, (p.y / GRID).round() as i64) +} + +fn reversed(c: CubicBez) -> CubicBez { + CubicBez::new(c.p3, c.p2, c.p1, c.p0) +} + +/// The edges of `faces`, each once, joined end to end into paths ([`three_d_wireframe_in`]). +pub(crate) fn edges(faces: &[PathData]) -> Result<Vec<PathData>, String> { + let mut seen: HashSet<[Snap; 4]> = HashSet::new(); + let mut segments: Vec<CubicBez> = vec![]; + for sp in faces.iter().flat_map(|f| &f.subpaths) { + for i in 0..sp.segment_count() { + let mut c = sp.segment(i); + if sp.segment_is_line(i) { + c = CubicBez::new(c.p0, c.p0, c.p3, c.p3); + } + if [c.p0, c.p1, c.p2, c.p3].iter().any(|p| !p.x.is_finite() || !p.y.is_finite()) { + continue; + } + let key = [c.p0, c.p1, c.p2, c.p3].map(snap); + // A segment that starts and ends on one grid point with its handles there too draws nothing. + if key.iter().all(|k| *k == key[0]) { + continue; + } + let back = [key[3], key[2], key[1], key[0]]; + if seen.contains(&back) || !seen.insert(key) { + continue; + } + if segments.len() >= MAX_WIRE_EDGES { + return Err(format!("the wireframe has more than {MAX_WIRE_EDGES} edges")); + } + segments.push(c); + } + } + Ok(chain(&segments)) +} + +/// `segments` joined end to end: each path starts at the first segment not yet used and takes in +/// the unused segments that meet its ends until none is left at either end, or it closes. +fn chain(segments: &[CubicBez]) -> Vec<PathData> { + let mut at: HashMap<Snap, Vec<usize>> = HashMap::new(); + for (i, c) in segments.iter().enumerate() { + at.entry(snap(c.p0)).or_default().push(i); + if snap(c.p3) != snap(c.p0) { + at.entry(snap(c.p3)).or_default().push(i); + } + } + let mut used = vec![false; segments.len()]; + // The next unused segment at `point`, turned to leave it (`leave`) or to arrive at it. + let mut take = |used: &mut Vec<bool>, point: Snap, leave: bool| -> Option<CubicBez> { + let list = at.get_mut(&point)?; + while let Some(&i) = list.last() { + if used.get(i).copied().unwrap_or(true) { + list.pop(); + continue; + } + if let Some(u) = used.get_mut(i) { + *u = true; + } + let c = *segments.get(i)?; + let starts = snap(c.p0) == point; + return Some(if starts == leave { c } else { reversed(c) }); + } + None + }; + let mut out = vec![]; + for (i, first) in segments.iter().enumerate() { + if used.get(i).copied().unwrap_or(true) { + continue; + } + if let Some(u) = used.get_mut(i) { + *u = true; + } + let mut run: VecDeque<CubicBez> = VecDeque::from([*first]); + // A path of one anchor has no segment (`SubPath::segment_count`), so a run of one segment + // that comes back to its start stays open, with its two ends on one point. + let closes = |run: &VecDeque<CubicBez>| run.len() > 1 && run.front().zip(run.back()).is_some_and(|(f, b)| snap(f.p0) == snap(b.p3)); + while !closes(&run) { + let Some(end) = run.back().map(|c| snap(c.p3)) else { break }; + let Some(c) = take(&mut used, end, true) else { break }; + run.push_back(c); + } + while !closes(&run) { + let Some(start) = run.front().map(|c| snap(c.p0)) else { break }; + let Some(c) = take(&mut used, start, false) else { break }; + run.push_front(c); + } + out.push(PathData::single(subpath(&run, closes(&run)))); + } + out +} + +/// `run`, segments that meet end to end, as one subpath; a closed one ends at its first anchor. +fn subpath(run: &VecDeque<CubicBez>, closed: bool) -> SubPath { + let mut anchors: Vec<Anchor> = vec![]; + if let Some(first) = run.front() { + let h_in = if closed { run.back().map_or(first.p0, |b| b.p2) } else { first.p0 }; + anchors.push(Anchor::with_handles(first.p0, h_in, first.p1)); + } + for (k, c) in run.iter().enumerate() { + let h_out = run.get(k + 1).map_or(c.p3, |next| next.p1); + anchors.push(Anchor::with_handles(c.p3, c.p2, h_out)); + } + // A closed run's last anchor is its first, whose in handle already comes from the last segment. + if closed { + anchors.pop(); + } + SubPath::new(anchors, closed) +} + +#[cfg(test)] +mod tests; diff --git a/crates/effects/src/solids/wireframe/tests.rs b/crates/effects/src/solids/wireframe/tests.rs new file mode 100644 index 0000000000..792fbdb28a --- /dev/null +++ b/crates/effects/src/solids/wireframe/tests.rs @@ -0,0 +1,235 @@ +use serde_json::{Value, json}; +use vectorcraft_doc::color::{Color, Paint}; +use vectorcraft_doc::{Appearance, AppearanceItem, Node, NodeId}; +use vectorcraft_geom::{BezPath, Rect}; + +use super::*; + +fn square(x: f64, y: f64, size: f64) -> PathData { + let mut b = BezPath::new(); + b.move_to((x, y)); + b.line_to((x + size, y)); + b.line_to((x + size, y + size)); + b.line_to((x, y + size)); + b.close_path(); + PathData::from_bezpath(&b) +} + +/// A filled 100 pt square without a stroke, with effect `id` and `params`. +fn solid_square(id: &str, params: Value) -> Node { + let mut n = Node::path(NodeId(1), square(100.0, 100.0, 100.0), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + n.appearance.effects.push(crate::new_effect(id, ¶ms).unwrap()); + n +} + +/// Every segment of `wire`, each as its two ends on the grid. +fn segments(wire: &[PathData]) -> Vec<(Snap, Snap)> { + wire.iter() + .flat_map(|p| &p.subpaths) + .flat_map(|sp| (0..sp.segment_count()).map(move |i| sp.segment(i))) + .map(|c| (snap(c.p0), snap(c.p3))) + .collect() +} + +fn bounds(paths: &[PathData]) -> Rect { + paths.iter().filter_map(PathData::bounds).reduce(|a, b| a.union(b)).unwrap() +} + +/// The paths of the faces `art` draws (every leaf of the art). +fn face_paths(art: &Node) -> Vec<PathData> { + let mut out = vec![]; + art.walk(&mut |c| out.extend(c.path_data().cloned())); + out +} + +#[test] +fn two_faces_that_share_an_edge_give_it_once() { + let wire = edges(&[square(0.0, 0.0, 10.0), square(10.0, 0.0, 10.0)]).unwrap(); + let segs = segments(&wire); + assert_eq!(segs.len(), 7, "{segs:?}"); + for (i, a) in segs.iter().enumerate() { + for b in segs.iter().skip(i + 1) { + assert!(a != b && (a.1, a.0) != *b, "{a:?} twice"); + } + } +} + +#[test] +fn a_loop_of_edges_is_one_closed_path_and_a_curve_stays_a_curve() { + let wire = edges(&[square(0.0, 0.0, 10.0)]).unwrap(); + assert_eq!(wire.len(), 1); + assert!(wire[0].subpaths[0].closed); + assert_eq!(wire[0].subpaths[0].anchors.len(), 4); + + let mut b = BezPath::new(); + b.move_to((0.0, 0.0)); + b.curve_to((0.0, 10.0), (10.0, 10.0), (10.0, 0.0)); + b.close_path(); + let wire = edges(&[PathData::from_bezpath(&b)]).unwrap(); + let curved = wire.iter().flat_map(|p| &p.subpaths).any(|sp| (0..sp.segment_count()).any(|i| !sp.segment_is_line(i))); + assert!(curved, "{wire:?}"); +} + +/// A single curve that comes back to its start keeps its segment: it stays open, with two anchors on +/// one point, since a path of one anchor has no segment. +#[test] +fn a_single_curve_that_comes_back_to_its_start_keeps_its_segment() { + let p = Point::new(0.0, 0.0); + let anchors = vec![Anchor::with_handles(p, p, Point::new(0.0, 10.0)), Anchor::with_handles(p, Point::new(10.0, 10.0), p)]; + let face = PathData::single(SubPath::new(anchors, false)); + assert_eq!(face.subpaths[0].segment_count(), 1); + let wire = edges(&[face]).unwrap(); + assert_eq!(wire.len(), 1); + let sp = &wire[0].subpaths[0]; + assert_eq!(sp.segment_count(), 1, "{sp:?}"); + assert!(!sp.segment_is_line(0)); +} + +#[test] +fn edges_without_length_or_with_non_finite_points_are_left_out() { + let point = PathData::single(SubPath::polyline(&[Point::new(5.0, 5.0), Point::new(5.0, 5.0)], false)); + let bad = PathData::single(SubPath::polyline(&[Point::new(f64::NAN, 0.0), Point::new(1.0, 1.0)], false)); + assert!(edges(&[point, bad]).unwrap().is_empty()); + assert!(edges(&[]).unwrap().is_empty()); +} + +#[test] +fn a_box_turned_off_axis_shows_the_nine_edges_of_its_three_faces() { + let n = solid_square(super::super::EXTRUDE, json!({})); + let wire = three_d_wireframe_in(None, &n).unwrap(); + assert_eq!(segments(&wire).len(), 9, "{wire:?}"); + // The wireframe covers what the effect draws, in the same place. + let art = super::super::solid_art(&n).unwrap(); + let (w, a) = (bounds(&wire), bounds(&face_paths(&art))); + for (x, y) in [(w.x0, a.x0), (w.y0, a.y0), (w.x1, a.x1), (w.y1, a.y1)] { + assert!((x - y).abs() < 1e-6, "{w:?} {a:?}"); + } +} + +#[test] +fn the_classic_wireframe_surface_expands_to_all_twelve_edges() { + let n = solid_square(super::super::CLASSIC_EXTRUDE, json!({"surface": "wireframe"})); + assert_eq!(segments(&three_d_wireframe_in(None, &n).unwrap()).len(), 12); +} + +#[test] +fn revolve_inflate_and_rotate_expand_too() { + for id in [crate::REVOLVE, super::super::INFLATE, ROTATE] { + let wire = three_d_wireframe_in(None, &solid_square(id, json!({}))).unwrap_or_else(|e| panic!("{id}: {e}")); + assert!(!wire.is_empty(), "{id}"); + assert!(wire.iter().flat_map(|p| &p.subpaths).flat_map(|sp| &sp.anchors).all(|a| a.p.x.is_finite() && a.p.y.is_finite()), "{id}"); + } + // Rotate is one flat face: its outline. + let plane = three_d_wireframe_in(None, &solid_square(ROTATE, json!({}))).unwrap(); + assert_eq!(segments(&plane).len(), 4); +} + +/// Revolve (Classic) and Rotate (Classic) expand to the edges of the faces they draw, in the same +/// place. +#[test] +fn revolve_classic_and_rotate_classic_expand_too() { + let n = solid_square(crate::CLASSIC_REVOLVE, json!({})); + let wire = three_d_wireframe_in(None, &n).unwrap(); + assert!(!wire.is_empty()); + let art = crate::revolve_art(&n).unwrap(); + let (w, a) = (bounds(&wire), bounds(&face_paths(&art))); + for (x, y) in [(w.x0, a.x0), (w.y0, a.y0), (w.x1, a.x1), (w.y1, a.y1)] { + assert!((x - y).abs() < 1e-6, "{w:?} {a:?}"); + } + // On a fill, with a geometry effect after it. + let mut n = solid_square(crate::CLASSIC_REVOLVE, json!({})); + let fx = n.appearance.effects.remove(0); + for item in &mut n.appearance.items { + if matches!(item, AppearanceItem::Fill(_)) { + item.effects_mut().push(fx.clone()); + } + } + let plain = bounds(&three_d_wireframe_in(None, &n).unwrap()); + for item in &mut n.appearance.items { + if matches!(item, AppearanceItem::Fill(_)) { + item.effects_mut().push(crate::new_effect("distort.transform", &json!({"moveH": 50.0})).unwrap()); + } + } + let moved = bounds(&three_d_wireframe_in(None, &n).unwrap()); + assert!((moved.x0 - plain.x0 - 50.0).abs() < 1e-6 && (moved.y0 - plain.y0).abs() < 1e-6, "{plain:?} {moved:?}"); + // Rotate (Classic) is one flat face: its outline. + let plane = three_d_wireframe_in(None, &solid_square(super::super::CLASSIC_ROTATE, json!({}))).unwrap(); + assert_eq!(segments(&plane).len(), 4); +} + +/// The geometry effects after a 3D effect reshape each face on its own, as they reshape each face +/// of the drawn surface: two faces that touch stay two outlines. +#[test] +fn later_geometry_effects_reshape_each_face_on_its_own() { + let n = solid_square(super::super::EXTRUDE, json!({})); + let fx = [crate::new_effect("path.offsetPath", &json!({"offset": 1.0})).unwrap()]; + let out = reshaped(vec![square(0.0, 0.0, 10.0), square(10.0, 0.0, 10.0)], &fx, &GeomContext::of(&n)); + assert_eq!(out.len(), 2, "{out:?}"); + let (a, b) = (out[0].bounds().unwrap(), out[1].bounds().unwrap()); + assert!((a.x0 + 1.0).abs() < 1e-3 && (a.x1 - 11.0).abs() < 1e-3, "{a:?}"); + assert!((b.x0 - 9.0).abs() < 1e-3 && (b.x1 - 21.0).abs() < 1e-3, "{b:?}"); +} + +/// A geometry effect after a fill's 3D effect moves that fill's edges, as it moves its drawn surface. +#[test] +fn a_geometry_effect_after_a_fill_s_3d_effect_reshapes_its_edges() { + for id in [super::super::EXTRUDE, crate::REVOLVE] { + let mut n = solid_square(id, json!({})); + let fx = n.appearance.effects.remove(0); + for item in &mut n.appearance.items { + if matches!(item, AppearanceItem::Fill(_)) { + item.effects_mut().push(fx.clone()); + } + } + let plain = bounds(&three_d_wireframe_in(None, &n).unwrap_or_else(|e| panic!("{id}: {e}"))); + for item in &mut n.appearance.items { + if matches!(item, AppearanceItem::Fill(_)) { + item.effects_mut().push(crate::new_effect("distort.transform", &json!({"moveH": 50.0})).unwrap()); + } + } + let moved = bounds(&three_d_wireframe_in(None, &n).unwrap()); + assert!((moved.x0 - plain.x0 - 50.0).abs() < 1e-6 && (moved.y0 - plain.y0).abs() < 1e-6, "{id}: {plain:?} {moved:?}"); + } +} + +/// With two 3D effects, a geometry effect between them reshapes the faces of the one drawn only +/// once: Revolve is drawn, so a Transform before it moves its profile and not its faces again. +#[test] +fn a_geometry_effect_before_the_drawn_3d_effect_is_not_applied_again() { + let mut n = solid_square(crate::REVOLVE, json!({})); + n.appearance.effects.insert(0, crate::new_effect("distort.transform", &json!({"moveH": 50.0})).unwrap()); + let alone = bounds(&three_d_wireframe_in(None, &n).unwrap()); + n.appearance.effects.insert(0, crate::new_effect(super::super::EXTRUDE, &json!({})).unwrap()); + let both = bounds(&three_d_wireframe_in(None, &n).unwrap()); + assert!((both.x0 - alone.x0).abs() < 1e-6 && (both.x1 - alone.x1).abs() < 1e-6, "{alone:?} {both:?}"); +} + +/// A clipping group with Revolve and Rotate draws Revolve, which cuts the art's fills as one piece +/// in the top fill's place. Its wireframe is cut the same way, so art with more fills than a 3D +/// effect takes members still expands, to the edges of Revolve alone. +#[test] +fn a_clipping_group_with_revolve_and_rotate_expands_the_art_revolve_cuts() { + let mut art = Node::path(NodeId(3), square(100.0, 100.0, 100.0), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + let fill = art.appearance.items.iter().find(|i| matches!(i, AppearanceItem::Fill(_))).cloned().unwrap(); + art.appearance.items = vec![fill; super::super::MAX_MEMBERS + 4]; + let mut clip = Node::path(NodeId(2), square(100.0, 100.0, 50.0), Appearance::default()); + if let vectorcraft_doc::NodeKind::Path { clipping, .. } = &mut clip.kind { + *clipping = true; + } + let mut n = Node::new(NodeId(1), vectorcraft_doc::NodeKind::Group { children: vec![Arc::new(clip), Arc::new(art)], clip: true }); + n.appearance.effects.push(crate::new_effect(crate::REVOLVE, &json!({})).unwrap()); + let alone = segments(&three_d_wireframe_in(None, &n).unwrap()); + n.appearance.effects.push(crate::new_effect(ROTATE, &json!({})).unwrap()); + assert!(crate::revolve_art_in(None, &n).is_some(), "the canvas draws Revolve"); + let both = segments(&three_d_wireframe_in(None, &n).unwrap()); + assert_eq!(both, alone); +} + +#[test] +fn an_object_without_a_visible_3d_effect_is_an_error() { + let mut n = solid_square(super::super::EXTRUDE, json!({})); + n.appearance.effects[0].visible = false; + assert!(three_d_wireframe_in(None, &n).unwrap_err().contains("no 3D effect")); + n.appearance.effects.clear(); + assert!(three_d_wireframe_in(None, &n).is_err()); +} diff --git a/crates/effects/src/stroke/arrow.rs b/crates/effects/src/stroke/arrow.rs index c96dcb477c..d188bcafd6 100644 --- a/crates/effects/src/stroke/arrow.rs +++ b/crates/effects/src/stroke/arrow.rs @@ -4,7 +4,8 @@ //! in the back wall of hollow ones (with the cap kept out of the hole) and at the chevron's inner //! corner. With [`ArrowAlign::Tip`] the tip sits on the end point and the stroke is shortened by //! the inset; with [`ArrowAlign::Extend`] the path keeps its length and the tip sits the inset -//! past the end point. Heads added after the first ten are drawn in local units ([`local`]). +//! past the end point. Heads added after the first ten are drawn in local units ([`local`]), as are +//! custom heads, whose stroke ends halfway along their length. use std::borrow::Cow; @@ -37,8 +38,14 @@ pub(super) fn pieces<'a>(bp: &'a BezPath, st: &StrokeLayer) -> StrokePieces<'a> let last = subs.last().filter(|s| !s.1).map(|s| s.0.clone()); let cap = cap_extent(st.cap, st.width); let (hw0, hw1) = (st.arrow_weight(false), st.arrow_weight(true)); - let start = st.start_arrow.zip(first).map(|(k, r)| (k, r, inset(k, hw0, cap))); - let end = st.end_arrow.zip(last).map(|(k, r)| (k, r, inset(k, hw1, cap))); + let start = st.start_arrow.clone().zip(first).map(|(k, r)| { + let i = inset(&k, hw0, cap); + (k, r, i) + }); + let end = st.end_arrow.clone().zip(last).map(|(k, r)| { + let i = inset(&k, hw1, cap); + (k, r, i) + }); if start.is_none() && end.is_none() { return StrokePieces { line: Cow::Borrowed(bp), heads: vec![] }; } @@ -56,7 +63,8 @@ pub(super) fn pieces<'a>(bp: &'a BezPath, st: &StrokeLayer) -> StrokePieces<'a> } else { (end_pt + outward * inset, outward) }; - heads.push(Arrow { kind, outline: shape(kind, tip, dir, hw), tip, dir, inset }); + let outline = shape(&kind, tip, dir, hw); + heads.push(Arrow { kind, outline, tip, dir, inset }); }; if let Some((k, r, i)) = start { place(k, r, true, i, hw0); @@ -173,8 +181,20 @@ fn bar(hw: f64) -> f64 { /// Where the notch of the (open) arrow sits, as a fraction of the length. const NOTCH: f64 = 0.7; +/// How far [`super::stroke_pieces`] trims the line under each end's head: the head's inset from +/// the tip, along the path. Both are 0 without a head at that end, and in [`ArrowAlign::Extend`], +/// where the stroke keeps its full length. +pub(super) fn trims(st: &StrokeLayer) -> (f64, f64) { + if st.arrow_align != ArrowAlign::Tip { + return (0.0, 0.0); + } + let cap = cap_extent(st.cap, st.width); + let inset_of = |kind: &Option<Arrowhead>, end: bool| kind.as_ref().map_or(0.0, |k| inset(k, st.arrow_weight(end), cap)); + (inset_of(&st.start_arrow, false), inset_of(&st.end_arrow, true)) +} + /// Distance from the tip where the stroke ends, for a stroke whose cap reaches `cap` past its end. -fn inset(kind: Arrowhead, hw: f64, cap: f64) -> f64 { +fn inset(kind: &Arrowhead, hw: f64, cap: f64) -> f64 { let l = len(hw); // Solid heads: halfway in, far enough that the cap stays behind the tip. let solid = |back: f64| (back / 2.0).max(cap); @@ -187,6 +207,7 @@ fn inset(kind: Arrowhead, hw: f64, cap: f64) -> f64 { Arrowhead::TriangleOpen | Arrowhead::CircleOpen | Arrowhead::SquareOpen => hollow(l), // The inner corner of the chevron: arm / sin(half angle). Arrowhead::ArrowOpen => (arm(hw) * (l * l + l * l / 4.0).sqrt() / (l / 2.0)).max(cap), + Arrowhead::Custom(c) => (c.stop() * hw).max(cap), _ => match local_stop(kind) { Stop::At(u) => (u * hw).max(cap), Stop::Wall(back) => hollow(back * hw), @@ -195,7 +216,7 @@ fn inset(kind: Arrowhead, hw: f64, cap: f64) -> f64 { } /// Outline of a `kind` head of weight `hw` with its tip at `tip`, pointing along `dir`. -fn shape(kind: Arrowhead, tip: Point, dir: Vec2, hw: f64) -> BezPath { +fn shape(kind: &Arrowhead, tip: Point, dir: Vec2, hw: f64) -> BezPath { let n = Vec2::new(-dir.y, dir.x); let l = len(hw); let half = l / 2.0; @@ -253,7 +274,7 @@ const HEX: f64 = 2.0 * 1.732_050_807_568_877_2; const LOCAL_TOL: f64 = 1e-3; /// Where the stroke ends under a head drawn in local units ([`local`]), in those units. -fn local_stop(kind: Arrowhead) -> Stop { +fn local_stop(kind: &Arrowhead) -> Stop { match kind { Arrowhead::Target | Arrowhead::TagOpen | Arrowhead::DiamondOpen => Stop::Wall(4.0), Arrowhead::HexagonOpen => Stop::Wall(HEX), @@ -276,8 +297,8 @@ fn local_stop(kind: Arrowhead) -> Stop { /// The outline of a head added after the first ten, in local units: x from the tip (0) back /// along the line (to at most 4; the line arrow's square-cut arms 4.71), y across it (−2 to 2, /// the line arrow −4 to 4; positive to the right of the direction the head points). Every shape -/// is generated here. -fn local(kind: Arrowhead) -> BezPath { +/// is generated here, and a custom head's outline is its own. +fn local(kind: &Arrowhead) -> BezPath { let mut p = BezPath::new(); let poly = |p: &mut BezPath, pts: &[(f64, f64)]| polygon(p, &pts.iter().map(|&q| Point::from(q)).collect::<Vec<_>>()); let ring_poly = |p: &mut BezPath, pts: &[(f64, f64)]| ring_polygon(p, &pts.iter().map(|&q| Point::from(q)).collect::<Vec<_>>(), ring(1.0)); @@ -373,6 +394,7 @@ fn local(kind: Arrowhead) -> BezPath { let t = FRAC_1_SQRT_2; poly(&mut p, &[(0.0, 0.0), (4.0, 4.0), (4.0 + t, 4.0 - t), (2.0 * t, 0.0), (4.0 + t, t - 4.0), (4.0, -4.0)]); } + Arrowhead::Custom(c) => p = c.path.to_bezpath(), // The first ten are drawn by `shape`. Arrowhead::Triangle | Arrowhead::TriangleOpen diff --git a/crates/effects/src/stroke/dash.rs b/crates/effects/src/stroke/dash.rs index 400f3b58b9..f174069c4e 100644 --- a/crates/effects/src/stroke/dash.rs +++ b/crates/effects/src/stroke/dash.rs @@ -134,6 +134,10 @@ impl Plan { fn fitted(mut segs: Vec<PathSeg>, mut lens: Vec<f64>, closed: bool, period: f64) -> Self { let n = segs.len(); + // A subpath with no segments (a lone moveto) has no runs to fit. + if n == 0 { + return Self::exact(segs, lens, closed, period); + } // Corners: where segments with length meet at a kink (zero-length ones have no direction). let live: Vec<usize> = (0..n).filter(|&i| lens[i] > EPS).collect(); let mut corners: Vec<usize> = live.windows(2).filter(|w| kink(&segs[w[0]], &segs[w[1]])).map(|w| w[1]).collect(); diff --git a/crates/effects/src/stroke/gradient.rs b/crates/effects/src/stroke/gradient.rs index 1cb79e9c72..ffd128b6dd 100644 --- a/crates/effects/src/stroke/gradient.rs +++ b/crates/effects/src/stroke/gradient.rs @@ -18,11 +18,11 @@ 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}; -use vectorcraft_doc::{GradientMesh, LineJoin, MeshPoint, StrokeAlign, StrokeGradientMode, StrokeLayer}; +use vectorcraft_doc::{GradientMesh, LineCap, LineJoin, MeshPoint, StrokeAlign, StrokeGradientMode, StrokeLayer}; use vectorcraft_geom::FillRule; use super::width::{flatten, left, length, split_at}; -use super::{aligned_width, cap_extent, is_closed, segments, subpaths, unit}; +use super::{aligned_width, arrow, cap_extent, is_closed, segments, subpaths, unit}; /// Largest stretch of a rib on a turn's bisector (1 / cos of half the turn, about 74°) before the /// corner gets a fan of ribs round its outside. @@ -32,6 +32,12 @@ const SHARP: f64 = 1.25; const HAIRPIN: f64 = 4.0; /// Rows of a mesh across the stroke (more where the gradient has stops). const MESH_ROWS: usize = 16; +/// The most stops of the gradient [`gradient_meshes`] puts rows or columns at +/// ([`Gradient::fitted`]: past it, the stops that change the colors least are left out). +pub(crate) const MAX_MESH_STOPS: usize = 1024; +/// The most points of one mesh [`gradient_meshes`] makes, unless a single pair of ribs needs more: +/// a subpath with more ribs than leave room for a row at each stop becomes several meshes. +pub(crate) const MAX_MESH_POINTS: usize = 1 << 20; /// The most of a subpath one column of a mesh along the stroke spans. const MESH_STEP: f64 = 1.0 / 32.0; /// The most of a subpath one slice spans while a width profile shapes the across gradient. @@ -97,7 +103,10 @@ impl Lay<'_> { /// 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 + // A square cap's corners stand √2 of the half-width out from where the dash ends, and a + // dash can end just past a corner: reach that far, or they paint outside every slice. + let diag = if self.st.dash.is_some() && self.st.cap == LineCap::Square { std::f64::consts::SQRT_2 } else { 1.0 }; + self.half(t) * diag + self.margin } /// The across band at fraction `t` of a subpath whose visible side is `side` (`Some(true)`: @@ -162,6 +171,9 @@ fn strips(bp: &BezPath, rule: FillRule, st: &StrokeLayer, tol: f64, margin: f64, return vec![]; } let heads = (st.head_reach(false), st.head_reach(true)); + // With a tip-aligned arrowhead the stroke's line, and with it the width profile, stops at the + // head's inset from the tip (`stroke_pieces`). + let trims = arrow::trims(st); 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)); @@ -170,27 +182,34 @@ fn strips(bp: &BezPath, rule: FillRule, st: &StrokeLayer, tol: f64, margin: f64, let count = subs.len(); let mut out = vec![]; for (k, (range, closed)) in subs.into_iter().enumerate() { - let (pts, corner) = flatten(&segments(&bp.elements()[range]), closed, tol.max(1e-4)); - let side = - (st.align != StrokeAlign::Center && closed_path && closed).then(|| band_on_left(bp, rule, &pts, st.align, (4.0 * tol).min(hw / 2.0))); + let segs = segments(&bp.elements()[range]); + let flat = flatten(&segs, closed, tol.max(1e-4)); + let side = (st.align != StrokeAlign::Center && closed_path && closed) + .then(|| band_on_left(bp, rule, &flat.pts, st.align, (4.0 * tol).min(hw / 2.0))); // Arrowheads sit on the start of the first subpath and the end of the last one. let heads = (if k == 0 { heads.0 } else { 0.0 }, if k + 1 == count { heads.1 } else { 0.0 }); - let ribs = match pts.len() { + let trims = (if k == 0 { trims.0 } else { 0.0 }, if k + 1 == count { trims.1 } else { 0.0 }); + let ribs = match flat.pts.len() { 0 => continue, // 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)); 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)] + vec![Rib::square(flat.pts[0] - d * e, d, r, 0.0, b), Rib::square(flat.pts[0] + d * e, d, r, 0.0, b)] } _ => { - let total = length(&pts, closed); + let total = length(&flat.pts, closed); if total <= 1e-12 { continue; } let steps = if max_dt < 1.0 { (1.0 / max_dt).ceil() as usize } else { 1 }; let profile = st.profile.iter().flat_map(|p| p.points.iter().map(|q| q.0)); let heads = if closed { (0.0, 0.0) } else { heads }; + // A tip-aligned arrowhead shortens the line it sits on, and the stroke's outline + // reads the width profile along the shortened line (`stroke_pieces`); the ribs + // must read it there too, or on a profile that changes fast they cover a narrower + // band than the stroke paints. + let span = if closed { (0.0, total) } else { (trims.0.min(total), (total - trims.1).max(trims.0)) }; // Where an arrowhead's reach ends gets a rib of its own, so the ribs that reach // across a head run all the way there instead of narrowing towards the next corner // from the head's tip, which leaves the corners of its base outside (#5964). @@ -200,11 +219,11 @@ fn strips(bp: &BezPath, rule: FillRule, st: &StrokeLayer, tol: f64, margin: f64, .copied() .chain(profile) .chain((1..steps).map(|i| i as f64 / steps as f64)) - .map(|t| t * total) + .map(|t| span.0 + (span.1 - span.0) * t) .chain(head_ends) .collect(); - let (pts, _) = split_at(&pts, &corner, closed, &at); - strip(&lay, &pts, closed, total, side, heads) + let (pts, _, _) = split_at(&flat, closed, &at, &segs); + strip(&lay, &pts, closed, total, side, heads, span) } }; out.push(ribs); @@ -226,8 +245,9 @@ fn band_on_left(bp: &BezPath, rule: FillRule, pts: &[Point], align: StrokeAlign, } /// The ribs along one flattened subpath `pts` of length `total` (`heads`: how far arrowheads -/// reach from its start and end). -fn strip(lay: &Lay, pts: &[Point], closed: bool, total: f64, side: Option<bool>, heads: (f64, f64)) -> Vec<Rib> { +/// reach from its start and end). `span` is the stretch of the subpath the width profile is laid +/// along: the whole of it, or what is left between tip-aligned arrowheads. +fn strip(lay: &Lay, pts: &[Point], closed: bool, total: f64, side: Option<bool>, heads: (f64, f64), span: (f64, f64)) -> Vec<Rib> { 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(); @@ -249,7 +269,9 @@ fn strip(lay: &Lay, pts: &[Point], closed: bool, total: f64, side: Option<bool>, // 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(); + // The fraction of the profile at how far `s` is along the subpath: the profile spans `span`. + let t_at = |s: f64| if span.1 > span.0 { ((s - span.0) / (span.1 - span.0)).clamp(0.0, 1.0) } else { 0.0 }; + let cover: Vec<f64> = (0..n).map(|i| if closed && i == 0 { lay.cover(0.0).max(lay.cover(1.0)) } else { lay.cover(t_at(along[i])) }).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, @@ -279,7 +301,7 @@ fn strip(lay: &Lay, pts: &[Point], closed: bool, total: f64, side: Option<bool>, let (first, last) = if closed { (0, n) } else { (1, n - 1) }; for i in first..last { let v = i % n; - let t = along[v] / total; + let t = t_at(along[v]); 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 }; @@ -351,9 +373,12 @@ pub struct Slice { } impl Slice { - /// The slice's paint: its piece of `g` as a linear gradient placed from `from` to `to`. - pub fn paint(&self, g: &Gradient) -> Paint { - let gradient = g.span(self.span.0 as f32, self.span.1 as f32); + /// The slice's paint: its piece of `unrolled` as a linear gradient placed from `from` to `to`. + /// `unrolled` is the stroke's gradient as [`Gradient::unrolled`] gives it (unrolled once for + /// all the slices), so one that repeats or reflects runs its stops that many times along (or + /// across) the stroke. + pub fn paint(&self, unrolled: &Gradient) -> Paint { + let gradient = unrolled.span(self.span.0 as f32, self.span.1 as f32); let end = if self.from.distance(self.to) > 1e-9 { self.to } else { self.from + Vec2::new(1.0, 0.0) }; let geom = GradientGeom { start: self.from, end, aspect: 1.0, focal: None }; Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), angle: geom.angle_deg(), ..GradientPaint::new(gradient) })) @@ -455,40 +480,72 @@ pub fn written_slices(bp: &BezPath, rule: FillRule, st: &StrokeLayer, outlines: _ => vectorcraft_pathops::stroke_region(outlines).to_bezpath(), }; let grow = if g.stops.iter().all(|s| s.opacity >= 1.0) { SLICE_GROW } else { 0.0 }; + let unrolled = g.unrolled(); let slices = gradient_slices(bp, rule, st, SLICE_TOL, SLICE_MARGIN, grow) .into_iter() .map(|s| { - let paint = s.paint(g); + let paint = s.paint(&unrolled); (s.shape, paint) }) .collect(); Some(WrittenSlices { clip, slices }) } +/// How far before and after a sharp step between two colors (two stops at one offset, as a +/// gradient that repeats has where one run meets the next) [`mesh_marks`] puts a mesh row or +/// column, as a fraction of the gradient's length. +const STEP_GAP: f64 = 1e-4; + +/// Where along gradient `g` (0 to 1) Outline Stroke's mesh puts a row or column for its stops +/// ([`Gradient::expanded_stops`]): at each stop, and for two stops at one offset (a sharp step, +/// or where a reflecting gradient turns back) also [`STEP_GAP`] before and after it, so the mesh +/// takes the color on each side. +fn mesh_marks(g: &Gradient) -> Vec<f64> { + let offsets: Vec<f64> = g.expanded_stops().iter().map(|s| f64::from(s.0)).collect(); + let shared = |i: usize| { + let t = offsets.get(i).copied().unwrap_or(0.0); + let near = |j: Option<usize>| j.and_then(|j| offsets.get(j)).is_some_and(|&u| (u - t).abs() < 1e-6); + near(i.checked_sub(1)) || near(i.checked_add(1)) + }; + let mut out = Vec::with_capacity(offsets.len() + 2); + for (i, &t) in offsets.iter().enumerate() { + out.push(t); + if shared(i) { + out.extend([(t - STEP_GAP).max(0.0), (t + STEP_GAP).min(1.0)]); + } + } + out +} + /// Outline Stroke of stroke `st` of `bp` (filled with `rule`) whose gradient `g` runs along or /// across it: a gradient mesh per subpath over all the stroke can paint there (clip it to the -/// stroke's outline), coloured as [`gradient_slices`] paint it. +/// stroke's outline), coloured as [`gradient_slices`] paint it. The gradient's stops are fitted to +/// [`MAX_MESH_STOPS`], and a subpath whose mesh would hold more than [`MAX_MESH_POINTS`] points is +/// split into meshes of fewer ribs ([`rib_pieces`]). pub fn gradient_meshes(bp: &BezPath, rule: FillRule, st: &StrokeLayer, g: &Gradient) -> Vec<GradientMesh> { + let fitted = g.fitted(MAX_MESH_STOPS); let across = st.gradient_mode == StrokeGradientMode::Across; - let color = |t: f64| g.sample_keep_model(t.clamp(0.0, 1.0) as f32); // Along: a column at each stop (colours are linear between columns), close enough to look smooth. - let marks: Vec<f64> = if across { vec![] } else { g.expanded_stops().iter().map(|s| s.0 as f64).collect() }; + let marks: Vec<f64> = if across { vec![] } else { mesh_marks(&fitted) }; let max_dt = match (across, st.profile.is_some()) { (false, _) => MESH_STEP, (true, true) => PROFILE_STEP, (true, false) => 1.0, }; // Rows across: the strip's edges, then (across) the band's left edge to its right edge with a row at each stop. - let mut us: Vec<f64> = if across { - (0..=MESH_ROWS).map(|i| i as f64 / MESH_ROWS as f64).chain(g.expanded_stops().iter().map(|s| s.0 as f64)).collect() - } else { - vec![0.5] - }; + let mut us: Vec<f64> = if across { (0..=MESH_ROWS).map(|i| i as f64 / MESH_ROWS as f64).chain(mesh_marks(&fitted)).collect() } else { vec![0.5] }; us.sort_by(f64::total_cmp); us.dedup_by(|a, b| (*a - *b).abs() < 1e-6); + let us = &us; + let g = &*fitted; + let color = |t: f64| g.sample_keep_model(t.clamp(0.0, 1.0) as f32); + // A mesh is a point for each row (and its two edges) on each rib: a strip with more ribs than + // that leaves room for is split into meshes of fewer ribs. + let per_mesh = MAX_MESH_POINTS / (us.len() + 2); strips(bp, rule, st, SLICE_TOL, SLICE_MARGIN, &marks, max_dt) .into_iter() .filter(|ribs| ribs.len() > 1) + .flat_map(|ribs| rib_pieces(ribs.len(), per_mesh).into_iter().map(move |r| ribs.get(r).unwrap_or_default().to_vec())) .map(|ribs| { let (rows, cols) = (us.len() + 1, ribs.len() - 1); // Each level across: a point on each rib and the gradient position there. @@ -525,3 +582,11 @@ pub fn gradient_meshes(bp: &BezPath, rule: FillRule, st: &StrokeLayer, g: &Gradi }) .collect() } + +/// The ribs (index ranges of `n`, at least two) of each mesh [`gradient_meshes`] makes of a strip: +/// at most `per_mesh` ribs each (at least two), each starting on the last rib of the one before, +/// so the meshes meet without a gap. +pub(crate) fn rib_pieces(n: usize, per_mesh: usize) -> Vec<std::ops::Range<usize>> { + let per_mesh = per_mesh.max(2); + (0..n.saturating_sub(1)).step_by(per_mesh - 1).map(|start| start..(start + per_mesh).min(n)).collect() +} diff --git a/crates/effects/src/stroke/tests.rs b/crates/effects/src/stroke/tests.rs index 46969ff639..1c79fd4805 100644 --- a/crates/effects/src/stroke/tests.rs +++ b/crates/effects/src/stroke/tests.rs @@ -232,16 +232,14 @@ fn line_outline_uses_the_profile_dashes_or_a_plain_stroke() { let plain = line_outline(&l, &stroke(10.0, |_| {}), 10.0, 1e-3); assert!(near(plain.area().abs(), 1000.0, 1e-6)); let lens = line_outline(&l, &stroke(10.0, |s| s.profile = Some(WidthProfile::lens())), 10.0, 1e-3); - // The lens swells on a cubic, flat at the middle: 7/12 of the full-width band (#5714). - assert!(near(lens.area().abs(), 1000.0 * 7.0 / 12.0, 0.05)); - // Each dash takes its widths from where it sits along the lens (0 → 1 → 0). Half of the lens - // rises as w(u) = u + u² − u³ (u from 0 to 1 across that half): the dash over 0..25 covers - // its first half, ∫₀^½ w = 29/192, the one over 50..75 the wider other half, 83/192. + // The lens is a parabola between its ends: 2/3 of the full-width band. + assert!(near(lens.area().abs(), 2000.0 / 3.0, 0.1)); + // Each dash takes its widths from where it sits along the lens (0 → 1 → 0). let st = stroke(10.0, |s| { s.profile = Some(WidthProfile::lens()); s.dash = Some(dashed(&[25.0, 25.0], 0.0)); }); - assert!(near(line_outline(&l, &st, 10.0, 1e-3).area().abs(), 500.0 * (29.0 + 83.0) / 192.0, 0.05)); + assert!(near(line_outline(&l, &st, 10.0, 1e-3).area().abs(), 1000.0 / 3.0, 0.1)); assert!(line_outline(&BezPath::new(), &st, 10.0, 1e-3).elements().is_empty()); } @@ -282,7 +280,7 @@ fn no_heads_borrows_the_path_and_closed_paths_get_none() { #[test] fn tip_mode_shortens_the_stroke_by_the_head_and_puts_the_tip_on_the_end_point() { for kind in Arrowhead::ALL { - let st = arrows(kind, ArrowAlign::Tip, LineCap::Butt); + let st = arrows(kind.clone(), ArrowAlign::Tip, LineCap::Butt); let l = line(0.0, 100.0); let p = stroke_pieces(&l, &st); let [h] = &p.heads[..] else { panic!("one head") }; @@ -337,7 +335,7 @@ fn extend_mode_keeps_the_path_and_overhangs_by_the_inset() { #[test] fn hollow_heads_are_rings_and_the_stroke_stays_out_of_the_hole() { for (kind, cap) in [(Arrowhead::CircleOpen, LineCap::Round), (Arrowhead::SquareOpen, LineCap::Square), (Arrowhead::TriangleOpen, LineCap::Butt)] { - let st = arrows(kind, ArrowAlign::Tip, cap); + let st = arrows(kind.clone(), ArrowAlign::Tip, cap); let l = line(0.0, 100.0); let p = stroke_pieces(&l, &st); let h = &p.heads[0]; @@ -363,7 +361,7 @@ fn hollow_heads_are_rings_and_the_stroke_stays_out_of_the_hole() { fn round_caps_never_poke_past_the_tip() { for kind in Arrowhead::ALL { for scale in [10.0, 100.0, 300.0] { - let mut st = arrows(kind, ArrowAlign::Tip, LineCap::Round); + let mut st = arrows(kind.clone(), ArrowAlign::Tip, LineCap::Round); st.arrow_scale = (scale, scale); let l = line(0.0, 100.0); let p = stroke_pieces(&l, &st); @@ -405,8 +403,8 @@ fn degenerate_paths_and_patterns_neither_panic_nor_hang() { for pat in patterns { for off in [0.0, -7.0, 1e12, f64::INFINITY] { let st = stroke(2.0, |s| { - s.start_arrow = Some(kind); - s.end_arrow = Some(kind); + s.start_arrow = Some(kind.clone()); + s.end_arrow = Some(kind.clone()); s.arrow_align = align; s.cap = cap; s.dash = Some(dashed(pat, off)); diff --git a/crates/effects/src/stroke/tests_arrows.rs b/crates/effects/src/stroke/tests_arrows.rs index 4328048991..a32a70245b 100644 --- a/crates/effects/src/stroke/tests_arrows.rs +++ b/crates/effects/src/stroke/tests_arrows.rs @@ -50,7 +50,7 @@ fn every_outline_is_drawn_inside_its_box_without_self_intersections() { let (o, d) = (Point::ORIGIN, Point::new(2.0, 2.0)); assert!(cross((o, d), (Point::new(0.0, 2.0), Point::new(2.0, 0.0))) && !cross((o, d), (d, Point::new(4.0, 0.0))), "the check itself"); for kind in Arrowhead::ALL { - let h = head(kind); + let h = head(kind.clone()); assert!(h.outline.area().abs() > 4.0, "{kind:?} is drawn"); let b = h.outline.bounding_box(); let (reach, side) = (2.0 * kind.reach(), 2.0 * kind.half_width()); @@ -73,7 +73,7 @@ fn every_outline_is_drawn_inside_its_box_without_self_intersections() { #[test] fn the_stroke_ends_inside_every_head() { for kind in Arrowhead::ALL { - let h = head(kind); + let h = head(kind.clone()); // Just in front of where the line stops, on its centre line. let end = h.tip - h.dir * (h.inset - 0.1); assert_ne!(h.outline.winding(end), 0, "{kind:?}: the line ends outside the head (inset {})", h.inset); @@ -112,3 +112,30 @@ fn half_arrows_barb_on_their_own_side() { assert!(head(Arrowhead::HalfArrowLeft).outline.bounding_box().y1 < 1.5); assert!(head(Arrowhead::HalfArrowRight).outline.bounding_box().y1 > 3.0); } + +#[test] +fn custom_heads_draw_their_own_art_at_the_tip() { + use vectorcraft_doc::CustomArrowhead; + use vectorcraft_geom::{PathData, SubPath}; + // From the tip back 3 units, 2 to the right of the line and 1 to the left. + let wedge = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(3.0, 2.0), Point::new(3.0, -1.0)], true)); + let kind = Arrowhead::Custom(std::sync::Arc::new(CustomArrowhead::new("Wedge".into(), wedge))); + let h = head(kind.clone()); + // Weight 2: drawn back to x 94, right of +x is +y on a y-down page. + let b = h.outline.bounding_box(); + assert!((b.x0 - 94.0).abs() < 1e-9 && (b.x1 - 100.0).abs() < 1e-9 && (b.y0 + 2.0).abs() < 1e-9 && (b.y1 - 4.0).abs() < 1e-9, "{b:?}"); + assert_eq!(h.outline.winding(Point::new(95.0, 1.0)), h.outline.winding(Point::new(95.0, 0.5))); + assert_ne!(h.outline.winding(Point::new(95.0, 1.0)), 0); + // The line stops halfway along the head. + assert!((h.inset - 3.0).abs() < 1e-9, "inset {}", h.inset); + // Extended, the tip sits the inset past the end point, and scaling scales the art. + let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 2.0); + (st.start_arrow, st.arrow_scale) = (Some(kind), (200.0, 100.0)); + let mut l = BezPath::new(); + l.move_to((0.0, 0.0)); + l.line_to((100.0, 0.0)); + let p = stroke_pieces(&l, &st); + let [s] = &p.heads[..] else { panic!("one head") }; + assert!((s.tip.x + 6.0).abs() < 1e-9 && s.dir.x < 0.0, "tip {:?}", s.tip); + assert!((s.outline.bounding_box().width() - 12.0).abs() < 1e-9); +} diff --git a/crates/effects/src/stroke/tests_fit.rs b/crates/effects/src/stroke/tests_fit.rs index b427fdbce7..cc69606aee 100644 --- a/crates/effects/src/stroke/tests_fit.rs +++ b/crates/effects/src/stroke/tests_fit.rs @@ -37,6 +37,20 @@ fn near(a: f64, b: f64, tol: f64) -> bool { // ---------------------------------------------------------------- dashes fitted to corners +/// A subpath with no segments (a lone moveto, as an HP-GL wedge of almost no radius gives) is +/// dashed fitted to corners without a panic, and the other subpaths keep their dashes. +#[test] +fn fitted_dashes_take_a_subpath_with_no_segments() { + let mut b = BezPath::new(); + b.move_to((5.0, 5.0)); + b.extend(line(100.0)); + let d = dash(&b, &fitted(&[10.0, 5.0], 0.0)).expect("dashed"); + assert!(moves(&d.path) > 1 && length(&d.path) > 0.0, "{:?}", d.path); + let mut lone = BezPath::new(); + lone.move_to((0.0, 0.0)); + assert!(dash(&lone, &fitted(&[10.0, 5.0], 0.0)).is_some_and(|d| d.path.elements().is_empty())); +} + #[test] fn every_corner_of_a_rectangle_falls_mid_dash() { // 100 × 50 with 12/6: the long sides hold 6 periods (scaled by 100/108), the short ones 3 @@ -155,9 +169,10 @@ fn each_dash_takes_its_width_from_the_profile_along_the_whole_path() { s.dash = Some(Dash { pattern: vec![10.0, 10.0], offset: 0.0, align_corners: false }); }); let o = line_outline(&line(100.0), &st, 10.0, 1e-3); - // The dash over 40..50 is near the lens's widest point; the one over 0..10 near its tip. + // The dash over 40..50 is near the lens's widest point; the one over 0..10 near its tip, + // where the smooth profile is thinner than a straight ramp (a parabola's first tenth). assert!(o.contains(Point::new(45.0, 4.0)) && o.contains(Point::new(45.0, -4.0)), "middle dash is wide"); - assert!(!o.contains(Point::new(5.0, 2.0)) && o.contains(Point::new(5.0, 0.3)), "first dash is thin"); + assert!(o.contains(Point::new(5.0, 0.8)) && !o.contains(Point::new(5.0, 1.2)), "first dash is thin"); assert!(!o.contains(Point::new(15.0, 0.0)), "gaps stay empty"); // Dots too: a round dot near the middle is bigger than one near an end. let st = stroke(10.0, |s| { @@ -166,7 +181,7 @@ fn each_dash_takes_its_width_from_the_profile_along_the_whole_path() { s.dash = Some(Dash { pattern: vec![0.0, 10.0], offset: 0.0, align_corners: false }); }); let o = line_outline(&line(100.0), &st, 10.0, 1e-3); - assert!(o.contains(Point::new(50.0, 4.5)) && !o.contains(Point::new(10.0, 1.5)) && o.contains(Point::new(10.0, 0.5))); + assert!(o.contains(Point::new(50.0, 4.5)) && o.contains(Point::new(10.0, 1.4)) && !o.contains(Point::new(10.0, 2.0))); } /// An L whose corner turns 90° at (100, 0), or a sharp V turning back at (100, 0). diff --git a/crates/effects/src/stroke/tests_gradient.rs b/crates/effects/src/stroke/tests_gradient.rs index a0056d6b32..784c84d1db 100644 --- a/crates/effects/src/stroke/tests_gradient.rs +++ b/crates/effects/src/stroke/tests_gradient.rs @@ -138,9 +138,8 @@ fn across_runs_from_the_left_edge_to_the_right() { let mut lens = st.clone(); lens.profile = Some(WidthProfile::lens()); let sl = slices(&line, &lens); - // A quarter of the way along, the lens is 0.625 as wide (its curve, #5714): its top edge is - // 3.125 up. - assert!(param(&sl, Point::new(25.0, -3.0)).unwrap() < 0.05); + // A quarter of the way along, the lens is three quarters as wide: its top edge is 3.75 up. + assert!(param(&sl, Point::new(25.0, -3.6)).unwrap() < 0.05); assert!((param(&sl, Point::new(50.0, -2.5)).unwrap() - 0.25).abs() < 0.02); } @@ -287,6 +286,94 @@ fn a_narrow_pass_beside_a_wide_one_leaves_its_edge_alone() { assert_covered(&hairpin, &st); } +/// A gradient along or across a stroke that repeats or reflects runs its stops that many times +/// along (or across) it: a slice's paint, and Outline Stroke's meshes, give each point the color +/// the spread gives its place. +#[test] +fn a_spread_gradient_runs_its_stops_along_the_stroke_that_many_times() { + use vectorcraft_color::GradientSpread; + let bp = poly(&[(0.0, 0.0), (120.0, 0.0)], false); + for (mode, spread) in [StrokeGradientMode::Along, StrokeGradientMode::Across] + .into_iter() + .flat_map(|m| [GradientSpread::Reflect, GradientSpread::Repeat].map(|s| (m, s))) + { + let mut st = stroke(10.0, mode); + let g = Gradient { spread, repeats: 3, ..Gradient::default() }; + st.paint = Paint::Gradient(Box::new(GradientPaint::new(g.clone()))); + for s in slices(&bp, &st) { + let Paint::Gradient(p) = s.paint(&g.unrolled()) else { panic!("a gradient slice") }; + let geom = p.geom.unwrap(); + for u in [0.1, 0.5, 0.9] { + let at = s.from + (s.to - s.from) * u; + let t = s.span.0 + (s.span.1 - s.span.0) * u; + // Where two runs meet, Repeat's color is the next run's start or the last one's end. + if (t * 3.0 - (t * 3.0).round()).abs() < 1e-9 { + continue; + } + let want = g.sample(g.spread_param(t) as f32).0.to_rgb(); + let got = p.gradient.sample(geom.param_at(vectorcraft_color::GradientKind::Linear, at) as f32).0.to_rgb(); + assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 1e-3), "{mode:?} at {t}: {want:?} vs {got:?}"); + } + } + // Outline Stroke: the mesh comes back to white where each run starts again, and reaches + // black where each run ends, on both sides of a sharp step between runs. + let count = |g: &Gradient, hex: &str| { + gradient_meshes(&bp, FillRule::NonZero, &st, g).iter().flat_map(|m| m.points.iter()).filter(|p| p.color.to_hex() == hex).count() + }; + for hex in ["#ffffff", "#000000"] { + let (spread, pad) = (count(&g, hex), count(&Gradient::default(), hex)); + assert!(spread > pad, "{mode:?} {:?} {hex}: {spread} vs {pad}", g.spread); + } + } +} + +/// Where a reflecting gradient turns back past a narrow last stop, Outline Stroke's mesh keeps that +/// stop's color. +#[test] +fn a_narrow_peak_where_a_reflecting_gradient_turns_back_stays_in_the_mesh() { + use vectorcraft_color::GradientSpread; + let bp = poly(&[(0.0, 0.0), (120.0, 0.0)], false); + let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(0.995, Color::BLACK), GradientStop::new(1.0, Color::WHITE)]; + for mode in [StrokeGradientMode::Along, StrokeGradientMode::Across] { + let mut st = stroke(10.0, mode); + let g = Gradient { spread: GradientSpread::Reflect, repeats: 100, ..Gradient::new(vectorcraft_color::GradientKind::Linear, stops.clone()) }; + st.paint = Paint::Gradient(Box::new(GradientPaint::new(g.clone()))); + let whites = + gradient_meshes(&bp, FillRule::NonZero, &st, &g).iter().flat_map(|m| m.points.iter()).filter(|p| p.color.to_hex() == "#ffffff").count(); + // The gradient turns back at white 50 times. + assert!(whites >= 50, "{mode:?}: {whites}"); + } +} + +/// Outline Stroke's mesh across a stroke of many ribs, with a gradient of many stops repeated 100 +/// times: each mesh holds at most so many points, and every run still starts on its first color. +#[test] +fn a_mesh_across_many_ribs_and_stops_stays_bounded() { + use vectorcraft_color::GradientSpread; + let pts: Vec<(f64, f64)> = (0..1200).map(|i| (i as f64 * 10.0, if i % 2 == 0 { 0.0 } else { 10.0 })).collect(); + let bp = poly(&pts, false); + let stops: Vec<GradientStop> = (0..200).map(|i| GradientStop::new(i as f32 / 199.0, Color::gray(1.0 - i as f32 / 199.0))).collect(); + let g = Gradient { spread: GradientSpread::Repeat, repeats: 100, ..Gradient::new(vectorcraft_color::GradientKind::Linear, stops) }; + let mut st = stroke(4.0, StrokeGradientMode::Across); + st.paint = Paint::Gradient(Box::new(GradientPaint::new(g.clone()))); + let meshes = gradient_meshes(&bp, FillRule::NonZero, &st, &g); + assert!(!meshes.is_empty()); + for m in &meshes { + assert!(m.points.len() <= super::gradient::MAX_MESH_POINTS, "{} points", m.points.len()); + // A row at the start of each of the 100 runs, on every rib, is white. + let light = m.points.iter().filter(|p| p.color.to_rgb()[0] > 0.97).count(); + assert!(light >= 100 * (m.cols as usize + 1), "{light} light points of {}", m.points.len()); + } + // A strip of more ribs than one mesh has room for is split into meshes that share their end + // ribs, every rib in one of them. + use super::gradient::rib_pieces; + assert_eq!(rib_pieces(5, 3), [0..3, 2..5]); + assert_eq!(rib_pieces(4, 3), [0..3, 2..4]); + let one = rib_pieces(2, 1000); + assert_eq!((one.len(), one.first()), (1, Some(&(0..2)))); + assert_eq!(rib_pieces(3, 0), [0..2, 1..3]); +} + /// #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. diff --git a/crates/effects/src/stroke/tests_reach.rs b/crates/effects/src/stroke/tests_reach.rs index 29a48343ed..5c66c9fe9d 100644 --- a/crates/effects/src/stroke/tests_reach.rs +++ b/crates/effects/src/stroke/tests_reach.rs @@ -78,6 +78,35 @@ fn a_butt_capped_open_path_is_measured_where_it_paints() { } } +#[test] +fn beveled_corners_are_measured_where_they_paint() { + let mut tip = BezPath::new(); + tip.move_to((0.0, 100.0)); + tip.line_to((20.0, 0.0)); + tip.line_to((40.0, 100.0)); + tip.close_path(); + let mut chevron = BezPath::new(); + chevron.move_to((0.0, 100.0)); + chevron.line_to((20.0, 0.0)); + chevron.line_to((40.0, 100.0)); + // A rectangle with no width turns back at its top and bottom. + let flat = vectorcraft_geom::shapes::rectangle(Rect::new(3.0, 100.0, 3.0, 150.0)).to_bezpath(); + let ps = paths(); + for (name, bp) in [("tip", &tip), ("chevron", &chevron), ("zigzag", &ps[1]), ("triangle", &ps[2]), ("flat", &flat)] { + for cap in [LineCap::Butt, LineCap::Round, LineCap::Square] { + for (join, limit) in [(LineJoin::Bevel, 10.0), (LineJoin::Miter, 1.0), (LineJoin::Miter, 2.0), (LineJoin::Miter, 10.0)] { + let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 20.0); + (st.cap, st.join, st.miter_limit) = (cap, join, limit); + let painted = outline_region(&PathData::from_bezpath(bp), FillRule::NonZero, &st).to_bezpath().bounding_box(); + let bounds = st.bounds_on(bp, bp.bounding_box()); + for (got, want) in [(bounds.x0, painted.x0), (bounds.y0, painted.y0), (bounds.x1, painted.x1), (bounds.y1, painted.y1)] { + assert!((got - want).abs() < 0.05, "{name} {cap:?} {join:?} {limit}: measured {bounds:?}, paints {painted:?}"); + } + } + } + } +} + #[test] fn bounds_and_clicks_cover_what_every_stroke_paints() { let profiles = [None, Some(WidthProfile::lens()), Some(WidthProfile { points: vec![(0.0, 2.0, 0.5), (0.6, 0.8, 1.6), (1.0, 1.2, 0.3)] })]; @@ -99,14 +128,27 @@ fn bounds_and_clicks_cover_what_every_stroke_paints() { } } +/// Custom heads: one wholly behind its tip, and a long one reaching as far in front of its tip as +/// behind it (its tip sits halfway along it past the end point with Extend). +fn custom_heads() -> Vec<Arrowhead> { + use vectorcraft_geom::{Point as P, SubPath}; + let head = |name: &str, pts: &[(f64, f64)]| { + let pts: Vec<P> = pts.iter().map(|&(x, y)| P::new(x, y)).collect(); + let path = PathData::single(SubPath::polyline(&pts, true)); + Arrowhead::Custom(std::sync::Arc::new(vectorcraft_doc::CustomArrowhead::new(name.into(), path))) + }; + vec![head("Wedge", &[(0.0, 0.0), (3.0, 2.0), (3.0, -1.0)]), head("Spindle", &[(-10.0, 0.0), (0.0, 2.0), (10.0, 0.0), (0.0, -2.0)])] +} + #[test] fn bounds_and_clicks_cover_every_arrowhead() { let bp = &paths()[0]; - for kind in Arrowhead::ALL { + for kind in Arrowhead::ALL.into_iter().chain(custom_heads()) { for align in [ArrowAlign::Extend, ArrowAlign::Tip] { for (scale, cap) in [(50.0, LineCap::Round), (100.0, LineCap::Butt), (300.0, LineCap::Square)] { let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 3.0); - (st.start_arrow, st.end_arrow, st.arrow_align, st.arrow_scale, st.cap) = (Some(kind), Some(kind), align, (scale, scale), cap); + (st.start_arrow, st.end_arrow, st.arrow_align, st.arrow_scale, st.cap) = + (Some(kind.clone()), Some(kind.clone()), align, (scale, scale), cap); check(bp, &st, &format!("{kind:?} {align:?} {scale}%")); } } diff --git a/crates/effects/src/stroke/width.rs b/crates/effects/src/stroke/width.rs index 4a9dc26784..0b307cc6b5 100644 --- a/crates/effects/src/stroke/width.rs +++ b/crates/effects/src/stroke/width.rs @@ -3,17 +3,18 @@ //! A stroke with a [`WidthProfile`] is drawn as a filled outline: each subpath is flattened, and //! at every sample the left and right offsets `width/2 · factor(t)` (t = fraction of the //! subpath's length) are placed along the normal. Corners of the path take the stroke's miter, -//! round or bevel join on their outer side (smooth points bend round), open subpaths get butt, -//! round or projecting caps (the round cap blends the two side widths), and closed subpaths become -//! two loops of opposite orientation filled with the non-zero rule. Dashes are pieces of a longer -//! subpath and read the profile where they sit along it ([`outline_spans`]). +//! round or bevel join on their outer side (smooth points offset along the curve's normal), open +//! subpaths get butt, round or projecting caps (the round cap blends the two side widths), and +//! closed subpaths become two loops of opposite orientation filled with the non-zero rule. Dashes +//! are pieces of a longer subpath and read the profile where they sit along it ([`outline_spans`]). use std::f64::consts::PI; -use kurbo::{BezPath, ParamCurve, PathEl, PathSeg, Point, Rect, Vec2}; +use kurbo::{BezPath, ParamCurve, ParamCurveNearest, PathEl, PathSeg, Point, Rect, Vec2}; use vectorcraft_doc::{LineCap, LineJoin, StrokeLayer, WidthProfile}; +use vectorcraft_pathops::fit_cubics_through; -use super::{kink, segments, subpaths, unit}; +use super::{kink, segments, subpaths, tangent, unit}; /// Filled outline of `bp` stroked with `width` scaled by `profile`, with the caps, joins and miter /// limit of `st`, flattened to `tol`. @@ -24,15 +25,16 @@ pub fn width_outline(bp: &BezPath, width: f64, profile: &WidthProfile, st: &Stro /// Outline only flattened segments near `near`, retaining each run's original fractions of its /// whole subpath for the width profile. `None` means no segments could be omitted. pub(super) fn width_outline_near(bp: &BezPath, width: f64, profile: &WidthProfile, st: &StrokeLayer, tol: f64, near: Rect) -> Option<BezPath> { - let ctx = Ctx { half: width / 2.0, profile, cap: st.cap, join: st.join, miter_limit: st.miter_limit, tol: tol.max(1e-4) }; + let ctx = Ctx::new(width, profile, st, tol); let mut out = BezPath::new(); let mut cut = false; for (r, closed) in subpaths(bp) { if closed { return None; } - let (pts, corner) = flatten(&segments(&bp.elements()[r]), closed, ctx.tol); - let n = pts.len(); + let segs = segments(&bp.elements()[r]); + let flat = flatten(&segs, closed, ctx.tol); + let n = flat.pts.len(); if n < 2 { continue; } @@ -41,7 +43,7 @@ pub(super) fn width_outline_near(bp: &BezPath, width: f64, profile: &WidthProfil let mut kept = Vec::with_capacity(count); let mut total = 0.0; for i in 0..count { - let (a, b) = (pts[i], pts[i + 1]); + let (a, b) = (flat.pts[i], flat.pts[i + 1]); let len = a.distance(b); if !len.is_finite() { return None; @@ -51,7 +53,7 @@ pub(super) fn width_outline_near(bp: &BezPath, width: f64, profile: &WidthProfil kept.push(!(a.x.max(b.x) < near.x0 || a.x.min(b.x) > near.x1 || a.y.max(b.y) < near.y0 || a.y.min(b.y) > near.y1)); } if kept.iter().all(|v| *v) { - ctx.subpath(&mut out, &pts, &corner, closed, (0.0, 1.0)); + ctx.subpath(&mut out, &flat, &segs, closed, (0.0, 1.0), count as f64); continue; } cut = true; @@ -59,27 +61,31 @@ pub(super) fn width_outline_near(bp: &BezPath, width: f64, profile: &WidthProfil continue; } let mut walked = 0.0; - let mut run = Vec::new(); - let mut run_corner = Vec::new(); + let mut run: Option<Flat> = None; let mut from = 0.0; for i in 0..count { if kept[i] { - if run.is_empty() { + if run.is_none() { from = walked / total; - run.push(pts[i]); - run_corner.push(corner[i]); + run = Some(Flat { pts: vec![flat.pts[i]], corner: vec![flat.corner[i]], seg_of: vec![], param: vec![] }); } - run.push(pts[i + 1]); - run_corner.push(corner[i + 1]); - } else if run.len() > 1 { - ctx.subpath(&mut out, &run, &run_corner, false, (from, walked / total)); - run.clear(); - run_corner.clear(); + if let Some(part) = run.as_mut() { + part.pts.push(flat.pts[i + 1]); + part.corner.push(flat.corner[i + 1]); + part.seg_of.push(flat.seg_of[i]); + part.param.push(flat.param[i]); + } + } else if let Some(part) = run.take() + && part.pts.len() > 1 + { + ctx.subpath(&mut out, &part, &segs, false, (from, walked / total), count as f64); } walked += lengths[i]; } - if run.len() > 1 { - ctx.subpath(&mut out, &run, &run_corner, false, (from, walked / total)); + if let Some(part) = run + && part.pts.len() > 1 + { + ctx.subpath(&mut out, &part, &segs, false, (from, walked / total), count as f64); } } cut.then_some(out) @@ -89,12 +95,15 @@ pub(super) fn width_outline_near(bp: &BezPath, width: f64, profile: &WidthProfil /// `spans[i]` of the subpath it was cut from (see [`Dashed::spans`](super::Dashed::spans)); /// subpaths without a span are whole. pub(super) fn outline_spans(bp: &BezPath, spans: &[(f64, f64)], width: f64, profile: &WidthProfile, st: &StrokeLayer, tol: f64) -> BezPath { - let ctx = Ctx { half: width / 2.0, profile, cap: st.cap, join: st.join, miter_limit: st.miter_limit, tol: tol.max(1e-4) }; + let ctx = Ctx::new(width, profile, st, tol); let mut out = BezPath::new(); for (i, (r, closed)) in subpaths(bp).into_iter().enumerate() { - let (pts, corner) = flatten(&segments(&bp.elements()[r]), closed, ctx.tol); - if pts.len() > 1 { - ctx.subpath(&mut out, &pts, &corner, closed, spans.get(i).copied().unwrap_or((0.0, 1.0))); + let segs = segments(&bp.elements()[r]); + let flat = flatten(&segs, closed, ctx.tol); + if flat.pts.len() > 1 { + let span = spans.get(i).copied().unwrap_or((0.0, 1.0)); + let pieces = if closed { flat.pts.len() } else { flat.pts.len() - 1 }.max(1); + ctx.subpath(&mut out, &flat, &segs, closed, span, pieces as f64 / (span.1 - span.0)); } } out @@ -105,19 +114,34 @@ pub(super) fn left(t: Vec2) -> Vec2 { Vec2::new(t.y, -t.x) } +/// A flattened subpath: its points, which of them are corners, and the source segment and +/// parameter range that drew each flattened piece (so a sample added between two points can read +/// that piece's tangent instead of the chord's direction). +pub(super) struct Flat { + pub(super) pts: Vec<Point>, + pub(super) corner: Vec<bool>, + pub(super) seg_of: Vec<usize>, + /// The source segment's parameter range for each flattened piece. Restricting the tangent + /// search to this range keeps a sample on the branch that drew it when a cubic loops back + /// near itself. + pub(super) param: Vec<(f64, f64)>, +} + /// The flattened points of one subpath (consecutive duplicates removed; a closed one doesn't /// repeat its start), each marked when it is a corner of the path. -pub(super) fn flatten(segs: &[PathSeg], closed: bool, tol: f64) -> (Vec<Point>, Vec<bool>) { - let Some(s0) = segs.first() else { return (vec![], vec![]) }; - let (mut pts, mut corner) = (vec![s0.start()], vec![false]); - // The first and the last segment that drew something. - let (mut first, mut prev): (Option<&PathSeg>, Option<&PathSeg>) = (None, None); - for seg in segs { - let at = pts.len() - 1; +pub(super) fn flatten(segs: &[PathSeg], closed: bool, tol: f64) -> Flat { + let Some(s0) = segs.first() else { return Flat { pts: vec![], corner: vec![], seg_of: vec![], param: vec![] } }; + let mut flat = Flat { pts: vec![s0.start()], corner: vec![false], seg_of: vec![], param: vec![] }; + // The last segment that drew something, and the last parameter it reached. + let mut prev: Option<&PathSeg> = None; + let mut last_added: Option<(usize, f64)> = None; + for (si, seg) in segs.iter().enumerate() { + let at = flat.pts.len() - 1; + let before = flat.pts.len(); let mut push = |p: Point| { - if pts.last().is_none_or(|l| l.distance(p) > 1e-9) { - pts.push(p); - corner.push(false); + if flat.pts.last().is_none_or(|l| l.distance(p) > 1e-9) { + flat.pts.push(p); + flat.corner.push(false); } }; match seg { @@ -130,77 +154,151 @@ pub(super) fn flatten(segs: &[PathSeg], closed: bool, tol: f64) -> (Vec<Point>, } }), } - if pts.len() > at + 1 { - match prev { - Some(p) => corner[at] = kink(p, seg), - None => first = Some(seg), + if flat.pts.len() > before { + let end = flat.pts.len() - 1; + flat.seg_of.resize(end, si); + for slot in flat.seg_of.iter_mut().take(end).skip(at) { + *slot = si; + } + // Find each new point's source parameter, never going backwards. A point is on the + // curve, so its nearest parameter is exact except at a self-intersection, where the + // monotone search picks the branch that continues this flattened piece. + let mut ts = Vec::with_capacity(end - at + 1); + ts.push(0.0); + let mut t = 0.0; + for p in &flat.pts[at + 1..=end] { + if t >= 1.0 - 1e-12 { + t = 1.0; + } else { + let sub = seg.subsegment(t..1.0); + let nr = sub.nearest(*p, 1e-9); + t = (t + (1.0 - t) * nr.t).clamp(0.0, 1.0); + } + ts.push(t); + } + flat.param.extend(ts.windows(2).map(|w| (w[0], w[1]))); + last_added = ts.last().map(|t| (si, *t)); + if let Some(p) = prev { + flat.corner[at] = kink(p, seg); } prev = Some(seg); } } if closed { - if pts.len() > 1 && pts[0].distance(pts[pts.len() - 1]) <= 1e-9 { - pts.pop(); - corner.pop(); + if flat.pts.len() > 1 && flat.pts[0].distance(flat.pts[flat.pts.len() - 1]) <= 1e-9 { + flat.pts.pop(); + flat.corner.pop(); } - if let (Some(a), Some(b)) = (prev, first) { - corner[0] = kink(a, b); + if let (Some(a), Some(b)) = (segs.last(), segs.first()) { + flat.corner[0] = kink(a, b); + } + // The closing piece comes from the last source segment even when its endpoint is the + // already-present start point and did not add a flattened point. Keep a tangent (and its + // whole parameter range) for it. + flat.seg_of.truncate(flat.pts.len()); + flat.param.truncate(flat.pts.len()); + if flat.seg_of.len() < flat.pts.len() { + let last = segs.len().saturating_sub(1); + // A closing curve with interior flattened points has already reached a parameter + // before its end (the duplicated start point was not added); the missing piece starts + // where it left off, not at 0. + let start = match last_added { + Some((si, t)) if si == last => t, + _ => 0.0, + }; + flat.seg_of.resize(flat.pts.len(), last); + flat.param.resize(flat.pts.len(), (start, 1.0)); } } - (pts, corner) + flat } -/// The most samples added between two width points. -const MAX_SPAN_SAMPLES: usize = 64; -/// The most samples [`densify`] adds between width points along one piece of a subpath. -const MAX_CURVE_SAMPLES: usize = 4096; - -/// Insert samples where the profile has width points (the two points of a discontinuous point -/// share one sample), and between them where the profile's curve ([`WidthProfile::at`]) bends, so -/// that a straight run follows it to within `tol` with a stroke of half width `half`. `span` maps -/// the subpath onto the profile (see [`outline_spans`]). -fn densify(pts: &[Point], corner: &[bool], closed: bool, profile: &WidthProfile, span: (f64, f64), half: f64, tol: f64) -> (Vec<Point>, Vec<bool>) { - let total = length(pts, closed); +/// Insert samples where the profile has width points and between them, so its smooth curve is +/// drawn as a smooth outline along straight runs too (the two points of a discontinuous point +/// share one sample). `span` maps the subpath onto the profile (see [`outline_spans`]). +fn densify( + flat: &Flat, + segs: &[PathSeg], + closed: bool, + profile: &WidthProfile, + span: (f64, f64), + density: f64, +) -> (Vec<Point>, Vec<bool>, Vec<Vec2>) { + // Two samples per profile segment: the segment end plus its midpoint. The outline is fitted + // with cubics through these points, so a smooth width curve needs far fewer samples than it + // did when every pair of samples became a separate cubic. A profile with a strong bend gets + // one more subdivision; a flat profile draws the same straight pieces as before. + const SAMPLES: usize = 2; + const MAX_SAMPLES: usize = 8; + // The gap (in width factor) the straight line between two samples may leave: small enough + // that a sharp peak like the lens' needs one more piece, large enough that a long taper's + // gentle bend does not. + const BEND: f64 = 0.05; + let total = length(&flat.pts, closed); let range = span.1 - span.0; if total <= 1e-12 || range <= 1e-12 { - return (pts.to_vec(), corner.to_vec()); + return split_at(flat, closed, &[], segs); } - let along = |t: f64| (t - span.0) / range * total; // Where the profile's points fall along this piece (a span past 1 wraps round a closed path). - let mut marks: Vec<f64> = profile.points.iter().flat_map(|p| [p.0, p.0 + 1.0]).map(along).collect(); - let mut added = 0; - for shift in [0.0, 1.0] { - for w in profile.points.windows(2) { - let (a, b) = (&w[0], &w[1]); - let (t0, t1) = (a.0 + shift, b.0 + shift); - if t1 - t0 <= 1e-7 || t1 <= span.0 || t0 >= span.1 { - continue; - } - // A span whose curve is the straight line between its points (a two-point taper, - // points on one line) needs nothing between them. A cubic off the line is off it at a - // quarter or three quarters of the way. - let off_line = |u: f64| { - let (l, r) = profile.at(a.0 + (b.0 - a.0) * u); - half * (l - (a.1 + (b.1 - a.1) * u)).abs().max((r - (a.2 + (b.2 - a.2) * u)).abs()) - }; - if off_line(0.25) <= tol * 1e-3 && off_line(0.75) <= tol * 1e-3 { - continue; - } - // A monotone cubic span bends by at most 12 times its change in width over the span - // squared, so the chords of `n` equal parts stray at most 1.5 · change / n² from it. - let change = half * (b.1 - a.1).abs().max((b.2 - a.2).abs()); - let n = (1.5 * change / tol).sqrt().ceil(); - let n = if n.is_finite() { n.clamp(1.0, MAX_SPAN_SAMPLES as f64) as usize } else { MAX_SPAN_SAMPLES }; - for k in 1..n { - if added >= MAX_CURVE_SAMPLES { - break; - } - marks.push(along(t0 + (t1 - t0) * k as f64 / n as f64)); - added += 1; - } + let mut ts: Vec<f64> = profile.points.iter().flat_map(|p| [p.0, p.0 + 1.0]).collect(); + ts.sort_by(f64::total_cmp); + ts.dedup_by(|a, b| (*a - *b).abs() <= 1e-9); + // A flat profile draws the same straight pieces as before: sample only its points. + let constant = profile.points.first().is_some_and(|f| profile.points.iter().all(|p| (p.1 - f.1).abs() <= 1e-12 && (p.2 - f.2).abs() <= 1e-12)); + let cap = (4096 / ts.len().max(1)).max(1); + // A curved path's flattened points already sample the width along the subpath. On a dense + // piece the profile's own points are enough; a straight run has only its ends, so it needs + // the extra samples. This keeps curved, profiled art close to a uniform stroke's size. + let mut marks = Vec::with_capacity(ts.len() * SAMPLES); + for w in ts.windows(2) { + let (a, b) = (w[0], w[1]); + let samples = if constant { + 1 + } else { + // `ts` has the profile both at t and t + 1 for a dash crossing a closed seam; the + // shifted copy has the same shape, so measure its bend on the unshifted segment. + let start = a.rem_euclid(1.0); + let end = start + (b - a); + let want = adaptive_samples(profile, start, end, SAMPLES, MAX_SAMPLES, BEND).min(cap); + // How many of the flattened path's points already fall in this profile segment. + // `density` is measured on the whole subpath, not on this piece, so outlining only + // the piece near the view picks the same samples as outlining the whole subpath. + let existing = (b - a) * density; + if existing >= want as f64 { 1 } else { want } + }; + for k in 0..samples { + marks.push(a + (b - a) * k as f64 / samples as f64); } } - split_at(pts, corner, closed, &marks) + if let Some(&last) = ts.last() { + marks.push(last); + } + let marks: Vec<f64> = marks.into_iter().map(|t| (t - span.0) / range * total).collect(); + split_at(flat, closed, &marks, segs) +} + +/// How many pieces one profile segment needs so a cubic fit through their ends keeps the width +/// curve. A straight taper is already straight; a visible bend gets progressively more samples. +fn adaptive_samples(profile: &WidthProfile, t0: f64, t1: f64, base: usize, max: usize, bend: f64) -> usize { + let mut samples = base.max(1); + while samples < max { + // One probe in the middle of each piece: how far the curve leaves the straight line + // between the piece's ends. The more pieces, the closer the line follows the curve, so + // the loop only stops when the pieces it has are fine enough (or at `max`). + let mut dev = 0.0_f64; + for k in 0..samples { + let (a, b) = (k as f64 / samples as f64, (k + 1) as f64 / samples as f64); + let (la, ra) = profile.at(t0 + (t1 - t0) * a); + let (lb, rb) = profile.at(t0 + (t1 - t0) * b); + let (lm, rm) = profile.at(t0 + (t1 - t0) * (a + b) / 2.0); + dev = dev.max((lm - (la + lb) / 2.0).abs()).max((rm - (ra + rb) / 2.0).abs()); + } + if dev <= bend { + break; + } + samples *= 2; + } + samples } /// Length of a flattened subpath (see [`flatten`]). @@ -212,31 +310,70 @@ pub(super) fn length(pts: &[Point], closed: bool) -> f64 { /// A flattened subpath (see [`flatten`]) with points added `marks` along it (distances from its /// start; those on a point or off the subpath are ignored). -pub(super) fn split_at(pts: &[Point], corner: &[bool], closed: bool, marks: &[f64]) -> (Vec<Point>, Vec<bool>) { +pub(super) fn split_at(flat: &Flat, closed: bool, marks: &[f64], segs: &[PathSeg]) -> (Vec<Point>, Vec<bool>, Vec<Vec2>) { + let Flat { pts, corner, seg_of, param } = flat; let n = pts.len(); let seg_count = if closed { n } else { n.saturating_sub(1) }; - let mut out = (Vec::with_capacity(n + marks.len()), Vec::with_capacity(n + marks.len())); + // The source's direction at a source parameter. The chord direction is the secant, not the + // tangent: using it for points added inside a chord jogs the normal at every flatten vertex. + let source_at = |si: usize, t: f64| -> Vec2 { segs.get(si).map_or(Vec2::new(1.0, 0.0), |seg| tangent(seg, t)) }; + // A point added inside a flattened piece searches only that piece's source parameter range: + // a looping cubic can pass near itself, and a full-segment nearest would take the other + // branch's tangent. + let source_near = |p: Point, i: usize| -> Vec2 { + let Some(si) = seg_of.get(i).copied() else { return Vec2::new(1.0, 0.0) }; + let Some(seg) = segs.get(si) else { return Vec2::new(1.0, 0.0) }; + let (t0, t1) = param.get(i).copied().unwrap_or((0.0, 1.0)); + if t1 - t0 > 1e-12 { + let sub = seg.subsegment(t0..t1); + tangent(seg, t0 + (t1 - t0) * sub.nearest(p, 1e-9).t) + } else { + tangent(seg, t0) + } + }; + // At a shared point, average the arriving and leaving directions unless it is a corner. + let dir_at = |i: usize| -> Vec2 { + let incoming = if i == 0 { + if closed { seg_of.last().copied().zip(param.last().copied()) } else { None } + } else { + seg_of.get(i - 1).copied().zip(param.get(i - 1).copied()) + }; + let outgoing = seg_of.get(i).copied().zip(param.get(i).copied()); + let a = incoming.map(|(si, (_, t))| source_at(si, t)); + let b = outgoing.map(|(si, (t, _))| source_at(si, t)); + match (a, b) { + (Some(a), Some(b)) if !corner[i] => { + let sum = a + b; + if sum.hypot() > 1e-9 { unit(sum) } else { b } + } + (_, Some(b)) => b, + (Some(a), None) => a, + (None, None) => Vec2::new(1.0, 0.0), + } + }; + let mut out = (Vec::with_capacity(n + marks.len()), Vec::with_capacity(n + marks.len()), Vec::with_capacity(n + marks.len())); let mut acc = 0.0; - // Sorted once, so each segment finds its marks by search, not by a pass over all of them. - let mut marks = marks.to_vec(); - marks.sort_by(f64::total_cmp); for i in 0..seg_count { let (a, b) = (pts[i], pts[(i + 1) % n]); let len = a.distance(b); out.0.push(a); out.1.push(corner[i]); - let from = marks.partition_point(|d| *d <= acc + 1e-9); - let mut inner: Vec<f64> = marks.iter().skip(from).copied().take_while(|d| *d < acc + len - 1e-9).collect(); + out.2.push(dir_at(i)); + let mut inner: Vec<f64> = marks.iter().copied().filter(|d| *d > acc + 1e-9 && *d < acc + len - 1e-9).collect(); + inner.sort_by(f64::total_cmp); inner.dedup_by(|a, b| (*a - *b).abs() <= 1e-9); for d in inner { - out.0.push(a.lerp(b, (d - acc) / len)); + let p = a.lerp(b, (d - acc) / len); + out.0.push(p); out.1.push(false); + out.2.push(source_near(p, i)); } acc += len; } if !closed && n > 0 { out.0.push(pts[n - 1]); out.1.push(corner[n - 1]); + out.2.push(dir_at(n - 1)); } out } @@ -249,6 +386,8 @@ struct Ctx<'a> { join: LineJoin, miter_limit: f64, tol: f64, + /// The profile has one (left, right) width everywhere. + uniform: bool, } /// A vertex of a flattened subpath: where it is, the directions in and out, the lengths of the @@ -257,14 +396,31 @@ struct Vertex { p: Point, a: Vec2, b: Vec2, + /// The smooth tangent: the source curve's direction at this sample, or the average of its + /// arriving and leaving directions at a smooth join. A smooth point offsets along this + /// normal, not the chord bisector; otherwise the chord normal inside each flattened piece and + /// the bisector at each flatten vertex alternate and the edge is scalloped. + n: Vec2, la: f64, lb: f64, corner: bool, } -impl Ctx<'_> { - fn subpath(&self, out: &mut BezPath, pts: &[Point], corner: &[bool], closed: bool, span: (f64, f64)) { - let (pts, corner) = densify(pts, corner, closed, self.profile, span, self.half, self.tol); +impl<'a> Ctx<'a> { + fn new(width: f64, profile: &'a WidthProfile, st: &StrokeLayer, tol: f64) -> Self { + Self { + half: width / 2.0, + profile, + cap: st.cap, + join: st.join, + miter_limit: st.miter_limit, + tol: tol.max(1e-4), + uniform: profile.points.first().is_some_and(|f| profile.points.iter().all(|p| p.1 == f.1 && p.2 == f.2)), + } + } + + fn subpath(&self, out: &mut BezPath, flat: &Flat, segs: &[PathSeg], closed: bool, span: (f64, f64), density: f64) { + let (pts, corner, dirs) = densify(flat, segs, closed, self.profile, span, density); let n = pts.len(); let seg_count = if closed { n } else { n - 1 }; let seg_dir: Vec<Vec2> = (0..seg_count).map(|i| unit(pts[(i + 1) % n] - pts[i])).collect(); @@ -280,117 +436,398 @@ impl Ctx<'_> { // at a discontinuous point). let width_at = |d: f64| { let t = span.0 + (span.1 - span.0) * d / total; - let (b, a) = self.profile.around(if t > 1.0 { t - 1.0 } else { t }); + // A closed path joins its own start and end: a profile with different widths there + // is a step, not a stretch across the seam. + let (b, a) = if closed && span == (0.0, 1.0) && d <= 1e-12 { + (self.profile.around(1.0).0, self.profile.around(0.0).1) + } else { + self.profile.around(if t > 1.0 { t - 1.0 } else { t }) + }; let side = |(l, r): (f64, f64)| (self.half * l.max(0.0), self.half * r.max(0.0)); (side(b), side(a)) }; - let mut lpts = Vec::with_capacity(n); - let mut rpts = Vec::with_capacity(n); + let mut lpts: Vec<(Point, bool)> = Vec::with_capacity(n); + let mut rpts: Vec<(Point, bool)> = Vec::with_capacity(n); + // Only a butt cap makes the side end at a corner; square and round caps stay tangent to it. + let end_sharp = matches!(self.cap, LineCap::Butt); for (i, &p) in pts.iter().enumerate() { - let (before, after) = width_at(cum[i]); + let ((wl_b, wr_b), (wl_a, wr_a)) = width_at(cum[i]); if !closed && (i == 0 || i == n - 1) { - let nm = left(seg_dir[i.min(seg_count - 1)]); - let (wl, wr) = if i == 0 { after } else { before }; - lpts.push(p + nm * wl); - rpts.push(p - nm * wr); + let nm = left(dirs[i]); + let (wl, wr) = if i == 0 { (wl_a, wr_a) } else { (wl_b, wr_b) }; + lpts.push((p + nm * wl, end_sharp)); + rpts.push((p - nm * wr, end_sharp)); continue; } let ip = if i == 0 { seg_count - 1 } else { i - 1 }; - let v = Vertex { p, a: seg_dir[ip], b: seg_dir[i], la: cum[ip + 1] - cum[ip], lb: cum[i + 1] - cum[i], corner: corner[i] }; + let v = Vertex { p, a: seg_dir[ip], b: seg_dir[i], n: dirs[i], la: cum[ip + 1] - cum[ip], lb: cum[i + 1] - cum[i], corner: corner[i] }; // A step: the side goes straight out (or in) from the width before to the one after. - for (k, (wl, wr)) in [before, after].into_iter().enumerate() { - if k == 0 || (wl, wr) != before { - self.join(&mut lpts, &v, wl, 1.0); - self.join(&mut rpts, &v, wr, -1.0); - } + // Both ends of that straight piece are corners: the run before it must not round + // into the step. + let (step_l, step_r) = (wl_a != wl_b, wr_a != wr_b); + self.join(&mut lpts, &v, wl_b, 1.0, step_l); + self.join(&mut rpts, &v, wr_b, -1.0, step_r); + if step_l { + self.join(&mut lpts, &v, wl_a, 1.0, true); + } + if step_r { + self.join(&mut rpts, &v, wr_a, -1.0, true); } } if closed { - polygon(out, lpts.into_iter()); - polygon(out, rpts.into_iter().rev()); + polygon(out, lpts.into_iter(), self.tol); + polygon(out, rpts.into_iter().rev(), self.tol); return; } - let (t0, t1) = (seg_dir[0], seg_dir[seg_count - 1]); + let (t0, t1) = (dirs[0], dirs[n - 1]); let ((wl0, wr0), (wl1, wr1)) = (width_at(0.0).1, width_at(total).0); let mut ring = lpts; // End cap: from the left side around the end to the right side. - cap_points(&mut ring, pts[n - 1], left(t1), t1, wl1, wr1, self.cap); + cap_points(&mut ring, pts[n - 1], left(t1), t1, wl1, wr1, self.cap, self.tol); ring.extend(rpts.into_iter().rev()); // Start cap: from the right side around the start back to the left side. - cap_points(&mut ring, pts[0], -left(t0), -t0, wr0, wl0, self.cap); - polygon(out, ring.into_iter()); + cap_points(&mut ring, pts[0], -left(t0), -t0, wr0, wl0, self.cap, self.tol); + polygon(out, ring.into_iter(), self.tol); } - /// The offset points at `v` on one side (`side` 1: left, −1: right), `w` from the path: the - /// join on the outer side of a turn, the inner miter point (or a detour through the vertex - /// when that would overshoot a segment) on the inner side. - fn join(&self, pts: &mut Vec<Point>, v: &Vertex, w: f64, side: f64) { + /// The offset points at `v` on one side (`side` 1: left, −1: right), `w` from the path. A + /// smooth point follows the vertex normal, the offset of the curve itself; a corner takes the + /// join on its outer side and the inner miter point (or a detour through the vertex when that + /// would overshoot a segment) on its inner side. + /// + /// Each point says whether the outline is sharp there: a path corner, a miter tip, a width + /// step or a butt cap end. Only those break the smooth fitting; a rapid width change makes + /// the offset turn sharply, but it is not a corner and must not be fitted as one. + fn join(&self, pts: &mut Vec<(Point, bool)>, v: &Vertex, w: f64, side: f64, step: bool) { let (na, nb) = (left(v.a) * side, left(v.b) * side); let mid = na + nb; // Cosine of half the turn; the miter point is `w / c` out along `mid`. let c = mid.hypot() / 2.0; - let miter = |pts: &mut Vec<Point>| pts.push(v.p + mid * (w / (2.0 * c * c))); if w <= 0.0 { - pts.push(v.p); - } else if v.b.dot(na) <= 0.0 { + pts.push((v.p, true)); + return; + } + let miter = if c > 1e-9 { Some(v.p + mid * (w / (2.0 * c * c))) } else { None }; + // The offset of the smooth path itself is at `w` along the path normal. The polyline + // miter (`w / c`) is the offset of the flattened segments, not of the curve: at a tight + // curve it spiked every sample outward and left a scalloped edge. The source curve's + // tangent is the smooth normal; a corner still uses its two chords for the join. + let smooth = v.p + left(v.n) * (w * side); + if v.b.dot(na) <= 0.0 { // Outer side: the path turns away from it. - let excess = if c > 1e-9 { w * (1.0 / c - 1.0) } else { f64::INFINITY }; - match self.join { - _ if excess <= self.tol => miter(pts), - LineJoin::Miter if v.corner && 1.0 / c <= self.miter_limit => miter(pts), - LineJoin::Miter | LineJoin::Bevel if v.corner => pts.extend([v.p + na * w, v.p + nb * w]), - _ => self.arc(pts, v, na, nb, w), + if !v.corner { + // A smooth point has no join: its offset is along the path normal. + pts.push((smooth, step)); + } else { + let excess = if c > 1e-9 { w * (1.0 / c - 1.0) } else { f64::INFINITY }; + match self.join { + _ if excess <= self.tol => pts.push((miter.unwrap_or(v.p), true)), + LineJoin::Miter if c > 1e-9 && 1.0 / c <= self.miter_limit => pts.push((miter.unwrap_or(v.p), true)), + LineJoin::Miter | LineJoin::Bevel => pts.extend([(v.p + na * w, true), (v.p + nb * w, true)]), + _ => self.arc(pts, v, na, nb, w, step), + } } - } else if c > 1e-9 && w * (1.0 - c * c).sqrt() / c <= v.la.min(v.lb) { - miter(pts); + } else if c <= 1e-9 { + // A reversal has no inner miter; go through the vertex. That is a notch in the + // outline, so it stays sharp: fitting a curve through it would loop. + pts.extend([(v.p + na * w, true), (v.p, true), (v.p + nb * w, true)]); + } else if !v.corner { + // A smooth point's inner offset follows its normal too. With a constant profile, once + // the half-width reaches the local radius of curvature the offset crosses the centre of + // curvature and comes back as a reversed contour, which the non-zero fill rules into a + // hole. The stroke covers that centre, so cut through it instead: the cut is inside the + // painted region and does not show. (With varying widths the crossing usually marks a + // real caustic; a cut there would show as a slit, so leave it to the offset.) + let turn = 2.0 * c.clamp(-1.0, 1.0).acos(); + let radius = if turn > 1e-9 { 0.5 * (v.la + v.lb) / turn } else { f64::INFINITY }; + if self.uniform && w >= radius { + pts.push((smooth, true)); + pts.push((v.p, true)); + pts.push((smooth, true)); + } else { + pts.push((smooth, step)); + } + } else if w * (1.0 - c * c).sqrt() / c <= v.la.min(v.lb) { + // A corner's inner offset is its miter while that stays inside both segments. + pts.push((miter.unwrap_or(v.p), true)); } else { - pts.extend([v.p + na * w, v.p, v.p + nb * w]); + // The inner offset of a corner cuts through the vertex; keep that notch sharp. + pts.extend([(v.p + na * w, true), (v.p, true), (v.p + nb * w, true)]); } } /// A round join from `na` to `nb` (unit normals) at radius `w` around `v`; a full reversal - /// rounds through the direction of travel. - fn arc(&self, pts: &mut Vec<Point>, v: &Vertex, na: Vec2, nb: Vec2, w: f64) { + /// rounds through the direction of travel. `sharp` marks a step at the join's ends. + fn arc(&self, pts: &mut Vec<(Point, bool)>, v: &Vertex, na: Vec2, nb: Vec2, w: f64, sharp: bool) { let phi = if (na + nb).hypot() < 1e-9 { if Vec2::new(-na.y, na.x).dot(v.a) > 0.0 { PI } else { -PI } } else { na.cross(nb).atan2(na.dot(nb)) }; let step = 2.0 * (1.0 - (self.tol / w).min(1.0)).acos(); let steps = ((phi.abs() / step.max(1e-3)).ceil() as usize).clamp(1, 256); for k in 0..=steps { let (s, c) = (phi * k as f64 / steps as f64).sin_cos(); - pts.push(v.p + Vec2::new(na.x * c - na.y * s, na.x * s + na.y * c) * w); + pts.push((v.p + Vec2::new(na.x * c - na.y * s, na.x * s + na.y * c) * w, sharp)); } } } /// Cap points between `c + u·r0` and `c − u·r1`, bulging towards `v`. -fn cap_points(ring: &mut Vec<Point>, c: Point, u: Vec2, v: Vec2, r0: f64, r1: f64, cap: LineCap) { +#[allow(clippy::too_many_arguments)] +fn cap_points(ring: &mut Vec<(Point, bool)>, c: Point, u: Vec2, v: Vec2, r0: f64, r1: f64, cap: LineCap, tol: f64) { match cap { LineCap::Butt => {} LineCap::Square => { let h = (r0 + r1) / 2.0; - ring.push(c + u * r0 + v * h); - ring.push(c - u * r1 + v * h); + ring.push((c + u * r0 + v * h, true)); + ring.push((c - u * r1 + v * h, true)); } LineCap::Round => { - let steps = 16; + // Enough steps that the cap's facets stay within `tol`, as a round join does. + let r = r0.max(r1).max(1e-9); + let step = 2.0 * (1.0 - (tol / r).min(1.0)).acos(); + let steps = ((PI / step.max(1e-6)).ceil() as usize).clamp(8, 256); for k in 1..steps { - let a = std::f64::consts::PI * k as f64 / steps as f64; + let a = PI * k as f64 / steps as f64; let r = r0 + (r1 - r0) * (k as f64 / steps as f64); - ring.push(c + u * (a.cos() * r) + v * (a.sin() * r)); + ring.push((c + u * (a.cos() * r) + v * (a.sin() * r), false)); } } } } -fn polygon(out: &mut BezPath, mut pts: impl Iterator<Item = Point>) { - let Some(first) = pts.next() else { return }; - out.move_to(first); - for p in pts { - out.line_to(p); +/// Append `pts` as a closed contour (a width outline's ring or loop), through a smooth run's +/// points as cubic curves. Sampled as line segments, a curved, wide stroke shows the facets of +/// its offset whenever it is magnified; the cubics keep it smooth. A run whose points are +/// collinear stays a line, and the points marked sharp — caps, miter joins, width steps and path +/// corners — stay sharp. A rapid width change turns the offset sharply without being a corner: +/// marking corners here rather than measuring turns keeps that turn smooth. +fn polygon(out: &mut BezPath, pts: impl Iterator<Item = (Point, bool)>, tol: f64) { + let mut ring: Vec<(Point, bool)> = Vec::new(); + for (p, sharp) in pts { + if !p.x.is_finite() || !p.y.is_finite() { + return; + } + if let Some(last) = ring.last_mut() + && last.0.distance(p) <= 1e-9 + { + last.1 |= sharp; + continue; + } + ring.push((p, sharp)); + } + if ring.len() > 1 + && ring[0].0.distance(ring[ring.len() - 1].0) <= 1e-9 + && let Some(last) = ring.pop() + { + ring[0].1 |= last.1; + } + let n = ring.len(); + if n == 0 { + return; + } + if n < 3 { + out.move_to(ring[0].0); + if n == 2 { + out.line_to(ring[1].0); + } + out.close_path(); + return; + } + // Start at a sharp point when there is one, so no run has to wrap: `smooth_run` starts from + // whichever point is current, and starting anywhere else would bridge over the skipped arc. + match ring.iter().position(|&(_, sharp)| sharp) { + None => { + // A smooth closed loop: fit across the seam, so it doesn't start with a kink. + let pts: Vec<Point> = ring.iter().map(|&(p, _)| p).collect(); + out.move_to(pts[0]); + smooth_run(out, &pts, true, tol); + } + Some(first) => { + out.move_to(ring[first].0); + // From each sharp point to the next; the sharp points themselves stay sharp. + let mut i = first; + loop { + let mut j = (i + 1) % n; + while !ring[j].1 { + j = (j + 1) % n; + } + // A contour with a single sharp point comes back to it: the run is the whole + // loop, fitted non-cyclically so that point stays sharp. + let steps = if j == i { n } else { (j + n - i) % n }; + if steps == 1 { + out.line_to(ring[j].0); + } else { + let run: Vec<Point> = (0..=steps).map(|k| ring[(i + k) % n].0).collect(); + smooth_run(out, &run, false, tol); + } + if j == first { + break; + } + i = j; + } + } } out.close_path(); } +/// The derivative of the run at each point, in points per point of chord length. Each coordinate +/// is a shape-preserving cubic Hermite (Fritsch–Carlson): between two points it stays within their +/// coordinate range, so a cubic through a fast width pinch cannot bulge past the pinch and cross +/// the other side, and it has a flat slope at a local extremum. A Catmull–Rom tangent (the secant +/// across the neighbours) does neither: it overshoots a V and, with the uneven sample spacing of a +/// flattened path, leaves a scalloped edge. +fn tangents(run: &[Point], cyclic: bool) -> Vec<Vec2> { + let n = run.len(); + let segs = if cyclic { n } else { n.saturating_sub(1) }; + let mut h = vec![0.0; segs]; + for (i, hi) in h.iter_mut().enumerate() { + *hi = run[i].distance(run[(i + 1) % n]); + } + let slope = |d0: f64, d1: f64, h0: f64, h1: f64| { + if d0 * d1 <= 0.0 { + return 0.0; + } + let (w0, w1) = (2.0 * h1 + h0, h1 + 2.0 * h0); + let m = (w0 + w1) / (w0 / d0 + w1 / d1); + if m.is_finite() { m } else { 0.0 } + }; + // The one-sided slope of a run's end uses its two end secants, instead of only the last one. + // A coarse sample then still leaves the end of a profile curve with the right slope. + let end_slope = |d0: f64, d1: f64, h0: f64, h1: f64| { + if d0 * d1 <= 0.0 || h0 + h1 <= 1e-12 { + return 0.0; + } + let m = ((2.0 * h0 + h1) * d0 - h0 * d1) / (h0 + h1); + if m.is_finite() && m * d0 > 0.0 { + let cap = 3.0 * d0.abs(); + m.clamp(-cap, cap) + } else { + 0.0 + } + }; + let delta = |i: usize| -> Vec2 { + let hi = h[i % segs]; + if hi > 1e-12 { (run[(i + 1) % n] - run[i % n]) / hi } else { Vec2::ZERO } + }; + let mut out = vec![Vec2::ZERO; n]; + for (i, m) in out.iter_mut().enumerate() { + let (d0, d1) = (delta((i + n - 1) % n), delta(i % segs)); + let (h0, h1) = (h[(i + n - 1) % segs], h[i % segs]); + if h0 <= 1e-12 || h1 <= 1e-12 { + *m = if h1 > 1e-12 { d1 } else { d0 }; + } else if cyclic || (i > 0 && i + 1 < n) { + *m = Vec2::new(slope(d0.x, d1.x, h0, h1), slope(d0.y, d1.y, h0, h1)); + } else if i == 0 { + *m = if n >= 3 { + let (a, b) = (delta(0), delta(1)); + Vec2::new(end_slope(a.x, b.x, h[0], h[1]), end_slope(a.y, b.y, h[0], h[1])) + } else { + d1 + }; + } else { + *m = if n >= 3 { + let (a, b) = (delta(n - 2), delta(n - 3)); + Vec2::new(end_slope(a.x, b.x, h[n - 2], h[n - 3]), end_slope(a.y, b.y, h[n - 2], h[n - 3])) + } else { + d0 + }; + } + // A shape-preserving slope is flat in a coordinate at that coordinate's local extremum. + // Where both are extrema at one sample (a loop or a pinch in the sampled edge) the flat + // tangent would make a line and a kink; the secant across the sample keeps the curve C1 + // there, and the extremum itself is what trims the loop later. + if m.hypot() <= 1e-12 { + let prev = if cyclic || i > 0 { run[(i + n - 1) % n] } else { run[i] }; + let next = if cyclic || i + 1 < n { run[(i + 1) % n] } else { run[i] }; + let sec = next - prev; + if sec.hypot() > 1e-12 { + *m = sec.normalize(); + } + } + } + out +} + +/// Append a run of points as a fitted chain of cubics (or one line when they are collinear). +/// +/// A cubic through every flattened point, as this used to emit, keeps the outline smooth but puts +/// three coordinates per point into the file; a small, thin stroke then exports several times the +/// path data of the same stroke without a profile. Fit a chain within the outline tolerance +/// instead: the result is still G1 continuous and stays within `tol` of the sampled edge, but a +/// smooth side is a few cubics rather than one per flatten step. Profile bends that need finer +/// detail produce more cubics; straight runs stay lines. +fn smooth_run(out: &mut BezPath, run: &[Point], cyclic: bool, tol: f64) { + let n = run.len(); + if n < 2 { + return; + } + if !cyclic && is_straight(run, tol) { + out.line_to(run[n - 1]); + return; + } + let tans = tangents(run, cyclic); + let tol = tol.max(1e-6); + // A short run is one or two profile features, not flattened path detail. Fitting it loosely + // enough to save path data can let a handle cross the narrow side of a V; keep the + // shape-preserving per-point cubics there. + let segs = if cyclic { n } else { n - 1 }; + if n <= 3 { + for i in 0..segs { + let j = (i + 1) % n; + let h = run[i].distance(run[j]); + let (m0, m1) = (tans[i] * (h / 3.0), tans[j] * (h / 3.0)); + if m0.hypot() <= 1e-12 || m1.hypot() <= 1e-12 { + out.line_to(run[j]); + } else { + out.curve_to(run[i] + m0, run[j] - m1, run[j]); + } + } + return; + } + let unit_or = |v: Vec2, fallback: Vec2| { + let len = v.hypot(); + if len > 1e-12 { + v / len + } else { + let len = fallback.hypot(); + if len > 1e-12 { fallback / len } else { Vec2::new(1.0, 0.0) } + } + }; + let t0 = unit_or(tans[0], run[1] - run[0]); + let (pts, t0, t1) = if cyclic { + // Fit the seam too: the fit starts and arrives with the same tangent, so closing the + // contour adds no kink. + let mut pts = Vec::with_capacity(n + 1); + pts.extend_from_slice(run); + pts.push(run[0]); + (pts, t0, t0) + } else { + (run.to_vec(), t0, unit_or(tans[n - 1], run[n - 1] - run[n - 2])) + }; + // Fit tighter than the flattening tolerance: the fit's error is the whole outline's error, + // and a least-squares fit may sit on one side of the sampled edge, which would otherwise + // shift a profile's area visibly. The points lie on the outline's own curve, so the fit follows + // their curve between them rather than the chords through them. + let cubics = fit_cubics_through(&pts, t0, t1, tol * 0.1); + if cubics.is_empty() { + out.line_to(run[n - 1]); + return; + } + for c in cubics { + out.curve_to(c.p1, c.p2, c.p3); + } +} + +/// Are the run's points within the flattening tolerance of its chord? +fn is_straight(run: &[Point], tol: f64) -> bool { + let (a, b) = (run[0], run[run.len() - 1]); + let d = b - a; + let l = d.hypot(); + if l <= 1e-12 { + return false; + } + run.iter().all(|p| (d.cross(*p - a) / l).abs() <= tol.max(1e-6) * 0.25) +} + #[cfg(test)] mod tests { use super::*; @@ -423,13 +860,12 @@ mod tests { assert!((area(&width_outline(&line(), 10.0, &p, &capped(LineCap::Square), 0.01)) - 1100.0).abs() < 1e-6); } - /// The Lens outline swells on its curve, and a profile with one side at zero paints only the other side. + /// The lens eases up to full width and back down (a parabolic bump averaging two thirds of + /// the width); a one-sided profile keeps its side at zero and stays on the other. #[test] - fn lens_profile_swells_smoothly_and_one_sided_profiles_stay_on_their_side() { - // Each half of the lens rises on a cubic from 0 to full width, flat at the middle: it - // covers 7/12 of the full-width band (a diamond would cover half). + fn lens_profile_is_a_smooth_bump_and_one_sided_profiles_stay_on_their_side() { let a = area(&width_outline(&line(), 10.0, &WidthProfile::lens(), &capped(LineCap::Butt), 0.01)); - assert!((a - 1000.0 * 7.0 / 12.0).abs() < 0.5, "{a}"); + assert!((a - 2000.0 / 3.0).abs() < 0.1, "{a}"); let one = WidthProfile { points: vec![(0.0, 1.0, 0.0), (1.0, 1.0, 0.0)] }; let o = width_outline(&line(), 10.0, &one, &capped(LineCap::Butt), 0.01); assert!((area(&o) - 500.0).abs() < 1e-6); @@ -453,41 +889,103 @@ mod tests { assert!(a.is_finite() && (a - 3000.0).abs() < 150.0, "{a}"); } - /// #5714: between width points a straight run follows the profile's smooth curve, not a - /// straight line from one width to the next. #[test] - fn a_straight_run_follows_the_curve_between_width_points() { - // 5 pt either side at the ends, 15 pt at the middle: a quarter of the way along the curve - // is at 2.25 × 5 = 11.25 pt (a straight ramp would be at 10 pt). - let p = WidthProfile { points: vec![(0.0, 1.0, 1.0), (0.5, 3.0, 3.0), (1.0, 1.0, 1.0)] }; - let o = width_outline(&line(), 10.0, &p, &capped(LineCap::Butt), 0.01); - for y in [-11.0, 11.0] { - assert!(o.contains(kurbo::Point::new(25.0, y)), "inside at y {y}"); - } - for y in [-11.5, 11.5] { - assert!(!o.contains(kurbo::Point::new(25.0, y)), "outside at y {y}"); - } - // Round the widest point the side is flat: no corner sticks out above 15 pt. - let bb = o.bounding_box(); - assert!((bb.y0 + 15.0).abs() < 1e-6 && (bb.y1 - 15.0).abs() < 1e-6, "{bb:?}"); + fn a_closed_path_steps_where_its_profile_ends_differ() { + let mut sq = BezPath::new(); + sq.move_to((0.0, 0.0)); + sq.line_to((100.0, 0.0)); + sq.line_to((100.0, 100.0)); + sq.line_to((0.0, 100.0)); + sq.close_path(); + // 5 pt at the seam's start, 10 pt at its end: the ring must step between them, not + // stretch the last width point round the corner. + let p = WidthProfile { points: vec![(0.0, 1.0, 1.0), (1.0, 2.0, 2.0)] }; + let o = width_outline(&sq, 10.0, &p, &capped(LineCap::Butt), 0.01); + let at = |p: Point, x: f64, y: f64| (p.x - x).abs() < 1e-9 && (p.y - y).abs() < 1e-9; + let step = o.elements().windows(2).any(|w| match (w[0], w[1]) { + (PathEl::MoveTo(a), PathEl::LineTo(b)) | (PathEl::LineTo(a), PathEl::LineTo(b)) => { + at(a, -10.0, -10.0) && at(b, -5.0, -5.0) || at(a, -5.0, -5.0) && at(b, -10.0, -10.0) + } + _ => false, + }); + assert!(step, "{o:?}"); } - /// A taper is a straight ramp: its outline gets no samples between the width points. #[test] - fn a_straight_taper_gets_no_samples_between_its_points() { - let o = width_outline(&line(), 10.0, &WidthProfile::taper_end(), &capped(LineCap::Butt), 0.01); - assert_eq!(o.elements().len(), 5, "{:?}", o.elements()); + fn added_samples_follow_the_curve_not_the_flattened_chord() { + // A cubic with a tight S: its chords are far from its tangents. A sample inserted inside a + // chord must take the curve's direction there; the chord's direction is what made a wide + // profile scallop at every flatten vertex. + let mut b = BezPath::new(); + b.move_to((0.0, 0.0)); + b.curve_to((0.0, 120.0), (120.0, -120.0), (120.0, 0.0)); + let segs = segments(b.elements()); + let flat = flatten(&segs, false, 2.0); + assert!(flat.pts.len() >= 3); + let mut marks = vec![]; + let mut acc = 0.0; + for i in 0..flat.pts.len() - 1 { + let len = flat.pts[i].distance(flat.pts[i + 1]); + marks.push(acc + len / 2.0); + acc += len; + } + let (all, _, dirs) = split_at(&flat, false, &marks, &segs); + assert!(all.len() > flat.pts.len()); + let seg = segs[0]; + for (p, d) in all.iter().zip(&dirs) { + let want = tangent(&seg, seg.nearest(*p, 1e-9).t); + assert!(d.dot(want) > 0.999, "{d:?} vs {want:?} at {p:?}"); + } } - /// A profile read from a file may have thousands of points and absurd widths: the samples added - /// between them stay bounded and the outline finite. #[test] - fn samples_between_width_points_are_capped() { - let points = (0..=10_000).map(|i| (i as f64 / 10_000.0, if i % 2 == 0 { 0.0 } else { 1e12 }, 1.0)).collect(); - let o = width_outline(&line(), 10.0, &WidthProfile { points }, &capped(LineCap::Butt), 0.01); - let n = o.elements().len(); - assert!(n < 2 * (2 * 10_001 + MAX_CURVE_SAMPLES) + 64, "{n}"); - assert!(o.bounding_box().area().is_finite()); + fn a_wiggly_profile_on_a_curve_fits_without_kinks() { + // A rapid width change turns the offset sharply; that is not a path corner, so the + // outline must stay tangent-continuous through it (the old turn-angle test did not). + let c = kurbo::Circle::new((0.0, 0.0), 50.0).to_path(1e-3); + let p = WidthProfile { + points: vec![(0.0, 1.0, 1.0), (0.15, 3.0, 0.4), (0.3, 0.2, 2.8), (0.5, 2.5, 0.3), (0.7, 0.4, 2.2), (0.85, 2.0, 0.5), (1.0, 1.0, 1.0)], + }; + let o = width_outline(&c, 10.0, &p, &capped(LineCap::Butt), 0.01); + let mut cursor = None; + let mut prev: Option<Vec2> = None; + let mut kinks = 0; + let mut check = |a: Vec2, b: Vec2| { + let (la, lb) = (a.hypot(), b.hypot()); + if la > 1e-9 && lb > 1e-9 && (a.dot(b) <= 0.0 || a.cross(b).abs() / (la * lb) > 1e-6) { + kinks += 1; + } + }; + for el in o.elements() { + match el { + PathEl::MoveTo(p) => { + cursor = Some(*p); + prev = None; + } + PathEl::LineTo(p) => { + if let Some(q) = cursor { + let d = *p - q; + if let Some(a) = prev { + check(a, d); + } + prev = Some(d); + } + cursor = Some(*p); + } + PathEl::CurveTo(a, b, p) => { + if let Some(q) = cursor { + let d = if a.distance(q) > 1e-9 { *a - q } else { *b - q }; + if let Some(prev) = prev { + check(prev, d); + } + prev = Some(if p.distance(*b) > 1e-9 { *p - *b } else { *p - *a }); + } + cursor = Some(*p); + } + PathEl::QuadTo(_, _) | PathEl::ClosePath => {} + } + } + assert_eq!(kinks, 0, "{o:?}"); } #[test] @@ -512,4 +1010,108 @@ mod tests { let want = 2.0 * std::f64::consts::PI * 50.0 * 10.0; assert!((a - want).abs() / want < 0.01, "{a} vs {want}"); } + + #[test] + fn a_uniform_circle_narrower_than_its_stroke_has_no_hole() { + // Half-width 15 on a radius-5 circle: the inner offset crosses the centre. The constant + // stroke still covers the centre, so the outline must not leave a hole there. + let c = kurbo::Circle::new((0.0, 0.0), 5.0).to_path(1e-3); + let p = WidthProfile { points: vec![(0.0, 1.0, 1.0), (1.0, 1.0, 1.0)] }; + let o = width_outline(&c, 30.0, &p, &capped(LineCap::Butt), 0.01); + assert!(o.contains(Point::new(0.0, 0.0)), "{o:?}"); + } + + #[test] + fn a_quick_width_change_does_not_overshoot_its_samples() { + // Width falls to a point and comes back, unevenly on either side: the fitted edge must not + // dip past the point (that crossed the other edge and left a scalloped neck). + let mut run = vec![Point::new(0.0, 0.0), Point::new(10.0, -1.0), Point::new(20.0, -0.3)]; + let (mut a, mut b) = (BezPath::new(), BezPath::new()); + a.move_to(run[0]); + b.move_to(run[0]); + smooth_run(&mut a, &run, false, 0.0); + // Reverse the same points: the fit must stay inside the V from either direction too. + run.reverse(); + smooth_run(&mut b, &run, false, 0.0); + for path in [a, b] { + let mut start = Point::ZERO; + for el in path.elements() { + match el { + PathEl::MoveTo(p) => start = *p, + PathEl::CurveTo(c1, c2, p) => { + for c in [c1, c2] { + assert!(c.y >= -1.0 - 1e-9, "{c:?} in {path:?}"); + assert!(c.y <= start.y.max(p.y) + 1e-9, "{c:?} in {path:?}"); + } + start = *p; + } + _ => {} + } + } + } + } + + #[test] + fn added_samples_stay_on_their_flattened_branch() { + // This cubic loops back near itself. At a coarse tolerance a chord midpoint can be closer + // to the other branch; a full-segment nearest would then take that branch's tangent and + // spike the offset. Each inserted sample must use the parameter range of its own piece. + let mut b = BezPath::new(); + b.move_to((0.0, 0.0)); + b.curve_to((150.0, 100.0), (-50.0, 100.0), (100.0, 0.0)); + let segs = segments(b.elements()); + let seg = segs[0]; + let flat = flatten(&segs, false, 2.0); + let mut acc = 0.0; + let mut divergent = 0; + for i in 0..flat.pts.len() - 1 { + let len = flat.pts[i].distance(flat.pts[i + 1]); + if len <= 1e-12 { + continue; + } + let (t0, t1) = flat.param[i]; + let sub = seg.subsegment(t0..t1); + for k in 1..16 { + let (out, _, dirs) = split_at(&flat, false, &[acc + len * k as f64 / 16.0], &segs); + assert!(out.len() >= i + 2, "no sample inserted in piece {i}"); + let p = out[i + 1]; + let want = tangent(&seg, t0 + (t1 - t0) * sub.nearest(p, 1e-9).t); + assert!(dirs[i + 1].dot(want) > 0.999, "piece {i}, k {k}: {:?} vs {want:?}", dirs[i + 1]); + let full = tangent(&seg, seg.nearest(p, 1e-9).t); + if full.dot(want) < 0.9 { + divergent += 1; + } + } + acc += len; + } + assert!(divergent > 0, "the fixture did not cross the other branch"); + } + + #[test] + fn a_coarse_wide_circle_keeps_its_offset() { + // A wide stroke flattened coarsely: offsetting each flattened segment by its miter + // (`w / cos(θ/2)`) scalloped the circle outward at every sample. Smooth points follow the + // curve's normal instead, so the ring is the annulus between radii 10 and 30. + let c = kurbo::Circle::new((0.0, 0.0), 20.0).to_path(0.5); + let p = WidthProfile { points: vec![(0.0, 1.0, 1.0), (1.0, 1.0, 1.0)] }; + let a = area(&width_outline(&c, 20.0, &p, &capped(LineCap::Butt), 0.5)); + let want = std::f64::consts::PI * (30.0 * 30.0 - 10.0 * 10.0); + assert!((a - want).abs() / want < 0.01, "{a} vs {want}"); + } + + #[test] + fn profiled_outlines_stay_compact() { + // A smooth profile is fitted with cubics, so it must not turn every profile sample into + // exported path data. Compare it with the same curved path's uniform outline. + let circle = kurbo::Circle::new((0.0, 0.0), 5.0).to_path(0.01); + let count = |points| { + let p = WidthProfile { points }; + width_outline(&circle, 5.0, &p, &capped(LineCap::Butt), 0.01).elements().len() + }; + let uniform = count(vec![(0.0, 1.0, 1.0), (1.0, 1.0, 1.0)]); + let lens = count(WidthProfile::lens().points); + let wave = count(vec![(0.0, 0.3, 0.3), (0.25, 1.0, 1.0), (0.5, 0.3, 0.3), (0.75, 1.0, 1.0), (1.0, 0.3, 0.3)]); + assert!(lens <= uniform * 3 / 2, "lens {lens} vs uniform {uniform}"); + assert!(wave <= uniform * 3 / 2, "wave {wave} vs uniform {uniform}"); + } } diff --git a/crates/effects/src/tests.rs b/crates/effects/src/tests.rs index 532251bd73..48665539d9 100644 --- a/crates/effects/src/tests.rs +++ b/crates/effects/src/tests.rs @@ -4,6 +4,9 @@ use vectorcraft_geom::{Affine, PathData, Point, Rect, Shape, SubPath, shapes}; use super::*; +mod imageoutline; +mod painted; +mod rasterfollow; mod scale; mod transformfx; @@ -209,6 +212,57 @@ fn warp_arc_bends_the_top_edge() { assert!(b.x0 < -1.0 || b.x1 > 101.0, "{b:?}"); } +/// A Warp of `version` 1 bends its bounds as its style's Bézier net; one without a version, as +/// saved before the version existed, draws as it always did. Flag at 60 % on a 200 × 100 box: the +/// net moves the top edge up to 6 × 0.6 × 100 × max u(1 - u)(1 - 2u) = 34.64 out, the earlier map +/// moves it 0.6 × 25 = 15. +#[test] +fn a_warp_draws_with_the_map_its_version_names() { + let rect = shapes::rectangle(Rect::new(10.0, 20.0, 210.0, 120.0)); + // u(1 - u)(1 - 2u) peaks at √3 / 18. + let peak = 360.0 * 3f64.sqrt() / 18.0; + for (version, out) in [(json!(1), peak), (json!(null), 15.0), (json!(0), 15.0)] { + let b = run("warp.flag", json!({"bend": 60, "version": version}), &rect).bounds().unwrap(); + assert!(close(b.y0, 20.0 - out, 0.1) && close(b.y1, 120.0 + out, 0.1), "version {version}: {b:?}"); + assert!(close(b.x0, 10.0, 1e-9) && close(b.x1, 210.0, 1e-9), "version {version}: {b:?}"); + } +} + +/// A straight line has a box with no width or no height, and the net bends it as the middle of +/// the patch along that side: under Arc a vertical line stays vertical, and under Bulge, Fisheye, +/// Inflate and Squeeze a horizontal line stays straight. +#[test] +fn a_warp_bends_a_flat_box_as_the_middle_of_its_patch() { + let anchors = |p: &PathData| p.subpaths.iter().flat_map(|s| s.anchors.clone()).collect::<Vec<_>>(); + let vertical = shapes::line(Point::new(100.0, 0.0), Point::new(100.0, 100.0)); + let out = run("warp.arc", json!({"bend": 50, "version": 1}), &vertical); + assert!(anchors(&out).iter().all(|a| close(a.p.x, 100.0, 1e-9) && close(a.h_in.x, 100.0, 1e-9) && close(a.h_out.x, 100.0, 1e-9)), "{out:?}"); + let horizontal = shapes::line(Point::new(0.0, 50.0), Point::new(200.0, 50.0)); + for style in ["bulge", "fisheye", "inflate", "squeeze"] { + let out = run(&format!("warp.{style}"), json!({"bend": 50, "version": 1}), &horizontal); + assert!( + anchors(&out).iter().all(|a| close(a.p.y, 50.0, 1e-9) && close(a.h_in.y, 50.0, 1e-9) && close(a.h_out.y, 50.0, 1e-9)), + "{style}: {out:?}" + ); + } +} + +/// A new Warp takes the nets' version unless one is given, and the catalog's defaults carry none, +/// so a saved warp's params don't gain one. +#[test] +fn new_warps_take_the_nets_version() { + for (s, _) in WARP_STYLES { + let id = format!("warp.{s}"); + let Some(e) = crate::new_effect(&id, &json!({"bend": 20})) else { panic!("{id}") }; + assert_eq!(e.params["version"], json!(crate::WARP_NET), "{id}"); + let Some(e) = crate::new_effect(&id, &json!({"version": 0})) else { panic!("{id}") }; + assert_eq!(e.params["version"], json!(0), "{id}"); + assert!(crate::merged_params(&id, &json!({"bend": 20})).get("version").is_none(), "{id}"); + } + let Some(e) = crate::new_effect("distort.twist", &json!({})) else { panic!("twist") }; + assert!(e.params.get("version").is_none()); +} + #[test] fn transform_copies_and_move() { let out = run("distort.transform", json!({"moveH": 20, "copies": 3}), &square()); @@ -318,6 +372,317 @@ fn stacked_transform_copies_stay_within_the_image_budget() { assert_eq!(count(&evaluate_container(None, &g).unwrap()), 1001); } +/// A 40 × 40 px image placed at (0, 0) at one point a pixel, with id `id`. +fn warp_test_image(id: u64) -> std::sync::Arc<Node> { + use vectorcraft_doc::{ImageObject, NodeId}; + let im = ImageObject { key: "k".into(), width: 40, height: 40, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None }; + std::sync::Arc::new(Node::new(NodeId(id), NodeKind::Image(Box::new(im)))) +} + +/// How many images `art` holds, and the keys they have. +fn warp_test_images(art: &Node) -> (usize, std::collections::BTreeSet<String>) { + let (mut n, mut keys) = (0, std::collections::BTreeSet::new()); + art.walk(&mut |c| { + if let NodeKind::Image(im) = &c.kind { + n += 1; + keys.insert(im.key.clone()); + } + }); + (n, keys) +} + +#[test] +fn warped_images_stay_within_the_object_budget() { + use std::rc::Rc; + use std::sync::Arc; + + use vectorcraft_doc::NodeId; + let lift: crate::reshape::WarpMap = Rc::new(|p: Point| Point::new(p.x, p.y - p.x * 0.1)); + let cost = vectorcraft_doc::live::mesh_warp_cost(crate::reshape::WARP_IMAGE_CELLS); + let none = std::collections::HashSet::new(); + let k = || std::collections::BTreeSet::from(["k".to_string()]); + let warp = |art: &mut Node, warps: usize| { + let mut warped = crate::reshape::WarpedImages::new(); + for _ in 0..warps { + crate::reshape::mark_warped_images(art, &lift, &none, false, &mut 0, &mut warped); + } + warped + }; + // The art has room for one image's pieces only: neither image is cut, and each gets its own + // key back. + let mut art = Node::group(NodeId(1), vec![warp_test_image(2), warp_test_image(3)]); + let warped = warp(&mut art, 1); + let max = art.count() + cost; + crate::reshape::cut_warped_images_within(&mut art, &warped, max); + assert_eq!(warp_test_images(&art), (2, k())); + // With room for both, each is cut into 200 pieces once, however many warps it took. + let mut art = Node::group(NodeId(1), vec![warp_test_image(2), warp_test_image(3)]); + let warped = warp(&mut art, 3); + let max = art.count() + 2 * cost; + crate::reshape::cut_warped_images_within(&mut art, &warped, max); + assert_eq!(warp_test_images(&art), (400, k())); + // Images clipped by their frames: the second frame (the second path) kept its shape, so its + // image stays whole, and the first is cut. The third's frame is a group of two paths, the + // second of them kept, with an image after them, and its image sits in a group of its own: + // both stay whole too. + let frame = |id: u64| Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 40.0, 40.0)), Default::default())); + let clip_group = |id: u64, children: Vec<Arc<Node>>| Arc::new(Node::new(NodeId(id), NodeKind::Group { children, clip: true })); + let nested = clip_group( + 4, + vec![ + Arc::new(Node::group(NodeId(4), vec![frame(4), frame(4), warp_test_image(5)])), + Arc::new(Node::group(NodeId(4), vec![warp_test_image(4)])), + ], + ); + let mut art = + Node::group(NodeId(1), vec![clip_group(2, vec![frame(2), warp_test_image(2)]), clip_group(3, vec![frame(3), warp_test_image(3)]), nested]); + let (mut at, mut warped) = (0, crate::reshape::WarpedImages::new()); + crate::reshape::mark_warped_images(&mut art, &lift, &std::collections::HashSet::from([1, 3]), false, &mut at, &mut warped); + assert_eq!(at, 4); + crate::reshape::cut_warped_images_within(&mut art, &warped, usize::MAX); + assert_eq!(warp_test_images(&art), (203, k())); +} + +/// An image key from the document that looks like a key of the table is not read as one, and a +/// hidden image stays out of the bounds the later effects take, as it does before it is warped. +#[test] +fn warped_images_keep_document_keys_and_hidden_images_apart() { + use std::rc::Rc; + use std::sync::Arc; + + use vectorcraft_doc::NodeId; + let lift: crate::reshape::WarpMap = Rc::new(|p: Point| Point::new(p.x, p.y - p.x * 0.1)); + let none = std::collections::HashSet::new(); + let mut warped = crate::reshape::WarpedImages::new(); + let lookalike = format!("{}0", warped.prefix()); + let mut b = (*warp_test_image(3)).clone(); + if let NodeKind::Image(im) = &mut b.kind { + im.key = lookalike.clone(); + } + let mut art = Node::group(NodeId(1), vec![warp_test_image(2), Arc::new(b)]); + warped.reserve(&art); + crate::reshape::mark_warped_images(&mut art, &lift, &none, false, &mut 0, &mut warped); + crate::reshape::cut_warped_images_within(&mut art, &warped, usize::MAX); + assert_eq!(warp_test_images(&art), (400, std::collections::BTreeSet::from(["k".to_string(), lookalike]))); + // A layer of a 10 × 10 square and a hidden 40 × 40 image: the warped image is not measured. + let square = Arc::new(Node::path(NodeId(4), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default())); + let mut hidden = (*warp_test_image(5)).clone(); + hidden.visible = false; + let mut layer = Node::layer(NodeId(6), "Layer 1", vectorcraft_doc::LayerColor::Preset(0)); + if let Some(children) = layer.children_mut() { + *children = vec![square, Arc::new(hidden)]; + } + let before = layer.geometric_bounds(); + let mut warped = crate::reshape::WarpedImages::new(); + warped.reserve(&layer); + crate::reshape::mark_warped_images(&mut layer, &lift, &none, false, &mut 0, &mut warped); + assert_eq!(warped.bounds(&layer), before); + // A shown image is measured by the pieces it is cut into. + let mut art = Node::group(NodeId(1), vec![warp_test_image(2)]); + let mut warped = crate::reshape::WarpedImages::new(); + warped.reserve(&art); + crate::reshape::mark_warped_images(&mut art, &lift, &none, false, &mut 0, &mut warped); + let measured = warped.bounds(&art); + crate::reshape::cut_warped_images_within(&mut art, &warped, usize::MAX); + assert_eq!(measured, art.geometric_bounds()); + assert!(measured.is_some_and(|b| b.y0 < -3.9), "{measured:?}"); + // An image placed at a tiny scale (a placement with a tiny determinant) is cut too; one placed + // with no area is not. + for (scale, pieces) in [(1e-7, 200), (0.0, 1)] { + let mut image = (*warp_test_image(2)).clone(); + if let NodeKind::Image(im) = &mut image.kind { + im.xf = Affine::scale(scale); + } + let mut art = Node::group(NodeId(1), vec![Arc::new(image)]); + let mut warped = crate::reshape::WarpedImages::new(); + crate::reshape::mark_warped_images(&mut art, &lift, &none, false, &mut 0, &mut warped); + crate::reshape::cut_warped_images_within(&mut art, &warped, usize::MAX); + assert_eq!(warp_test_images(&art).0, pieces, "{scale}"); + } +} + +/// An image whose frame keeps its shape because the warp would pass the anchor budget keeps its +/// pixels as they are; within the budget, both bend. +#[test] +fn an_image_whose_frame_passes_the_budget_stays_whole() { + use std::sync::Arc; + + use vectorcraft_doc::NodeId; + let clipped = || { + let mut frame = Node::path(NodeId(1), shapes::rectangle(Rect::new(0.0, 0.0, 40.0, 40.0)), Appearance::default()); + if let NodeKind::Path { clipping, .. } = &mut frame.kind { + *clipping = true; + } + Node::new(NodeId(1), NodeKind::Group { children: vec![Arc::new(frame), warp_test_image(1)], clip: true }) + }; + let arc = fx("warp.arc", json!({"bend": 50, "version": 1})); + let k = || std::collections::BTreeSet::from(["k".to_string()]); + let mut art = clipped(); + crate::reshape::reshape_leaves_within(&mut art, &[&arc], Budget { anchors: 0, lines: 0 }, None); + assert_eq!(art.children().and_then(|c| c.first()).and_then(|c| c.path_data()).map(|p| p.anchor_count()), Some(4)); + assert_eq!(warp_test_images(&art), (1, k())); + let mut art = clipped(); + crate::reshape::reshape_leaves_within(&mut art, &[&arc], Budget::EFFECTS, None); + assert!(art.children().and_then(|c| c.first()).and_then(|c| c.path_data()).is_some_and(|p| p.anchor_count() > 4)); + assert_eq!(warp_test_images(&art), (200, k())); +} + +/// The first image under `n` (the first piece of a cut image). +fn first_image(n: &Node) -> Option<vectorcraft_doc::ImageObject> { + let mut first = None; + n.walk(&mut |c| { + if first.is_none() + && let NodeKind::Image(im) = &c.kind + { + first = Some((**im).clone()); + } + }); + first +} + +#[test] +fn effects_after_a_warp_reshape_an_images_frame_and_not_its_pieces() { + let image = |effects: Vec<Effect>| { + let mut n = (*warp_test_image(1)).clone(); + n.appearance.effects = effects; + n + }; + // Each piece's clipping path, and the image's frame (the outer clip group's clipping path). + let clips = |art: &Node| { + let (mut pieces, mut frame) = (vec![], None); + art.walk(&mut |c| { + if let NodeKind::Group { children, clip: true } = &c.kind + && let Some(path) = children.first().and_then(|p| p.path_data()) + { + if matches!(children.get(1).map(|i| &i.kind), Some(NodeKind::Image(_))) && path.anchor_count() == 3 { + pieces.push(path.anchor_count()); + } else if frame.is_none() { + frame = Some(path.anchor_count()); + } + } + }); + (pieces, frame) + }; + let arc = fx("warp.arc", json!({"bend": 50, "version": 1})); + for after in [ + fx("distort.roughen", json!({"size": 5, "detail": 10})), + fx("stylize.roundCorners", json!({"radius": 5})), + fx("path.offsetPath", json!({"offset": -2})), + ] { + let art = crate::reshape::reshape(None, &image(vec![arc.clone(), after.clone()]), None).unwrap(); + let (pieces, frame) = clips(&art); + assert_eq!(pieces.len(), 200, "{}", after.id); + assert!(frame.is_some_and(|n| n > 4), "{}: {frame:?}", after.id); + assert_eq!(warp_test_images(&art), (200, std::collections::BTreeSet::from(["k".to_string()])), "{}", after.id); + } + // Two warps cut the image once, through both maps; a Transform after them moves the pieces. + let flag = fx("warp.flag", json!({"bend": 30, "version": 1})); + let mv = fx("distort.transform", json!({"moveH": 100, "moveV": 0})); + let art = crate::reshape::reshape(None, &image(vec![arc.clone(), flag.clone()]), None).unwrap(); + assert_eq!(warp_test_images(&art).0, 200); + let moved = crate::reshape::reshape(None, &image(vec![arc.clone(), flag.clone(), mv]), None).unwrap(); + assert_eq!(warp_test_images(&moved).0, 200); + let box1 = Rect::new(0.0, 0.0, 40.0, 40.0); + let f1 = crate::warp::warp_map(box1, crate::warp::WarpStyle::Arc, &merged_params("warp.arc", &arc.params)); + // The flag bends the box the arc leaves, which the arc's frame measures. + let box2 = crate::reshape::reshape(None, &image(vec![arc.clone()]), None).unwrap().geometric_bounds().unwrap(); + let f2 = crate::warp::warp_map(box2, crate::warp::WarpStyle::Flag, &merged_params("warp.flag", &flag.params)); + // The first piece's corners: the pixels (0, 0), (4, 0) and (4, 4). + for (art, by) in [(&art, 0.0), (&moved, 100.0)] { + let piece = first_image(art).unwrap(); + for p in [Point::new(0.0, 0.0), Point::new(4.0, 0.0), Point::new(4.0, 4.0)] { + let want = f2(f1(p)) + vectorcraft_geom::Vec2::new(by, 0.0); + assert!((piece.xf * p).distance(want) < 1e-6, "{p:?}: {:?} {want:?}", piece.xf * p); + } + } +} + +/// A warp with no version (VectorCraft's earlier map) bends an image's pixels with that map, as it +/// bends the frame. +#[test] +fn an_images_pixels_take_the_map_their_warps_version_names() { + for version in [json!(null), json!(0), json!(1)] { + let mut params = json!({"bend": 50}); + if !version.is_null() { + params["version"] = version.clone(); + } + let mut n = (*warp_test_image(1)).clone(); + n.appearance.effects = vec![fx("warp.arc", params.clone())]; + let art = crate::reshape::reshape(None, &n, None).unwrap(); + let f = crate::warp::warp_map(Rect::new(0.0, 0.0, 40.0, 40.0), crate::warp::WarpStyle::Arc, &merged_params("warp.arc", ¶ms)); + let piece = first_image(&art).unwrap(); + for p in [Point::new(0.0, 0.0), Point::new(4.0, 0.0), Point::new(4.0, 4.0)] { + assert!((piece.xf * p).distance(f(p)) < 1e-6, "{version}: {p:?}"); + } + // The frame has an anchor where the map takes each corner. + let frame = art.children().and_then(|c| c.first()).and_then(|c| c.path_data()).unwrap(); + for corner in [Point::new(0.0, 0.0), Point::new(40.0, 0.0), Point::new(40.0, 40.0), Point::new(0.0, 40.0)] { + let near = frame.subpaths.iter().flat_map(|s| &s.anchors).any(|a| a.p.distance(f(corner)) < 1e-6); + assert!(near, "{version}: {corner:?}"); + } + } +} + +/// Under a group's Warp effect, a nested group's own placed gradient follows the nested group's +/// bounds to where its image's pieces draw them. +#[test] +fn a_nested_groups_gradient_follows_its_warped_image() { + use std::sync::Arc; + + use vectorcraft_color::{Color, Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop, Paint}; + use vectorcraft_doc::{Appearance, AppearanceItem, FillLayer, NodeId}; + 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 geom = GradientGeom { start: (5.0, 20.0).into(), end: (35.0, 20.0).into(), aspect: 1.0, focal: None }; + let placed = Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..GradientPaint::new(Gradient::new(GradientKind::Linear, stops)) })); + let mut inner = Node::group(NodeId(5), vec![warp_test_image(1)]); + inner.appearance.items.push(AppearanceItem::Fill(FillLayer::new(placed))); + let square = Node::path(NodeId(2), shapes::rectangle(Rect::new(60.0, 0.0, 100.0, 40.0)), Appearance::default()); + let mut g = Node::group(NodeId(10), vec![Arc::new(inner), Arc::new(square)]); + g.appearance.effects.push(fx("warp.arc", json!({"bend": 50, "version": 1}))); + let art = crate::group::evaluate_container(None, &g).unwrap(); + assert_eq!(warp_test_images(&art).0, 200); + let (from, mut to) = (Rect::new(0.0, 0.0, 40.0, 40.0), None); + art.walk(&mut |c| { + if c.id == NodeId(5) && to.is_none() { + to = c.geometric_bounds(); + } + }); + let to = to.unwrap(); + assert!(to.y0 < from.y0 - 1.0, "the pieces draw the image bent: {to:?}"); + let follow = |p: Point| Point::new(to.x0 + (p.x - from.x0) / from.width() * to.width(), to.y0 + (p.y - from.y0) / from.height() * to.height()); + let mut checked = 0; + art.walk(&mut |c| { + if c.id != NodeId(5) { + return; + } + for item in &c.appearance.items { + let Paint::Gradient(gp) = item.paint() else { continue }; + let got = gp.geom.unwrap(); + assert!(got.start.distance(follow(geom.start)) < 1e-6 && got.end.distance(follow(geom.end)) < 1e-6, "{got:?} in {to:?}"); + checked += 1; + } + }); + assert!(checked > 0); +} + +/// An image under a geometry effect other than a Warp draws as the image does: colorized by +/// a grayscale image's fill color, and smoothed or not. +#[test] +fn an_image_under_a_geometry_effect_keeps_its_color_and_smoothing() { + let mut n = (*warp_test_image(1)).clone(); + n.appearance.effects = vec![fx("distort.roughen", json!({"size": 5, "detail": 10}))]; + n.extras_mut().colorize = Some(Box::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)))); + n.extras_mut().pixelated = true; + let art = crate::reshape::reshape(None, &n, None).unwrap(); + let mut seen = vec![]; + art.walk(&mut |c| { + if matches!(c.kind, NodeKind::Image(_)) { + seen.push((c.extras().colorize.clone(), c.extras().pixelated)); + } + }); + assert_eq!(seen, vec![(n.extras().colorize.clone(), true)]); +} + /// What `effects` make of `path` within `budget`. fn within(effects: &[Effect], path: &PathData, budget: Budget) -> PathData { apply_geometry_within(effects, path, path.bounds().unwrap(), &GeomContext::default(), budget) @@ -523,6 +888,108 @@ fn a_hidden_path_past_the_budget_leaves_a_layers_gradients_free_to_move() { } } +/// Under a Warp effect a hidden path in a layer that keeps its shape past the budget does not hold +/// the layer's gradient in place either: it moves and scales from the layer's bounds to the warped +/// square's bounds, as the art and inside the art. +#[test] +fn a_hidden_path_past_the_budget_leaves_a_layers_gradients_free_to_follow_a_warp() { + use std::sync::Arc; + + use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop}; + use vectorcraft_doc::{AppearanceItem, FillLayer, LayerColor, NodeId, NodeKind, color::Paint}; + let stops = vec![GradientStop::new(0.0, vectorcraft_color::Color::BLACK), GradientStop::new(1.0, vectorcraft_color::Color::WHITE)]; + let geom = GradientGeom { start: (0.0, 50.0).into(), end: (100.0, 50.0).into(), aspect: 1.0, focal: None }; + let placed = Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..GradientPaint::new(Gradient::new(GradientKind::Linear, stops)) })); + let ends = |ap: &Appearance| match ap.fill_paint() { + Paint::Gradient(g) => g.geom.map(|g| (g.start, g.end)), + _ => None, + }; + let oval = || shapes::ellipse(Rect::new(0.0, 0.0, 100.0, 100.0)); + // A layer with a visible square and a hidden circle, both 0..100, and a gradient fill of its own. + let layer = || { + let square = Arc::new(Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default())); + let mut circle = Node::path(NodeId(4), oval(), Appearance::default()); + circle.visible = false; + let mut layer = Node::layer(NodeId(2), "Layer 1", LayerColor::Preset(0)); + if let NodeKind::Layer { children, .. } = &mut layer.kind { + *children = vec![square, Arc::new(circle)]; + } + layer.appearance.items.push(AppearanceItem::Fill(FillLayer::new(placed.clone()))); + layer + }; + // The box map from the layer's bounds (the square's) to `b`: (0, 50) and (100, 50) go to the + // middles of b's sides. + let near = |got: Option<(Point, Point)>, b: Rect| { + let mid = (b.y0 + b.y1) / 2.0; + got.is_some_and(|(s, e)| s.distance(Point::new(b.x0, mid)) < 1e-6 && e.distance(Point::new(b.x1, mid)) < 1e-6) + }; + for style in ["arc", "inflate", "flag"] { + let warp = fx(&format!("warp.{style}"), json!({"bend": 40.0, "horizontal": 20.0})); + // Room for the warped square beside the circle as it was, and not for the warped circle + // beside the warped square: the paths take the budget in turn, so the circle keeps its shape. + let mut probe = layer(); + crate::reshape::reshape_leaves_within(&mut probe, &[&warp], Budget::EFFECTS, None); + let warped = |k: usize| util::line_estimate(probe.children().unwrap()[k].path_data().unwrap()); + let circle = util::line_estimate(&oval()); + assert!(warped(1) > circle, "warp.{style}: the warped circle is drawn with more lines"); + let budget = Budget { anchors: usize::MAX, lines: warped(0) + circle }; + let mut art = layer(); + let carry = crate::reshape::reshape_leaves_within(&mut art, &[&warp], budget, None); + assert_eq!(art.children().unwrap()[1].path_data(), Some(&oval()), "{}: the hidden circle keeps its shape", warp.id); + let square = art.children().unwrap()[0].geometric_bounds().unwrap(); + assert!(square != Rect::new(0.0, 0.0, 100.0, 100.0), "{}: the square takes the effect: {square:?}", warp.id); + let mut own = Appearance::clone(&art.appearance); + carry.apply(&mut own); + assert!(near(ends(&own), square), "{}: the layer's gradient, as the art: {:?} for {square:?}", warp.id, ends(&own)); + let mut art = Node::group(NodeId(9), vec![Arc::new(layer())]); + crate::reshape::reshape_leaves_within(&mut art, &[&warp], budget, None); + let got = ends(&art.children().unwrap()[0].appearance); + assert!(near(got, square), "{}: the layer's gradient, inside the art: {got:?} for {square:?}", warp.id); + } +} + +/// A freeform gradient whose points were edited moves its points with a Warp effect from the +/// bounds before the warp to the bounds after it, on a path, on a group inside the art and on the +/// art itself, as a placed gradient does. +#[test] +fn edited_freeform_points_follow_a_warp() { + use std::sync::Arc; + + use vectorcraft_color::{Color, Freeform, FreeformPoint, Gradient, GradientKind, GradientPaint}; + use vectorcraft_doc::{AppearanceItem, FillLayer, NodeId, color::Paint}; + let mut ramp = GradientPaint::new(Gradient { kind: GradientKind::Freeform, ..Gradient::default() }); + let pt = |x: f64, c| FreeformPoint::new(Point::new(x, 50.0), c); + ramp.set_freeform(Freeform { points: vec![pt(0.0, Color::BLACK), pt(100.0, Color::WHITE)], ..Default::default() }); + assert!(ramp.geom.is_none() && !ramp.is_placed()); + let freeform = Paint::Gradient(Box::new(ramp)); + let points = |ap: &Appearance| match ap.fill_paint() { + Paint::Gradient(g) => g.freeform.as_ref().map(|f| f.points.iter().map(|p| p.at).collect::<Vec<_>>()), + _ => None, + }; + let square = |ap: Appearance| Arc::new(Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), ap)); + // The box map from the square's bounds to `b`: (0, 50) and (100, 50) go to the middles of b's sides. + let near = |got: Option<Vec<Point>>, b: Rect| { + let mid = (b.y0 + b.y1) / 2.0; + got.is_some_and(|p| p.len() == 2 && p[0].distance(Point::new(b.x0, mid)) < 1e-6 && p[1].distance(Point::new(b.x1, mid)) < 1e-6) + }; + for style in ["arc", "inflate", "rise"] { + let e = fx(&format!("warp.{style}"), json!({"bend": 40.0, "vertical": 20.0})); + let mut inner = Node::group(NodeId(2), vec![square(Appearance::default())]); + inner.appearance.items.push(AppearanceItem::Fill(FillLayer::new(freeform.clone()))); + let mut art = Node::group(NodeId(9), vec![square(Appearance::basic(freeform.clone(), Paint::None, 0.0)), Arc::new(inner)]); + art.appearance.items.push(AppearanceItem::Fill(FillLayer::new(freeform.clone()))); + let carry = crate::reshape::reshape_leaves_within(&mut art, &[&e], Budget::EFFECTS, None); + let b = art.geometric_bounds().unwrap(); + assert!(b != Rect::new(0.0, 0.0, 100.0, 100.0), "{}: the warp changes the bounds: {b:?}", e.id); + let members = art.children().unwrap(); + assert!(near(points(&members[0].appearance), b), "{}: the path's points {:?} for {b:?}", e.id, points(&members[0].appearance)); + assert!(near(points(&members[1].appearance), b), "{}: the inner group's points {:?} for {b:?}", e.id, points(&members[1].appearance)); + let mut own = Appearance::clone(&art.appearance); + carry.apply(&mut own); + assert!(near(points(&own), b), "{}: the art's own points {:?} for {b:?}", e.id, points(&own)); + } +} + /// A freeform gradient whose points were edited (its vector still fitted to the bounds) moves its /// points with a Transform effect and Free Distort, on a path, on a group inside the art and on the /// art itself, as a placed gradient does. @@ -889,6 +1356,96 @@ fn roughen_smooth_makes_no_cusps() { } } +#[test] +fn roughen_at_size_0_keeps_the_outline_and_spaces_its_points_evenly() { + use vectorcraft_geom::AnchorKind; + use vectorcraft_geom::kurbo::{ParamCurve, ParamCurveArclen, ParamCurveNearest}; + let (a, b) = (Point::new(0.0, 0.0), Point::new(300.0, 0.0)); + let curve = PathData::single(SubPath::new( + vec![ + vectorcraft_geom::Anchor::with_handles(a, a, Point::new(10.0, 40.0)), + vectorcraft_geom::Anchor::with_handles(b, Point::new(100.0, 200.0), b), + ], + false, + )); + let ellipse = shapes::ellipse(Rect::new(0.0, 0.0, 100.0, 50.0)); + // Two subpaths with lines and curves: a closed one whose last segment is a line, and an open + // one that ends with a line. + let (c, d, e, f) = (Point::new(100.0, 100.0), Point::new(200.0, 0.0), Point::new(300.0, 0.0), Point::new(300.0, 100.0)); + let mixed = PathData::new(vec![ + SubPath::new( + vec![ + vectorcraft_geom::Anchor::corner(a), + vectorcraft_geom::Anchor::with_handles(Point::new(100.0, 0.0), Point::new(100.0, 0.0), Point::new(160.0, 20.0)), + vectorcraft_geom::Anchor::with_handles(c, Point::new(160.0, 80.0), c), + ], + true, + ), + SubPath::new( + vec![ + vectorcraft_geom::Anchor::with_handles(d, d, Point::new(220.0, 60.0)), + vectorcraft_geom::Anchor::with_handles(e, Point::new(280.0, 60.0), e), + vectorcraft_geom::Anchor::corner(f), + ], + false, + ), + ]); + for path in [square(), ellipse, curve, mixed] { + let all: Vec<_> = path.subpaths.iter().flat_map(|sp| (0..sp.segment_count()).map(|i| sp.segment(i))).collect(); + let off = |q: Point| all.iter().map(|c| c.nearest(q, 1e-9).distance_sq).fold(f64::INFINITY, f64::min).sqrt(); + for params in + [json!({"size": 0}), json!({"size": 0, "points": "corner"}), json!({"size": 0, "relative": false, "points": "corner", "seed": 7})] + { + let out = run("distort.roughen", params.clone(), &path); + assert!(out.anchor_count() > path.anchor_count(), "{params}: the points are added"); + assert_eq!(out.subpaths.len(), path.subpaths.len(), "{params}"); + for (sp, got) in path.subpaths.iter().zip(&out.subpaths) { + assert_eq!(got.closed, sp.closed); + // Walk the result one original segment at a time: its pieces end on the segment's end anchor. + let mut at = 0; + for i in 0..sp.segment_count() { + let (orig, end) = (sp.segment(i), sp.anchors[(i + 1) % sp.anchors.len()]); + let start = got.anchors[at]; + let was = sp.anchors[i]; + assert_eq!((start.p, start.kind, start.has_in(), start.has_out()), (was.p, was.kind, was.has_in(), was.has_out()), "{params}"); + let mut pieces = vec![]; + loop { + let piece = got.segment(at); + for j in 0..=8 { + let q = piece.eval(j as f64 / 8.0); + assert!(off(q) < 1e-6, "{params}: {q:?} is {} off the outline", off(q)); + } + pieces.push(piece.arclen(1e-6)); + at += 1; + if piece.p3.distance(end.p) < 1e-9 { + break; + } + // A point the effect added: a corner without handles on a line, a smooth + // point whose handles follow the curve. + let added = got.anchors[at]; + if sp.segment_is_line(i) { + assert_eq!((added.kind, added.has_in(), added.has_out()), (AnchorKind::Corner, false, false), "{params}"); + } else { + assert_eq!(added.kind, AnchorKind::Smooth, "{params}"); + let (hi, ho) = (added.h_in - added.p, added.h_out - added.p); + assert!(hi.cross(ho).abs() < 1e-6 * hi.hypot() * ho.hypot() && hi.dot(ho) < 0.0, "{params}: {added:?}"); + } + } + assert!(pieces.len() > 1, "{params}: segment {i} is split"); + assert!(close(pieces.iter().sum::<f64>(), orig.arclen(1e-6), 1e-3), "{params}: {pieces:?}"); + let (lo, hi) = pieces.iter().fold((f64::INFINITY, 0.0f64), |(lo, hi), &l| (lo.min(l), hi.max(l))); + assert!(hi - lo < 1e-3, "{params}: segment {i}'s pieces from {lo} to {hi}"); + } + assert_eq!(at, got.segment_count(), "{params}"); + if !sp.closed { + let (last, was) = (got.anchors[at], sp.anchors[sp.anchors.len() - 1]); + assert_eq!((last.p, last.kind, last.has_in(), last.has_out()), (was.p, was.kind, was.has_in(), was.has_out()), "{params}"); + } + } + } + } +} + #[test] fn zigzag_ridge_count_and_amplitude() { let out = run("distort.zigZag", json!({"ridges": 4, "points": "corner", "size": 10}), &square()); diff --git a/crates/effects/src/tests/imageoutline.rs b/crates/effects/src/tests/imageoutline.rs new file mode 100644 index 0000000000..5ef3955254 --- /dev/null +++ b/crates/effects/src/tests/imageoutline.rs @@ -0,0 +1,338 @@ +//! Outline Object on an image's own fill or stroke: the outline of the image's opaque area, for +//! every pixel format with alpha, and the frame for one without. + +use std::sync::Arc; + +use serde_json::json; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{AppearanceItem, Document, Effect, FillLayer, ImageBlob, ImageObject, Node, NodeId, NodeKind, StrokeLayer}; +use vectorcraft_geom::{Affine, Rect}; + +use crate::*; + +fn fx(id: &str) -> Effect { + Effect { id: id.into(), params: json!({}), visible: true } +} + +/// `img` encoded as `format`. +fn encoded(img: image::DynamicImage, format: image::ImageFormat) -> Vec<u8> { + let mut out = vec![]; + img.write_to(&mut std::io::Cursor::new(&mut out), format).unwrap(); + out +} + +/// A 100×100 RGBA image, transparent but for an opaque disc of radius 30 in its middle. +fn disc() -> image::DynamicImage { + image::DynamicImage::ImageRgba8(image::RgbaImage::from_fn(100, 100, |x, y| { + let r = (f64::from(x) + 0.5 - 50.0).hypot(f64::from(y) + 0.5 - 50.0); + image::Rgba([255, 0, 0, if r <= 30.0 { 255 } else { 0 }]) + })) +} + +/// A document holding the encoded image `bytes` (key "img") and an image object of 100×100 pixels +/// placed at (50, 50) with the appearance items `items`, the image's own row at `contents`. +/// → (document, the image's node). +fn image_doc(bytes: Vec<u8>, items: Vec<AppearanceItem>, contents: usize) -> (Document, Node) { + let mut d = Document::new(200.0, 200.0); + d.images.insert("img".into(), ImageBlob::new("image/png", bytes)); + let mut n = Node::new( + NodeId(0), + NodeKind::Image(Box::new(ImageObject { + key: "img".into(), + width: 100, + height: 100, + xf: Affine::translate((50.0, 50.0)), + link: None, + placement: Default::default(), + pixels: None, + })), + ); + n.id = d.alloc_id(); + n.appearance.items = items; + n.appearance.set_contents_at(contents); + let l = d.layers[0].id; + d.insert(Some(l), 0, n.clone()).unwrap(); + (d, n) +} + +/// A PNG of `w × h` pixels with the color type `color` at `depth` bits, the chunks `extra` before +/// its pixels, and the filtered rows `rows` stored without compression. +fn png(w: u32, h: u32, color: u8, depth: u8, extra: &[(&[u8; 4], Vec<u8>)], rows: &[u8]) -> Vec<u8> { + fn crc(data: &[u8]) -> u32 { + let mut c = !0u32; + for &b in data { + c ^= u32::from(b); + for _ in 0..8 { + c = if c & 1 == 1 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 }; + } + } + !c + } + let mut out = b"\x89PNG\r\n\x1a\n".to_vec(); + let mut chunk = |kind: &[u8; 4], data: &[u8]| { + let mut body = kind.to_vec(); + body.extend_from_slice(data); + out.extend_from_slice(&u32::try_from(data.len()).unwrap().to_be_bytes()); + out.extend_from_slice(&body); + out.extend_from_slice(&crc(&body).to_be_bytes()); + }; + let mut ihdr = [w.to_be_bytes(), h.to_be_bytes()].concat(); + ihdr.extend([depth, color, 0, 0, 0]); + chunk(b"IHDR", &ihdr); + for (kind, data) in extra { + chunk(kind, data); + } + // A zlib stream of stored blocks. + let mut z = vec![0x78, 0x01]; + let blocks: Vec<&[u8]> = if rows.is_empty() { vec![rows] } else { rows.chunks(65_535).collect() }; + for (i, block) in blocks.iter().enumerate() { + let len = u16::try_from(block.len()).unwrap(); + z.push(u8::from(i + 1 == blocks.len())); + z.extend(len.to_le_bytes()); + z.extend((!len).to_le_bytes()); + z.extend_from_slice(block); + } + let (mut a, mut b) = (1u32, 0u32); + for &byte in rows { + a = (a + u32::from(byte)) % 65_521; + b = (b + a) % 65_521; + } + z.extend(((b << 16) | a).to_be_bytes()); + chunk(b"IDAT", &z); + chunk(b"IEND", &[]); + out +} + +fn stroke(effects: Vec<Effect>) -> AppearanceItem { + let mut s = StrokeLayer::new(Paint::solid(Color::BLACK), 4.0); + s.effects = effects; + AppearanceItem::Stroke(s) +} + +/// The bounds of the paths the image's own fills and strokes paint, below it first. +fn row_bounds(d: &Document, n: &Node) -> Vec<Rect> { + let art = reshape::reshape(Some(d), n, None).unwrap(); + let mut out = vec![]; + for c in art.children().unwrap() { + if matches!(c.kind, NodeKind::Path { .. }) { + out.push(c.geometric_bounds().unwrap()); + } + } + out +} + +fn near(r: Rect, want: [f64; 4], tol: f64) -> bool { + [r.x0 - want[0], r.y0 - want[1], r.x1 - want[2], r.y1 - want[3]].iter().all(|d| d.abs() < tol) +} + +#[test] +fn outline_object_follows_the_opaque_area_of_an_image_with_alpha() { + let gray_alpha = image::DynamicImage::ImageLumaA8(disc().to_luma_alpha8()); + let deep = image::DynamicImage::ImageRgba16(disc().to_rgba16()); + for (name, img) in [("rgba", disc()), ("gray and alpha", gray_alpha), ("16 bits a channel", deep)] { + let (d, n) = image_doc(encoded(img, image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1); + let rows = row_bounds(&d, &n); + assert_eq!(rows.len(), 1, "{name}"); + // The disc runs from 70 to 130; the frame from 50 to 150. + assert!(near(rows[0], [70.0, 70.0, 130.0, 130.0], 0.5), "{name}: {:?}", rows[0]); + } +} + +#[test] +fn outline_object_follows_the_frame_of_an_image_without_transparency() { + let opaque = image::DynamicImage::ImageRgb8(image::RgbImage::from_pixel(100, 100, image::Rgb([0, 0, 255]))); + let solid = image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(100, 100, image::Rgba([0, 0, 255, 200]))); + let formats = [ + ("jpeg", encoded(opaque.clone(), image::ImageFormat::Jpeg)), + ("rgb png", encoded(opaque, image::ImageFormat::Png)), + ("rgba png, every pixel more than half opaque", encoded(solid, image::ImageFormat::Png)), + ]; + for (name, bytes) in formats { + let (d, n) = image_doc(bytes, vec![stroke(vec![fx("path.outlineObject")])], 1); + let rows = row_bounds(&d, &n); + assert!(rows.len() == 1 && near(rows[0], [50.0, 50.0, 150.0, 150.0], 1e-9), "{name}: {rows:?}"); + } + // Pixels that can't be read keep the frame too. + let (d, n) = image_doc(b"not an image".to_vec(), vec![stroke(vec![fx("path.outlineObject")])], 1); + assert!(near(row_bounds(&d, &n)[0], [50.0, 50.0, 150.0, 150.0], 1e-9)); +} + +#[test] +fn convert_to_shape_keeps_the_frame_beside_outline_object() { + // Below the image: a fill with Convert to Shape, then a stroke with Outline Object; above it + // a stroke with Convert to Shape before Outline Object, which starts from the frame. + let rect = Effect { id: "convertToShape.rectangle".into(), params: json!({"relative": true, "extraW": 0, "extraH": 0}), visible: true }; + let mut fill = FillLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0))); + fill.effects = vec![rect.clone()]; + let items = vec![AppearanceItem::Fill(fill), stroke(vec![fx("path.outlineObject")]), stroke(vec![rect, fx("path.outlineObject")])]; + let (d, n) = image_doc(encoded(disc(), image::ImageFormat::Png), items, 2); + let rows = row_bounds(&d, &n); + assert_eq!(rows.len(), 3, "{rows:?}"); + assert!(near(rows[0], [50.0, 50.0, 150.0, 150.0], 1e-9), "{rows:?}"); + assert!(near(rows[1], [70.0, 70.0, 130.0, 130.0], 0.5), "{rows:?}"); + assert!(near(rows[2], [50.0, 50.0, 150.0, 150.0], 1e-9), "{rows:?}"); + // The image keeps its place between them. + let art = reshape::reshape(Some(&d), &n, None).unwrap(); + assert!(matches!(art.children().unwrap()[2].kind, NodeKind::Image(_))); +} + +#[test] +fn a_transparent_image_gives_outline_object_nothing_to_paint() { + let clear = image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(100, 100, image::Rgba([0, 0, 0, 100]))); + let (d, n) = image_doc(encoded(clear, image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1); + assert!(row_bounds(&d, &n).is_empty()); + let art = reshape::reshape(Some(&d), &n, None).unwrap(); + assert!(matches!(art.children().unwrap().as_slice(), [only] if matches!(only.kind, NodeKind::Image(_)))); +} + +#[test] +fn the_outline_follows_the_images_own_pixels_and_placement() { + // Pixels kept on the image itself (art made outside a document), placed at half size. + let (_, mut n) = image_doc(vec![], vec![stroke(vec![fx("path.outlineObject")])], 1); + if let NodeKind::Image(im) = &mut n.kind { + im.pixels = Some(Arc::new(ImageBlob::new("image/png", encoded(disc(), image::ImageFormat::Png)))); + im.xf = Affine::translate((10.0, 20.0)) * Affine::scale(0.5); + } + let art = reshape::reshape(None, &n, None).unwrap(); + let b = art.children().unwrap()[0].geometric_bounds().unwrap(); + // The disc runs from 20 to 80 pixels: half that, moved by (10, 20). + assert!(near(b, [20.0, 30.0, 50.0, 60.0], 0.3), "{b:?}"); +} + +#[test] +fn an_off_center_outline_turns_and_reflects_with_a_smaller_copy_of_the_pixels() { + // A 120×60 image whose opaque area is the rectangle from (12, 6) to (40, 24), its pixels a + // copy at half size (as a linked image's preview is), turned a quarter and reflected. + let half = image::DynamicImage::ImageRgba8(image::RgbaImage::from_fn(60, 30, |x, y| { + image::Rgba([255, 0, 0, if (6..20).contains(&x) && (3..12).contains(&y) { 255 } else { 0 }]) + })); + let (d, mut n) = image_doc(encoded(half, image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1); + let xf = Affine::translate((100.0, 40.0)) * Affine::rotate(std::f64::consts::FRAC_PI_2) * Affine::scale_non_uniform(-1.0, 1.0); + if let NodeKind::Image(im) = &mut n.kind { + (im.width, im.height, im.xf) = (120, 60, xf); + } + let rows = row_bounds(&d, &n); + let want = xf.transform_rect_bbox(Rect::new(12.0, 6.0, 40.0, 24.0)); + // The rectangle runs from (76, 0) to (94, 28); a flip in either direction, or the copy's + // width and height swapped, would move it. + assert!(near(want, [76.0, 0.0, 94.0, 28.0], 1e-9), "{want:?}"); + assert!(rows.len() == 1 && near(rows[0], [want.x0, want.y0, want.x1, want.y1], 0.5), "{rows:?}"); +} + +#[test] +fn an_image_in_a_group_exports_with_its_outline() { + let (mut d, n) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1); + let l = d.layers[0].id; + d.remove(n.id).unwrap(); + let g = d.alloc_id(); + d.insert(Some(l), 0, Node::group(g, vec![Arc::new(n)])).unwrap(); + let baked = bake_document(&d).unwrap(); + let mut paths = vec![]; + for layer in &baked.layers { + layer.walk(&mut |c| { + if matches!(c.kind, NodeKind::Path { .. }) && (c.appearance.stroke_width() - 4.0).abs() < 1e-9 { + paths.push(c.geometric_bounds().unwrap()); + } + }); + } + assert!(matches!(paths.as_slice(), [b] if near(*b, [70.0, 70.0, 130.0, 130.0], 0.5)), "{paths:?}"); +} + +/// The bounds of the paths stroked 4 pt in `d` with its effects baked, as exports write it. +fn baked_strokes(d: &Document) -> Vec<Rect> { + let baked = bake_document(d).unwrap(); + let mut paths = vec![]; + for layer in &baked.layers { + layer.walk(&mut |c| { + if matches!(c.kind, NodeKind::Path { .. }) && (c.appearance.stroke_width() - 4.0).abs() < 1e-9 { + paths.push(c.geometric_bounds().unwrap()); + } + }); + } + paths +} + +#[test] +fn an_image_under_a_clipping_mask_or_with_an_opacity_mask_exports_with_its_outline() { + let disc_outline = |paths: &[Rect]| matches!(paths, [b] if near(*b, [70.0, 70.0, 130.0, 130.0], 0.5)); + // Under a clipping mask that covers the whole image. + let (mut d, n) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1); + let l = d.layers[0].id; + d.remove(n.id).unwrap(); + let clip = Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 200.0)), Default::default()); + let g = d.alloc_id(); + d.insert(Some(l), 0, Node::new(g, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(n)], clip: true })).unwrap(); + let paths = baked_strokes(&d); + assert!(disc_outline(&paths), "{paths:?}"); + // With an opacity mask. + let (mut d, mut n) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1); + let mut white = Node::path(NodeId(999), vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 200.0)), Default::default()); + white.appearance.set_fill(Paint::solid(Color::WHITE)); + n.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(Node::group(NodeId(998), vec![Arc::new(white)]), true))); + let id = n.id; + *d.node_mut(id).unwrap() = n; + let paths = baked_strokes(&d); + assert!(disc_outline(&paths), "{paths:?}"); +} + +#[test] +fn outline_object_on_a_fill_and_on_an_indexed_image_follows_the_opaque_area() { + let mut fill = FillLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0))); + fill.effects = vec![fx("path.outlineObject")]; + let (d, n) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![AppearanceItem::Fill(fill)], 1); + let rows = row_bounds(&d, &n); + assert!(matches!(rows.as_slice(), [b] if near(*b, [70.0, 70.0, 130.0, 130.0], 0.5)), "{rows:?}"); + // A palette image whose first color is transparent (a tRNS chunk). + let mut rows = vec![]; + for y in 0..100 { + rows.push(0); + for x in 0..100 { + let r = (f64::from(x) + 0.5 - 50.0).hypot(f64::from(y) + 0.5 - 50.0); + rows.push(u8::from(r <= 30.0)); + } + } + let palette = png(100, 100, 3, 8, &[(b"PLTE", vec![0, 0, 0, 255, 0, 0]), (b"tRNS", vec![0, 255])], &rows); + let (d, n) = image_doc(palette, vec![stroke(vec![fx("path.outlineObject")])], 1); + let rows = row_bounds(&d, &n); + assert!(matches!(rows.as_slice(), [b] if near(*b, [70.0, 70.0, 130.0, 130.0], 0.5)), "{rows:?}"); +} + +#[test] +fn an_image_too_large_or_too_complex_to_outline_keeps_its_frame() { + // 72 megapixels at 8 bits a channel, and 42 at 16: refused before their pixels are read. + for (w, h, depth) in [(9000, 8000, 8), (7000, 6000, 16)] { + let bytes = png(w, h, 6, depth, &[], &[]); + assert!(matches!(vectorcraft_trace::decode_alpha(&bytes), Err(vectorcraft_trace::TraceError::TooLarge { .. })), "{w}×{h}"); + let (d, n) = image_doc(bytes, vec![stroke(vec![fx("path.outlineObject")])], 1); + assert!(matches!(row_bounds(&d, &n).as_slice(), [b] if near(*b, [50.0, 50.0, 150.0, 150.0], 1e-9)), "{w}×{h}"); + } + // A checkerboard of 2 px squares, whose outline would need more than 100,000 anchor points. + let checker = image::RgbaImage::from_fn(640, 640, |x, y| image::Rgba([0, 0, 0, if (x / 2 + y / 2) % 2 == 0 { 255 } else { 0 }])); + let (d, n) = + image_doc(encoded(image::DynamicImage::ImageRgba8(checker), image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1); + assert!(matches!(row_bounds(&d, &n).as_slice(), [b] if near(*b, [50.0, 50.0, 150.0, 150.0], 1e-9))); +} + +#[test] +fn an_outline_is_traced_once_for_its_pixels_and_dropped_with_them() { + let traces = || reshape::TRACES.with(std::cell::Cell::get); + let (d, n) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1); + let NodeKind::Image(im) = &n.kind else { panic!("not an image") }; + let before = traces(); + let first = reshape::opaque_area(&[Some(&d)], im).unwrap(); + assert_eq!(traces(), before + 1); + for _ in 0..3 { + row_bounds(&d, &n); + } + assert_eq!(reshape::opaque_area(&[Some(&d)], im).unwrap(), first); + assert_eq!(traces(), before + 1); + let pixels = Arc::downgrade(&d.images.get(&im.key).unwrap().bytes); + assert!(reshape::keeps_outline(&pixels)); + // Once the document and its pixels are gone, the next trace drops their entry. + drop(d); + assert!(pixels.upgrade().is_none()); + let (other, _) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![], 1); + reshape::opaque_area(&[Some(&other)], im).unwrap(); + assert_eq!(traces(), before + 2); + assert!(!reshape::keeps_outline(&pixels)); +} diff --git a/crates/effects/src/tests/painted.rs b/crates/effects/src/tests/painted.rs new file mode 100644 index 0000000000..31dadc865e --- /dev/null +++ b/crates/effects/src/tests/painted.rs @@ -0,0 +1,270 @@ +//! Live-effect plug-ins that paint what they return, run on each fill a painted effect returned. + +use serde_json::json; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Effect, Node, NodeId, NodeKind}; +use vectorcraft_geom::{Anchor, PathData, Point, Rect, SubPath, shapes}; +use vectorcraft_plugins::wat as tpl; + +use crate::geometry::Budget; +use crate::reshape; +use crate::reshape::{HELD_PEAK, PLUGIN_RUNS}; + +/// Installs live-effect plug-in `id`, which paints what it returns, replacing one with the same id: +/// its effect returns `output` whatever it is given. +fn install_painting(id: &str, output: &serde_json::Value) { + let manifest = format!(r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"effect","api":2,"paintOutput":true,"params":{{}}}}"#); + let module = wat::parse_str(tpl::returning(&manifest, &output.to_string())).unwrap(); + vectorcraft_plugins::registry::install_bytes(&module).unwrap(); +} + +/// An open path of `curves` tall curves, each drawn with about 5,200 lines. +fn tall_curves(curves: u32) -> PathData { + let h = 3_000_000.0; + let anchors = (0..=curves) + .map(|i| { + let x = 40.0 + f64::from(i); + Anchor::with_handles(Point::new(x, 0.0), Point::new(x, -h), Point::new(x, h)) + }) + .collect(); + PathData::single(SubPath::new(anchors, false)) +} + +/// Installs live-effect plug-in `id`, which reshapes the path it is given: its effect returns +/// `output` whatever it is given. +fn install_reshaping(id: &str, output: &serde_json::Value) { + let manifest = format!(r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"effect","params":{{}}}}"#); + let module = wat::parse_str(tpl::returning(&manifest, &output.to_string())).unwrap(); + vectorcraft_plugins::registry::install_bytes(&module).unwrap(); +} + +/// `curves` curves from `x`, each `h` tall at its handles. +fn curves_at(x: f64, curves: u32, h: f64) -> SubPath { + let anchors = (0..=curves) + .map(|i| { + let x = x + f64::from(i); + Anchor::with_handles(Point::new(x, 0.0), Point::new(x, -h), Point::new(x, h)) + }) + .collect(); + SubPath::new(anchors, false) +} + +/// An open path, `dx` to the right of 40, drawn with about `lines` lines: tall curves and one +/// curve that makes up the rest. +fn drawn_with(lines: usize, dx: f64) -> PathData { + let h = 3_000_000.0; + let per = Budget::of(&PathData::single(curves_at(0.0, 1, h))).lines; + let tall = u32::try_from(lines / per).unwrap(); + let rest = lines % per; + let mut subpaths = vec![curves_at(40.0 + dx, tall, h)]; + if rest > 0 { + // A curve `h` tall at its handles is drawn with about √(9h) lines. + let rest = rest as f64; + subpaths.push(curves_at(40.0 + dx + f64::from(tall) + 2.0, 1, rest * rest / 9.0)); + } + PathData::new(subpaths) +} + +/// Stacks a painted effect that returns `first` on a path drawn with about `lines` lines with five +/// later effects on a square's fill, the `k`th returning that path `k` to the right (`later` +/// installs each). Each piece's share of the budget is counted once, so every effect fits, and the +/// art ends on the last effect's path, painted by `paints`. +fn later_effects_count_each_piece_once(name: &str, lines: usize, first: &serde_json::Value, later: fn(&str, &serde_json::Value), paints: &[Paint]) { + let near = drawn_with(lines, 0.0); + let drawn = Budget::of(&near).lines; + assert!(drawn.abs_diff(lines) <= 2, "the path is drawn with {drawn} lines"); + let first_id = format!("test.effects.{name}.first"); + let mut first = first.clone(); + first["objects"][0]["path"] = serde_json::to_value(&near).unwrap(); + install_painting(&first_id, &first); + let mut ids = vec![format!("plugin.{first_id}")]; + for k in 1..=5u8 { + let id = format!("test.effects.{name}.later{k}"); + later(&id, &json!({"objects": [{"path": drawn_with(lines, f64::from(k))}]})); + ids.push(format!("plugin.{id}")); + } + let mut n = + Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + let fill = n.appearance.items.iter().position(|i| i.is_fill()).unwrap(); + for id in ids { + n.appearance.items[fill].effects_mut().push(Effect { id, params: json!({}), visible: true }); + } + let art = reshape(None, &n, None).unwrap(); + let mut paths = vec![]; + // The path is a compound path of two (the tall curves and the one that makes up the rest). + art.walk(&mut |c| { + let bounds = match &c.kind { + NodeKind::Compound { children, .. } => children.iter().filter_map(|k| k.path_data().and_then(PathData::bounds)).reduce(|a, b| a.union(b)), + _ => c.path_data().and_then(PathData::bounds), + }; + let paints: Vec<Paint> = c.appearance.items.iter().map(|i| i.paint().clone()).filter(|p| !p.is_none()).collect(); + if bounds.is_some() && !paints.is_empty() { + paths.push((bounds, paints)); + } + }); + assert_eq!(paths, [(drawn_with(lines, 5.0).bounds(), paints.to_vec())]); +} + +/// Later geometry effects on the two fills a painted effect returned run on each fill, and the +/// path they both stay on counts its piece's share of the budget once: each fill's result, drawn +/// with about 200 lines fewer than half the budget allows, fits at every stage. +#[test] +fn later_geometry_effects_on_two_fills_count_the_piece_once() { + let colors = [Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 1.0, 0.0))]; + let fills: Vec<_> = colors.iter().map(|p| serde_json::to_value(p).unwrap()).collect(); + let lines = Budget::EFFECTS.lines / 2 - 200; + later_effects_count_each_piece_once("twofills", lines, &json!({"objects": [{"fills": fills}]}), install_reshaping, &colors); +} + +/// Later painted effects on a painted effect's piece count the piece's share of the budget once: +/// each run's pieces take the place of the piece they were made of, so a result drawn with about +/// 300 lines fewer than the budget allows fits at every stage. +#[test] +fn later_painted_effects_on_a_painted_piece_count_it_once() { + let lines = Budget::EFFECTS.lines - 300; + later_effects_count_each_piece_once("painted", lines, &json!({"objects": [{}]}), install_painting, &[Paint::solid(Color::BLACK)]); +} + +/// A path's bounds and the paints of its fills and strokes. +type PaintedPath = (Option<Rect>, Vec<Paint>); + +/// The paths of the art a painted effect `name` that returns `square` with eight fills makes, each +/// path with its paints, when a later effect returns `first` on the first fill and `rest` on the +/// others, painting what it returns when `paints`; and the eight paints. Checks that the plug-in +/// results kept from one fill to the next never cost more than the effects' budget together. +fn eight_fills_then(name: &str, square: &PathData, paints: bool, results: (&PathData, &PathData)) -> (Vec<PaintedPath>, Vec<Paint>) { + let (paths, colors, _) = fills_then(name, 8, square, paints, results); + (paths, colors) +} + +/// [`eight_fills_then`] with `n` fills, and how many times the later effect ran on a fill. +fn fills_then(name: &str, n: u8, square: &PathData, paints: bool, (first, rest): (&PathData, &PathData)) -> (Vec<PaintedPath>, Vec<Paint>, usize) { + let colors: Vec<Paint> = (0..n).map(|i| Paint::solid(Color::rgb(f32::from(i) / f32::from(n), 0.0, 0.0))).collect(); + let fills: Vec<_> = colors.iter().map(|p| serde_json::to_value(p).unwrap()).collect(); + let fills_id = format!("test.effects.{name}.fills"); + install_painting(&fills_id, &json!({"objects": [{"path": square, "fills": fills}]})); + let each_id = format!("test.effects.{name}.each"); + let declared = if paints { r#","api":2,"paintOutput":true"# } else { "" }; + let manifest = format!(r#"{{"id":"{each_id}","name":"Test {each_id}","version":"1","kind":"effect"{declared},"params":{{}}}}"#); + let (on_first, on_rest) = (json!({"objects": [{"path": first}]}).to_string(), json!({"objects": [{"path": rest}]}).to_string()); + let module = wat::parse_str(tpl::when_given_else(&manifest, tpl::Given::Params, r#""item":{"fill":0}"#, &on_first, &on_rest)).unwrap(); + vectorcraft_plugins::registry::install_bytes(&module).unwrap(); + let mut n = + Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + let fill = n.appearance.items.iter().position(|i| i.is_fill()).unwrap(); + for id in [fills_id, each_id] { + n.appearance.items[fill].effects_mut().push(Effect { id: format!("plugin.{id}"), params: json!({}), visible: true }); + } + HELD_PEAK.with(|p| p.set(Budget { anchors: 0, lines: 0 })); + PLUGIN_RUNS.with(|r| r.set(0)); + let art = reshape(None, &n, None).unwrap(); + let runs = PLUGIN_RUNS.with(std::cell::Cell::get); + let mut paths = vec![]; + art.walk(&mut |c| { + if let Some(p) = c.path_data() { + let paints: Vec<Paint> = c.appearance.items.iter().map(|i| i.paint().clone()).filter(|p| !p.is_none()).collect(); + if !paints.is_empty() { + paths.push((p.bounds(), paints)); + } + } + }); + let peak = HELD_PEAK.with(std::cell::Cell::get); + assert!(Budget::EFFECTS.fits(peak), "the results kept cost {peak:?}"); + (paths, colors, runs) +} + +/// A later painted effect's results on eight fills, each costing more than half the effects' +/// budget and the first fill's on another path than the rest: only the first fill's result fits, +/// the other fills stay together on the square, and the results kept never cost more than the +/// budget together. +#[test] +fn painted_results_that_do_not_fit_are_not_kept() { + let square = shapes::rectangle(Rect::new(40.0, 40.0, 60.0, 60.0)); + let (large, other) = (tall_curves(900), PathData::single(curves_at(3_000.0, 900, 3_000_000.0))); + let (paths, colors) = eight_fills_then("held", &square, true, (&large, &other)); + assert_eq!(paths, [(large.bounds(), colors[..1].to_vec()), (square.bounds(), colors[1..].to_vec())]); +} + +/// A later effect that reshapes each of eight painted fills to the same path, drawn with about a +/// fifth of the effects' budget: the fills share that one path, and the results that move onto it +/// are not kept as well, so what is kept never costs more than the budget. +#[test] +fn results_on_one_path_are_not_kept_for_each_fill() { + let square = shapes::rectangle(Rect::new(40.0, 40.0, 60.0, 60.0)); + let same = tall_curves(300); + let (paths, colors) = eight_fills_then("merged", &square, false, (&same, &same)); + assert_eq!(paths, [(same.bounds(), colors)]); +} + +/// A later effect that reshapes each of eight painted fills to the same path, drawn with more than +/// half the effects' budget: the path costs the art once, so every fill moves onto it, although a +/// second copy of it would not fit. +#[test] +fn results_on_one_path_share_it_near_the_budget() { + let square = shapes::rectangle(Rect::new(40.0, 40.0, 60.0, 60.0)); + let large = tall_curves(900); + let (paths, colors) = eight_fills_then("shared", &square, false, (&large, &large)); + assert_eq!(paths, [(large.bounds(), colors)]); +} + +/// An open path of tall curves `dx` to the right of 40, drawn with about `share` of the effects' +/// budget's lines. +fn drawn_share(share: f64, dx: f64) -> PathData { + let h = 3_000_000.0; + let per = Budget::of(&PathData::single(curves_at(0.0, 1, h))).lines as f64; + let curves = (Budget::EFFECTS.lines as f64 * share / per) as u32; + PathData::single(curves_at(40.0 + dx, curves, h)) +} + +/// A later painted effect runs once on each of three fills although the results are placed twice: +/// a result that fits both placings is kept between them, and one that did not fit in the first is +/// not run again when it does not fit the second either. The first fill's result (a tenth of the +/// budget) and the second's (half of it) fit, the third's (half of it) does not, and the square +/// (45%) left for the third fill then has no room; in the second placing the second fill's result +/// does not fit beside the square kept for the fills after it. +#[test] +fn a_later_plug_in_runs_once_on_each_fill_across_both_placings() { + let (square, first, rest) = (drawn_share(0.45, 0.0), drawn_share(0.1, 2_000.0), drawn_share(0.5, 4_000.0)); + let (paths, colors, runs) = fills_then("once", 3, &square, true, (&first, &rest)); + assert_eq!(paths, [(first.bounds(), colors[..1].to_vec()), (square.bounds(), colors[1..].to_vec())]); + assert_eq!(runs, 3, "the later effect ran {runs} times on three fills"); +} + +/// A built-in geometry effect on two strokes that a painted effect returned, which doubles the lines +/// of a path drawn with 30% of the budget: the second stroke's result does not fit beside the +/// first's, but it is the same path, so it is built again with all the room the art leaves and +/// both strokes are drawn on that one path. +#[test] +fn a_built_in_result_on_the_path_before_it_is_taken_near_the_budget() { + let square = drawn_share(0.3, 0.0); + let transform = json!({"scaleV": 400}); + let tall = crate::distort::transform_within(&square, square.bounds().unwrap(), &transform, 0, usize::MAX); + let (s, t) = (Budget::of(&square).lines, Budget::of(&tall).lines); + let lines = Budget::EFFECTS.lines; + assert!(t > lines / 2 + lines / 20 && t < lines - lines / 20 && s + t < lines, "the paths are drawn with {s} and {t} lines"); + let colors = [Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 1.0, 0.0))]; + let strokes: Vec<_> = colors.iter().map(|p| json!({"paint": p, "width": 1})).collect(); + let id = "test.effects.builtin.strokes"; + install_painting(id, &json!({"objects": [{"path": square, "strokes": strokes}]})); + let mut n = + Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0)); + let stroke = n.appearance.items.iter().position(|i| !i.is_fill()).unwrap(); + n.appearance.items[stroke].effects_mut().push(Effect { id: format!("plugin.{id}"), params: json!({}), visible: true }); + n.appearance.items[stroke].effects_mut().push(Effect { id: "distort.transform".into(), params: transform, visible: true }); + let art = reshape(None, &n, None).unwrap(); + let mut paths = vec![]; + art.walk(&mut |c| { + if let Some(p) = c.path_data() { + let paints: Vec<Paint> = c.appearance.items.iter().map(|i| i.paint().clone()).filter(|p| !p.is_none()).collect(); + if !paints.is_empty() { + paths.push((p.bounds(), paints)); + } + } + }); + // One path, scaled about a reference point of the piece's own, painted by both strokes. + assert_eq!(paths.len(), 1, "{paths:?}"); + let (bounds, paints) = &paths[0]; + assert_eq!(paints, &colors.to_vec()); + let height = |b: Option<Rect>| b.map_or(0.0, |b| b.height()); + assert!((height(*bounds) - height(tall.bounds())).abs() < 1.0, "{bounds:?} is not {:?} tall", tall.bounds()); +} diff --git a/crates/effects/src/tests/rasterfollow.rs b/crates/effects/src/tests/rasterfollow.rs new file mode 100644 index 0000000000..a610ae7c71 --- /dev/null +++ b/crates/effects/src/tests/rasterfollow.rs @@ -0,0 +1,843 @@ +//! Raster effects listed before a Transform effect follow it: the Transform effect transforms +//! what they paint. + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Document, Effect, Node, NodeId}; +use vectorcraft_geom::{Affine, Anchor, PathData, Point, Rect, SubPath, shapes}; + +use crate::geometry::{Budget, MAX_EFFECT_LINES, apply_geometry_carrying_within}; +use crate::{Carry, GeomContext, RasterFx, apply_geometry_carrying, bake_document, expand_outlined, raster_effects}; + +fn fx(id: &str, params: Value) -> Effect { + Effect { id: id.into(), params, visible: true } +} + +fn shadow(x: f64, y: f64, blur: f64) -> Effect { + fx("stylize.dropShadow", json!({"x": x, "y": y, "blur": blur})) +} + +fn transform(params: Value) -> Effect { + fx("distort.transform", params) +} + +/// The offset and blur of the first Drop Shadow `effects` draw. +fn drawn_shadow(effects: &[Effect]) -> (f64, f64, f64) { + match raster_effects(effects).first() { + Some(RasterFx::DropShadow { dx, dy, blur, .. }) => (*dx, *dy, *blur), + other => panic!("expected a drop shadow, got {other:?}"), + } +} + +fn close(a: (f64, f64, f64), b: (f64, f64, f64)) -> bool { + (a.0 - b.0).abs() < 1e-9 && (a.1 - b.1).abs() < 1e-9 && (a.2 - b.2).abs() < 1e-9 +} + +/// A 50 pt red square with `effects`. +fn square(id: u64, effects: Vec<Effect>) -> Node { + let mut n = Node::path( + NodeId(id), + shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), + Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0), + ); + n.appearance.effects = effects; + n +} + +#[test] +fn a_transform_after_a_drop_shadow_scales_its_offset_and_blur() { + for strokes in [false, true] { + let effects = [shadow(10.0, 10.0, 4.0), transform(json!({"scaleH": 200, "scaleV": 200, "strokes": strokes}))]; + assert!(close(drawn_shadow(&effects), (20.0, 20.0, 8.0)), "Scale Strokes & Effects {strokes}: {:?}", drawn_shadow(&effects)); + } +} + +#[test] +fn a_drop_shadow_after_a_transform_keeps_its_offset() { + let effects = [transform(json!({"scaleH": 200, "scaleV": 200, "strokes": true})), shadow(10.0, 10.0, 4.0)]; + assert!(close(drawn_shadow(&effects), (10.0, 10.0, 4.0)), "{:?}", drawn_shadow(&effects)); +} + +#[test] +fn the_offset_follows_an_uneven_scale_a_rotation_and_a_reflection() { + let uneven = [shadow(10.0, 10.0, 4.0), transform(json!({"scaleH": 200, "scaleV": 100}))]; + assert!(close(drawn_shadow(&uneven), (20.0, 10.0, 4.0 * 2f64.sqrt())), "{:?}", drawn_shadow(&uneven)); + // A turn of 90° counterclockwise on screen takes an offset to the right to one upward. + let turned = [shadow(10.0, 0.0, 4.0), transform(json!({"rotate": 90}))]; + let (dx, dy, blur) = drawn_shadow(&turned); + assert!(dx.abs() < 1e-9 && (dy + 10.0).abs() < 1e-9 && (blur - 4.0).abs() < 1e-9, "{dx} {dy} {blur}"); + let reflected = [shadow(10.0, 0.0, 4.0), transform(json!({"reflectX": true}))]; + assert!(close(drawn_shadow(&reflected), (-10.0, 0.0, 4.0)), "{:?}", drawn_shadow(&reflected)); +} + +#[test] +fn transforms_after_the_shadow_apply_in_order() { + let effects = [shadow(10.0, 0.0, 0.0), transform(json!({"scaleH": 200, "scaleV": 200})), transform(json!({"rotate": 90}))]; + let (dx, dy, _) = drawn_shadow(&effects); + assert!(dx.abs() < 1e-9 && (dy + 20.0).abs() < 1e-9, "{dx} {dy}"); + // Only the Transform after a shadow moves it. + let between = [shadow(10.0, 0.0, 0.0), transform(json!({"scaleH": 200, "scaleV": 200})), shadow(0.0, 10.0, 0.0)]; + let drawn = raster_effects(&between); + let offsets: Vec<(f64, f64)> = drawn + .iter() + .filter_map(|r| match r { + RasterFx::DropShadow { dx, dy, .. } => Some((*dx, *dy)), + _ => None, + }) + .collect(); + assert_eq!(offsets, vec![(20.0, 0.0), (0.0, 10.0)]); +} + +#[test] +fn transforms_that_leave_the_art_or_copy_it_leave_the_shadow() { + for params in [ + json!({"scaleH": 200, "scaleV": 200, "objects": false, "strokes": true}), + json!({"scaleH": 200, "scaleV": 200, "copies": 1}), + json!({"scaleH": 200, "scaleV": 200, "random": true}), + ] { + let effects = [shadow(10.0, 10.0, 4.0), transform(params.clone())]; + assert!(close(drawn_shadow(&effects), (10.0, 10.0, 4.0)), "{params}: {:?}", drawn_shadow(&effects)); + } + let mut hidden = transform(json!({"scaleH": 200, "scaleV": 200})); + hidden.visible = false; + let effects = [shadow(10.0, 10.0, 4.0), hidden]; + assert!(close(drawn_shadow(&effects), (10.0, 10.0, 4.0)), "{:?}", drawn_shadow(&effects)); +} + +/// A hidden shadow kept when the Transform effect is applied (Expand Appearance) draws as it would +/// have before, once it is shown. +#[test] +fn a_hidden_shadow_follows_the_transform_it_loses() { + let mut hidden = shadow(10.0, 10.0, 4.0); + hidden.visible = false; + let kept = crate::raster::without_geometry(&[hidden, transform(json!({"scaleH": 200, "scaleV": 200}))]); + assert_eq!(kept.len(), 1); + let mut shown = kept[0].clone(); + shown.visible = true; + assert!(close(drawn_shadow(&[shown]), (20.0, 20.0, 8.0))); +} + +/// Rasterize keeps its room around the art: its image keeps its own pixel grid. +#[test] +fn rasterize_before_a_transform_keeps_its_options() { + let rasterize = fx(crate::RASTERIZE, json!({"addAround": 6})); + let effects = [rasterize.clone(), transform(json!({"scaleH": 200, "scaleV": 200}))]; + assert_eq!(crate::raster::followed(&effects)[0], rasterize); + assert_eq!(crate::raster::without_geometry(&effects), vec![rasterize]); +} + +/// An SVG filter keeps its options: it paints in its own user space. +#[test] +fn an_svg_filter_before_a_transform_keeps_its_options() { + let filter = fx(crate::SVG_FILTER, json!({"origin": [10, 10]})); + let effects = [filter.clone(), transform(json!({"scaleH": 200, "scaleV": 200, "rotate": 90}))]; + assert_eq!(crate::raster::followed(&effects)[0], filter); + assert_eq!(crate::raster::without_geometry(&effects), vec![filter]); +} + +/// The offset of every Drop Shadow drawn on `n` and the nodes under it, from the object's effects +/// and from each fill's and stroke's. +fn shadows_in(n: &Node) -> Vec<(f64, f64)> { + let mut out = vec![]; + n.walk(&mut |m| { + let lists = std::iter::once(&m.appearance.effects).chain(m.appearance.items.iter().map(|i| i.effects())); + for list in lists { + for r in raster_effects(list) { + if let RasterFx::DropShadow { dx, dy, .. } = r { + out.push((dx, dy)); + } + } + } + }); + out +} + +fn near(a: &[(f64, f64)], b: &[(f64, f64)]) -> bool { + a.len() == b.len() && a.iter().zip(b).all(|(p, q)| (p.0 - q.0).abs() < 1e-9 && (p.1 - q.1).abs() < 1e-9) +} + +/// A square whose fill carries `effects` of its own. +fn fill_square(id: u64, effects: Vec<Effect>) -> Node { + let mut n = square(id, vec![]); + if let Some(item) = n.appearance.items.first_mut() { + *item.effects_mut() = effects; + } + n +} + +/// A fill's own Transform effect transforms the fill's raster effects before it: drawn as they are +/// (no options), drawn through the art the Transform Patterns or Scale Strokes & Effects option +/// makes, expanded and baked. Scale Strokes & Effects does not scale a shadow that follows the +/// Transform effect a second time. +#[test] +fn a_fills_shadow_follows_the_fills_own_transform() { + let cases = [ + (json!({"rotate": 90}), (0.0, -10.0)), + (json!({"rotate": 90, "strokes": true}), (0.0, -10.0)), + (json!({"scaleH": 200, "scaleV": 200, "strokes": true}), (20.0, 0.0)), + (json!({"scaleH": 200, "scaleV": 200, "patterns": true}), (20.0, 0.0)), + (json!({"reflectX": true, "patterns": true}), (-10.0, 0.0)), + ]; + for (params, want) in cases { + let n = fill_square(11, vec![shadow(10.0, 0.0, 0.0), transform(params.clone())]); + // Drawn and expanded through its art when an option makes some. + if crate::has_transform_art(&n) { + let art = crate::reshape(None, &n, None).unwrap(); + assert!(near(&shadows_in(&art), &[want]), "{params}: drawn {:?}", shadows_in(&art)); + let expanded = expand_outlined(None, &n, None).unwrap(); + assert!(near(&shadows_in(&expanded), &[want]), "{params}: expanded {:?}", shadows_in(&expanded)); + } else { + assert!(near(&shadows_in(&n), &[want]), "{params}: drawn {:?}", shadows_in(&n)); + } + let mut d = Document::new(800.0, 800.0); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, n).unwrap(); + let baked = bake_document(&d).unwrap(); + let b = baked.node(NodeId(11)).unwrap(); + assert!(near(&shadows_in(b), &[want]), "{params}: baked {:?}", shadows_in(b)); + } +} + +/// A Transform effect after a fill's own Transform effect with Scale Strokes & Effects on turns the +/// shadow between them, which the first one leaves as it is; a Transform effect that moves at random +/// holds the shadow before it back from the Transform effects after it. +#[test] +fn a_fills_later_transform_turns_the_shadow_after_its_first() { + let n = fill_square( + 12, + vec![transform(json!({"scaleH": 200, "scaleV": 200, "strokes": true})), shadow(10.0, 0.0, 0.0), transform(json!({"rotate": 90}))], + ); + let art = crate::reshape(None, &n, None).unwrap(); + assert!(near(&shadows_in(&art), &[(0.0, -10.0)]), "{:?}", shadows_in(&art)); + let held = fill_square( + 13, + vec![ + shadow(10.0, 0.0, 0.0), + transform(json!({"scaleH": 200, "scaleV": 200, "random": true, "strokes": true})), + transform(json!({"rotate": 90})), + ], + ); + let art = crate::reshape(None, &held, None).unwrap(); + let drawn = shadows_in(&art); + assert!(drawn.len() == 1 && drawn[0].0 > 0.0 && drawn[0].1.abs() < 1e-9, "{drawn:?}"); +} + +/// A fill's own Transform effect with Transform Patterns or Scale Strokes & Effects on leaves the +/// fill's raster effects after it as they are: they paint around the transformed art, its copies +/// included. With Transform Objects off it leaves the raster effects before it as they are too. +/// Drawn, expanded and baked alike. +#[test] +fn a_fills_own_transform_leaves_the_shadow_after_it() { + let cases = [ + vec![transform(json!({"scaleH": 200, "scaleV": 200, "strokes": true})), shadow(10.0, 0.0, 0.0)], + vec![transform(json!({"scaleH": 200, "scaleV": 200, "patterns": true, "strokes": true})), shadow(10.0, 0.0, 0.0)], + vec![transform(json!({"scaleH": 200, "scaleV": 200, "moveH": 120, "copies": 1, "strokes": true})), shadow(10.0, 0.0, 0.0)], + vec![transform(json!({"scaleH": 200, "scaleV": 200, "objects": false, "strokes": true})), shadow(10.0, 0.0, 0.0)], + vec![shadow(10.0, 0.0, 0.0), transform(json!({"scaleH": 200, "scaleV": 200, "objects": false, "strokes": true}))], + // A later Transform effect with an option leaves the shadow after it as well. + vec![ + transform(json!({"scaleH": 200, "scaleV": 200, "patterns": true})), + transform(json!({"scaleH": 150, "scaleV": 150, "strokes": true})), + shadow(10.0, 0.0, 0.0), + ], + ]; + for effects in cases { + let n = fill_square(18, effects.clone()); + let art = crate::reshape(None, &n, None).unwrap(); + let drawn = shadows_in(&art); + assert!(!drawn.is_empty() && near(&drawn, &vec![(10.0, 0.0); drawn.len()]), "{effects:?}: drawn {drawn:?}"); + let expanded = shadows_in(&expand_outlined(None, &n, None).unwrap()); + assert!(!expanded.is_empty() && near(&expanded, &vec![(10.0, 0.0); expanded.len()]), "{effects:?}: expanded {expanded:?}"); + let mut d = Document::new(800.0, 800.0); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, n).unwrap(); + let baked = bake_document(&d).unwrap(); + let b = shadows_in(baked.node(NodeId(18)).unwrap()); + assert!(!b.is_empty() && near(&b, &vec![(10.0, 0.0); b.len()]), "{effects:?}: baked {b:?}"); + } +} + +/// A geometry effect after a fill's own Transform effect with Scale Strokes & Effects on reshapes +/// the transformed art by its own distance, as it does after an object's Transform effect. +#[test] +fn a_fills_own_transform_leaves_the_offset_after_it() { + let offset = fx("path.offsetPath", json!({"offset": 5})); + let scaled = transform(json!({"scaleH": 200, "scaleV": 200, "strokes": true})); + let n = fill_square(19, vec![scaled.clone(), offset.clone()]); + let on_fill = crate::reshape(None, &n, None).unwrap(); + let on_object = crate::reshape(None, &square(20, vec![scaled, offset]), None).unwrap(); + let (fill, object) = (on_fill.geometric_bounds().unwrap(), on_object.geometric_bounds().unwrap()); + // The 50 pt square scaled to 100 pt about its center, then offset by 5 pt on each side. + assert!((fill.width() - 110.0).abs() < 1e-6 && (fill.height() - 110.0).abs() < 1e-6, "{fill:?}"); + assert!((fill.width() - object.width()).abs() < 1e-6 && (fill.x0 - object.x0).abs() < 1e-6, "{fill:?} {object:?}"); + let expanded = expand_outlined(None, &n, None).unwrap().geometric_bounds().unwrap(); + assert!((expanded.width() - 110.0).abs() < 1e-6 && (expanded.x0 - fill.x0).abs() < 1e-6, "expanded {expanded:?}"); +} + +/// The SVG filters on `n` and the nodes under it, from the object's effects and from each fill's +/// and stroke's. +fn filters_in(n: &Node) -> Vec<Effect> { + let mut out = vec![]; + n.walk(&mut |m| { + let lists = std::iter::once(&m.appearance.effects).chain(m.appearance.items.iter().map(|i| i.effects())); + out.extend(lists.flatten().filter(|e| e.id == crate::SVG_FILTER).cloned()); + }); + out +} + +/// An SVG filter after a fill's own Transform effect with Scale Strokes & Effects on keeps its +/// scale and the origin of its user space, as it does after the same Transform effect without +/// options and after an object's own Transform effect. +#[test] +fn a_fills_own_transform_leaves_the_svg_filter_after_it() { + let filter = fx(crate::SVG_FILTER, json!({"scale": 1.0, "origin": [10.0, 10.0]})); + for params in [ + json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "strokes": true}), + json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "patterns": true}), + json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "copies": 1, "strokes": true}), + json!({"scaleH": 200, "scaleV": 200, "objects": false, "strokes": true}), + ] { + let art = crate::reshape(None, &fill_square(21, vec![transform(params.clone()), filter.clone()]), None).unwrap(); + let drawn = filters_in(&art); + assert!(!drawn.is_empty() && drawn.iter().all(|e| *e == filter), "{params}: {drawn:?}"); + } + let object = square(22, vec![transform(json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "strokes": true})), filter.clone()]); + let art = crate::reshape(None, &object, None).unwrap(); + assert!(!filters_in(&art).is_empty() && filters_in(&art).iter().all(|e| *e == filter), "{:?}", filters_in(&art)); +} + +/// The 3D effects keep the shadow before a Transform effect that shapes the art they project, the +/// object's and its fill's 3D effect alike. +#[test] +fn a_shadow_before_a_transform_follows_it_into_3d_art() { + let before = vec![shadow(10.0, 0.0, 0.0), transform(json!({"scaleH": 200, "scaleV": 200}))]; + for three_d in [crate::EXTRUDE, crate::REVOLVE] { + let art = |n: &Node| if three_d == crate::EXTRUDE { crate::solid_art(n) } else { crate::revolve_art(n) }; + let mut on_object = before.clone(); + on_object.push(fx(three_d, json!({}))); + let projected = art(&square(14, on_object)).unwrap(); + assert!(near(&shadows_in(&projected), &[(20.0, 0.0)]), "{three_d} on the object: {:?}", shadows_in(&projected)); + let mut on_fill = square(15, before.clone()); + if let Some(item) = on_fill.appearance.items.first_mut() { + *item.effects_mut() = vec![fx(three_d, json!({}))]; + } + let projected = art(&on_fill).unwrap(); + assert!(near(&shadows_in(&projected), &[(20.0, 0.0)]), "{three_d} on the fill: {:?}", shadows_in(&projected)); + } +} + +/// An object's Transform effect transforms the raster effects of its fills when only a fill has a +/// 3D effect: the shadow after that fill's 3D effect and another fill's shadow, as it does without +/// the 3D effect. +#[test] +fn an_objects_transform_moves_its_fills_shadows_beside_a_fills_3d_effect() { + for three_d in [crate::EXTRUDE, crate::REVOLVE] { + let art = |n: &Node| if three_d == crate::EXTRUDE { crate::solid_art(n) } else { crate::revolve_art(n) }; + let mut n = fill_square(18, vec![fx(three_d, json!({})), shadow(10.0, 10.0, 0.0)]); + let mut other = n.appearance.items[0].clone(); + *other.effects_mut() = vec![shadow(10.0, 10.0, 0.0)]; + n.appearance.items.push(other); + n.appearance.effects = vec![transform(json!({"scaleH": 200, "scaleV": 100}))]; + let drawn = shadows_in(&art(&n).unwrap()); + assert!(drawn.len() > 1 && near(&drawn, &vec![(20.0, 10.0); drawn.len()]), "{three_d}: {drawn:?}"); + } +} + +#[test] +fn glows_blurs_and_feathers_scale_with_the_transform_after_them() { + let effects = [ + fx("stylize.outerGlow", json!({"blur": 5})), + fx("stylize.innerGlow", json!({"blur": 5})), + fx("stylize.feather", json!({"radius": 5})), + fx("blur.gaussian", json!({"radius": 5})), + transform(json!({"scaleH": 50, "scaleV": 50})), + ]; + let sizes: Vec<f64> = raster_effects(&effects) + .iter() + .map(|r| match r { + RasterFx::OuterGlow { blur, .. } | RasterFx::InnerGlow { blur, .. } => *blur, + RasterFx::Feather { radius } | RasterFx::GaussianBlur { radius, .. } => *radius, + other => panic!("unexpected {other:?}"), + }) + .collect(); + assert_eq!(sizes, vec![2.5; 4]); + // How far the shadow paints past the object follows too. + let shadowed = [shadow(10.0, 10.0, 0.0), transform(json!({"scaleH": 200, "scaleV": 200}))]; + assert_eq!(crate::outset(&shadowed, Rect::new(0.0, 0.0, 100.0, 100.0)), 20.0); +} + +#[test] +fn pixel_filter_sizes_scale_with_the_transform_after_them() { + let effects = [ + fx("artistic.coloredPencil", json!({"pencilWidth": 5})), + fx("artistic.paintDaubs", json!({"brushSize": 10})), + transform(json!({"scaleH": 200, "scaleV": 200})), + ]; + let drawn = raster_effects(&effects); + assert!(matches!(drawn.first(), Some(RasterFx::Pixel(crate::PixelFx::ColoredPencil { width, .. })) if (width - 10.0).abs() < 1e-9), "{drawn:?}"); + assert!(matches!(drawn.get(1), Some(RasterFx::Pixel(crate::PixelFx::PaintDaubs { size, .. })) if (size - 20.0).abs() < 1e-9), "{drawn:?}"); +} + +/// A Transform effect after a 3D effect that makes copies or moves at random holds back the shadow +/// before the 3D effect, as it does without the 3D effect. +#[test] +fn a_copying_transform_after_3d_holds_the_shadow_back() { + for later in [json!({"copies": 1}), json!({"scaleH": 150, "scaleV": 150, "random": true})] { + let plain = [shadow(10.0, 0.0, 0.0), transform(json!({"scaleH": 200, "scaleV": 200})), transform(later.clone())]; + assert!(close(drawn_shadow(&plain), (10.0, 0.0, 0.0)), "{later}: {:?}", drawn_shadow(&plain)); + for three_d in [crate::EXTRUDE, crate::REVOLVE] { + let art = |n: &Node| if three_d == crate::EXTRUDE { crate::solid_art(n) } else { crate::revolve_art(n) }; + let effects = vec![plain[0].clone(), plain[1].clone(), fx(three_d, json!({})), plain[2].clone()]; + let projected = art(&square(16, effects)).unwrap(); + let drawn = shadows_in(&projected); + assert!(!drawn.is_empty() && near(&drawn, &vec![(10.0, 0.0); drawn.len()]), "{three_d} {later}: {drawn:?}"); + } + } +} + +/// In a fill's own effects, a Transform effect that makes copies after a Transform effect with +/// Transform Patterns on holds back the shadow before both, and before a Transform effect between +/// them. +#[test] +fn a_fills_copying_transform_holds_back_the_shadow_before_an_earlier_transform() { + let patterns = transform(json!({"scaleH": 200, "scaleV": 200, "patterns": true})); + let copies = transform(json!({"copies": 1})); + let lists = [ + vec![shadow(10.0, 0.0, 0.0), patterns.clone(), copies.clone()], + vec![shadow(10.0, 0.0, 0.0), patterns, transform(json!({"rotate": 90})), copies], + ]; + for effects in lists { + let n = fill_square(17, effects.clone()); + let art = crate::reshape(None, &n, None).unwrap(); + let drawn = shadows_in(&art); + assert!(!drawn.is_empty() && near(&drawn, &vec![(10.0, 0.0); drawn.len()]), "{} effects: {drawn:?}", effects.len()); + } +} + +#[test] +fn expanded_and_exported_objects_keep_the_shadow_the_canvas_draws() { + let effects = vec![shadow(10.0, 10.0, 4.0), transform(json!({"scaleH": 200, "scaleV": 200}))]; + // A path drawn through its art (Scale Strokes & Effects on), expanded. + let mut with_options = effects.clone(); + with_options[1] = transform(json!({"scaleH": 200, "scaleV": 200, "strokes": true})); + let n = square(7, with_options); + let expanded = expand_outlined(None, &n, None).unwrap(); + assert!(close(drawn_shadow(&expanded.appearance.effects), (20.0, 20.0, 8.0)), "{:?}", expanded.appearance.effects); + // A path and a group, baked for export. + let mut d = Document::new(800.0, 800.0); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, square(8, effects.clone())).unwrap(); + let mut g = Node::group(NodeId(9), vec![std::sync::Arc::new(square(10, vec![]))]); + g.appearance.effects = effects.clone(); + d.insert(Some(layer), 1, g).unwrap(); + let baked = bake_document(&d).unwrap(); + for id in [8, 9] { + let b = baked.node(NodeId(id)).unwrap(); + assert!(!b.appearance.effects.iter().any(|e| e.id == "distort.transform"), "{id}: {:?}", b.appearance.effects); + assert!(close(drawn_shadow(&b.appearance.effects), (20.0, 20.0, 8.0)), "{id}: {:?}", b.appearance.effects); + } +} + +/// A group of `members` with `effects` of its own. +fn group(id: u64, members: Vec<Node>, effects: Vec<Effect>) -> Node { + let mut g = Node::group(NodeId(id), members.into_iter().map(std::sync::Arc::new).collect()); + g.appearance.effects = effects; + g +} + +/// The node with `id` under `n`. +fn node_in(n: &Node, id: u64) -> Node { + let mut found = None; + n.walk(&mut |m| { + if m.id == NodeId(id) && found.is_none() { + found = Some(m.clone()); + } + }); + found.unwrap_or_else(|| panic!("no node {id}")) +} + +/// The offset of the Drop Shadow that the first fill of `n` draws, its own effects and `n`'s +/// Transform effects applied ([`crate::item_effects_in`]). +fn fill_shadow(n: &Node) -> (f64, f64) { + let item = n.appearance.items.first().unwrap(); + match raster_effects(&crate::item_effects_in(&n.appearance.effects, item.effects())).first() { + Some(RasterFx::DropShadow { dx, dy, .. }) => (*dx, *dy), + other => panic!("expected a drop shadow, got {other:?}"), + } +} + +/// A group's Transform effect transforms the raster effects of what the group holds with the art, +/// whatever its options: a member's own shadow, a member's fill's shadow and a nested group's own +/// shadow, drawn (the group's art) and baked. +#[test] +fn a_groups_transform_moves_its_members_shadows() { + let cases = [ + (json!({"scaleH": 200, "scaleV": 200}), (20.0, 20.0)), + (json!({"scaleH": 200, "scaleV": 100, "strokes": true}), (20.0, 10.0)), + (json!({"rotate": 90, "patterns": true}), (10.0, -10.0)), + (json!({"rotate": 90, "strokes": true}), (10.0, -10.0)), + ]; + for (params, want) in cases { + let members = vec![ + square(21, vec![shadow(10.0, 10.0, 0.0)]), + fill_square(22, vec![shadow(10.0, 10.0, 0.0)]), + group(23, vec![square(24, vec![])], vec![shadow(10.0, 10.0, 0.0)]), + ]; + let g = group(20, members, vec![transform(params.clone())]); + let art = crate::evaluate_container(None, &g).unwrap(); + assert!(near(&shadows_in(&art), &[want; 3]), "{params}: drawn {:?}", shadows_in(&art)); + let mut d = Document::new(800.0, 800.0); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, g).unwrap(); + let baked = bake_document(&d).unwrap(); + for id in [21, 22, 23] { + let b = baked.node(NodeId(id)).unwrap(); + assert!(near(&shadows_in(b), &[want]), "{params}: {id} baked {:?}", shadows_in(b)); + } + } +} + +/// A group's Transform effect that makes copies or moves at random leaves its members' shadows as +/// they are, as it leaves the shadows listed before it in its own effects. +#[test] +fn a_groups_copying_transform_leaves_its_members_shadows() { + for params in [json!({"scaleH": 200, "scaleV": 200, "copies": 1}), json!({"scaleH": 200, "scaleV": 200, "random": true})] { + let g = group(25, vec![square(26, vec![shadow(10.0, 10.0, 0.0)]), square(27, vec![])], vec![transform(params.clone())]); + let art = crate::evaluate_container(None, &g).unwrap(); + let drawn = shadows_in(&art); + assert!(!drawn.is_empty() && near(&drawn, &vec![(10.0, 10.0); drawn.len()]), "{params}: {drawn:?}"); + } +} + +/// The Transform effects inside a group apply before the group's: a member's own turn of 90° +/// applies to its shadow before the group's uneven scale does, for the member's own shadow, its +/// fill's shadow, and the shadow of a member of a nested group that has the turn. +#[test] +fn a_groups_transform_applies_after_its_members_own() { + let turn = || transform(json!({"rotate": 90})); + let uneven = || transform(json!({"scaleH": 200, "scaleV": 100})); + // Turned first, (10, 0) goes to (0, -10), which the scale leaves; scaled first, it would be (0, -20). + let want = (0.0, -10.0); + let own = group(30, vec![square(31, vec![shadow(10.0, 0.0, 0.0), turn()])], vec![uneven()]); + let art = crate::evaluate_container(None, &own).unwrap(); + assert!(near(&shadows_in(&art), &[want]), "own: {:?}", shadows_in(&art)); + let mut on_fill = fill_square(33, vec![shadow(10.0, 0.0, 0.0)]); + on_fill.appearance.effects = vec![turn()]; + let art = crate::evaluate_container(None, &group(32, vec![on_fill], vec![uneven()])).unwrap(); + // The member is drawn as its art: a group with its id holding the turned square. + let filled = node_in(&art, 33).children().and_then(|ch| ch.first().map(|c| (**c).clone())).unwrap(); + assert!(near(&[fill_shadow(&filled)], &[want]), "fill: {:?}", fill_shadow(&filled)); + let nested = group(34, vec![group(35, vec![square(36, vec![shadow(10.0, 0.0, 0.0)])], vec![turn()])], vec![uneven()]); + let art = crate::evaluate_container(None, &nested).unwrap(); + assert!(near(&shadows_in(&art), &[want]), "nested: {:?}", shadows_in(&art)); +} + +/// An object's Transform effect transforms the raster effects of its fills and strokes with the +/// art, whatever its options: drawn, drawn through the art an option makes, and baked. One that +/// makes copies leaves them. +#[test] +fn an_objects_transform_moves_its_fills_shadows() { + let cases = [ + (json!({"scaleH": 200, "scaleV": 100}), (20.0, 10.0)), + (json!({"scaleH": 200, "scaleV": 100, "strokes": true}), (20.0, 10.0)), + (json!({"rotate": 90, "patterns": true}), (10.0, -10.0)), + (json!({"rotate": 90, "strokes": true}), (10.0, -10.0)), + (json!({"scaleH": 200, "scaleV": 200, "copies": 1}), (10.0, 10.0)), + ]; + for (params, want) in cases { + let mut n = fill_square(40, vec![shadow(10.0, 10.0, 0.0)]); + n.appearance.effects = vec![transform(params.clone())]; + if crate::has_transform_art(&n) { + let art = crate::reshape(None, &n, None).unwrap(); + let drawn = shadows_in(&art); + assert!(!drawn.is_empty() && near(&drawn, &vec![want; drawn.len()]), "{params}: drawn {drawn:?}"); + } else { + assert!(near(&[fill_shadow(&n)], &[want]), "{params}: drawn {:?}", fill_shadow(&n)); + } + let mut d = Document::new(800.0, 800.0); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, n).unwrap(); + let baked = bake_document(&d).unwrap(); + let drawn = shadows_in(baked.node(NodeId(40)).unwrap()); + assert!(!drawn.is_empty() && near(&drawn, &vec![want; drawn.len()]), "{params}: baked {drawn:?}"); + } +} + +/// A 10 pt image at the origin with `effects`. +fn image(id: u64, effects: Vec<Effect>) -> Node { + let mut n = Node::new( + NodeId(id), + vectorcraft_doc::NodeKind::Image(Box::new(vectorcraft_doc::ImageObject { + key: "k".into(), + width: 10, + height: 10, + xf: vectorcraft_geom::Affine::IDENTITY, + link: None, + placement: Default::default(), + pixels: None, + })), + ); + n.appearance.effects = effects; + n +} + +/// A group's Transform effect transforms, with Scale Strokes & Effects off or on, the raster +/// effects that a member's own Transform effect with copies holds back: they keep their value +/// through the member's effect and transform with the group's. That holds for a shadow listed +/// before the member's copying effect, one listed after it, a fill's shadow under it, the shadow +/// of a member of a nested group with such an effect, and an image's shadow. +#[test] +fn a_groups_transform_moves_the_shadows_its_members_copies_hold_back() { + let copies = || transform(json!({"moveH": 60, "copies": 1})); + // Halved and turned 90° counterclockwise on screen, (10, 10) goes to (5, -5). + let want = (5.0, -5.0); + for strokes in [false, true] { + let mut on_fill = fill_square(73, vec![shadow(10.0, 10.0, 0.0)]); + on_fill.appearance.effects = vec![copies()]; + let members = vec![ + square(71, vec![shadow(10.0, 10.0, 0.0), copies()]), + square(72, vec![copies(), shadow(10.0, 10.0, 0.0)]), + on_fill, + group(74, vec![square(75, vec![shadow(10.0, 10.0, 0.0)])], vec![copies()]), + image(76, vec![shadow(10.0, 10.0, 0.0)]), + ]; + let g = group(70, members, vec![transform(json!({"scaleH": 50, "scaleV": 50, "rotate": 90, "strokes": strokes}))]); + let art = crate::evaluate_container(None, &g).unwrap(); + for id in [71, 72, 73, 75, 76] { + let drawn = shadows_in(&node_in(&art, id)); + assert!(near(&drawn, &[want]), "Scale Strokes & Effects {strokes}: {id} {drawn:?}"); + } + } +} + +/// A group's Transform effect transforms the raster effects in the art of a member's linked opacity +/// mask with the member, a path's or an image's, with Scale Strokes & Effects off or on. +#[test] +fn a_groups_transform_moves_the_shadow_in_a_members_mask() { + let masked = |mut n: Node, id: u64| { + n.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(square(id, vec![shadow(10.0, 10.0, 0.0)]), true))); + n + }; + for strokes in [false, true] { + let params = json!({"scaleH": 50, "scaleV": 50, "rotate": 90, "strokes": strokes}); + let g = group(80, vec![masked(square(81, vec![]), 82), masked(image(83, vec![]), 84)], vec![transform(params)]); + let art = crate::evaluate_container(None, &g).unwrap(); + for id in [81, 83] { + let member = node_in(&art, id); + let mask = member.extras().mask.as_deref().unwrap(); + assert!(near(&shadows_in(&mask.art), &[(5.0, -5.0)]), "Scale Strokes & Effects {strokes}: {id} {:?}", shadows_in(&mask.art)); + } + } +} + +/// A group's Transform effect transforms the shadows of its members' fills that carry a Transform +/// effect of their own with Scale Strokes & Effects on, with the group's Scale Strokes & Effects off +/// or on: a shadow listed after the fill's Transform effect keeps its value through that effect and +/// transforms with the group's, and one listed before it follows the fill's Transform effect and +/// then the group's. Drawn through each member's art. +#[test] +fn a_groups_transform_moves_its_members_fills_shadows_beside_their_own_transform() { + let scaled = || transform(json!({"scaleH": 200, "scaleV": 200, "strokes": true})); + // Halved and turned 90° counterclockwise on screen, (10, 10) goes to (5, -5); doubled first by + // the fill's own Transform effect, it goes to (10, -10). + let cases = [(91, vec![scaled(), shadow(10.0, 10.0, 0.0)], (5.0, -5.0)), (92, vec![shadow(10.0, 10.0, 0.0), scaled()], (10.0, -10.0))]; + for strokes in [false, true] { + let members = cases.iter().map(|(id, effects, _)| fill_square(*id, effects.clone())).collect(); + let g = group(90, members, vec![transform(json!({"scaleH": 50, "scaleV": 50, "rotate": 90, "strokes": strokes}))]); + let art = crate::evaluate_container(None, &g).unwrap(); + for (id, _, want) in &cases { + let member = node_in(&art, *id); + // The member is drawn as its art, its fill's own Transform effect applied. + let drawn = shadows_in(&member); + assert!(!drawn.is_empty() && near(&drawn, &vec![*want; drawn.len()]), "Scale Strokes & Effects {strokes}: {id} {drawn:?}"); + } + } +} + +/// A closed path of `n` curves along the x axis, 2 pt apart, each drawn with 14 lines at 1 px/pt +/// and with 425 once scaled 1000 times ([`crate::util::line_estimate`]). +fn wavy(n: usize) -> PathData { + let anchors = (0..=n) + .map(|i| { + let x = 2.0 * i as f64; + Anchor::with_handles(Point::new(x, 0.0), Point::new(x - 0.5, -20.0), Point::new(x + 0.5, 20.0)) + }) + .collect(); + PathData::single(SubPath::new(anchors, true)) +} + +/// A red path `id` along `path` with object effects `effects`. +fn path_node(id: u64, path: PathData, effects: Vec<Effect>) -> Node { + let mut n = Node::path(NodeId(id), path, Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0)); + n.appearance.effects = effects; + n +} + +/// A Transform effect scaling 1000 times. +fn thousandfold() -> Effect { + transform(json!({"scaleH": 100000, "scaleV": 100000})) +} + +/// `n` baked on its own ([`bake_document`]). +fn baked(n: Node) -> Node { + let id = n.id; + let mut d = Document::new(800.0, 800.0); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, n).unwrap(); + bake_document(&d).unwrap().node(id).unwrap().clone() +} + +/// A Transform effect whose result passes the 8 million lines of the effect budget is left out, so +/// the art stays where it is, and the shadow before it keeps its offset and blur with it: drawn, +/// baked for export, and once shown after baking when it is hidden. One within the budget moves +/// and scales both. +#[test] +fn a_transform_past_the_line_budget_moves_the_art_with_its_shadow() { + let path = wavy(30_000); + assert!(Budget::EFFECTS.fits(Budget::of(&path)), "{:?}", Budget::of(&path)); + let candidate = Budget::of(&path.transformed(Affine::scale(1000.0))); + assert!(candidate.lines > MAX_EFFECT_LINES, "{candidate:?}"); + let b = path.bounds().unwrap(); + let n = path_node(30, path.clone(), vec![shadow(10.0, 5.0, 4.0), thousandfold()]); + let (g, carry) = apply_geometry_carrying(&n.appearance.effects, &path, b, &GeomContext::of(&n)); + assert_eq!(g, path, "the art stays where it is"); + assert!(carry.skipped()); + let mut drawn = n.appearance.effects.clone(); + carry.hide_skipped(&mut drawn); + assert!(close(drawn_shadow(&drawn), (10.0, 5.0, 4.0)), "drawn {:?}", drawn_shadow(&drawn)); + let out = baked(n.clone()); + assert_eq!(out.geometric_bounds(), Some(b)); + assert!(close(drawn_shadow(&out.appearance.effects), (10.0, 5.0, 4.0)), "baked {:?}", drawn_shadow(&out.appearance.effects)); + // A hidden shadow keeps its values too, once shown. + let mut hidden = shadow(10.0, 5.0, 4.0); + hidden.visible = false; + let out = baked(path_node(31, path.clone(), vec![hidden, thousandfold()])); + let mut shown = out.appearance.effects.clone(); + shown.iter_mut().for_each(|e| e.visible = true); + assert!(close(drawn_shadow(&shown), (10.0, 5.0, 4.0)), "shown {:?}", drawn_shadow(&shown)); + // A fill's own shadow before its own Transform effect stays too. + let mut fill = path_node(35, path.clone(), vec![]); + if let Some(item) = fill.appearance.items.first_mut() { + *item.effects_mut() = vec![shadow(10.0, 5.0, 4.0), thousandfold()]; + } + let out = baked(fill); + assert!(near(&shadows_in(&out), &[(10.0, 5.0)]), "baked fill {:?}", shadows_in(&out)); + // Within the budget, both move. + let doubled = path_node(32, path.clone(), vec![shadow(10.0, 5.0, 4.0), transform(json!({"scaleH": 200, "scaleV": 200}))]); + let (g, carry) = apply_geometry_carrying(&doubled.appearance.effects, &path, b, &GeomContext::of(&doubled)); + assert!(g != path && !carry.skipped()); + let out = baked(doubled); + assert!(close(drawn_shadow(&out.appearance.effects), (20.0, 10.0, 8.0)), "baked {:?}", drawn_shadow(&out.appearance.effects)); +} + +/// The art of a path whose Transform effect is left out past the budget ([`crate::shape_art`], +/// as a group's or a mask's member is drawn) keeps the object's shadow and its fill's shadow with +/// their own offsets. +#[test] +fn the_shape_art_of_a_skipped_transform_keeps_its_shadows() { + let mut n = path_node(34, wavy(30_000), vec![shadow(10.0, 5.0, 4.0), thousandfold()]); + if let Some(item) = n.appearance.items.first_mut() { + *item.effects_mut() = vec![shadow(1.0, 0.5, 0.0)]; + } + let art = crate::shape_art(None, &n, None).unwrap(); + assert!(near(&shadows_in(&art), &[(10.0, 5.0), (1.0, 0.5)]), "{:?}", shadows_in(&art)); +} + +/// A path whose own Transform effect is left out past the budget, in a group whose geometry effect +/// (a move, which leaves offsets as they are) runs after its members' own, is drawn with its shadow +/// at its own offset; one within the budget scales the shadow with the path. +#[test] +fn a_members_skipped_transform_keeps_its_shadow_under_its_groups_effects() { + for (last, want) in [(thousandfold(), (10.0, 5.0)), (transform(json!({"scaleH": 200, "scaleV": 200})), (20.0, 10.0))] { + let member = path_node(38, wavy(30_000), vec![shadow(10.0, 5.0, 4.0), last.clone()]); + let g = group(37, vec![member], vec![transform(json!({"moveH": 5, "moveV": 5}))]); + let art = crate::evaluate_container(None, &g).unwrap(); + assert!(near(&shadows_in(&node_in(&art, 38)), &[want]), "{last:?}: {:?}", shadows_in(&node_in(&art, 38))); + } +} + +/// Of two Transform effects after a shadow, the shadow follows only the ones that ran: the first +/// left out past the budget, or hidden, and the second within it; and both when the first's +/// result is exactly at the limit. +#[test] +fn only_transforms_that_ran_move_a_preceding_shadow() { + let circle = shapes::ellipse(Rect::new(0.0, 0.0, 100.0, 100.0)); + let b = circle.bounds().unwrap(); + let doubled = Budget::of(&circle.transformed(Affine::scale(2.0))).lines; + assert!(doubled > Budget::of(&circle).lines); + let run = |effects: &[Effect], lines: usize| { + let mut carry = Carry::default(); + apply_geometry_carrying_within(effects, &circle, b, &GeomContext::default(), Budget { anchors: 1000, lines }, Some(&mut carry)); + let mut drawn = effects.to_vec(); + carry.hide_skipped(&mut drawn); + drawn_shadow(&drawn) + }; + let effects = vec![shadow(10.0, 0.0, 4.0), transform(json!({"scaleH": 200, "scaleV": 200})), transform(json!({"rotate": 90}))]; + // Turned 90° counterclockwise on screen, (10, 0) goes to (0, -10). + let only_turned = run(&effects, doubled - 1); + assert!(only_turned.0.abs() < 1e-9 && (only_turned.1 + 10.0).abs() < 1e-9 && (only_turned.2 - 4.0).abs() < 1e-9, "{only_turned:?}"); + let both = run(&effects, doubled); + assert!(both.0.abs() < 1e-9 && (both.1 + 20.0).abs() < 1e-9 && (both.2 - 8.0).abs() < 1e-9, "{both:?}"); + let mut hidden = effects.clone(); + hidden[1].visible = false; + let turned = run(&hidden, doubled); + assert!(turned.0.abs() < 1e-9 && (turned.1 + 10.0).abs() < 1e-9 && (turned.2 - 4.0).abs() < 1e-9, "{turned:?}"); +} + +/// A fill's own Transform effect left out past the budget, after a Transform effect of that fill +/// that makes it a piece of its own (Transform Patterns), leaves the piece and the shadow before it +/// as they were. One within the budget scales both. +#[test] +fn a_skipped_item_transform_keeps_its_shadow() { + let path = wavy(30_000); + let b = path.bounds().unwrap(); + for (last, want) in [(thousandfold(), (10.0, 5.0)), (transform(json!({"scaleH": 200, "scaleV": 200})), (20.0, 10.0))] { + let mut n = path_node(33, path.clone(), vec![]); + if let Some(item) = n.appearance.items.first_mut() { + *item.effects_mut() = vec![transform(json!({"patterns": true})), shadow(10.0, 5.0, 4.0), last.clone()]; + } + let art = crate::reshape(None, &n, None).unwrap(); + assert!(near(&shadows_in(&art), &[want]), "{last:?}: {:?}", shadows_in(&art)); + if want == (10.0, 5.0) { + assert_eq!(art.geometric_bounds(), Some(b), "the piece stays where it is"); + } + // The same with the Transform effect before the one that makes the piece. + let mut n = path_node(36, path.clone(), vec![]); + if let Some(item) = n.appearance.items.first_mut() { + *item.effects_mut() = vec![shadow(10.0, 5.0, 4.0), last.clone(), transform(json!({"patterns": true}))]; + } + let art = crate::reshape(None, &n, None).unwrap(); + assert!(near(&shadows_in(&art), &[want]), "{last:?} first: {:?}", shadows_in(&art)); + } +} + +/// A group's Transform effect moves each member's shadow as it moves that member: the member whose +/// result would pass what the budget leaves keeps its shape and its shadow, and the other takes +/// both. +#[test] +fn a_group_transform_follows_only_the_members_it_moved() { + let small = path_node(41, shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), vec![shadow(1.0, 0.5, 0.0)]); + let large = path_node(42, wavy(30_000), vec![shadow(1.0, 0.5, 0.0)]); + let g = group(40, vec![small, large], vec![thousandfold()]); + let art = crate::evaluate_container(None, &g).unwrap(); + assert!(near(&shadows_in(&node_in(&art, 41)), &[(1000.0, 500.0)]), "{:?}", shadows_in(&node_in(&art, 41))); + assert!(near(&shadows_in(&node_in(&art, 42)), &[(1.0, 0.5)]), "{:?}", shadows_in(&node_in(&art, 42))); +} + +/// A Transform effect that makes copies, or has Transform Objects off, keeps its own rule for the +/// shadow before it, past the budget or not: the shadow stays as it is, and the pass does not +/// report it as left out. +#[test] +fn copying_and_object_disabled_transforms_keep_their_existing_shadow_rules() { + let path = wavy(30_000); + let b = path.bounds().unwrap(); + for t in [ + transform(json!({"scaleH": 100000, "scaleV": 100000, "copies": 1})), + transform(json!({"scaleH": 100000, "scaleV": 100000, "objects": false})), + ] { + let effects = vec![shadow(10.0, 5.0, 4.0), t.clone()]; + let (_, carry) = apply_geometry_carrying(&effects, &path, b, &GeomContext::default()); + assert!(!carry.skipped(), "{t:?}"); + assert!(close(drawn_shadow(&effects), (10.0, 5.0, 4.0)), "{t:?}: {:?}", drawn_shadow(&effects)); + } +} diff --git a/crates/effects/src/tests/transformfx.rs b/crates/effects/src/tests/transformfx.rs index de69116b79..1046f3c437 100644 --- a/crates/effects/src/tests/transformfx.rs +++ b/crates/effects/src/tests/transformfx.rs @@ -222,7 +222,7 @@ fn each_copy_of_a_strokes_own_transform_scales_its_weight_once_more() { } #[test] -fn a_fills_own_transform_with_scale_strokes_and_effects_scales_its_later_effects() { +fn a_fills_own_transform_with_scale_strokes_and_effects_leaves_its_later_effects() { let mut n = stroke_with_effect(json!({})); if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() { f.effects.push(transform(json!({"scaleH": 300, "scaleV": 300, "strokes": true}))); @@ -231,10 +231,10 @@ fn a_fills_own_transform_with_scale_strokes_and_effects_scales_its_later_effects let art = reshape(None, &n, None).unwrap(); let fill = leaves(&art).into_iter().find(|p| p.appearance.stroke().is_none()).unwrap(); let AppearanceItem::Fill(f) = &fill.appearance.items[0] else { panic!("not a fill") }; - // The Offset Path, scaled from 5 to 15, applies to the transformed fill's path. + // The Offset Path applies to the transformed fill's path at its own 5 pt. assert!(f.effects.is_empty(), "{:?}", f.effects); let w = fill.geometric_bounds().unwrap().width(); - assert!(close(w, 330.0), "{w}"); + assert!(close(w, 310.0), "{w}"); } #[test] diff --git a/crates/effects/src/warp.rs b/crates/effects/src/warp.rs index 84f196a8b4..4b117d4142 100644 --- a/crates/effects/src/warp.rs +++ b/crates/effects/src/warp.rs @@ -1,25 +1,49 @@ //! Warp effects: 15 envelope styles plus horizontal/vertical perspective distortion. //! -//! Each style is a map on normalised box coordinates (x, y) ∈ [-1, 1]² (y down). The path is -//! split into short pieces whose control points are mapped (see `map_nonlinear`). +//! A warp with `version` [`WARP_NET`] is its style's Bézier patch over the box ([`WarpNet`]); +//! one without (saved before the version existed) is a map on normalized box coordinates +//! (x, y) ∈ [-1, 1]² (y down), [`warp_point`]. The path is split into short pieces whose control +//! points are mapped (see `map_nonlinear`). use serde_json::Value; use vectorcraft_geom::{PathData, Point, Rect}; use crate::util::{map_nonlinear_within, num, text}; -pub use vectorcraft_doc::live::{WarpStyle, warp_point}; +pub use vectorcraft_doc::live::{WARP_NET, WarpNet, WarpStyle, uses_net, warp_point, warp_version}; + +/// The map version warp params `p` ask for: their `version`, 0 (the first map) when absent. +pub fn map_version(p: &Value) -> u32 { + let v = num(p, "version", 0.0); + if v.is_finite() && v >= 0.0 { v.min(f64::from(u32::MAX)) as u32 } else { 0 } +} /// Apply a warp to `path` using box `b`, making at most `max` anchors ([`map_nonlinear_within`]). pub fn warp(path: &PathData, b: Rect, style: WarpStyle, p: &Value, max: usize) -> PathData { + let piece = b.width().hypot(b.height()) / 24.0; + map_nonlinear_within(path, piece, max, warp_map(b, style, p)) +} + +/// The point map a warp of `style` with params `p` applies to box `b`: what [`warp`] moves each +/// point of a path to. +pub(crate) fn warp_map(b: Rect, style: WarpStyle, p: &Value) -> Box<dyn Fn(Point) -> Point> { let bend = num(p, "bend", 50.0).clamp(-100.0, 100.0) / 100.0; let dh = num(p, "horizontal", 0.0).clamp(-100.0, 100.0) / 100.0; let dv = num(p, "vertical", 0.0).clamp(-100.0, 100.0) / 100.0; let vertical = text(p, "orientation", "horizontal").eq_ignore_ascii_case("vertical"); + if uses_net(map_version(p)) { + let net = WarpNet::new(style, bend, dh, dv, b.width(), b.height(), vertical); + let (w, h) = (b.width(), b.height()); + // A box with no width or no height takes the middle of the patch along that side. + return Box::new(move |q: Point| { + let (u, v) = (if w > 0.0 { (q.x - b.x0) / w } else { 0.5 }, if h > 0.0 { (q.y - b.y0) / h } else { 0.5 }); + b.origin() + net.at(u, v).to_vec2() + }); + } let c = b.center(); let hw = (b.width() / 2.0).max(1e-9); let hh = (b.height() / 2.0).max(1e-9); - let f = |q: Point| { + Box::new(move |q: Point| { let (x, y) = ((q.x - c.x) / hw, (q.y - c.y) / hh); let (x2, y2) = if vertical { let (a, b2) = warp_point(style, bend, dh, dv, hw / hh, y, x); @@ -28,18 +52,17 @@ pub fn warp(path: &PathData, b: Rect, style: WarpStyle, p: &Value, max: usize) - warp_point(style, bend, dh, dv, hh / hw, x, y) }; Point::new(c.x + x2 * hw, c.y + y2 * hh) - }; - let piece = b.width().hypot(b.height()) / 24.0; - map_nonlinear_within(path, piece, max, f) + }) } /// Does warp effect `id` with params `p` move any point? Every style leaves the box as it is with -/// no bend and no distortion, and Arc (`warp.arc`) takes a bend under 0.0001 % as none: the -/// threshold must match the one in [`warp_point`]'s Arc case (`warp_bends_when_the_warp_moves_the_outline` -/// tests both sides of it). +/// no bend and no distortion. With the first map, Arc (`warp.arc`) takes a bend under 0.0001 % as +/// none: the threshold must match the one in [`warp_point`]'s Arc case +/// (`warp_bends_when_the_warp_moves_the_outline` tests both sides of it). With [`WarpNet`] any +/// bend moves the outline. pub(crate) fn bends(id: &str, p: &Value) -> bool { let share = |key: &str, default: f64| num(p, key, default).clamp(-100.0, 100.0) / 100.0; let bend = share("bend", 50.0); - let bent = if id == "warp.arc" { bend.abs() >= 1e-6 } else { bend != 0.0 }; + let bent = if id == "warp.arc" && !uses_net(map_version(p)) { bend.abs() >= 1e-6 } else { bend != 0.0 }; bent || share("horizontal", 0.0) != 0.0 || share("vertical", 0.0) != 0.0 } diff --git a/crates/effects/tests/envelope_ink.rs b/crates/effects/tests/envelope_ink.rs index a95906cc1b..45ac0fb64d 100644 --- a/crates/effects/tests/envelope_ink.rs +++ b/crates/effects/tests/envelope_ink.rs @@ -6,20 +6,38 @@ use std::sync::Arc; use vectorcraft_doc::{CharStyle, Node, NodeId, NodeKind, TextObject}; -use vectorcraft_geom::{Point, Rect}; +use vectorcraft_geom::{Point, Rect, Shape}; +use vectorcraft_text::test_fonts::{HEIGHT_FAMILY, height_font}; /// 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())) } +/// "Type" at 48 pt in a face the test adds, so its glyphs draw on a machine without craft-fonts or +/// system fonts. +fn type_in_test_face() -> TextObject { + assert!(vectorcraft_text::FontDb::global().add_font(height_font(true).unwrap()) > 0, "the test face loads"); + TextObject::point(Point::new(10.0, 60.0), "Type", CharStyle { font_family: HEIGHT_FAMILY.into(), size: 48.0, ..Default::default() }) +} + +/// The box of the outlines `t`'s glyphs draw, in document space, measured glyph by glyph. +fn outline_box(t: &TextObject) -> Rect { + let laid = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + let outlines: Vec<Rect> = laid.glyphs.iter().filter(|g| !g.outline.elements().is_empty()).map(|g| (t.xf * &g.outline).bounding_box()).collect(); + assert_eq!(outlines.len(), 4, "every glyph of \"Type\" draws an outline"); + outlines.into_iter().reduce(|a, b| a.union(b)).unwrap() +} + #[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 t = type_in_test_face(); 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()); + let ink = outline_box(&t); assert!(laid.height() - ink.height() > 1.0, "the laid-out box {laid:?} reaches past the glyphs {ink:?}"); + let measured = vectorcraft_text::envelope_ink(&t, t.xf, None).unwrap(); + assert!(off(measured, ink) < 1e-6, "the envelope measure gives the glyphs' box: {measured:?} vs {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:?}"); diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 836d4b7448..0fccbcdecb 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -67,6 +67,11 @@ log = { workspace = true } [target.'cfg(unix)'.dependencies] rustix = { workspace = true, features = ["std", "process"] } +# Whether a recovery area's lock file is still the one that was opened (`FolderStore::still_named`). +# Already in Cargo.lock (walkdir), so this adds no new crate. +[target.'cfg(windows)'.dependencies] +same-file = "1.0.6" + # 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 } diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 72e33b8993..166436b0c8 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -4,6 +4,8 @@ pub mod actionset; mod addons; mod apiref; pub(crate) mod appearance; +pub mod arrowheads; +mod artboardalign; mod assets; mod attributes; pub mod brushlib; @@ -80,7 +82,7 @@ pub mod rasterfx; mod recolor; pub mod recovery; pub mod scripts; -mod select; +pub(crate) mod select; pub(crate) mod shaper; pub mod shortcutset; pub(crate) mod slices; @@ -105,6 +107,7 @@ mod variablecmds; pub(crate) mod views; pub mod wand; pub mod webexport; +mod wireframe; mod xform; use serde::Serialize; @@ -242,6 +245,12 @@ pub fn has_selected_member(s: &Session) -> std::result::Result<(), String> { let Some(root) = ordinary_isolation(st) else { return has_selection(s) }; if st.selection.objects.iter().any(|id| inside_isolation(&st.doc, root, *id)) { Ok(()) } else { Err("nothing selected".into()) } } +/// [`has_selected_member`], or a ruler guide is selected outside isolation mode: Object › Lock › +/// Selection and Object › Hide › Selection. +pub fn has_selected_member_or_guide(s: &Session) -> std::result::Result<(), String> { + let st = s.active().ok_or("no document open")?; + if ordinary_isolation(st).is_none() && !st.selection.guides.is_empty() { Ok(()) } else { has_selected_member(s) } +} /// Whether `id` lies inside the isolated object `root` (the root itself does not). pub(crate) fn inside_isolation(d: &vectorcraft_doc::Document, root: vectorcraft_doc::NodeId, id: vectorcraft_doc::NodeId) -> bool { id != root && d.ancestry(id).is_some_and(|a| a.contains(&root)) @@ -297,6 +306,7 @@ pub fn command_specs() -> &'static [CommandSpec] { // Split out of `paint` (M3.8); kept next to it so lists in registry order (the command // palette, `engine.commands`) show them where they always were. v.extend(stroke::specs()); + v.extend(arrowheads::specs()); v.extend(appearance::specs()); v.extend(style::specs()); v.extend(swatch::specs()); @@ -308,6 +318,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(draw2::specs()); v.extend(xform::specs()); v.extend(effectcmd::specs()); + v.extend(wireframe::specs()); v.extend(pathops::specs()); v.extend(compoundshape::specs()); v.extend(typecmd::specs()); @@ -334,6 +345,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(variablecmds::specs()); v.extend(docinfo::specs()); v.extend(panelcmds::specs()); + v.extend(artboardalign::specs()); v.extend(buildcmds::specs()); v.extend(shaper::specs()); v.extend(brushsym::specs()); @@ -420,8 +432,13 @@ pub(crate) fn bad(cmd: &str, msg: impl Into<String>) -> EngineError { pub(crate) fn f64_or(p: &Value, key: &str, default: f64) -> f64 { p.get(key).and_then(Value::as_f64).unwrap_or(default) } +/// The number `p` gives for `key`. A missing key or null is "missing number `{key}`"; any other +/// value, such as `"40"`, is "`{key}` must be a number, not {v}", as [`number_or`] words it. pub(crate) fn f64_req(p: &Value, key: &str, cmd: &str) -> Result<f64> { - p.get(key).and_then(Value::as_f64).ok_or_else(|| bad(cmd, format!("missing number `{key}`"))) + match p.get(key) { + None | Some(Value::Null) => Err(bad(cmd, format!("missing number `{key}`"))), + Some(v) => v.as_f64().ok_or_else(|| bad(cmd, format!("`{key}` must be a number, not {v}"))), + } } /// The number `p` gives for `key`, or `default` when `p` leaves it out or gives null. Any other /// value, such as `"40"`, is an error: "`{key}` must be a number, not {v}". @@ -495,8 +512,13 @@ fn id_entry(value: &Value, key: &str, index: usize, cmd: &str) -> Result<NodeId> /// them), each checked ([`checked_id`]): a malformed one, or one naming no object, is an error, /// never the selection. `None` when it gives neither (or gives them as `null`). pub(crate) fn given_objects(s: &Session, p: &Value, command: &str) -> Result<Option<Vec<NodeId>>> { + given_nodes(s, p, command, false) +} +/// The nodes `p` gives `command`, as [`given_objects`] reads them; ruler guide nodes are taken +/// too when `guides`, else refused. +pub(crate) fn given_nodes(s: &Session, p: &Value, command: &str, guides: bool) -> Result<Option<Vec<NodeId>>> { if p.get("ids").is_some_and(|v| !v.is_null()) { - return checked_ids_param(s, p, "ids", command).map(Some); + return checked_nodes_param(s, p, "ids", command, guides).map(Some); } match p.get("id").filter(|v| !v.is_null()) { None => Ok(None), @@ -504,7 +526,24 @@ pub(crate) fn given_objects(s: &Session, p: &Value, command: &str) -> Result<Opt Some(Value::String(r)) if r.starts_with('$') => { Err(bad(command, format!("`id` is the step reference {r:?}, which only `run` and `command_batch` resolve"))) } - Some(v) => Ok(Some(vec![checked_id(s, v, command)?])), + Some(v) => Ok(Some(vec![checked_node(s, v, command, guides)?])), + } +} +/// The objects `p` gives `command`, as [`given_objects`] reads them, checked only for their form: +/// for a command that looks its objects up itself, outside the document's layers too. +pub(crate) fn given_object_ids(p: &Value, command: &str) -> Result<Option<Vec<NodeId>>> { + if p.get("ids").is_some_and(|v| !v.is_null()) { + return ids_param(p, "ids", command); + } + match p.get("id").filter(|v| !v.is_null()) { + None => Ok(None), + Some(Value::String(r)) if r.starts_with('$') => { + Err(bad(command, format!("`id` is the step reference {r:?}, which only `run` and `command_batch` resolve"))) + } + Some(v) => { + let id = v.as_u64().map(NodeId).ok_or_else(|| bad(command, format!("invalid object id {v}: expected a non-negative integer")))?; + Ok(Some(vec![id])) + } } } /// `v` as an index, a count or a byte offset: past `usize::MAX` reads as `usize::MAX`, past the end of any list. @@ -513,9 +552,18 @@ pub(crate) fn index(v: u64) -> usize { } /// Validate all explicit targets before a command changes the document or selection. pub(crate) fn checked_ids_param(s: &Session, p: &Value, key: &str, command: &str) -> Result<Vec<NodeId>> { + checked_nodes_param(s, p, key, command, false) +} +/// The `key` list as [`checked_ids_param`] checks it; ruler guide nodes are taken too when +/// `guides`, else refused. +pub(crate) fn checked_nodes_param(s: &Session, p: &Value, key: &str, command: &str, guides: bool) -> Result<Vec<NodeId>> { let values = p.get(key).and_then(Value::as_array).ok_or_else(|| bad(command, format!("{key} must be an array of non-negative integer object ids")))?; - values.iter().enumerate().map(|(index, value)| id_entry(value, key, index, command).and_then(|_| checked_id(s, value, command))).collect() + values + .iter() + .enumerate() + .map(|(index, value)| id_entry(value, key, index, command).and_then(|_| checked_node(s, value, command, guides))) + .collect() } /// The objects a command acts on: `ids` when given (every one checked, and those inside another @@ -529,11 +577,16 @@ pub(crate) fn checked_ids_or_selection(s: &Session, p: &Value, command: &str) -> } pub(crate) fn checked_id(s: &Session, value: &Value, command: &str) -> Result<NodeId> { + checked_node(s, value, command, false) +} +/// `value` as the id of a node of the active document; a ruler guide's is taken only when +/// `guides`. +pub(crate) fn checked_node(s: &Session, value: &Value, command: &str, guides: bool) -> Result<NodeId> { let id = value.as_u64().map(NodeId).ok_or_else(|| bad(command, format!("invalid object id {value}: expected a non-negative integer")))?; match s.doc()?.doc.node(id) { None => Err(bad(command, format!("no such object id {value}"))), // The guide commands take ruler guides by index. - Some(n) if n.is_ruler_guide() => Err(bad(command, format!("id {value} is a ruler guide, not an object"))), + Some(n) if n.is_ruler_guide() && !guides => Err(bad(command, format!("id {value} is a ruler guide, not an object"))), Some(_) => Ok(id), } } @@ -749,10 +802,14 @@ pub(crate) fn unique_name_from(base: &str, next: &mut std::collections::HashMap< /// The most presets one presets file imports: each is looked up among the saved ones. pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000; +pub(crate) use addons::{DecodedImages, refresh_color_masks}; +/// Document Info's category titles and the Objects category's count labels. +pub use docinfo::{CATEGORIES, OBJECT_LABELS}; pub use docmenu::guide_indexes; 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 use plugin_call::{Location, key_location, location_in, location_keys}; pub(crate) use vectorcraft_doc::range::parse_range; /// A date param in Unix seconds that defaults to the clock: `None` when absent (now, see diff --git a/crates/engine/src/cmd/addons.rs b/crates/engine/src/cmd/addons.rs index 324d7bde58..66c67651a3 100644 --- a/crates/engine/src/cmd/addons.rs +++ b/crates/engine/src/cmd/addons.rs @@ -5,13 +5,17 @@ mod arrange; mod cleanup; mod color; mod contour; +mod cutting; mod document; +mod image; mod pathtools; mod pen; mod select; mod shapes; mod typetools; +pub(crate) use image::{DecodedImages, refresh_color_masks}; + use super::CommandSpec; /// The commands of every built-in add-on. @@ -20,7 +24,9 @@ pub fn specs() -> Vec<CommandSpec> { v.extend(cleanup::specs()); v.extend(color::specs()); v.extend(contour::specs()); + v.extend(cutting::specs()); v.extend(document::specs()); + v.extend(image::specs()); v.extend(pathtools::specs()); v.extend(pen::specs()); v.extend(select::specs()); diff --git a/crates/engine/src/cmd/addons/cleanup/tests.rs b/crates/engine/src/cmd/addons/cleanup/tests.rs index b20eb0d59b..1184687366 100644 --- a/crates/engine/src/cmd/addons/cleanup/tests.rs +++ b/crates/engine/src/cmd/addons/cleanup/tests.rs @@ -341,6 +341,33 @@ fn fix_all_is_one_undo_step() { assert_eq!(s.doc().unwrap().doc.artboards.len(), doc.artboards.len()); } +#[test] +fn a_long_straight_run_loses_its_inner_anchors_in_one_step() { + let mut s = session(); + let n: u32 = 5_000; + let mut pts: Vec<(f64, f64)> = (0..n).map(|i| (10.0 + f64::from(i) * 0.05, 150.0)).collect(); + pts.push((260.0, 190.0)); + let id = line(&mut s, &pts); + let other = rect(&mut s, 300.0, 20.0, 40.0, 40.0); + select(&mut s, &[other]); + let check = s.execute("addon.cleanup.check", &json!({"kinds": ["collinearAnchors"], "scope": "document"})).unwrap(); + assert_eq!(check["total"], n - 2, "{check}"); + assert_eq!(check["findings"][0]["ids"], json!([id.0])); + let shown = s.execute("addon.cleanup.show", &json!({"kind": "collinearAnchors", "scope": "document"})).unwrap(); + assert_eq!(shown["count"], n - 2); + assert_eq!(s.doc().unwrap().selection.objects, [id], "Show selects the path"); + select(&mut s, &[other]); + let (steps, before) = (undo_steps(&s), node(&s, id).unwrap()); + let r = s.execute("addon.cleanup.fix", &json!({"kinds": ["collinearAnchors"], "scope": "document"})).unwrap(); + assert_eq!((r["total"].as_u64(), r["fixed"]["collinearAnchors"].as_u64()), (Some(u64::from(n) - 2), Some(u64::from(n) - 2))); + assert_eq!(undo_steps(&s), steps + 1); + assert_eq!(s.doc().unwrap().selection.objects, [other], "Fix keeps the selection"); + let ends: Vec<(f64, f64)> = node(&s, id).unwrap().path_data().unwrap().subpaths[0].anchors.iter().map(|a| (a.p.x, a.p.y)).collect(); + assert_eq!(ends, [(10.0, 150.0), (10.0 + f64::from(n - 1) * 0.05, 150.0), (260.0, 190.0)]); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(node(&s, id).unwrap(), before); +} + #[test] fn the_scope_is_the_selection_or_the_document() { let mut s = session(); diff --git a/crates/engine/src/cmd/addons/cleanup/text.rs b/crates/engine/src/cmd/addons/cleanup/text.rs index 10fd432dfc..7d7dcbb197 100644 --- a/crates/engine/src/cmd/addons/cleanup/text.rs +++ b/crates/engine/src/cmd/addons/cleanup/text.rs @@ -12,7 +12,7 @@ use vectorcraft_doc::{CharStyle, Document, Justify, Node, NodeId, NodeKind, Para use vectorcraft_geom::{Affine, Point, Vec2}; use vectorcraft_text::{FontDb, FontMatch, TextLayout, edit}; -use crate::cmd::fonts::{edit_symbol_texts, symbol_texts}; +use crate::cmd::fonts::{art_texts_of, edit_art_texts_of}; use crate::cmd::textedit::{editing_range, editing_story}; use crate::cmd::typecmd::refresh_bounds; use crate::cmd::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, switch_or, text_param}; @@ -108,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> { "Replace Missing Fonts…", ["Object", "Plug-ins", "Artwork Cleanup"], None, - "{font?: family (default: the default type font, Source Sans 3; any of its names)} set every character of the document's type (the type in the art of its symbols included) whose font family isn't available in `font`, in the style it has closest to the one each had, as one undo step → {runs (style runs changed), font}", + "{font?: family (default: the default type font, Source Sans 3; any of its names)} set every character of the document's type (the type in its opacity masks and in the art of its symbols and patterns included, hidden or locked type and disabled masks too) whose font family isn't available in `font`, in the style it has closest to the one each had, as one undo step → {runs (style runs changed), font}", has_doc, replace_fonts ), @@ -982,8 +982,9 @@ fn replace_fonts(s: &mut Session, p: &Value) -> Result<Value> { } }); } - // The type in the symbols' art too, which exports name when its font is missing. - if ids.is_empty() && !symbol_texts(d, None).into_iter().any(|(t, _)| lacks(t)) { + // The type in opacity masks and in the art of symbols and patterns too, hidden or locked type + // included, which exports name when its font is missing. + if ids.is_empty() && !art_texts_of(d).into_iter().any(|(_, t, _)| lacks(t)) { return Err(EngineError::Other("No fonts are missing".into())); } let runs = s.edit("Replace Missing Fonts", |d, _| { @@ -1008,7 +1009,7 @@ fn replace_fonts(s: &mut Session, p: &Value) -> Result<Value> { replace(t); } } - edit_symbol_texts(d, None, &|t, _| lacks(t), &mut replace); + edit_art_texts_of(d, &lacks, &mut replace); Ok(runs) })?; Ok(json!({ "runs": runs, "font": family })) diff --git a/crates/engine/src/cmd/addons/cleanup/text/tests.rs b/crates/engine/src/cmd/addons/cleanup/text/tests.rs index 0af24be36a..3769cf3b42 100644 --- a/crates/engine/src/cmd/addons/cleanup/text/tests.rs +++ b/crates/engine/src/cmd/addons/cleanup/text/tests.rs @@ -415,3 +415,53 @@ fn replace_missing_fonts_reaches_the_type_in_symbols() { s.execute("symbol.exitEditing", &json!({})).unwrap(); assert_eq!(crate::cmd::fonts::substitution_warning(&s.doc().unwrap().doc), None); } + +/// Replace Missing Fonts reaches the type in opacity masks (of a hidden object, disabled, in a +/// symbol's art) and in a pattern swatch nothing paints with, and the export warning, the missing +/// fonts list and Find Font name that type's font until it is replaced. +#[test] +fn replace_missing_fonts_reaches_the_type_in_masks_and_patterns() { + let mut s = session(); + let mask = |s: &mut Session, owner: NodeId, art: NodeId| { + s.edit("Mask", |d, _| { + let art = d.remove(art)?; + d.node_mut(owner).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*art).clone(), true))); + Ok(()) + }) + .unwrap(); + }; + let lost = |s: &mut Session| text(s, json!({"x": 40, "y": 60, "text": "Lost", "size": 20, "font": "No Such Font Family"})); + let rect = + |s: &mut Session| NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 20})).unwrap()["id"].as_u64().unwrap()); + let (hidden, disabled, in_symbol) = (rect(&mut s), rect(&mut s), rect(&mut s)); + for owner in [hidden, disabled, in_symbol] { + let t = lost(&mut s); + mask(&mut s, owner, t); + } + s.execute("select.set", &json!({"ids": [hidden.0]})).unwrap(); + s.execute("object.hide", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [disabled.0]})).unwrap(); + s.execute("transparency.disableOpacityMask", &json!({})).unwrap(); + s.execute("symbol.new", &json!({"name": "Mark", "ids": [in_symbol.0]})).unwrap(); + let t = lost(&mut s); + s.execute("object.pattern.make", &json!({"ids": [t.0], "name": "Unused", "edit": false})).unwrap(); + select(&mut s, &[t]); + s.execute("edit.clear", &json!({})).unwrap(); + let mut on_layers = 0; + s.doc().unwrap().doc.walk(|n| on_layers += usize::from(matches!(n.kind, NodeKind::Text(_)))); + assert_eq!(on_layers, 0, "the type is only in masks, a symbol and a pattern"); + let missing = |s: &Session| crate::cmd::fontfiles::missing_fonts(&s.doc().unwrap().doc).into_iter().map(|f| f.family).collect::<Vec<_>>(); + assert_eq!(missing(&s), ["No Such Font Family"]); + assert!(crate::cmd::fonts::substitution_warning(&s.doc().unwrap().doc).is_some_and(|w| w.contains("No Such Font Family"))); + let listed = s.execute("text.fonts", &json!({})).unwrap(); + assert_eq!((listed[0]["family"].as_str(), listed[0]["objects"].as_u64()), (Some("No Such Font Family"), Some(4)), "{listed}"); + let steps = |s: &Session| s.doc().unwrap().history.undo.len(); + let before = steps(&s); + let r = s.execute("addon.cleanup.replaceFonts", &json!({})).unwrap(); + assert_eq!(r["runs"].as_u64(), Some(4), "{r}"); + assert_eq!(steps(&s), before + 1); + assert!(missing(&s).is_empty()); + assert_eq!(crate::cmd::fonts::substitution_warning(&s.doc().unwrap().doc), None); + assert_eq!(other(s.execute("addon.cleanup.replaceFonts", &json!({}))), "No fonts are missing"); + assert_eq!(steps(&s), before + 1); +} diff --git a/crates/engine/src/cmd/addons/color/legend.rs b/crates/engine/src/cmd/addons/color/legend.rs index e2f38a7a17..e6942378be 100644 --- a/crates/engine/src/cmd/addons/color/legend.rs +++ b/crates/engine/src/cmd/addons/color/legend.rs @@ -137,7 +137,7 @@ fn legend(s: &mut Session, p: &Value) -> Result<Value> { let parent = st.target_parent()?; let text_size = (size / 7.0).clamp(4.0, 12.0); let pad = (size / 12.0).clamp(1.0, 8.0); - let style = super::super::super::create::new_type_style(s, &json!({ "size": text_size })); + let style = super::super::super::create::new_type_style(s, &json!({ "size": text_size }), C)?; let count = swatches.len(); // Each chip's fill links to its swatch, as paint.setFill {swatch} links art: editing a global or // spot swatch then recolours the legend too. diff --git a/crates/engine/src/cmd/addons/cutting.rs b/crates/engine/src/cmd/addons/cutting.rs new file mode 100644 index 0000000000..2734ca10b3 --- /dev/null +++ b/crates/engine/src/cmd/addons/cutting.rs @@ -0,0 +1,16 @@ +//! Cutting Tools (`addon.cutting.*`), a built-in add-on that prepares art for cutting. Stencil +//! Bridges cuts bridges out of the selected art so that a stencil cut from it holds together +//! ([`stencil`]), and Weed Box and Lines adds a weed box and weeding lines around the selected art +//! for vinyl cutting ([`weed`]). Its submenu (Object › Plug-ins › Cutting Tools) and dialogs are +//! the UI's. + +mod stencil; +mod weed; + +use super::super::CommandSpec; + +pub fn specs() -> Vec<CommandSpec> { + let mut v = stencil::specs(); + v.extend(weed::specs()); + v +} diff --git a/crates/engine/src/cmd/addons/cutting/stencil.rs b/crates/engine/src/cmd/addons/cutting/stencil.rs new file mode 100644 index 0000000000..dc415ce73d --- /dev/null +++ b/crates/engine/src/cmd/addons/cutting/stencil.rs @@ -0,0 +1,172 @@ +//! Stencil Bridges (`addon.cutting.bridges`), a command of the built-in Cutting Tools add-on: it +//! cuts bridges out of the selected art so that a stencil cut from it holds together. Each island +//! of the stencil sheet (the inside of an O, a hole in a shape) stays joined to the sheet by strips +//! of a set width across the art (<https://en.wikipedia.org/wiki/Stencil> describes islands and +//! bridges). The art becomes one compound path with the gaps cut, and type is measured by its +//! glyph outlines. The original goes to a new hidden layer or is replaced. The geometry is +//! `vectorcraft_pathops::addons::stencil`. + +#[cfg(test)] +mod tests; + +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use vectorcraft_geom::{FillRule, PathData}; +use vectorcraft_pathops::addons::stencil::{BRIDGE_WIDTH_RANGE, BridgeDirection, BridgeSpec, MAX_BRIDGES_PER_ISLAND, stencil_bridges}; + +use super::super::super::edit::selected_roots; +use super::super::super::object::choice; +use super::super::super::pathops::{length_given, node_path, pf_leaves, shape_node, style_of}; +use super::super::super::{CommandSpec, bad, cmd, has_selection, number_or, switch_or}; +use crate::{EngineError, Result, Session}; + +/// Stencil Bridges' command (the id in [`specs`]). +pub const BRIDGES: &str = "addon.cutting.bridges"; +/// The ways bridges run, as `direction` takes them. +pub const DIRECTIONS: [&str; 3] = ["vertical", "horizontal", "shortest"]; +/// A bridge's width when none is given, in points. +pub const DEFAULT_WIDTH: f64 = 2.0; +/// The name of the hidden layer the original art goes to (numbered when it is taken). +const ORIGINAL_LAYER: &str = "Stencil Original"; + +pub fn specs() -> Vec<CommandSpec> { + vec![cmd!( + "addon.cutting.bridges", + "Stencil Bridges…", + ["Object", "Plug-ins", "Cutting Tools"], + None, + "{width?: pt 0.01..1000 (2), count?: whole number 1..16 of bridges each island gets (1; fewer where it has no room and more where other islands are joined to the sheet through it), direction?: \"vertical\" | \"horizontal\" | \"shortest\" (the shortest crossing among 12 directions 15° apart) (\"vertical\"), keepOriginal?: true (the selected objects that make up the art go to a new hidden layer named \"Stencil Original\"; false: they are replaced)} cut bridges out of the selected art so that a stencil cut from it holds together: every island (an area the art encloses, such as the inside of an O or a hole in a shape) is joined to the area around the art by strips `width` wide across the art, the shortest crossings first, then spread around the island. The art is measured by the area its outlines enclose, whatever their paint (open paths closed as a fill closes them; type by its glyph outlines; groups by their members; hidden objects left out) and becomes one compound path with the gaps cut, painted as the topmost selected shape, in the place of the topmost selected object that has outlines. Selected objects with no outlines in the art stay where they are. Art with no islands, or none a bridge of the width fits, is left as it is, with a warning and no undo step; islands the cut result still encloses are counted in `unbridged`, with a warning. Art that reaches more than 10000000 pt from the origin, has more than 200000 anchors, whose combined area has more than 4000 outlines, whose outlines need more than 200000 straight segments, or that takes more work to measure than a fixed budget allows is refused. One undo step; the new path is selected → {id, islands, bridges, unbridged, original (the hidden layer's id, or null), warning?}", + has_selection, + bridges + )] +} + +fn bridges(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = BRIDGES; + let width = length_given(p, "width", C)?.unwrap_or(DEFAULT_WIDTH); + let (lo, hi) = BRIDGE_WIDTH_RANGE; + if !(lo..=hi).contains(&width) { + return Err(bad(C, format!("`width` must be from {lo} to {hi} pt"))); + } + let count = number_or(p, "count", 1.0, C)?; + if count.fract() != 0.0 || !(1.0..=MAX_BRIDGES_PER_ISLAND as f64).contains(&count) { + return Err(bad(C, format!("`count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND}"))); + } + let direction = match choice(p, C, "direction", &DIRECTIONS)?.unwrap_or("vertical") { + "horizontal" => BridgeDirection::Horizontal, + "shortest" => BridgeDirection::Shortest, + _ => BridgeDirection::Vertical, + }; + let keep = switch_or(p, "keepOriginal", true, C)?; + let selected = selected_roots(s)?; + let (bridged, style, roots) = { + let d = &s.doc()?.doc; + // The art's outlines, the selected objects they come from, and the topmost object that + // has some, whose paint the result takes. + let mut parts: Vec<(PathData, FillRule)> = vec![]; + let mut roots = vec![]; + let mut top = None; + for id in selected { + let n = d.node(id).ok_or(EngineError::NoNode(id))?; + let mut leaves = vec![]; + shown_leaves(d, n, &mut leaves); + let before = parts.len(); + for leaf in leaves { + if let Some(part) = node_path(&leaf).filter(|(p, _)| !p.is_empty()) { + parts.push(part); + top = Some(leaf); + } + } + if parts.len() > before { + roots.push(id); + } + } + let Some(top) = top else { + let label = "Stencil Bridges"; + return Err(EngineError::Other(format!("{label}: select paths, compound paths, groups or text"))); + }; + let refs: Vec<(&PathData, FillRule)> = parts.iter().map(|(p, r)| (p, *r)).collect(); + let spec = BridgeSpec { width, count: count as usize, direction }; + let bridged = stencil_bridges(&refs, spec).map_err(|e| match e { + vectorcraft_pathops::PathOpsError::TooComplex => { + EngineError::Other("Stencil Bridges: the selected art is too large or too detailed to bridge".into()) + } + e => EngineError::Other(e.to_string()), + })?; + (bridged, style_of(&top), roots) + }; + let summary = |id: Option<NodeId>, original: Option<NodeId>| { + json!({ + "id": id.map(|i| i.0), "islands": bridged.islands, "bridges": bridged.bridges, "unbridged": bridged.unbridged, + "original": original.map(|i| i.0), + }) + }; + if bridged.islands == 0 { + let mut r = summary(None, None); + // The warnings are written as `EngineError::Other` so that the i18n message scan + // (`untranslated_report`) finds them. + r["warning"] = json!(EngineError::Other("The selected art has no islands to bridge".into()).to_string()); + return Ok(r); + } + if bridged.bridges == 0 { + let mut r = summary(None, None); + r["warning"] = json!(EngineError::Other("No bridge of this width fits across the selected art".into()).to_string()); + return Ok(r); + } + let path = bridged.path.clone(); + let (id, original) = s.edit("Stencil Bridges", |d, sel| { + let mut made = shape_node(d, path, None); + style.apply(&mut made); + let mut taken = vec![]; + let id = d.wrap(&roots, |nodes| { + taken = nodes; + made + })?; + let original = if keep { Some(hide_originals(d, taken)?) } else { None }; + sel.set([id]); + Ok((id, original)) + })?; + let mut r = summary(Some(id), original); + if bridged.unbridged > 0 { + r["warning"] = json!(EngineError::Other("Some islands could not be joined to the area around the art".into()).to_string()); + } + Ok(r) +} + +/// The leaf shapes of `n` as [`pf_leaves`] gives them, leaving out hidden objects and the members +/// of hidden groups. +fn shown_leaves(d: &Document, n: &Node, out: &mut Vec<Node>) { + if !n.visible { + return; + } + match &n.kind { + NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } if !n.is_compound_shape() => { + for c in children { + shown_leaves(d, c, out); + } + } + _ => pf_leaves(d, n, out), + } +} + +/// Put `nodes` in a new hidden layer above the others, in their order, and return its id. +fn hide_originals(d: &mut Document, nodes: Vec<Arc<Node>>) -> Result<NodeId> { + let mut taken = std::collections::HashSet::new(); + d.walk(|n| { + if n.is_layer() { + taken.extend(n.name.clone()); + } + }); + let name = std::iter::once(ORIGINAL_LAYER.to_string()) + .chain((2..).map(|i| format!("{ORIGINAL_LAYER} {i}"))) + .find(|name| !taken.contains(name)) + .unwrap_or_else(|| ORIGINAL_LAYER.to_string()); + let layer = d.add_layer(Some(&name)); + for (i, n) in nodes.into_iter().enumerate() { + d.insert(Some(layer), i, Arc::unwrap_or_clone(n))?; + } + d.node_mut(layer).ok_or(EngineError::NoNode(layer))?.visible = false; + Ok(layer) +} diff --git a/crates/engine/src/cmd/addons/cutting/stencil/tests.rs b/crates/engine/src/cmd/addons/cutting/stencil/tests.rs new file mode 100644 index 0000000000..b21f0fef5c --- /dev/null +++ b/crates/engine/src/cmd/addons/cutting/stencil/tests.rs @@ -0,0 +1,356 @@ +//! Tests for `addon.cutting.bridges`: bridges cut out of the selected art keep a stencil's islands +//! attached. + +use kurbo::Shape; +use serde_json::{Value, json}; +use vectorcraft_doc::NodeKind; + +use super::super::super::super::pathops::node_path; +use crate::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + s +} + +fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { + let r = s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap(); + NodeId(r["id"].as_u64().unwrap()) +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap(); +} + +/// `outer` less each of `holes` (x, y, width, height), as one compound path, selected. +fn shape_with_holes(s: &mut Session, outer: (f64, f64, f64, f64), holes: &[(f64, f64, f64, f64)]) -> NodeId { + let mut ids = vec![rect(s, outer.0, outer.1, outer.2, outer.3)]; + for h in holes { + ids.push(rect(s, h.0, h.1, h.2, h.3)); + } + select(s, &ids); + let r = s.execute("object.pathfinder.minusFront", &json!({})).unwrap(); + let id = NodeId(r["ids"][0].as_u64().unwrap()); + select(s, &[id]); + id +} + +/// A square O: 100 pt across at (100, 100), with bars 20 pt thick. +fn letter_o(s: &mut Session) -> NodeId { + shape_with_holes(s, (100.0, 100.0, 100.0, 100.0), &[(120.0, 120.0, 60.0, 60.0)]) +} + +fn id_of(r: &Value) -> NodeId { + NodeId(r["id"].as_u64().unwrap()) +} + +fn node(s: &Session, id: NodeId) -> vectorcraft_doc::Node { + s.doc().unwrap().doc.node(id).cloned().unwrap() +} + +/// Is `(x, y)` inside the area object `id` fills? +fn fills(s: &Session, id: NodeId, x: f64, y: f64) -> bool { + let (path, rule) = node_path(&node(s, id)).unwrap(); + let w = path.to_bezpath().winding(kurbo::Point::new(x, y)); + match rule { + vectorcraft_geom::FillRule::EvenOdd => w % 2 != 0, + vectorcraft_geom::FillRule::NonZero => w != 0, + } +} + +fn undo_steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +#[test] +fn an_o_gets_a_bridge_and_the_original_goes_to_a_hidden_layer() { + let mut s = session(); + let o = letter_o(&mut s); + let fill = node(&s, o).appearance.fill_paint(); + let steps = undo_steps(&s); + let r = s.execute("addon.cutting.bridges", &json!({"width": 4})).unwrap(); + assert_eq!((r["islands"].clone(), r["bridges"].clone(), r["unbridged"].clone()), (json!(1), json!(1), json!(0))); + assert!(r.get("warning").is_none(), "{r}"); + let made = id_of(&r); + assert_eq!(s.doc().unwrap().selection.objects, vec![made]); + assert_eq!(undo_steps(&s), steps + 1, "one undo step"); + // The bridge crosses the top bar in the middle; the rest of the O stays, painted as it was. + assert!(!fills(&s, made, 150.0, 110.0)); + assert!(fills(&s, made, 130.0, 110.0) && fills(&s, made, 150.0, 190.0) && fills(&s, made, 110.0, 150.0)); + assert_eq!(node(&s, made).appearance.fill_paint(), fill); + // The original, unchanged, is on a new hidden layer. + let layer = NodeId(r["original"].as_u64().unwrap()); + let l = node(&s, layer); + assert_eq!((l.name.as_deref(), l.visible), (Some("Stencil Original"), false)); + let held = s.doc().unwrap().doc.children(Some(layer)).map(|c| c.iter().map(|n| n.id).collect::<Vec<_>>()); + assert_eq!(held, Some(vec![o])); + // The island is joined to the sheet: the result has none left. + let again = s.execute("addon.cutting.bridges", &json!({"width": 4})).unwrap(); + assert_eq!(again["islands"], json!(0)); + assert!(again["warning"].as_str().is_some_and(|w| w.contains("no islands")), "{again}"); + assert_eq!(undo_steps(&s), steps + 1, "no islands: no undo step"); + // Undo puts the O back where it was and takes the layer away. + s.execute("edit.undo", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.node(layer).is_none() && d.node(made).is_none() && d.node(o).is_some_and(|n| n.visible)); +} + +#[test] +fn keep_original_off_replaces_the_art() { + let mut s = session(); + let o = letter_o(&mut s); + let layers = s.doc().unwrap().doc.layers.len(); + let r = s.execute("addon.cutting.bridges", &json!({"width": 4, "keepOriginal": false})).unwrap(); + assert_eq!(r["original"], Value::Null); + let d = &s.doc().unwrap().doc; + assert!(d.node(o).is_none() && d.node(id_of(&r)).is_some()); + assert_eq!(d.layers.len(), layers); +} + +#[test] +fn the_bridge_is_as_wide_as_asked() { + for width in [2.0, 8.0] { + let mut s = session(); + letter_o(&mut s); + let r = s.execute("addon.cutting.bridges", &json!({"width": width})).unwrap(); + let made = id_of(&r); + let half = width / 2.0; + assert!(!fills(&s, made, 150.0 - half * 0.9, 110.0) && !fills(&s, made, 150.0 + half * 0.9, 110.0), "{width}"); + assert!(fills(&s, made, 150.0 - half * 1.2, 110.0) && fills(&s, made, 150.0 + half * 1.2, 110.0), "{width}"); + } +} + +#[test] +fn the_width_takes_units() { + let mut s = session(); + letter_o(&mut s); + let r = s.execute("addon.cutting.bridges", &json!({"width": "2 mm"})).unwrap(); + let made = id_of(&r); + // 2 mm is about 5.67 pt. + assert!(!fills(&s, made, 152.5, 110.0) && fills(&s, made, 154.0, 110.0)); +} + +#[test] +fn the_shortest_crossing_takes_the_thinnest_bar() { + let mut s = session(); + // The left bar is 5 pt thick, the others 20. + shape_with_holes(&mut s, (100.0, 100.0, 100.0, 100.0), &[(105.0, 120.0, 75.0, 60.0)]); + let r = s.execute("addon.cutting.bridges", &json!({"width": 4, "direction": "shortest"})).unwrap(); + let made = id_of(&r); + assert!(!fills(&s, made, 102.5, 150.0), "the bridge crosses the thin bar"); + assert!(fills(&s, made, 150.0, 110.0) && fills(&s, made, 190.0, 150.0)); +} + +#[test] +fn horizontal_bridges_cross_the_sides() { + let mut s = session(); + letter_o(&mut s); + let r = s.execute("addon.cutting.bridges", &json!({"width": 4, "direction": "horizontal"})).unwrap(); + let made = id_of(&r); + assert!(!fills(&s, made, 110.0, 150.0) || !fills(&s, made, 190.0, 150.0)); + assert!(fills(&s, made, 150.0, 110.0) && fills(&s, made, 150.0, 190.0)); +} + +#[test] +fn a_shape_with_two_holes_gets_a_bridge_for_each() { + let mut s = session(); + shape_with_holes(&mut s, (100.0, 100.0, 100.0, 50.0), &[(110.0, 110.0, 30.0, 30.0), (160.0, 110.0, 30.0, 30.0)]); + let r = s.execute("addon.cutting.bridges", &json!({"width": 3, "count": 2})).unwrap(); + assert_eq!((r["islands"].clone(), r["bridges"].clone(), r["unbridged"].clone()), (json!(2), json!(4), json!(0))); + let made = id_of(&r); + for x in [125.0, 175.0] { + assert!(!fills(&s, made, x, 105.0) && !fills(&s, made, x, 145.0), "{x}: a bridge above and below each hole"); + } +} + +#[test] +fn type_is_bridged_by_its_glyph_outlines_and_stays_type() { + let mut s = session(); + let t = NodeId(s.execute("text.create", &json!({"x": 100, "y": 300, "text": "O", "size": 144})).unwrap()["id"].as_u64().unwrap()); + select(&mut s, &[t]); + let r = s.execute("addon.cutting.bridges", &json!({"width": 3})).unwrap(); + assert_eq!((r["islands"].clone(), r["bridges"].clone(), r["unbridged"].clone()), (json!(1), json!(1), json!(0)), "{r}"); + assert!(matches!(node(&s, id_of(&r)).kind, NodeKind::Path { .. } | NodeKind::Compound { .. })); + // The type itself is not converted: it is on the hidden layer, still type. + assert!(matches!(node(&s, t).kind, NodeKind::Text(_))); + assert!(!node(&s, NodeId(r["original"].as_u64().unwrap())).visible); +} + +#[test] +fn the_result_is_painted_as_the_topmost_object_with_outlines() { + let mut s = session(); + let o = letter_o(&mut s); + // Type holding only a space draws no outlines, so it does not set the paint, though it is on top. + let t = NodeId(s.execute("text.create", &json!({"x": 100, "y": 300, "text": " ", "size": 24})).unwrap()["id"].as_u64().unwrap()); + select(&mut s, &[o]); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let red = node(&s, o).appearance.fill_paint(); + select(&mut s, &[o, t]); + let r = s.execute("addon.cutting.bridges", &json!({"width": 4})).unwrap(); + assert_eq!(node(&s, id_of(&r)).appearance.fill_paint(), red); +} + +#[test] +fn hidden_members_of_a_group_are_left_out() { + let mut s = session(); + let o = letter_o(&mut s); + // A hidden square that would fill the O's hole, grouped with it. + let cover = rect(&mut s, 120.0, 120.0, 60.0, 60.0); + select(&mut s, &[o, cover]); + let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + select(&mut s, &[cover]); + s.execute("object.hide", &json!({})).unwrap(); + select(&mut s, &[g]); + let r = s.execute("addon.cutting.bridges", &json!({"width": 4})).unwrap(); + assert_eq!((r["islands"].clone(), r["bridges"].clone()), (json!(1), json!(1)), "{r}"); +} + +#[test] +fn art_without_islands_changes_nothing() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 50.0, 50.0); + select(&mut s, &[a]); + let (steps, count) = (undo_steps(&s), s.doc().unwrap().doc.node_count()); + let r = s.execute("addon.cutting.bridges", &json!({})).unwrap(); + assert_eq!((r["islands"].clone(), r["bridges"].clone(), r["id"].clone()), (json!(0), json!(0), Value::Null)); + assert!(r["warning"].as_str().is_some(), "{r}"); + assert_eq!((undo_steps(&s), s.doc().unwrap().doc.node_count()), (steps, count)); +} + +#[test] +fn an_island_too_narrow_for_the_width_is_reported() { + let mut s = session(); + shape_with_holes(&mut s, (100.0, 100.0, 100.0, 100.0), &[(149.0, 120.0, 2.0, 60.0)]); + let steps = undo_steps(&s); + let r = s.execute("addon.cutting.bridges", &json!({"width": 4})).unwrap(); + assert_eq!((r["islands"].clone(), r["bridges"].clone(), r["unbridged"].clone()), (json!(1), json!(0), json!(1))); + assert!(r["warning"].as_str().is_some_and(|w| w.contains("No bridge")), "{r}"); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn islands_left_without_a_bridge_are_reported_beside_the_ones_bridged() { + let mut s = session(); + // A wide hole on the left and a 2 pt slot on the right. + shape_with_holes(&mut s, (100.0, 100.0, 200.0, 100.0), &[(120.0, 120.0, 60.0, 60.0), (249.0, 120.0, 2.0, 60.0)]); + let steps = undo_steps(&s); + let r = s.execute("addon.cutting.bridges", &json!({"width": 4})).unwrap(); + assert_eq!((r["islands"].clone(), r["bridges"].clone(), r["unbridged"].clone()), (json!(2), json!(1), json!(1))); + assert!(r["warning"].as_str().is_some_and(|w| w.contains("could not be joined")), "{r}"); + assert_eq!(undo_steps(&s), steps + 1); + assert!(!fills(&s, id_of(&r), 150.0, 110.0), "the wide hole is bridged"); +} + +#[test] +fn each_run_keeps_its_original_on_a_layer_of_its_own() { + let mut s = session(); + letter_o(&mut s); + let first = s.execute("addon.cutting.bridges", &json!({"width": 4})).unwrap(); + shape_with_holes(&mut s, (300.0, 100.0, 100.0, 100.0), &[(320.0, 120.0, 60.0, 60.0)]); + let second = s.execute("addon.cutting.bridges", &json!({"width": 4})).unwrap(); + let name = |r: &Value| node(&s, NodeId(r["original"].as_u64().unwrap())).name; + assert_eq!((name(&first).as_deref(), name(&second).as_deref()), (Some("Stencil Original"), Some("Stencil Original 2"))); +} + +#[test] +fn bad_params_are_refused() { + let mut s = session(); + letter_o(&mut s); + let steps = undo_steps(&s); + for (key, p) in [ + ("width", json!({"width": 0})), + ("width", json!({"width": 5000})), + ("width", json!({"width": "wide"})), + ("count", json!({"count": 0})), + ("count", json!({"count": 1.5})), + ("count", json!({"count": 17})), + ("count", json!({"count": "two"})), + ("direction", json!({"direction": "diagonal"})), + ("direction", json!({"direction": 90})), + ("keepOriginal", json!({"keepOriginal": "yes"})), + ] { + let e = s.execute("addon.cutting.bridges", &p).unwrap_err().to_string(); + assert!(e.contains(key), "{p}: {e}"); + } + assert_eq!(undo_steps(&s), steps); + assert!(s.execute("addon.cutting.bridges", &json!({"width": 4})).is_ok(), "good params run"); +} + +#[test] +fn art_too_detailed_to_bridge_is_refused_with_a_message_that_says_so() { + let mut s = session(); + let parent = s.doc().unwrap().target_parent().unwrap(); + let id = s + .edit("dense", |d, sel| { + // More anchors than Stencil Bridges measures. + let mut zigzag = kurbo::BezPath::new(); + zigzag.move_to((100.0, 100.0)); + for i in 1..=vectorcraft_pathops::addons::stencil::MAX_STENCIL_SEGMENTS { + zigzag.line_to((100.0 + i as f64 * 0.001, if i % 2 == 0 { 100.0 } else { 101.0 })); + } + zigzag.close_path(); + let huge = vectorcraft_geom::PathData::from_bezpath(&zigzag); + let n = vectorcraft_doc::Node::path(d.alloc_id(), huge, vectorcraft_doc::Appearance::default()); + let id = n.id; + d.insert(parent, usize::MAX, n)?; + sel.set([id]); + Ok(id) + }) + .unwrap(); + select(&mut s, &[id]); + let steps = undo_steps(&s); + let e = s.execute("addon.cutting.bridges", &json!({"width": 4})).unwrap_err().to_string(); + assert!(e.contains("Stencil Bridges: the selected art is too large or too detailed to bridge"), "{e}"); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn selected_objects_without_outlines_stay_where_they_are() { + for keep in [true, false] { + let mut s = session(); + let o = letter_o(&mut s); + // Type holding only a space has no outlines. + let t = NodeId(s.execute("text.create", &json!({"x": 100, "y": 300, "text": " ", "size": 24})).unwrap()["id"].as_u64().unwrap()); + let layer = |s: &Session, id: NodeId| s.doc().unwrap().doc.layer_of(id); + let before = layer(&s, t); + select(&mut s, &[o, t]); + let r = s.execute("addon.cutting.bridges", &json!({"width": 4, "keepOriginal": keep})).unwrap(); + assert_eq!(r["bridges"], json!(1), "{r}"); + assert!(node(&s, t).visible && layer(&s, t) == before, "keep {keep}: the type stays where it was"); + if keep { + let held = + s.doc().unwrap().doc.children(Some(NodeId(r["original"].as_u64().unwrap()))).map(|c| c.iter().map(|n| n.id).collect::<Vec<_>>()); + assert_eq!(held, Some(vec![o])); + } + } +} + +#[test] +fn the_result_takes_the_place_of_the_topmost_selected_object() { + let mut s = session(); + let o = letter_o(&mut s); + let between = rect(&mut s, 400.0, 100.0, 50.0, 50.0); + let o2 = shape_with_holes(&mut s, (500.0, 100.0, 100.0, 100.0), &[(520.0, 120.0, 60.0, 60.0)]); + let above = rect(&mut s, 400.0, 300.0, 50.0, 50.0); + select(&mut s, &[o, o2]); + let r = s.execute("addon.cutting.bridges", &json!({"width": 4, "keepOriginal": false})).unwrap(); + let made = id_of(&r); + let d = &s.doc().unwrap().doc; + let order: Vec<NodeId> = d.children(d.layer_of(made)).unwrap().iter().map(|n| n.id).collect(); + let at = |id: NodeId| order.iter().position(|i| *i == id).unwrap(); + assert!(at(between) < at(made) && at(made) < at(above), "{order:?}"); +} + +#[test] +fn the_result_is_one_path_when_one_outline_is_left() { + for (count, plain) in [(1, true), (2, false)] { + let mut s = session(); + letter_o(&mut s); + let r = s.execute("addon.cutting.bridges", &json!({"width": 4, "count": count})).unwrap(); + let kind = node(&s, id_of(&r)).kind; + // One bridge leaves a C, one outline; two leave two pieces. + assert_eq!(matches!(kind, NodeKind::Path { .. }), plain, "count {count}"); + assert_eq!(matches!(kind, NodeKind::Compound { .. }), !plain, "count {count}"); + } +} diff --git a/crates/engine/src/cmd/addons/cutting/weed.rs b/crates/engine/src/cmd/addons/cutting/weed.rs new file mode 100644 index 0000000000..8a6375a595 --- /dev/null +++ b/crates/engine/src/cmd/addons/cutting/weed.rs @@ -0,0 +1,160 @@ +//! Weed Box and Lines (`addon.cutting.weed`), a command of the built-in Cutting Tools add-on for +//! vinyl cutting: around the selected art it adds a weed box (a rectangle at a margin around the +//! art) and weeding lines across it that stop at the art, so the waste vinyl around the art lifts +//! off in pieces (<https://help.arlon.com/what-is-a-weeding-border>). The art is measured by the +//! outlines a cutter cuts ([`geometry`]). + +mod geometry; +#[cfg(test)] +mod tests; + +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_color::Paint; +use vectorcraft_color::swatch::REGISTRATION; +use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind}; +use vectorcraft_geom::{Rect, shapes}; + +use super::super::super::edit::selected_roots; +use super::super::super::object::choice; +use super::super::super::paint::swatch_solid; +use super::super::super::pathops::{length_given, number_given}; +use super::super::super::{CommandSpec, bad, cmd, has_selection, switch_or, text_param}; +use crate::{EngineError, Result, Session}; + +/// Weed Box and Lines' command. +pub const WEED: &str = "addon.cutting.weed"; +/// Which way the weeding lines run. +pub const DIRECTIONS: [&str; 3] = ["horizontal", "vertical", "both"]; +/// The largest margin, gap or spacing, in points. +const MAX_DISTANCE: f64 = 100_000.0; +/// The most weeding lines each way. +const MAX_COUNT: usize = 1000; +/// The most pieces of weeding line one run adds. +const MAX_PIECES: usize = 100_000; + +pub fn specs() -> Vec<CommandSpec> { + vec![cmd!( + "addon.cutting.weed", + "Weed Box and Lines…", + ["Object", "Plug-ins", "Cutting Tools"], + None, + "{margin?: pt 0..100000 (9: from the art to the weed box), box?: true (false: the weeding lines only), direction?: \"horizontal\" | \"vertical\" | \"both\" (\"both\"), count?: whole number 0..1000 of lines each way (1), spacing?: pt more than 0 and at most 100000 (instead of count, never with it: as few lines as keep them at most this far apart, up to 1000 each way), gap?: pt 0..100000 (0: the lines stop at the art's outlines), weight?: pt 0.01..1000 (0.3), swatch?: a color swatch the lines are stroked in (\"[Registration]\")} add a weed box around the selected art and weeding lines across it that divide it evenly, each running from one side of the box to the other and left out over the art and within `gap` of its outlines, so the waste lifts off in pieces. The art is measured by the outlines a cutter cuts: closed paths enclose their area by their fill rule and open paths are lines, compound paths by all their subpaths, type by its glyph outlines, a clip group by what shows inside its clipping path, images by their frames, placed files by the art they show (by their boxes when the file can't be read), symbol instances by their art and live objects by the art they draw; strokes, effects and hidden objects are left out. One group named Weeding, stroked with no fill, on top of the current layer (outside the clip groups around a group edited in isolation), selected, as one undo step → {id: the group, box: its weed box or null, lines (pieces of weeding line)}", + has_selection, + weed + )] +} + +/// The distance `p` gives for `key` (0..[`MAX_DISTANCE`]), or `default`. +fn distance(p: &Value, key: &str, default: f64) -> Result<f64> { + match length_given(p, key, WEED)? { + None => Ok(default), + Some(v) if (0.0..=MAX_DISTANCE).contains(&v) => Ok(v), + Some(_) => Err(bad(WEED, format!("`{key}` must be from 0 to {MAX_DISTANCE} pt"))), + } +} + +/// How many lines divide a side `length` long: `count`, or as few as keep them at most `spacing` +/// apart. +fn lines_across(length: f64, count: Option<usize>, spacing: Option<f64>) -> Result<usize> { + let n = match spacing { + // `length / spacing` strips, rounded up, need one line fewer. + Some(s) => ((length / s - 1e-9).ceil() - 1.0).max(0.0), + None => return Ok(count.unwrap_or(1)), + }; + if n > MAX_COUNT as f64 { + return Err(bad(WEED, format!("`spacing` makes more than {MAX_COUNT} lines across the box"))); + } + Ok(n as usize) +} + +/// Where the Weeding group goes: `parent`, or, when `parent` is inside a clip group or clipping +/// sublayer (a group edited in isolation), the container around the outermost of them. A clipping +/// path would hide the lines and the box, which lie outside the art. +fn outside_clips(d: &Document, parent: Option<NodeId>) -> Option<NodeId> { + let clips = |id: NodeId| d.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Group { clip: true, .. } | NodeKind::Layer { clip: true, .. })); + let (mut at, mut out) = (parent, parent); + while let Some(p) = at { + let up = d.parent_of(p); + if clips(p) { + match up { + Some(up) if d.is_editable(up) => out = Some(up), + _ => break, + } + } + at = up; + } + out +} + +fn weed(s: &mut Session, p: &Value) -> Result<Value> { + let margin = distance(p, "margin", 9.0)?; + let gap = distance(p, "gap", 0.0)?; + let with_box = switch_or(p, "box", true, WEED)?; + let direction = choice(p, WEED, "direction", &DIRECTIONS)?.unwrap_or("both"); + let count = match number_given(p, "count", WEED)? { + None => None, + Some(n) if n.fract() == 0.0 && (0.0..=MAX_COUNT as f64).contains(&n) => Some(n as usize), + Some(_) => return Err(bad(WEED, format!("`count` must be a whole number from 0 to {MAX_COUNT}"))), + }; + let spacing = match length_given(p, "spacing", WEED)? { + None => None, + Some(v) if v > 0.0 && v <= MAX_DISTANCE => Some(v), + Some(_) => return Err(bad(WEED, format!("`spacing` must be more than 0 and at most {MAX_DISTANCE} pt"))), + }; + if count.is_some() && spacing.is_some() { + return Err(bad(WEED, "give `count` or `spacing`, not both")); + } + let weight = match length_given(p, "weight", WEED)? { + None => 0.3, + Some(v) if (0.01..=1000.0).contains(&v) => v, + Some(_) => return Err(bad(WEED, "`weight` must be from 0.01 to 1000 pt")), + }; + let swatch = text_param(p, "swatch", WEED)?.unwrap_or(REGISTRATION); + let stroke = swatch_solid(&s.doc()?.doc, swatch, None).map_err(|e| bad(WEED, e))?; + let roots = selected_roots(s)?; + if roots.is_empty() { + return Err(bad(WEED, "select the art to weed")); + } + let d = &s.doc()?.doc; + let parent = outside_clips(d, s.doc()?.target_parent()?); + // Placed files' art uses their resources (symbols) under names of their own. + let placed = d.with_placed_art(); + let region = geometry::Reader::new(&placed).read_ids(&roots).map_err(|e| bad(WEED, e))?; + let region = region.ok_or_else(|| bad(WEED, "the selection has no outlines to weed around"))?; + let outline = region.outline().map_err(|e| bad(WEED, e))?; + let art = outline.iter().fold(None, |r: Option<Rect>, &(a, b)| Some(r.map_or(Rect::from_points(a, b), |r| r.union_pt(a).union_pt(b)))); + let frame = art.ok_or_else(|| bad(WEED, "the selection has no outlines to weed around"))?.inflate(margin, margin); + if !(frame.width().is_finite() && frame.height().is_finite()) { + return Err(bad(WEED, "the selected art is too large to measure")); + } + let each = |on: bool, length: f64| if on { lines_across(length, count, spacing) } else { Ok(0) }; + let counts = + geometry::Counts { horizontal: each(direction != "vertical", frame.height())?, vertical: each(direction != "horizontal", frame.width())? }; + let pieces = geometry::lines(®ion, &outline, frame, counts, gap, MAX_PIECES).map_err(|e| bad(WEED, e))?; + if pieces.is_empty() && !with_box { + return Err(EngineError::Other("Weed Box and Lines: no weeding line fits outside the art, and the weed box is off".into())); + } + let ap = Appearance::basic(Paint::None, stroke, weight); + let (group, weed_box, lines) = s.edit("Weed Box and Lines", |d, sel| { + let mut children = vec![]; + let mut weed_box = None; + if with_box { + let mut b = Node::path(d.alloc_id(), shapes::rectangle(frame), ap.clone()); + b.name = Some("Weed Box".into()); + weed_box = Some(b.id); + children.push(Arc::new(b)); + } + for (a, b) in &pieces { + children.push(Arc::new(Node::path(d.alloc_id(), shapes::line(*a, *b), ap.clone()))); + } + let mut g = Node::group(d.alloc_id(), children); + g.name = Some("Weeding".into()); + let id = g.id; + d.insert(parent, usize::MAX, g)?; + sel.set([id]); + Ok((id, weed_box, pieces.len())) + })?; + Ok(json!({ "id": group.0, "box": weed_box.map(|b| b.0), "lines": lines })) +} diff --git a/crates/engine/src/cmd/addons/cutting/weed/geometry.rs b/crates/engine/src/cmd/addons/cutting/weed/geometry.rs new file mode 100644 index 0000000000..0db89fb2ee --- /dev/null +++ b/crates/engine/src/cmd/addons/cutting/weed/geometry.rs @@ -0,0 +1,770 @@ +//! The geometry of Weed Box and Lines: the selected art as the outlines a cutter cuts ([`Region`]), +//! and the weeding lines across a box that stop at those outlines or at a gap from them +//! ([`lines`]). +//! +//! A region is measured along one straight line at a time. A closed outline encloses its area by +//! its fill rule, an open one is a line with no area, a group is the union of its members and a +//! clip group is what its members draw inside its clipping path. Along a weeding line the region +//! gives the stretches inside its area ([`Region::spans`]), and its outline pieces +//! ([`Region::outline`]) give the stretches within the gap of an outline. + +use std::cell::Cell; + +use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use vectorcraft_geom::{BezPath, FillRule, PathEl, Point, Rect}; + +use super::super::super::super::pathops::node_path; + +/// How closely curves are followed, in points. +const TOLERANCE: f64 = 0.02; +/// The most points the outlines of one selection are measured by, once curves are followed in +/// straight segments (each subpath's points, its first one included). +pub(super) const MAX_POINTS: usize = 200_000; +/// The most tests of a segment against another one measuring a clip group's outlines takes. +const MAX_PAIRS: usize = 40_000_000; +/// The deepest groups, symbol instances and live objects are opened inside one another: as deep +/// as any object is drawn. +pub(super) const MAX_DEPTH: usize = vectorcraft_doc::depth::MAX_DRAWN_DEPTH; +/// The most pairs of an outline segment and a weeding line it comes near that one run measures. +const MAX_NEAR: usize = 10_000_000; +/// Pieces of weeding line shorter than this, in points, are left out. +const MIN_PIECE: f64 = 0.01; + +/// A straight segment. +pub(super) type Segment = (Point, Point); + +/// One subpath followed in straight segments. +#[derive(Clone, Debug)] +pub(super) struct Poly { + points: Vec<Point>, + closed: bool, + /// The box around `points`. + bounds: Rect, +} + +impl Poly { + /// The segments, with the closing one of a closed subpath. + fn segments(&self) -> impl Iterator<Item = Segment> + '_ { + let closing = self.closed.then(|| (self.points.last().copied(), self.points.first().copied())); + self.points.windows(2).map(|w| (w[0], w[1])).chain(closing.and_then(|(a, b)| Some((a?, b?)))) + } +} + +/// The selected art as the outlines a cutter cuts. +#[derive(Clone, Debug)] +pub(super) enum Region { + /// A path, compound path or type: its subpaths with the rule its closed ones fill by. + Shape { polys: Vec<Poly>, rule: FillRule }, + /// Everything its members draw. + Union(Vec<Region>), + /// What `content` draws inside `clip`. + Clip { clip: Box<Region>, content: Box<Region> }, +} + +/// Reads the selected objects into a [`Region`], keeping count of the outline points. +pub(super) struct Reader<'a> { + doc: &'a Document, + points: usize, +} + +impl<'a> Reader<'a> { + pub(super) fn new(doc: &'a Document) -> Self { + Self { doc, points: 0 } + } + + /// The region of `nodes` together, `None` when they hold no outlines. + pub(super) fn read(&mut self, nodes: &[&Node]) -> Result<Option<Region>, String> { + let mut parts = vec![]; + for n in nodes { + parts.extend(self.node(n, 0)?); + } + Ok(union(parts)) + } + + fn node(&mut self, n: &Node, depth: usize) -> Result<Option<Region>, String> { + if depth > MAX_DEPTH { + return Err(format!("the selected art is nested more than {MAX_DEPTH} levels deep")); + } + if !n.visible { + return Ok(None); + } + match &n.kind { + NodeKind::Path { guide: true, .. } | NodeKind::RulerGuide { .. } => Ok(None), + NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Text(_) => self.shape(n), + NodeKind::Group { clip, .. } | NodeKind::Layer { clip, .. } => { + let members = n.editing_children(); + if *clip { + let Some((first, rest)) = members.split_first() else { return Ok(None) }; + let Some(clip) = self.clip_region(first)? else { return Ok(None) }; + let mut parts = vec![]; + for c in rest { + parts.extend(self.node(c, depth + 1)?); + } + Ok(union(parts).map(|content| Region::Clip { clip: Box::new(clip), content: Box::new(content) })) + } else { + let mut parts = vec![]; + for c in members { + parts.extend(self.node(c, depth + 1)?); + } + Ok(union(parts)) + } + } + NodeKind::Image(im) => { + let (w, h) = (f64::from(im.width), f64::from(im.height)); + let corners = [Point::new(0.0, 0.0), Point::new(w, 0.0), Point::new(w, h), Point::new(0.0, h)].map(|p| im.xf * p); + self.polygon(&corners) + } + // An instance of a symbol the document doesn't have draws nothing. + NodeKind::SymbolInstance { .. } => match vectorcraft_render::effects::outline_object(Some(self.doc), n) { + Some(art) => self.node(&art, depth + 1), + None => Ok(None), + }, + NodeKind::PlacedDocument(p) => { + // The art of the file it shows; a file that can't be read shows its preview in its + // box, which may be rotated. + if vectorcraft_doc::placed_document::read_cached(p).is_none() { + return self.polygon(&p.corners()); + } + let art = vectorcraft_render::effects::expand_live_deep(Some(self.doc), n); + if std::mem::discriminant(&art.kind) == std::mem::discriminant(&n.kind) { + self.polygon(&p.corners()) + } else { + self.node(&art, depth + 1) + } + } + NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Mesh(_) | NodeKind::Repeat(_) | NodeKind::Intertwine { .. } => { + // The art a live object draws, as the exporters write it; an object that stays + // as it is is measured by its box. + let art = vectorcraft_render::effects::expand_live_deep(Some(self.doc), n); + if std::mem::discriminant(&art.kind) == std::mem::discriminant(&n.kind) { self.frame(n) } else { self.node(&art, depth + 1) } + } + } + } + + /// The region a clipping path `first` clips to, whatever its own visibility: the region the + /// renderer clips to (a path, a compound path, type by its glyphs, a group's visible members, + /// an image's frame). `None` when it clips to nothing, and the clipped art is hidden. + fn clip_region(&mut self, first: &Node) -> Result<Option<Region>, String> { + let Some((outline, rule)) = vectorcraft_render::effects::clip_outline(first) else { return Ok(None) }; + let mut polys = self.polys(outline)?; + // A region is filled: an open subpath clips as if closed. + polys.iter_mut().for_each(|p| p.closed = true); + Ok((!polys.is_empty()).then_some(Region::Shape { polys, rule })) + } + + /// The region of the objects `ids` together, each within the clipping paths of the clip groups + /// and layers around it (an object selected inside a clip group shows only within its clipping + /// path, and not at all inside a hidden group or layer; a clipping path is measured as its clip + /// group), `None` when they show no outlines. + pub(super) fn read_ids(&mut self, ids: &[NodeId]) -> Result<Option<Region>, String> { + let doc = self.doc; + let clips = |n: &Node| matches!(n.kind, NodeKind::Group { clip: true, .. } | NodeKind::Layer { clip: true, .. }); + // Every object's place in the tree, found in one walk. + let places = doc.index_paths(ids.iter().copied()); + let mut paths = vec![]; + for id in ids { + let Some(mut path) = places.get(id).cloned() else { continue }; + // A clipping path selected on its own stands for the art it shows: its clip group. + while let (Some(n), Some(up)) = (doc.node_at(&path), path.split_last().map(|(_, up)| up).and_then(|up| doc.node_at(up))) { + if !(clips(up) && up.editing_children().first().is_some_and(|f| f.id == n.id)) { + break; + } + path.pop(); + } + paths.push(path); + } + // An object selected twice, or inside another selected object, is measured once, with it. + paths.sort(); + paths.dedup(); + let mut kept: Vec<Vec<usize>> = vec![]; + for path in paths { + if !kept.last().is_some_and(|k| path.starts_with(k)) { + kept.push(path); + } + } + let mut parts = vec![]; + 'ids: for path in &kept { + let Some(n) = doc.node_at(path) else { continue }; + // Art in a hidden group or layer isn't shown, and isn't measured. + if (1..path.len()).any(|depth| path.get(..depth).and_then(|p| doc.node_at(p)).is_some_and(|c| !c.visible)) { + continue; + } + let Some(mut region) = self.read(&[n])? else { continue }; + // The containers around the object, innermost first. + let mut child = n.id; + for depth in (1..path.len()).rev() { + let Some(container) = path.get(..depth).and_then(|p| doc.node_at(p)) else { break }; + if clips(container) + && let Some(first) = container.editing_children().first().filter(|f| f.id != child) + { + let Some(clip) = self.clip_region(first)? else { continue 'ids }; + region = Region::Clip { clip: Box::new(clip), content: Box::new(region) }; + } + child = container.id; + } + parts.push(region); + } + Ok(union(parts)) + } + + /// A path, compound path or type as its outlines. + fn shape(&mut self, n: &Node) -> Result<Option<Region>, String> { + // Each anchor is at least one point, so a path past the budget errs before it is copied. + if anchors(n) > MAX_POINTS.saturating_sub(self.points) { + return Err(too_many()); + } + let Some((path, rule)) = node_path(n) else { return Ok(None) }; + let polys = self.polys(path.to_bezpath())?; + Ok((!polys.is_empty()).then_some(Region::Shape { polys, rule })) + } + + /// The box of an object whose outlines can't be read. + fn frame(&mut self, n: &Node) -> Result<Option<Region>, String> { + match n.geometric_bounds_with(&self.doc.symbol_boxes()) { + Some(r) => self.polygon(&[Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)]), + None => Ok(None), + } + } + + /// A closed polygon through `points`. + fn polygon(&mut self, points: &[Point]) -> Result<Option<Region>, String> { + let poly = poly(points.to_vec(), true); + self.count(poly.iter().map(|p| p.points.len()).sum())?; + Ok(poly.map(|p| Region::Shape { polys: vec![p], rule: FillRule::NonZero })) + } + + fn count(&mut self, n: usize) -> Result<(), String> { + self.points = self.points.saturating_add(n); + if self.points > MAX_POINTS { Err(too_many()) } else { Ok(()) } + } + + /// The subpaths of `path` followed in straight segments. + fn polys(&mut self, path: BezPath) -> Result<Vec<Poly>, String> { + let (mut out, mut current, points) = (vec![], vec![], Cell::new(0usize)); + let left = MAX_POINTS.saturating_sub(self.points); + // Past the budget no further curve is followed (one curve gives at most + // `MAX_FLATTEN_PER_CURVE` points), and the read fails below. + let elements = path.into_iter().take_while(|_| points.get() <= left); + vectorcraft_geom::flatten(elements, TOLERANCE, |el| { + points.set(points.get() + 1); + if points.get() > left { + return; + } + match el { + PathEl::MoveTo(p) => { + out.extend(poly(std::mem::take(&mut current), false)); + current.push(p); + } + PathEl::LineTo(p) => current.push(p), + PathEl::ClosePath => out.extend(poly(std::mem::take(&mut current), true)), + PathEl::QuadTo(..) | PathEl::CurveTo(..) => {} + } + }); + if points.get() > left { + return Err(too_many()); + } + out.extend(poly(current, false)); + self.count(out.iter().map(|p: &Poly| p.points.len()).sum())?; + Ok(out) + } +} + +fn too_many() -> String { + format!("the selected art has too many outline points to measure (more than {MAX_POINTS})") +} + +/// The anchors of a path or compound path node, read without copying its path; 0 for type. +fn anchors(n: &Node) -> usize { + match &n.kind { + NodeKind::Path { path, .. } => path.anchor_count(), + NodeKind::Compound { children, .. } => children.iter().fold(0, |sum, c| sum.saturating_add(anchors(c))), + _ => 0, + } +} + +/// A subpath through `points`, `None` for fewer than two points or one that isn't finite. +fn poly(points: Vec<Point>, closed: bool) -> Option<Poly> { + if points.len() < 2 || points.iter().any(|p| !p.x.is_finite() || !p.y.is_finite()) { + return None; + } + let first = *points.first()?; + let bounds = points.iter().fold(Rect::from_points(first, first), |r, p| r.union_pt(*p)); + Some(Poly { points, closed, bounds }) +} + +/// One region of `parts`, `None` when there are none. +fn union(mut parts: Vec<Region>) -> Option<Region> { + match parts.len() { + 0 => None, + 1 => parts.pop(), + _ => Some(Region::Union(parts)), + } +} + +/// `p` as (along, across) a weeding line: horizontal lines run along x, vertical ones along y. +fn uv(p: Point, vertical: bool) -> (f64, f64) { + if vertical { (p.y, p.x) } else { (p.x, p.y) } +} + +/// Sorts `spans` and joins those that overlap or touch. +fn merged(mut spans: Vec<(f64, f64)>) -> Vec<(f64, f64)> { + spans.sort_by(|a, b| a.0.total_cmp(&b.0)); + let mut out: Vec<(f64, f64)> = Vec::with_capacity(spans.len()); + for (a, b) in spans { + match out.last_mut() { + Some(last) if a <= last.1 => last.1 = last.1.max(b), + _ => out.push((a, b)), + } + } + out +} + +/// Where sorted, joined spans `a` and `b` overlap. +fn intersected(a: &[(f64, f64)], b: &[(f64, f64)]) -> Vec<(f64, f64)> { + let (mut i, mut j, mut out) = (0, 0, vec![]); + while let (Some(&(a0, a1)), Some(&(b0, b1))) = (a.get(i), b.get(j)) { + let (lo, hi) = (a0.max(b0), a1.min(b1)); + if lo <= hi { + out.push((lo, hi)); + } + if a1 < b1 { + i += 1; + } else { + j += 1; + } + } + out +} + +/// Where segment a→b crosses the line `across` = `c`, along it, and which way (1 when `across` +/// grows from a to b), `None` when it doesn't. Each crossing counts once: an end exactly on the +/// line counts as past it. +fn crosses(a: Point, b: Point, vertical: bool, c: f64) -> Option<(f64, i32)> { + let ((u0, v0), (u1, v1)) = (uv(a, vertical), uv(b, vertical)); + ((v0 <= c && v1 > c) || (v1 <= c && v0 > c)).then(|| (u0 + (c - v0) * (u1 - u0) / (v1 - v0), if v1 > v0 { 1 } else { -1 })) +} + +/// The stretches inside an area filled by `rule`, from where its outlines cross a line, sorted +/// along it. +fn filled(crossings: impl IntoIterator<Item = (f64, i32)>, rule: FillRule) -> Vec<(f64, f64)> { + let (mut winding, mut start, mut out) = (0, 0.0, vec![]); + let inside = |w: i32| match rule { + FillRule::NonZero => w != 0, + FillRule::EvenOdd => w % 2 != 0, + }; + for (u, dir) in crossings { + let was = inside(winding); + winding += dir; + match (was, inside(winding)) { + (false, true) => start = u, + (true, false) => out.push((start, u)), + _ => {} + } + } + merged(out) +} + +/// Where the closed outlines of a region's shapes cross a set of weeding lines: for each line, the +/// crossings as (shape, place along the line, direction), sorted by shape and then by place. Shapes +/// are numbered in the order [`Region::shapes`] lists them. +pub(super) type Crossings = Vec<Vec<(usize, f64, i32)>>; + +/// Where the shapes of each part of a region are numbered among its [`Crossings`]. +#[derive(Debug)] +pub(super) enum Layout { + Shape, + /// The number of each part's first shape, from the union's first, and the parts' layouts. + Union { + starts: Vec<usize>, + parts: Vec<Layout>, + }, + /// The clipping path's shapes come first. + Clip { + clip_shapes: usize, + clip: Box<Layout>, + content: Box<Layout>, + }, +} + +impl Layout { + /// The layout of `region` and how many shapes it has. + pub(super) fn of(region: &Region) -> (Layout, usize) { + match region { + Region::Shape { .. } => (Layout::Shape, 1), + Region::Union(parts) => { + let (mut starts, mut layouts, mut n) = (vec![], vec![], 0); + for r in parts { + let (l, k) = Layout::of(r); + starts.push(n); + layouts.push(l); + n += k; + } + (Layout::Union { starts, parts: layouts }, n) + } + Region::Clip { clip, content } => { + let ((lc, a), (lt, b)) = (Layout::of(clip), Layout::of(content)); + (Layout::Clip { clip_shapes: a, clip: Box::new(lc), content: Box::new(lt) }, a + b) + } + } + } +} + +/// The [`Crossings`] of `region` with the lines `across` = v0 + (k + 1)·step, k < `count`. Errs +/// past [`MAX_NEAR`] crossings in all. +pub(super) fn crossings(region: &Region, vertical: bool, v0: f64, step: f64, count: usize) -> Result<Crossings, String> { + let mut shapes = vec![]; + region.shapes(&mut shapes); + let at = |k: usize| v0 + step * (k as f64 + 1.0); + // The lines a segment may cross: those from just below its lower end to its higher end. + let candidates = |(a, b): Segment| { + let (va, vb) = (uv(a, vertical).1, uv(b, vertical).1); + if step <= 0.0 || va == vb { + return 0..0; + } + let first = (((va.min(vb) - v0) / step).floor() - 1.0).clamp(0.0, count as f64); + let end = ((va.max(vb) - v0) / step).ceil().clamp(0.0, count as f64); + (first as usize)..(end as usize) + }; + let closed = |polys: &[Poly]| polys.iter().filter(|p| p.closed).flat_map(Poly::segments).collect::<Vec<_>>(); + let total = shapes.iter().flat_map(|(polys, _)| closed(polys)).fold(0usize, |n, s| n.saturating_add(candidates(s).len())); + if total > MAX_NEAR { + return Err("the weeding lines cross the art's outlines too many times to measure; use fewer lines".into()); + } + let mut out: Crossings = vec![vec![]; count]; + for (i, (polys, _)) in shapes.iter().enumerate() { + for (a, b) in closed(polys) { + for k in candidates((a, b)) { + if let (Some((u, dir)), Some(line)) = (crosses(a, b, vertical, at(k)), out.get_mut(k)) { + line.push((i, u, dir)); + } + } + } + } + for line in &mut out { + line.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1))); + } + Ok(out) +} + +impl Region { + /// The stretches of the line `across` = `c` (horizontal: y = c, along x; vertical: x = c, + /// along y) inside the region's area, sorted and joined. + pub(super) fn spans(&self, vertical: bool, c: f64) -> Vec<(f64, f64)> { + match self { + Region::Shape { polys, rule } => { + let mut crossings: Vec<(f64, i32)> = vec![]; + for p in polys.iter().filter(|p| p.closed) { + let (lo, hi) = if vertical { (p.bounds.x0, p.bounds.x1) } else { (p.bounds.y0, p.bounds.y1) }; + if c >= lo && c <= hi { + crossings.extend(p.segments().filter_map(|(a, b)| crosses(a, b, vertical, c))); + } + } + crossings.sort_by(|a, b| a.0.total_cmp(&b.0)); + filled(crossings, *rule) + } + Region::Union(parts) => merged(parts.iter().flat_map(|r| r.spans(vertical, c)).collect()), + Region::Clip { clip, content } => intersected(&clip.spans(vertical, c), &content.spans(vertical, c)), + } + } + + /// The region's shapes with their fill rules, in a fixed order. + fn shapes<'a>(&'a self, out: &mut Vec<(&'a [Poly], FillRule)>) { + match self { + Region::Shape { polys, rule } => out.push((polys, *rule)), + Region::Union(parts) => parts.iter().for_each(|r| r.shapes(out)), + Region::Clip { clip, content } => { + clip.shapes(out); + content.shapes(out); + } + } + } + + /// [`Region::spans`] on a weeding line, from `line`, the line's [`Crossings`] with the + /// region's shapes, numbered from `base` (`layout` is the region's [`Layout`]). Only the parts + /// the line crosses are visited: a part it doesn't cross has no stretch inside its area. + pub(super) fn spans_on(&self, layout: &Layout, line: &[(usize, f64, i32)], base: usize) -> Vec<(f64, f64)> { + if line.is_empty() { + return vec![]; + } + match (self, layout) { + (Region::Shape { rule, .. }, Layout::Shape) => filled(line.iter().map(|&(_, u, dir)| (u, dir)), *rule), + (Region::Union(parts), Layout::Union { starts, parts: layouts }) => { + let (mut out, mut rest) = (vec![], line); + while let Some(&(id, ..)) = rest.first() { + // The part whose shapes the next crossing is on, and its crossings. + let j = starts.partition_point(|&s| base + s <= id).saturating_sub(1); + let (Some(r), Some(l), Some(&start)) = (parts.get(j), layouts.get(j), starts.get(j)) else { break }; + let end = starts.get(j + 1).map_or(usize::MAX, |&s| base + s); + let n = rest.partition_point(|c| c.0 < end); + if n == 0 { + break; + } + let (mine, after) = rest.split_at(n); + out.extend(r.spans_on(l, mine, base + start)); + rest = after; + } + merged(out) + } + (Region::Clip { clip, content }, Layout::Clip { clip_shapes, clip: lc, content: lt }) => { + let (a, b) = line.split_at(line.partition_point(|c| c.0 < base + clip_shapes)); + if a.is_empty() || b.is_empty() { + return vec![]; + } + intersected(&clip.spans_on(lc, a, base), &content.spans_on(lt, b, base + clip_shapes)) + } + _ => vec![], + } + } + + /// Is `p` inside the region's area or on one of `segments`, the outlines it shows? + fn contains(&self, p: Point, segments: &[Segment]) -> bool { + const EPS: f64 = 1e-7; + self.spans(false, p.y).iter().any(|&(a, b)| p.x >= a - EPS && p.x <= b + EPS) || segments.iter().any(|&(a, b)| distance(p, a, b) <= EPS) + } + + /// The pieces of outline the region shows: every outline of a shape and of a group's members, + /// and in a clip group the members' outlines inside the clipping path and the clipping path's + /// outline where the members' area or outlines are. Errs past [`MAX_PAIRS`], counted over + /// every clip group in the region together. + pub(super) fn outline(&self) -> Result<Vec<Segment>, String> { + self.outline_counted(&mut 0) + } + + /// [`Region::outline`], adding the measure's work to `work`. + fn outline_counted(&self, work: &mut usize) -> Result<Vec<Segment>, String> { + match self { + Region::Shape { polys, .. } => Ok(polys.iter().flat_map(Poly::segments).collect()), + Region::Union(parts) => { + let mut out = vec![]; + for r in parts { + out.extend(r.outline_counted(work)?); + } + Ok(out) + } + Region::Clip { clip, content } => { + // Each side's area is bounded by the outlines it shows, so the pieces are cut and + // tested against those, never against art a nested clip hides. + let (clip_shown, content_shown) = (clip.outline_counted(work)?, content.outline_counted(work)?); + let mut out = within(&content_shown, clip, &clip_shown, work)?; + out.extend(within(&clip_shown, content, &content_shown, work)?); + Ok(out) + } + } + } + + /// The points of the region's closed outlines, those a nested clip hides included: what one + /// [`Region::spans`] looks at, at most. + fn closed_points(&self) -> usize { + match self { + Region::Shape { polys, .. } => polys.iter().filter(|p| p.closed).map(|p| p.points.len()).sum(), + Region::Union(parts) => parts.iter().map(Region::closed_points).sum(), + Region::Clip { clip, content } => clip.closed_points().saturating_add(content.closed_points()), + } + } +} + +fn too_complex_clip() -> String { + "a clip group in the selection has too many outline segments to measure".into() +} + +/// The pieces of `segments` inside `region` (or on its outlines), cut where they cross +/// `region_segments`, the outlines the region shows. Each segment, and each piece of one tested +/// for being inside, adds the region's closed outline points (hidden ones included) and its +/// shown segment count to `work`, and the measure errs past [`MAX_PAIRS`]. +fn within(segments: &[Segment], region: &Region, region_segments: &[Segment], work: &mut usize) -> Result<Vec<Segment>, String> { + let mut out = vec![]; + let cost = region.closed_points().saturating_add(region_segments.len()).max(1); + let charge = |work: &mut usize| { + *work = work.saturating_add(cost); + if *work > MAX_PAIRS { Err(too_complex_clip()) } else { Ok(()) } + }; + for &(a, b) in segments { + charge(work)?; + let mut cuts = vec![0.0, 1.0]; + let seg_box = Rect::from_points(a, b); + for &(c, d) in region_segments { + if touches(seg_box, Rect::from_points(c, d)) { + cuts.extend(crossing(a, b, c, d)); + } + } + cuts.sort_by(f64::total_cmp); + cuts.dedup_by(|x, y| (*x - *y).abs() < 1e-12); + let at = |t: f64| a + (b - a) * t; + for w in cuts.windows(2) { + let (t0, t1) = (w[0], w[1]); + if t1 - t0 < 1e-12 { + continue; + } + charge(work)?; + if region.contains(at((t0 + t1) / 2.0), region_segments) { + out.push((at(t0), at(t1))); + } + } + } + Ok(out) +} + +/// Do boxes `a` and `b` overlap or touch? +fn touches(a: Rect, b: Rect) -> bool { + a.x0 <= b.x1 && b.x0 <= a.x1 && a.y0 <= b.y1 && b.y0 <= a.y1 +} + +/// Where along a→b (0 to 1) segment c→d crosses or touches it: one place, or the ends of the +/// shared stretch when the two lie on one line. +fn crossing(a: Point, b: Point, c: Point, d: Point) -> Vec<f64> { + let (r, s) = (b - a, d - c); + let denom = r.cross(s); + let qp = c - a; + let len2 = r.hypot2(); + if len2 == 0.0 { + return vec![]; + } + if denom.abs() <= 1e-12 * len2.sqrt() * s.hypot().max(1e-300) { + // Parallel: the ends of c→d on a→b when the two lie on one line. + if qp.cross(r).abs() > 1e-9 * len2.sqrt() { + return vec![]; + } + return [c, d].iter().map(|p| (*p - a).dot(r) / len2).filter(|t| (0.0..=1.0).contains(t)).collect(); + } + let t = qp.cross(s) / denom; + let u = qp.cross(r) / denom; + if (0.0..=1.0).contains(&t) && (0.0..=1.0).contains(&u) { vec![t] } else { vec![] } +} + +/// The distance from `p` to segment a→b. +fn distance(p: Point, a: Point, b: Point) -> f64 { + let ab = b - a; + let len2 = ab.hypot2(); + let t = if len2 > 0.0 { ((p - a).dot(ab) / len2).clamp(0.0, 1.0) } else { 0.0 }; + (p - (a + ab * t)).hypot() +} + +/// The stretch of the line `across` = `c` within `gap` of segment a→b, `None` when the line +/// passes farther away. With no gap it is where the segment meets the line. +fn near(a: Point, b: Point, vertical: bool, c: f64, gap: f64) -> Option<(f64, f64)> { + let ((u0, v0), (u1, v1)) = (uv(a, vertical), uv(b, vertical)); + if gap <= 0.0 { + if v0 == v1 { + return (v0 == c).then_some((u0.min(u1), u0.max(u1))); + } + if c < v0.min(v1) || c > v0.max(v1) { + return None; + } + let u = u0 + (c - v0) * (u1 - u0) / (v1 - v0); + return Some((u, u)); + } + let mut lo = f64::INFINITY; + let mut hi = f64::NEG_INFINITY; + let mut take = |x: f64, y: f64| { + lo = lo.min(x); + hi = hi.max(y); + }; + // The round ends. + for (u, v) in [(u0, v0), (u1, v1)] { + let dv = (c - v).abs(); + if dv <= gap { + let h = (gap * gap - dv * dv).max(0.0).sqrt(); + take(u - h, u + h); + } + } + // The band along the segment: points whose foot falls on it, within the gap of it. + let (du, dv) = (u1 - u0, v1 - v0); + let len = du.hypot(dv); + if len > 0.0 { + // Each condition is linear in the position x along the line: k·x + m ≥ 0. + let mut range = (f64::NEG_INFINITY, f64::INFINITY); + let mut keep = |k: f64, m: f64| { + if k == 0.0 { + if m < 0.0 { + range = (1.0, 0.0); + } + } else if k > 0.0 { + range.0 = range.0.max(-m / k); + } else { + range.1 = range.1.min(-m / k); + } + }; + // The foot at or after a: (x - u0)·du + (c - v0)·dv ≥ 0. + keep(du, -u0 * du + (c - v0) * dv); + // The foot at or before b. + keep(-du, u0 * du - (c - v0) * dv + len * len); + // Within the gap on either side: |(x - u0)·dv - (c - v0)·du| ≤ gap·len. + let cross0 = -u0 * dv - (c - v0) * du; + keep(-dv, -cross0 + gap * len); + keep(dv, cross0 + gap * len); + if range.0 <= range.1 { + take(range.0, range.1); + } + } + (lo <= hi).then_some((lo, hi)) +} + +/// How many weeding lines run each way. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct Counts { + pub horizontal: usize, + pub vertical: usize, +} + +/// The weeding lines across `frame`: `n.horizontal` horizontal and `n.vertical` vertical lines that +/// divide it evenly, each from one side of the frame to the other, left out where it is inside the +/// region's area or within `gap` of one of its outlines (`outline`). Pieces are in order along each +/// line, the horizontal lines first, top to bottom. Errs past [`MAX_NEAR`] pairs of an outline +/// segment and a line it comes within `gap` of, past [`MAX_NEAR`] crossings of the region's +/// outlines with the lines one way, or past `max_pieces` pieces. +pub(super) fn lines(region: &Region, outline: &[Segment], frame: Rect, n: Counts, gap: f64, max_pieces: usize) -> Result<Vec<Segment>, String> { + let mut out = vec![]; + let (layout, _) = Layout::of(region); + for (vertical, count) in [(false, n.horizontal), (true, n.vertical)] { + let ((u0, v0), (u1, v1)) = (uv(Point::new(frame.x0, frame.y0), vertical), uv(Point::new(frame.x1, frame.y1), vertical)); + let step = (v1 - v0) / (count as f64 + 1.0); + // A frame with no height (for horizontal lines) or no width has no waste to divide. + if step <= 0.0 { + continue; + } + // The lines (0-based) each outline segment comes within `gap` of: lines k (1-based) lie at + // v0 + k·step. The range is widened by a small tolerance so that a line whose position + // rounds just past a segment's end is still measured; `near` drops lines the segment misses. + let reach = |&(a, b): &Segment| { + let (va, vb) = (uv(a, vertical).1, uv(b, vertical).1); + let (lo, hi) = (va.min(vb) - gap, va.max(vb) + gap); + let first = ((lo - v0) / step - 1e-9).ceil().max(1.0); + let last = ((hi - v0) / step + 1e-9).floor().min(count as f64); + if step > 0.0 && first <= last { (first as usize - 1)..(last as usize) } else { 0..0 } + }; + // The outlines near each line, found once for all of them, by index into `outline`. + let pairs = outline.iter().fold(0usize, |sum, s| sum.saturating_add(reach(s).len())); + if pairs > MAX_NEAR { + return Err("the weeding lines pass too close to too many outline segments to measure; use fewer lines or a smaller gap".into()); + } + let mut near_line: Vec<Vec<usize>> = vec![vec![]; count]; + for (j, s) in outline.iter().enumerate() { + for k in reach(s) { + if let Some(list) = near_line.get_mut(k) { + list.push(j); + } + } + } + let crossed = crossings(region, vertical, v0, step, count)?; + for (i, segments) in near_line.iter().enumerate() { + let c = v0 + step * (i as f64 + 1.0); + let mut blocked = region.spans_on(&layout, crossed.get(i).map(Vec::as_slice).unwrap_or_default(), 0); + blocked.extend(segments.iter().filter_map(|&j| outline.get(j)).filter_map(|&(a, b)| near(a, b, vertical, c, gap))); + let mut from = u0; + let point = |u: f64| if vertical { Point::new(c, u) } else { Point::new(u, c) }; + for (a, b) in merged(blocked) { + if a - from >= MIN_PIECE && a <= u1 { + out.push((point(from), point(a.min(u1)))); + } + from = from.max(b); + } + if u1 - from >= MIN_PIECE { + out.push((point(from), point(u1))); + } + if out.len() > max_pieces { + return Err(format!("the weeding lines would be more than {max_pieces} pieces")); + } + } + } + Ok(out) +} diff --git a/crates/engine/src/cmd/addons/cutting/weed/tests.rs b/crates/engine/src/cmd/addons/cutting/weed/tests.rs new file mode 100644 index 0000000000..69114f8991 --- /dev/null +++ b/crates/engine/src/cmd/addons/cutting/weed/tests.rs @@ -0,0 +1,933 @@ +//! Tests for `addon.cutting.weed`: a weed box around the selected art and weeding lines across it +//! that stop at the art's outlines. + +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_color::Paint; +use vectorcraft_doc::{Appearance, Node, NodeKind}; +use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, Shape, shapes}; + +use super::super::super::super::pathops::text_outline; +use crate::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + s +} + +fn id_of(v: &Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { + id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()) +} + +fn line(s: &mut Session, pts: &[(f64, f64)]) -> NodeId { + let anchors: Vec<Value> = pts.iter().map(|(x, y)| json!({"x": x, "y": y})).collect(); + id_of(&s.execute("path.create", &json!({"anchors": anchors, "closed": false})).unwrap()) +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap(); +} + +fn node(s: &Session, id: NodeId) -> Node { + s.doc().unwrap().doc.node(id).cloned().unwrap() +} + +/// Runs Weed Box and Lines with `p` and gives the group it made. +fn weed(s: &mut Session, p: Value) -> (Value, Node) { + let r = s.execute("addon.cutting.weed", &p).unwrap(); + let g = node(s, id_of(&r)); + (r, g) +} + +/// The weed box's rectangle in group `g`, if it has one. +fn weed_box(g: &Node) -> Option<Rect> { + g.children().unwrap().iter().find(|c| c.name.as_deref() == Some("Weed Box")).map(|c| c.geometric_bounds().unwrap()) +} + +/// The weeding lines in group `g` as their two ends, rounded to 1/1000 pt. +fn lines(g: &Node) -> Vec<((f64, f64), (f64, f64))> { + let r = |v: f64| (v * 1000.0).round() / 1000.0; + g.children() + .unwrap() + .iter() + .filter(|c| c.name.is_none()) + .map(|c| match &c.kind { + NodeKind::Path { path, .. } => { + let a: Vec<Point> = path.anchors().map(|(_, _, a)| a.p).collect(); + assert_eq!(a.len(), 2, "a weeding line is one straight segment"); + ((r(a[0].x), r(a[0].y)), (r(a[1].x), r(a[1].y))) + } + other => panic!("not a path: {other:?}"), + }) + .collect() +} + +#[test] +fn a_weed_box_and_lines_go_around_a_rectangle() { + let mut s = session(); + rect(&mut s, 100.0, 100.0, 50.0, 40.0); + let undo = s.doc().unwrap().history.undo.len(); + let (r, g) = weed(&mut s, json!({"margin": 10})); + assert_eq!(g.name.as_deref(), Some("Weeding")); + assert_eq!(weed_box(&g), Some(Rect::new(90.0, 90.0, 160.0, 150.0))); + // One line each way through the middle, left out over the art. + assert_eq!( + lines(&g), + [((90.0, 120.0), (100.0, 120.0)), ((150.0, 120.0), (160.0, 120.0)), ((125.0, 90.0), (125.0, 100.0)), ((125.0, 140.0), (125.0, 150.0))] + ); + assert_eq!(r["lines"], json!(4)); + assert_eq!(r["box"], json!(weed_box_id(&g))); + // Stroked in Registration with no fill, selected, as one undo step that takes it all away. + for c in g.children().unwrap() { + assert_eq!(c.appearance.fill_paint(), Paint::None, "no fill"); + assert!(c.appearance.stroke_paint().is_registration()); + } + assert_eq!(s.doc().unwrap().selection.objects, [g.id]); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.node(g.id).is_none()); +} + +fn weed_box_id(g: &Node) -> u64 { + g.children().unwrap().iter().find(|c| c.name.as_deref() == Some("Weed Box")).unwrap().id.0 +} + +#[test] +fn lines_stop_at_the_outline_and_cross_the_hole_of_a_compound_path() { + let mut s = session(); + let outer = rect(&mut s, 100.0, 100.0, 100.0, 100.0); + let inner = rect(&mut s, 130.0, 130.0, 40.0, 40.0); + select(&mut s, &[outer, inner]); + let c = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap()); + // Both subpaths wind the same way, so the fill rule alone decides whether the inner one is a + // hole. + let same_way = |rule: FillRule| { + move |d: &mut vectorcraft_doc::Document, _: &mut vectorcraft_doc::Selection| -> Result<()> { + let Some(NodeKind::Compound { children, rule: r }) = d.node_mut(c).map(|n| &mut n.kind) else { panic!("not a compound path") }; + *r = rule; + let area = |n: &Node| match &n.kind { + NodeKind::Path { path, .. } => path.subpaths[0].signed_area(), + _ => panic!("not a path"), + }; + let outer = area(&children[0]).signum(); + for child in children.iter_mut() { + if area(child).signum() != outer + && let NodeKind::Path { path, .. } = &mut std::sync::Arc::make_mut(child).kind + { + path.reverse(); + } + } + Ok(()) + } + }; + s.edit("even-odd", same_way(FillRule::EvenOdd)).unwrap(); + select(&mut s, &[c]); + let (_, g) = weed(&mut s, json!({"margin": 10, "direction": "horizontal"})); + // The waste in the hole is cut too; the ring itself is not. + assert_eq!(lines(&g), [((90.0, 150.0), (100.0, 150.0)), ((130.0, 150.0), (170.0, 150.0)), ((200.0, 150.0), (210.0, 150.0))]); + // With the non-zero rule the inner subpath fills, and no line crosses it. + s.edit("non-zero", same_way(FillRule::NonZero)).unwrap(); + select(&mut s, &[c]); + let (_, g) = weed(&mut s, json!({"margin": 10, "direction": "horizontal"})); + assert_eq!(lines(&g), [((90.0, 150.0), (100.0, 150.0)), ((200.0, 150.0), (210.0, 150.0))]); +} + +#[test] +fn a_gap_keeps_the_lines_away_from_the_outline() { + let mut s = session(); + rect(&mut s, 100.0, 100.0, 50.0, 40.0); + let (_, g) = weed(&mut s, json!({"margin": 20, "gap": 5, "direction": "horizontal"})); + assert_eq!(weed_box(&g), Some(Rect::new(80.0, 80.0, 170.0, 160.0))); + assert_eq!(lines(&g), [((80.0, 120.0), (95.0, 120.0)), ((155.0, 120.0), (170.0, 120.0))]); + // The gap is a distance from the outline: a line passing 5 pt beside a corner, with a gap of + // 6, stops √11 pt short of the corner's height. + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 50.0, 40.0); + let b = rect(&mut s, 200.0, 60.0, 10.0, 120.0); + select(&mut s, &[a, b]); + let (_, g) = weed(&mut s, json!({"margin": 0, "gap": 6, "direction": "vertical"})); + assert_eq!(weed_box(&g), Some(Rect::new(100.0, 60.0, 210.0, 180.0))); + assert_eq!(lines(&g), [((155.0, 60.0), (155.0, 96.683)), ((155.0, 143.317), (155.0, 180.0))]); +} + +#[test] +fn a_box_with_no_height_gets_no_lines_across_it() { + // A horizontal line with no margin: the box is as flat as the line, and no weeding line runs + // along it. + let mut s = session(); + let l = line(&mut s, &[(100.0, 150.0), (200.0, 150.0)]); + let n = s.doc().unwrap().doc.node_count(); + assert!(s.execute("addon.cutting.weed", &json!({"margin": 0, "direction": "horizontal", "box": false})).is_err()); + assert_eq!(s.doc().unwrap().doc.node_count(), n, "nothing to add"); + select(&mut s, &[l]); + let (_, g) = weed(&mut s, json!({"margin": 0, "direction": "horizontal"})); + assert_eq!(weed_box(&g), Some(Rect::new(100.0, 150.0, 200.0, 150.0))); + assert_eq!(lines(&g), []); +} + +#[test] +fn an_open_path_stops_a_line_where_it_crosses() { + let mut s = session(); + line(&mut s, &[(100.0, 100.0), (100.0, 200.0)]); + let (_, g) = weed(&mut s, json!({"margin": 10, "direction": "horizontal", "gap": 2})); + assert_eq!(lines(&g), [((90.0, 150.0), (98.0, 150.0)), ((102.0, 150.0), (110.0, 150.0))]); +} + +#[test] +fn type_is_measured_by_its_glyph_outlines() { + let mut s = session(); + let t = id_of(&s.execute("text.create", &json!({"x": 100, "y": 200, "text": "OHO", "size": 72})).unwrap()); + let glyphs = match &node(&s, t).kind { + NodeKind::Text(t) => text_outline(t), + _ => panic!("not type"), + }; + let ink = glyphs.bounds().unwrap(); + let (_, g) = weed(&mut s, json!({"margin": 10, "count": 3, "direction": "horizontal"})); + let b = weed_box(&g).unwrap(); + for (got, want) in [(b.x0, ink.x0 - 10.0), (b.y0, ink.y0 - 10.0), (b.x1, ink.x1 + 10.0), (b.y1, ink.y1 + 10.0)] { + assert!((got - want).abs() < 0.05, "the box is 10 pt around the glyphs: {b:?} vs {ink:?}"); + } + // No piece of line runs over a glyph: each piece's middle is outside the ink. + let shape = glyphs.to_bezpath(); + let pieces = lines(&g); + assert!(pieces.len() > 3, "the letters break the lines: {pieces:?}"); + for ((x0, y0), (x1, y1)) in pieces { + let mid = Point::new((x0 + x1) / 2.0, (y0 + y1) / 2.0); + assert_eq!(shape.winding(mid), 0, "{mid:?} is outside the glyphs"); + } +} + +#[test] +fn a_clip_group_is_measured_by_what_shows() { + let mut s = session(); + let big = rect(&mut s, 0.0, 0.0, 400.0, 300.0); + let clip = rect(&mut s, 100.0, 100.0, 50.0, 40.0); + select(&mut s, &[big, clip]); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + let (_, g) = weed(&mut s, json!({"margin": 10})); + assert_eq!(weed_box(&g), Some(Rect::new(90.0, 90.0, 160.0, 150.0))); + assert_eq!(lines(&g).len(), 4); + // Art that shows only partly: the clip path's edge where the art is, and the art's edge + // inside the clip. + let mut s = session(); + let art = rect(&mut s, 120.0, 0.0, 100.0, 300.0); + let clip = rect(&mut s, 100.0, 100.0, 50.0, 40.0); + select(&mut s, &[art, clip]); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + let (_, g) = weed(&mut s, json!({"margin": 10, "direction": "horizontal"})); + assert_eq!(weed_box(&g), Some(Rect::new(110.0, 90.0, 160.0, 150.0))); + assert_eq!(lines(&g), [((110.0, 120.0), (120.0, 120.0)), ((150.0, 120.0), (160.0, 120.0))]); +} + +#[test] +fn a_group_as_the_clipping_path_clips_by_its_members() { + // Make Clipping Mask takes a path, a compound path or type; an opened file can clip by a + // group, as this one does. + let mut s = session(); + let parent = s.doc().unwrap().target_parent().unwrap(); + let id = s + .edit("clip group", |d, sel| { + let mut r = |x: f64, w: f64, y: f64, h: f64| { + Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, y, x + w, y + h)), Appearance::default())) + }; + let (a, b, art) = (r(100.0, 50.0, 100.0, 40.0), r(250.0, 50.0, 100.0, 40.0), r(0.0, 400.0, 0.0, 300.0)); + let clip = Arc::new(Node::group(d.alloc_id(), vec![a, b])); + let mut g = Node::group(d.alloc_id(), vec![clip, art]); + if let NodeKind::Group { clip, .. } = &mut g.kind { + *clip = true; + } + let id = g.id; + d.insert(parent, usize::MAX, g)?; + sel.set([id]); + Ok(id) + }) + .unwrap(); + select(&mut s, &[id]); + let (_, g) = weed(&mut s, json!({"margin": 10, "direction": "horizontal"})); + // The art shows through both rectangles, and the line is cut between them too. + assert_eq!(weed_box(&g), Some(Rect::new(90.0, 90.0, 310.0, 150.0))); + assert_eq!(lines(&g), [((90.0, 120.0), (100.0, 120.0)), ((150.0, 120.0), (250.0, 120.0)), ((300.0, 120.0), (310.0, 120.0))]); +} + +#[test] +fn lines_near_too_many_outline_segments_are_refused() { + let mut s = session(); + // A zigzag of 12,000 segments; with a gap as tall as the box, each of 1,000 lines comes near + // every segment. + let mut zigzag = BezPath::new(); + zigzag.move_to((100.0, 100.0)); + for i in 1..=12_000 { + zigzag.line_to((100.0 + f64::from(i) * 0.01, if i % 2 == 0 { 100.0 } else { 101.0 })); + } + let parent = s.doc().unwrap().target_parent().unwrap(); + let id = s + .edit("zigzag", |d, sel| { + let n = Node::path(d.alloc_id(), PathData::from_bezpath(&zigzag), Appearance::default()); + let id = n.id; + d.insert(parent, usize::MAX, n)?; + sel.set([id]); + Ok(id) + }) + .unwrap(); + select(&mut s, &[id]); + let n = s.doc().unwrap().doc.node_count(); + let e = s.execute("addon.cutting.weed", &json!({"count": 1000, "gap": 50, "direction": "horizontal"})).unwrap_err(); + assert!(e.to_string().contains("too many outline segments"), "{e}"); + assert_eq!(s.doc().unwrap().doc.node_count(), n); + // Fewer lines measure. + s.execute("addon.cutting.weed", &json!({"count": 10, "gap": 50, "direction": "horizontal"})).unwrap(); +} + +/// Adds a clip group, clipping path `clip` over `art` (both unpainted), and selects it. +fn clip_group(s: &mut Session, clip: PathData, art: PathData) -> NodeId { + let parent = s.doc().unwrap().target_parent().unwrap(); + let id = s + .edit("clip group", |d, sel| { + let clip = Arc::new(Node::path(d.alloc_id(), clip, Appearance::default())); + let art = Arc::new(Node::path(d.alloc_id(), art, Appearance::default())); + let mut g = Node::group(d.alloc_id(), vec![clip, art]); + if let NodeKind::Group { clip, .. } = &mut g.kind { + *clip = true; + } + let id = g.id; + d.insert(parent, usize::MAX, g)?; + sel.set([id]); + Ok(id) + }) + .unwrap(); + select(s, &[id]); + id +} + +#[test] +fn an_open_clipping_path_clips_as_if_closed() { + let mut s = session(); + let mut v = BezPath::new(); + v.move_to((100.0, 100.0)); + v.line_to((150.0, 200.0)); + v.line_to((200.0, 100.0)); + clip_group(&mut s, PathData::from_bezpath(&v), shapes::rectangle(Rect::new(0.0, 0.0, 400.0, 300.0))); + let (_, g) = weed(&mut s, json!({"margin": 10, "direction": "horizontal"})); + // The art shows inside the triangle the V closes; the line stops at its sides. + assert_eq!(weed_box(&g), Some(Rect::new(90.0, 90.0, 210.0, 210.0))); + assert_eq!(lines(&g), [((90.0, 150.0), (125.0, 150.0)), ((175.0, 150.0), (210.0, 150.0))]); +} + +#[test] +fn art_a_nested_clip_hides_adds_no_outline() { + // A clip group, clipping path A, holding a clip group whose clipping path B shows a small + // rectangle and hides a line that runs along A's bottom edge. + let mut s = session(); + let parent = s.doc().unwrap().target_parent().unwrap(); + let id = s + .edit("nested clips", |d, sel| { + let mut path = |p: PathData| Arc::new(Node::path(d.alloc_id(), p, Appearance::default())); + let mut l = BezPath::new(); + l.move_to((0.0, 200.0)); + l.line_to((400.0, 200.0)); + let (b, shown, hidden) = ( + path(shapes::rectangle(Rect::new(100.0, 100.0, 150.0, 140.0))), + path(shapes::rectangle(Rect::new(110.0, 110.0, 140.0, 130.0))), + path(PathData::from_bezpath(&l)), + ); + let a = path(shapes::rectangle(Rect::new(50.0, 50.0, 300.0, 200.0))); + let clipped = |mut g: Node| { + if let NodeKind::Group { clip, .. } = &mut g.kind { + *clip = true; + } + g + }; + let inner = Arc::new(clipped(Node::group(d.alloc_id(), vec![b, shown, hidden]))); + let outer = clipped(Node::group(d.alloc_id(), vec![a, inner])); + let id = outer.id; + d.insert(parent, usize::MAX, outer)?; + sel.set([id]); + Ok(id) + }) + .unwrap(); + select(&mut s, &[id]); + let (_, g) = weed(&mut s, json!({"margin": 10, "count": 0})); + assert_eq!(weed_box(&g), Some(Rect::new(100.0, 100.0, 150.0, 140.0)), "only the shown rectangle is measured"); +} + +#[test] +fn art_a_nested_clip_hides_counts_toward_the_clip_limit() { + // A clip group, clipping path A of 20,000 segments, holding a clip group whose small clipping + // path B shows a rectangle and hides a closed zigzag C of 20,000 points across every row of A. + // The inner group shows four outline pieces, but testing each piece of A for being inside it + // looks at all of C. + let mut s = session(); + let parent = s.doc().unwrap().target_parent().unwrap(); + let id = s + .edit("nested clips", |d, sel| { + let mut path = |p: BezPath| Arc::new(Node::path(d.alloc_id(), PathData::from_bezpath(&p), Appearance::default())); + let mut a = BezPath::new(); + a.move_to((0.0, 0.0)); + for i in 1..=20_000 { + a.line_to((f64::from(i) * 0.02, if i % 2 == 0 { 0.0 } else { 0.5 })); + } + a.line_to((400.0, 300.0)); + a.line_to((0.0, 300.0)); + a.close_path(); + let mut c = BezPath::new(); + c.move_to((300.0, 0.0)); + for i in 1..=20_000 { + c.line_to((300.0 + f64::from(i) * 0.002, if i % 2 == 0 { 0.0 } else { 300.0 })); + } + c.close_path(); + let b = path(shapes::rectangle(Rect::new(100.0, 100.0, 150.0, 140.0)).to_bezpath()); + let shown = path(shapes::rectangle(Rect::new(110.0, 110.0, 140.0, 130.0)).to_bezpath()); + let (a, c) = (path(a), path(c)); + let clipped = |mut g: Node| { + if let NodeKind::Group { clip, .. } = &mut g.kind { + *clip = true; + } + g + }; + let inner = Arc::new(clipped(Node::group(d.alloc_id(), vec![b, shown, c]))); + let outer = clipped(Node::group(d.alloc_id(), vec![a, inner])); + let id = outer.id; + d.insert(parent, usize::MAX, outer)?; + sel.set([id]); + Ok(id) + }) + .unwrap(); + select(&mut s, &[id]); + let n = s.doc().unwrap().doc.node_count(); + let e = s.execute("addon.cutting.weed", &json!({"margin": 10, "count": 0})).unwrap_err(); + assert!(e.to_string().contains("too many outline segments"), "{e}"); + assert_eq!(s.doc().unwrap().doc.node_count(), n); +} + +#[test] +fn art_selected_inside_a_clip_group_is_measured_by_what_shows() { + // The rectangle runs far outside the clipping path; selected on its own, it still shows only + // inside it. + let mut s = session(); + let clip = shapes::rectangle(Rect::new(100.0, 100.0, 150.0, 140.0)); + let g = clip_group(&mut s, clip, shapes::rectangle(Rect::new(120.0, 0.0, 220.0, 300.0))); + let art = node(&s, g).children().unwrap()[1].id; + select(&mut s, &[art]); + let (_, w) = weed(&mut s, json!({"margin": 10, "direction": "horizontal"})); + assert_eq!(weed_box(&w), Some(Rect::new(110.0, 90.0, 160.0, 150.0))); + assert_eq!(lines(&w), [((110.0, 120.0), (120.0, 120.0)), ((150.0, 120.0), (160.0, 120.0))]); + // The clipping path selected on its own is measured by the art it shows. + let clip_path = node(&s, g).children().unwrap()[0].id; + select(&mut s, &[clip_path]); + let (_, w) = weed(&mut s, json!({"margin": 10, "direction": "horizontal"})); + assert_eq!(weed_box(&w), Some(Rect::new(110.0, 90.0, 160.0, 150.0))); + // With the art selected too, or the group, the group is measured once. + let d = &s.doc().unwrap().doc; + let outline = |ids: &[NodeId]| super::geometry::Reader::new(d).read_ids(ids).unwrap().unwrap().outline().unwrap().len(); + assert_eq!(outline(&[clip_path, art]), outline(&[g])); + assert_eq!(outline(&[g, art, g]), outline(&[g])); +} + +#[test] +fn art_in_a_hidden_group_is_left_out() { + let mut s = session(); + let shown = rect(&mut s, 300.0, 300.0, 20.0, 20.0); + let a = rect(&mut s, 100.0, 100.0, 50.0, 40.0); + let b = rect(&mut s, 200.0, 100.0, 50.0, 40.0); + select(&mut s, &[a, b]); + let g = id_of(&s.execute("object.group", &json!({})).unwrap()); + s.edit("hide", |d, _| { + if let Some(n) = d.node_mut(g) { + n.visible = false; + } + Ok(()) + }) + .unwrap(); + select(&mut s, &[a]); + assert!(s.execute("addon.cutting.weed", &json!({})).is_err(), "nothing selected shows"); + select(&mut s, &[a, shown]); + let (_, w) = weed(&mut s, json!({"margin": 10})); + assert_eq!(weed_box(&w), Some(Rect::new(290.0, 290.0, 330.0, 330.0))); +} + +#[test] +fn art_in_a_hidden_group_is_not_measured() { + // Selected art in a hidden group with more outline points than the limit doesn't count toward + // it. + let mut s = session(); + let shown = rect(&mut s, 300.0, 300.0, 20.0, 20.0); + let mut p = BezPath::new(); + p.move_to((100.0, 100.0)); + for i in 1..=super::geometry::MAX_POINTS as u32 { + p.line_to((100.0 + f64::from(i) * 0.001, if i % 2 == 0 { 100.0 } else { 101.0 })); + } + let dense = insert(&mut s, |id| Node::path(id, PathData::from_bezpath(&p), Appearance::default())); + let g = id_of(&s.execute("object.group", &json!({})).unwrap()); + s.edit("hide", |d, _| { + if let Some(n) = d.node_mut(g) { + n.visible = false; + } + Ok(()) + }) + .unwrap(); + select(&mut s, &[dense, shown]); + let (_, w) = weed(&mut s, json!({"margin": 10})); + assert_eq!(weed_box(&w), Some(Rect::new(290.0, 290.0, 330.0, 330.0))); +} + +#[test] +fn clip_outlines_crossing_too_often_are_refused() { + // A clipping path whose 700 edges each run across the art, and open art whose 700 segments + // each run down across the clipping path: every pair crosses, and each of the 490,000 pieces + // of art between crossings would be tested against all 700 edges. + let zigzag = |across: bool| { + let mut p = BezPath::new(); + for i in 0..=700 { + let (along, side) = (100.0 + f64::from(i) * 0.25, if i % 2 == 0 { 100.0 } else { 300.0 }); + let pt = if across { (side, along) } else { (along, side) }; + if i == 0 { p.move_to(pt) } else { p.line_to(pt) } + } + p + }; + let mut clip = zigzag(true); + clip.close_path(); + let mut s = session(); + clip_group(&mut s, PathData::from_bezpath(&clip), PathData::from_bezpath(&zigzag(false))); + let n = s.doc().unwrap().doc.node_count(); + let e = s.execute("addon.cutting.weed", &json!({})).unwrap_err(); + assert!(e.to_string().contains("too many outline segments"), "{e}"); + assert_eq!(s.doc().unwrap().doc.node_count(), n); +} + +/// Each weeding line's stretches inside the art, found from the crossings indexed once for all the +/// lines, match those found by measuring the whole art along that line. +#[test] +fn indexed_crossings_find_the_same_stretches() { + let mut s = session(); + let mut ids = vec![]; + let outer = rect(&mut s, 100.0, 100.0, 100.0, 100.0); + let inner = rect(&mut s, 130.0, 130.0, 40.0, 40.0); + select(&mut s, &[outer, inner]); + ids.push(id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap())); + let big = rect(&mut s, 220.0, 50.0, 200.0, 200.0); + let window = id_of(&s.execute("shape.ellipse", &json!({"x": 260, "y": 80, "width": 90, "height": 120})).unwrap()); + select(&mut s, &[big, window]); + ids.push(id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap())); + ids.push(id_of(&s.execute("text.create", &json!({"x": 100, "y": 320, "text": "WEED 8", "size": 60})).unwrap())); + ids.push(line(&mut s, &[(90.0, 40.0), (450.0, 380.0)])); + let a = rect(&mut s, 300.0, 300.0, 30.0, 30.0); + let b = id_of(&s.execute("shape.ellipse", &json!({"x": 320, "y": 310, "width": 60, "height": 40})).unwrap()); + select(&mut s, &[a, b]); + ids.push(id_of(&s.execute("object.group", &json!({})).unwrap())); + let d = &s.doc().unwrap().doc; + let nodes: Vec<&Node> = ids.iter().filter_map(|id| d.node(*id)).collect(); + let region = super::geometry::Reader::new(d).read(&nodes).unwrap().unwrap(); + let (layout, _) = super::geometry::Layout::of(®ion); + let count = 97; + for vertical in [false, true] { + let (v0, v1) = (30.0, 400.0); + let step = (v1 - v0) / (count as f64 + 1.0); + let crossed = super::geometry::crossings(®ion, vertical, v0, step, count).unwrap(); + assert_eq!(crossed.len(), count); + let mut hit = 0; + for (k, line) in crossed.iter().enumerate() { + let c = v0 + step * (k as f64 + 1.0); + let want = region.spans(vertical, c); + hit += usize::from(!want.is_empty()); + assert_eq!(region.spans_on(&layout, line, 0), want, "line {k}, vertical {vertical}"); + } + assert!(hit > count / 2, "most lines cross the art ({hit})"); + } +} + +/// An outline that lies on a weeding line stops it even when the line's position rounds just past +/// the outline's: the one line across 0.1 to 0.5 lies at 0.1 + 0.2, which is 0.30000000000000004, +/// and (0.30000000000000004 - 0.1) / 0.2 is 1.0000000000000002. +#[test] +fn an_outline_on_a_rounded_line_position_stops_the_line() { + let doc = vectorcraft_doc::Document::new(800.0, 600.0); + let c = 0.1 + 0.2; + let mut p = BezPath::new(); + p.move_to((20.0, c)); + p.line_to((80.0, c)); + let n = Node::path(NodeId(1), PathData::from_bezpath(&p), Appearance::default()); + let region = super::geometry::Reader::new(&doc).read(&[&n]).unwrap().unwrap(); + let outline = region.outline().unwrap(); + let counts = super::geometry::Counts { horizontal: 1, vertical: 0 }; + let pieces = super::geometry::lines(®ion, &outline, Rect::new(0.0, 0.1, 100.0, 0.5), counts, 0.0, 100).unwrap(); + assert_eq!(pieces, [(Point::new(0.0, c), Point::new(20.0, c)), (Point::new(80.0, c), Point::new(100.0, c))]); +} + +#[test] +fn art_nested_too_deep_is_refused() { + // A rectangle inside `levels` groups, each holding the next. A document keeps none this deep, + // but the art symbol instances and live objects draw nests further. + let doc = vectorcraft_doc::Document::new(800.0, 600.0); + let nested = |levels: usize| { + let mut n = Node::path(NodeId(1), shapes::rectangle(Rect::new(100.0, 100.0, 150.0, 140.0)), Appearance::default()); + for i in 0..levels { + n = Node::group(NodeId(i as u64 + 2), vec![Arc::new(n)]); + } + n + }; + let read = |n: &Node| super::geometry::Reader::new(&doc).read(&[n]); + assert!(read(&nested(super::geometry::MAX_DEPTH)).unwrap().is_some()); + let e = read(&nested(super::geometry::MAX_DEPTH + 1)).unwrap_err(); + assert!(e.contains("nested more than"), "{e}"); +} + +#[test] +fn spacing_divides_the_box_into_strips_no_wider() { + let mut s = session(); + rect(&mut s, 100.0, 100.0, 10.0, 40.0); + // The box is 60 pt tall: three strips of 20 pt. + let (_, g) = weed(&mut s, json!({"margin": 10, "spacing": 25, "direction": "horizontal", "box": false})); + assert_eq!(weed_box(&g), None); + let ys: Vec<f64> = lines(&g).iter().map(|l| l.0.1).collect(); + assert_eq!(ys, [110.0, 110.0, 130.0, 130.0]); + let mut s = session(); + rect(&mut s, 100.0, 100.0, 10.0, 40.0); + assert!(s.execute("addon.cutting.weed", &json!({"spacing": 0.01})).is_err(), "too many lines"); +} + +#[test] +fn the_lines_take_a_swatch() { + let mut s = session(); + s.execute("swatch.new", &json!({"name": "Cut", "color": "cmyk 0 100 0 0", "spot": true})).unwrap(); + rect(&mut s, 100.0, 100.0, 50.0, 40.0); + let (_, g) = weed(&mut s, json!({"swatch": "Cut", "weight": 1})); + for c in g.children().unwrap() { + match c.appearance.stroke_paint() { + Paint::Solid { swatch, .. } => assert_eq!(swatch.as_deref(), Some("Cut")), + other => panic!("stroke {other:?}"), + } + assert_eq!(c.appearance.stroke_width(), 1.0); + } +} + +/// Adds the object `make` makes with a new id to the current layer, selects it and gives its id. +fn insert(s: &mut Session, make: impl FnOnce(NodeId) -> Node) -> NodeId { + let parent = s.doc().unwrap().target_parent().unwrap(); + let id = s + .edit("insert", |d, _| { + let n = make(d.alloc_id()); + let id = n.id; + d.insert(parent, usize::MAX, n)?; + Ok(id) + }) + .unwrap(); + select(s, &[id]); + id +} + +/// A 100 pt square turned 45° about (300, 300): a diamond 141.42 pt across. +fn diamond_xf() -> Affine { + Affine::translate((300.0, 300.0)) * Affine::rotate(std::f64::consts::FRAC_PI_4) * Affine::translate((-50.0, -50.0)) +} + +/// The weeding lines of `g` at height `y` (to 1/1000 pt). +fn at(g: &Node, y: f64) -> Vec<(f64, f64)> { + lines(g).into_iter().filter(|((_, y0), (_, y1))| *y0 == y && *y1 == y).map(|((x0, _), (x1, _))| (x0, x1)).collect() +} + +/// The diamond's weeding with three horizontal lines and a margin of 10: the box, and where the +/// first line's left piece ends. +fn diamond_weeding(s: &mut Session) -> (Rect, f64) { + let (_, g) = weed(s, json!({"margin": 10, "count": 3, "direction": "horizontal"})); + let b = weed_box(&g).unwrap(); + let y = ((b.y0 + b.height() / 4.0) * 1000.0).round() / 1000.0; + let first = at(&g, y); + assert_eq!(first.len(), 2, "{first:?}"); + (b, first[0].1) +} + +#[test] +fn an_image_is_measured_by_its_frame_as_turned() { + let mut s = session(); + let im = vectorcraft_doc::ImageObject { + key: "image".into(), + width: 100, + height: 100, + xf: diamond_xf(), + link: None, + placement: Default::default(), + pixels: None, + }; + insert(&mut s, |id| Node::new(id, NodeKind::Image(Box::new(im)))); + let (b, end) = diamond_weeding(&mut s); + let half = 50.0 * std::f64::consts::SQRT_2; + assert!((b.x0 - (290.0 - half)).abs() < 1e-3 && (b.y1 - (310.0 + half)).abs() < 1e-3, "{b:?}"); + // A quarter of the box down, the line meets the diamond's upper left edge, not its bounds. + let y = b.y0 + b.height() / 4.0; + assert!((end - (300.0 - (y - (300.0 - half)))).abs() < 0.01, "{end} at {y}"); +} + +#[test] +fn a_placed_file_is_measured_by_the_art_it_shows() { + let dir = crate::tests_links::Folder::new("weed-placed"); + // A file with a 60 × 40 artboard and a 20 pt wide rectangle at each side (hidden when + // `hidden`), placed centered on (200, 150) and selected. + let place = |s: &mut Session, name: &str, hidden: bool| { + let src = dir.file(name); + let mut d = vectorcraft_doc::Document::new(60.0, 40.0); + let layer = d.layers[0].id; + for x in [0.0, 40.0] { + let id = d.alloc_id(); + let look = Appearance::basic(Paint::solid(vectorcraft_color::Color::BLACK), Paint::None, 0.0); + let mut n = Node::path(id, shapes::rectangle(Rect::new(x, 0.0, x + 20.0, 40.0)), look); + n.visible = !hidden; + d.insert(Some(layer), 0, n).unwrap(); + } + crate::tests_links::write(&src, &vectorcraft_format::save_file(&d)); + let r = s.execute("file.place", &json!({"path": src, "at": [200, 150]})).unwrap(); + select(s, &[NodeId(r["ids"][0].as_u64().unwrap())]); + }; + let mut s = session(); + place(&mut s, "pair.vectorcraft", false); + let (_, g) = weed(&mut s, json!({"margin": 10, "direction": "horizontal"})); + // The rectangles lie at 170..190 and 210..230; the line runs between them too. + assert_eq!(at(&g, 150.0), [(160.0, 170.0), (190.0, 210.0), (230.0, 240.0)]); + // A file read but shown in a box with no size shows nothing, and its box isn't measured. + let id = NodeId(s.execute("file.place", &json!({"path": dir.file("pair.vectorcraft"), "at": [400, 150]})).unwrap()["ids"][0].as_u64().unwrap()); + s.edit("no size", |d, _| { + if let Some(NodeKind::PlacedDocument(p)) = d.node_mut(id).map(|n| &mut n.kind) { + (p.width, p.height) = (0.0, 0.0); + } + Ok(()) + }) + .unwrap(); + select(&mut s, &[id]); + let e = s.execute("addon.cutting.weed", &json!({})).unwrap_err(); + assert!(e.to_string().contains("has no outlines"), "{e}"); + // A file read with nothing showing has no outlines, and its box isn't measured instead. + let mut s = session(); + place(&mut s, "hidden.vectorcraft", true); + let e = s.execute("addon.cutting.weed", &json!({})).unwrap_err(); + assert!(e.to_string().contains("has no outlines"), "{e}"); + // A file whose art is an instance of a symbol of its own: the instance's art is measured. + let src = dir.file("symbol.vectorcraft"); + let mut d = vectorcraft_doc::Document::new(60.0, 40.0); + let look = Appearance::basic(Paint::solid(vectorcraft_color::Color::BLACK), Paint::None, 0.0); + let art = Node::path(NodeId(900), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 40.0)), look); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Bar".into(), art: Arc::new(art) }); + let (layer, id) = (d.layers[0].id, d.alloc_id()); + d.insert(Some(layer), 0, Node::new(id, NodeKind::SymbolInstance { symbol: "Bar".into(), xf: Affine::IDENTITY })).unwrap(); + crate::tests_links::write(&src, &vectorcraft_format::save_file(&d)); + let mut s = session(); + let r = s.execute("file.place", &json!({"path": src, "at": [200, 150]})).unwrap(); + select(&mut s, &[NodeId(r["ids"][0].as_u64().unwrap())]); + let (_, g) = weed(&mut s, json!({"margin": 10})); + let b = weed_box(&g).unwrap(); + assert!(b.x0 >= 160.0 - 1e-6 && b.x1 <= 240.0 + 1e-6 && b.width() < 41.0, "the bar, not the whole box: {b:?}"); +} + +#[test] +fn a_placed_file_that_cant_be_read_is_measured_by_its_box_as_turned() { + let mut s = session(); + let p = vectorcraft_doc::PlacedDocument { + link: vectorcraft_doc::LinkInfo::new("/no/such/file.pdf"), + key: "missing".into(), + bounding: false, + page_box: Default::default(), + width: 100.0, + height: 100.0, + xf: diamond_xf(), + placement: Default::default(), + }; + insert(&mut s, |id| Node::new(id, NodeKind::PlacedDocument(Box::new(p)))); + let (b, end) = diamond_weeding(&mut s); + let half = 50.0 * std::f64::consts::SQRT_2; + let y = b.y0 + b.height() / 4.0; + assert!((end - (300.0 - (y - (300.0 - half)))).abs() < 0.01, "{end} at {y}"); +} + +#[test] +fn a_symbol_instance_is_measured_by_its_art() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 20.0, 40.0); + let b = rect(&mut s, 140.0, 100.0, 20.0, 40.0); + select(&mut s, &[a, b]); + let inst = id_of(&s.execute("symbol.new", &json!({"name": "Pair"})).unwrap()); + select(&mut s, &[inst]); + let (_, g) = weed(&mut s, json!({"margin": 10, "direction": "horizontal"})); + // The line runs between the two rectangles too. + assert_eq!(at(&g, 120.0), [(90.0, 100.0), (120.0, 140.0), (160.0, 170.0)]); + // An instance of a symbol the document doesn't have draws nothing, and has no outlines. + s.edit("lose the symbol", |d, _| { + if let Some(NodeKind::SymbolInstance { symbol, .. }) = d.node_mut(inst).map(|n| &mut n.kind) { + *symbol = "Missing".into(); + } + Ok(()) + }) + .unwrap(); + select(&mut s, &[inst]); + let n = s.doc().unwrap().doc.node_count(); + let e = s.execute("addon.cutting.weed", &json!({})).unwrap_err(); + assert!(e.to_string().contains("has no outlines"), "{e}"); + assert_eq!(s.doc().unwrap().doc.node_count(), n); + let shown = rect(&mut s, 300.0, 300.0, 20.0, 20.0); + select(&mut s, &[inst, shown]); + let (_, g) = weed(&mut s, json!({"margin": 10})); + assert_eq!(weed_box(&g), Some(Rect::new(290.0, 290.0, 330.0, 330.0))); +} + +#[test] +fn a_blend_is_measured_by_the_art_it_draws() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 20.0, 40.0); + let b = rect(&mut s, 200.0, 100.0, 20.0, 40.0); + let blend = id_of(&s.execute("object.blend.make", &json!({"ids": [a.0, b.0], "steps": 1})).unwrap()); + select(&mut s, &[blend]); + let (_, g) = weed(&mut s, json!({"margin": 10, "direction": "horizontal"})); + // The step halfway between the two rectangles stops the line too. + assert_eq!(at(&g, 120.0), [(90.0, 100.0), (120.0, 150.0), (170.0, 200.0), (220.0, 230.0)]); +} + +#[test] +fn the_group_goes_on_top_of_the_current_layer_and_hidden_layers_are_left_out() { + let mut s = session(); + let first = s.doc().unwrap().doc.layers[0].id; + let hidden = rect(&mut s, 100.0, 100.0, 50.0, 40.0); + let art = id_of(&s.execute("layer.new", &json!({"name": "Art"})).unwrap()); + let shown = rect(&mut s, 300.0, 300.0, 20.0, 20.0); + let below = rect(&mut s, 400.0, 400.0, 20.0, 20.0); + s.edit("hide", |d, _| { + if let Some(n) = d.node_mut(first) { + n.visible = false; + } + Ok(()) + }) + .unwrap(); + select(&mut s, &[hidden]); + assert!(s.execute("addon.cutting.weed", &json!({})).is_err(), "art in a hidden layer doesn't show"); + select(&mut s, &[hidden, shown]); + let (_, g) = weed(&mut s, json!({"margin": 10})); + assert_eq!(weed_box(&g), Some(Rect::new(290.0, 290.0, 330.0, 330.0))); + let d = &s.doc().unwrap().doc; + assert_eq!(d.parent_of(g.id), Some(art)); + assert_eq!(d.node(art).unwrap().children().unwrap().last().map(|c| c.id), Some(g.id), "on top"); + // A hidden object selected on its own shows nothing. + s.edit("hide", |d, _| { + if let Some(n) = d.node_mut(below) { + n.visible = false; + } + Ok(()) + }) + .unwrap(); + select(&mut s, &[below]); + assert!(s.execute("addon.cutting.weed", &json!({})).is_err(), "a hidden object doesn't show"); +} + +#[test] +fn the_group_goes_outside_a_clip_group_edited_in_isolation() { + let mut s = session(); + let layer = s.doc().unwrap().doc.layers[0].id; + let g = clip_group(&mut s, shapes::rectangle(Rect::new(100.0, 100.0, 150.0, 140.0)), shapes::rectangle(Rect::new(120.0, 0.0, 220.0, 300.0))); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + let art = node(&s, g).children().unwrap()[1].id; + select(&mut s, &[art]); + let (_, w) = weed(&mut s, json!({"margin": 10, "direction": "horizontal"})); + // The clipping path would hide the lines and the box around the art inside it. + let d = &s.doc().unwrap().doc; + assert_eq!(d.parent_of(w.id), Some(layer)); + assert_eq!(weed_box(&w), Some(Rect::new(110.0, 90.0, 160.0, 150.0))); + // A plain group edited in isolation inside a clip group: the group goes outside the clip group. + let mut s = session(); + let parent = s.doc().unwrap().target_parent().unwrap(); + let (inner, art) = s + .edit("clip group around a group", |d, _| { + let clip = Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(100.0, 100.0, 150.0, 140.0)), Appearance::default())); + let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(120.0, 0.0, 220.0, 300.0)), Appearance::default()); + let art_id = art.id; + let inner = Node::group(d.alloc_id(), vec![Arc::new(art)]); + let inner_id = inner.id; + let mut g = Node::group(d.alloc_id(), vec![clip, Arc::new(inner)]); + if let NodeKind::Group { clip, .. } = &mut g.kind { + *clip = true; + } + d.insert(parent, usize::MAX, g)?; + Ok((inner_id, art_id)) + }) + .unwrap(); + s.execute("object.isolate", &json!({"id": inner.0})).unwrap(); + select(&mut s, &[art]); + let (_, w) = weed(&mut s, json!({"margin": 10, "direction": "horizontal"})); + assert_eq!(s.doc().unwrap().doc.parent_of(w.id), parent); + assert_eq!(weed_box(&w), Some(Rect::new(110.0, 90.0, 160.0, 150.0))); +} + +/// Adds one path of `count` open vertical subpaths 2 pt apart, from (100, 100) down to y = 200. +fn bars(s: &mut Session, count: u32) -> NodeId { + let mut p = BezPath::new(); + for i in 0..count { + let x = 100.0 + f64::from(i) * 2.0; + p.move_to((x, 100.0)); + p.line_to((x, 200.0)); + } + insert(s, |id| Node::path(id, PathData::from_bezpath(&p), Appearance::default())) +} + +#[test] +fn more_than_the_most_pieces_of_line_is_refused() { + // 1,000 lines each cut into 100 pieces by 101 bars: as many as one run adds. + let mut s = session(); + bars(&mut s, 101); + let r = s.execute("addon.cutting.weed", &json!({"margin": 0, "count": 1000, "direction": "horizontal"})).unwrap(); + assert_eq!(r["lines"], json!(super::MAX_PIECES)); + // One bar more makes 1,000 pieces more. + let mut s = session(); + bars(&mut s, 102); + let n = s.doc().unwrap().doc.node_count(); + let e = s.execute("addon.cutting.weed", &json!({"margin": 0, "count": 1000, "direction": "horizontal"})).unwrap_err(); + assert!(e.to_string().contains("more than 100000 pieces"), "{e}"); + assert_eq!(s.doc().unwrap().doc.node_count(), n); +} + +#[test] +fn art_with_more_than_the_most_outline_points_is_refused() { + // An open zigzag of `points` points: one subpath, measured by its points. + let zigzag = |s: &mut Session, points: u32| { + let mut p = BezPath::new(); + p.move_to((100.0, 100.0)); + for i in 1..points { + p.line_to((100.0 + f64::from(i) * 0.001, if i % 2 == 0 { 100.0 } else { 101.0 })); + } + insert(s, |id| Node::path(id, PathData::from_bezpath(&p), Appearance::default())); + }; + let mut s = session(); + zigzag(&mut s, super::geometry::MAX_POINTS as u32); + s.execute("addon.cutting.weed", &json!({"count": 0})).unwrap(); + let mut s = session(); + zigzag(&mut s, super::geometry::MAX_POINTS as u32 + 1); + let e = s.execute("addon.cutting.weed", &json!({"count": 0})).unwrap_err(); + assert!(e.to_string().contains("too many outline points"), "{e}"); +} + +#[test] +fn bad_params_and_an_empty_selection_are_refused() { + let mut s = session(); + rect(&mut s, 100.0, 100.0, 50.0, 40.0); + for p in [ + json!({"margin": -1}), + json!({"gap": "x"}), + json!({"count": 1.5}), + json!({"count": 1001}), + json!({"count": 2, "spacing": 10}), + json!({"spacing": 0}), + json!({"direction": "diagonal"}), + json!({"box": "yes"}), + json!({"weight": 0}), + json!({"swatch": "no such swatch"}), + json!({"swatch": 3}), + json!({"box": false, "count": 0}), + ] { + let n = s.doc().unwrap().doc.node_count(); + assert!(s.execute("addon.cutting.weed", &p).is_err(), "{p}"); + assert_eq!(s.doc().unwrap().doc.node_count(), n, "nothing added for {p}"); + } + // The same art with good params is weeded; with nothing selected it is refused. + s.execute("addon.cutting.weed", &json!({"count": 2, "gap": "1 mm"})).unwrap(); + s.execute("select.set", &json!({"ids": []})).unwrap(); + assert!(s.execute("addon.cutting.weed", &json!({})).is_err()); +} diff --git a/crates/engine/src/cmd/addons/document.rs b/crates/engine/src/cmd/addons/document.rs index 654138a1dd..68681b50fa 100644 --- a/crates/engine/src/cmd/addons/document.rs +++ b/crates/engine/src/cmd/addons/document.rs @@ -132,8 +132,10 @@ fn export_all_open(s: &mut Session, p: &Value) -> Result<Value> { let active = s.active; for i in 0..s.docs.len() { // Each document in turn is the one Save a Copy writes; switching tabs this way leaves every - // document's tool and interaction alone, and the active one comes back below. + // document's tool and interaction alone, and the active one comes back below. Its colors + // are written through its own profiles. s.active = Some(i); + s.sync_front_profiles(); let Ok(st) = s.doc() else { continue }; let title = st.doc.title.clone(); let stem = fileio::file_stem(st.path.as_deref().unwrap_or(&title)); @@ -160,6 +162,7 @@ fn export_all_open(s: &mut Session, p: &Value) -> Result<Value> { } } s.active = active; + s.sync_front_profiles(); Ok(json!({ "files": files, "failed": failed, "format": format.id })) } diff --git a/crates/engine/src/cmd/addons/document/batch_trace.rs b/crates/engine/src/cmd/addons/document/batch_trace.rs index 61e59fc54f..084bd5ca27 100644 --- a/crates/engine/src/cmd/addons/document/batch_trace.rs +++ b/crates/engine/src/cmd/addons/document/batch_trace.rs @@ -113,7 +113,8 @@ pub(super) fn batch_trace_folder(s: &mut Session, p: &Value) -> Result<Value> { for path in &files { let opened_before = s.documents().len(); let one = |s: &mut Session| -> Result<String> { - s.execute("document.open", &json!({ "path": path }))?; + // A PSD or PSB is traced as its merged image, not as the first of its layers. + s.execute("document.open", &json!({ "path": path, "layers": false }))?; s.execute("select.all", &json!({}))?; s.execute(trace, &json!({ "preset": preset }))?; let stem = fileio::file_stem(path); diff --git a/crates/engine/src/cmd/addons/document/tests.rs b/crates/engine/src/cmd/addons/document/tests.rs index b0fbb41422..43e86caf52 100644 --- a/crates/engine/src/cmd/addons/document/tests.rs +++ b/crates/engine/src/cmd/addons/document/tests.rs @@ -333,6 +333,34 @@ fn batch_trace_folder_traces_and_saves_each_image() { let _ = std::fs::remove_dir_all(&dir); } +/// A layered PSD is traced as its merged image: a white layer under a black square gives the +/// square's shape, not a trace of the white layer alone. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn batch_trace_folder_traces_a_layered_psd_as_its_merged_image() { + const C: &str = "addon.document.batchTraceFolder"; + let dir = folder("batch-trace-psd"); + let (src, out) = (dir.join("in"), dir.join("out")); + std::fs::create_dir_all(&src).unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 24, "height": 24})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 24, "height": 24})).unwrap(); + s.execute("layer.new", &json!({"name": "Square"})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 6, "y": 6, "width": 12, "height": 12})).unwrap(); + let psd = s.execute("document.export", &json!({"format": "psd"})).unwrap(); + std::fs::write(src.join("two.psd"), vectorcraft_format::base64_decode(psd["dataBase64"].as_str().unwrap()).unwrap()).unwrap(); + let r = + s.execute(C, &json!({"folder": src, "destinationFolder": out, "format": "svg", "preset": "Black and White Logo", "expand": true})).unwrap(); + assert_eq!(r["traced"].as_array().unwrap().len(), 1, "{r}"); + let svg = std::fs::read_to_string(out.join("two.svg")).unwrap(); + assert!(svg.contains("fill=\"#000000\""), "the black square is traced: {svg}"); + let _ = std::fs::remove_dir_all(&dir); +} + /// Batch Trace Folder rejects optional values with the wrong type before opening images. #[cfg(not(target_arch = "wasm32"))] #[test] diff --git a/crates/engine/src/cmd/addons/image.rs b/crates/engine/src/cmd/addons/image.rs new file mode 100644 index 0000000000..898c28c707 --- /dev/null +++ b/crates/engine/src/cmd/addons/image.rs @@ -0,0 +1,649 @@ +//! Image Tools (`addon.image.*`), a built-in add-on. Remove Background makes the background of the +//! selected images transparent in their own pixels, as one undo step. The background is the most +//! common color along an image's edges, the average of its four corners, or colors the caller +//! picks. It is cleared where it reaches in from an edge, or wherever it is. The work is done here, +//! on the pixels; nothing is sent anywhere. Color Mask ([`mask`]) hides colors matched the same +//! way while the image keeps its pixels. They are VectorCraft additions. Its submenu (Object › +//! Plug-ins › Image Tools) and dialogs are the UI's. + +mod mask; +#[cfg(test)] +mod tests; + +pub(crate) use mask::refresh as refresh_color_masks; + +use std::collections::{HashMap, HashSet}; +use std::io::Cursor; +use std::sync::{Arc, Weak}; + +use image::{DynamicImage, ImageBuffer, LumaA, Rgba}; +use serde_json::{Value, json}; +use vectorcraft_color::Color; +use vectorcraft_doc::{ImageBlob, ImageObject, NodeId, NodeKind}; +use vectorcraft_geom::Affine; + +use super::super::fileio::{MAX_RASTER_ALLOC, ppi}; +use super::super::menucmds::has_image; +use super::super::paint::{PROCESS_ON_TRANSPARENCY, colorized_with_process}; +use super::super::{CommandSpec, Result, Session, bad, checked_ids_param, cmd, hex_with_alpha, number_or, switch_or, text_param}; + +/// Remove Background's command. +pub const REMOVE_BACKGROUND: &str = "addon.image.removeBackground"; +const C: &str = REMOVE_BACKGROUND; + +/// The most colors `colors` lists. +const MAX_COLORS: usize = 16; + +/// Bytes a pixel takes while it is worked on, beside its pixels: its level, whether the edge search +/// reached it, and its place in the search's stack (4 bytes, twice that while the stack grows). +const WORK_BYTES: u64 = 10; + +pub fn specs() -> Vec<CommandSpec> { + let mut v = vec![cmd!( + "addon.image.removeBackground", + "Remove Background…", + ["Object", "Plug-ins", "Image Tools"], + None, + "{background?: \"edges\" (default: the most common color along the image's edges; nothing is cleared when the edges hold at least as many clear pixels as pixels of that color) | \"corners\" (the average of the image's four corner pixels that are not clear; nothing is cleared when all four are clear) | \"colors\" (the colors in `colors`), colors?: [color…] or one string of them split by commas or spaces (1 to 16 colors, each a hex color \"#rrggbb\" or \"#rgb\" with or without the # or one of black, white, red, green and blue; needed with background: colors, and checked but not used with edges or corners), contiguous?: bool (true: only background pixels that reach in from an edge are cleared; false: they are cleared wherever they are; true), match?: \"distance\" (default: a color's RGB distance from a background color) | \"channels\" (its largest difference on one of red, green and blue), tolerance?: 0..100 (with distance, % of the largest RGB distance; with channels, % of 255 steps on one channel; a pixel this near a background color is cleared; 10), softness?: 0..100 (% past the tolerance over which pixels fade from cleared to kept; 10), ids?: [id…] (default: the selected images)} make the background of each image transparent in its own pixels, as one undo step: the image stays an image, embedded as a PNG with an alpha channel at the depth of its pixels (16-bit images keep 16 bits and grayscale images stay gray) with the source's color profile and resolution, and a linked image is embedded; a CMYK image, a linked image that shows its preview (embed or relink it first), an image too large to change, a result with no pixel left, and a grayscale image colorized with a process color (which can't colorize gray pixels with transparency) are refused, and an image whose pixels do not change is left as it is (no undo step when none changes) → {changed: the images changed, ids, cleared: the pixels made fully clear in them}", + has_image, + remove_background + )]; + v.extend(mask::specs()); + v +} + +/// Where the background's colors come from. +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum Background { + /// The most common color along the image's edges. + Edges, + /// The average of the image's four corner pixels that are not clear. + Corners, + /// These colors. + Colors(Vec<[u8; 3]>), +} + +/// How near a color is to a background color. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum Match { + /// The RGB distance, as a percentage of the largest one (black to white). + Distance, + /// The largest difference on one of red, green and blue, as a percentage of a channel's range. + Channels, +} + +/// What Remove Background clears: the background, whether only where it reaches in from an edge, +/// and how near a color must be to it (a percentage, measured as `measure` says) to be cleared, and +/// to fade out past that. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct Settings { + pub background: Background, + pub contiguous: bool, + pub measure: Match, + pub tolerance: f64, + pub softness: f64, +} + +impl Settings { + /// The settings `p` gives to command `cmd`, each checked. + fn read(p: &Value, cmd: &str) -> Result<Self> { + let percent = |key: &str| -> Result<f64> { + let v = number_or(p, key, 10.0, cmd)?; + if v.is_finite() && (0.0..=100.0).contains(&v) { Ok(v) } else { Err(bad(cmd, format!("`{key}` must be from 0 to 100"))) } + }; + let (tolerance, softness) = (percent("tolerance")?, percent("softness")?); + let colors = match p.get("colors") { + None | Some(Value::Null) => None, + Some(v) => Some(colors(v, cmd)?), + }; + let background = match text_param(p, "background", cmd)? { + None | Some("edges") => Background::Edges, + Some("corners") => Background::Corners, + Some("colors") => Background::Colors(colors.ok_or_else(|| colors_error(cmd))?), + Some(_) => return Err(bad(cmd, "`background` must be edges, corners or colors")), + }; + let measure = match text_param(p, "match", cmd)? { + None | Some("distance") => Match::Distance, + Some("channels") => Match::Channels, + Some(_) => return Err(bad(cmd, "`match` must be distance or channels")), + }; + let contiguous = switch_or(p, "contiguous", true, cmd)?; + Ok(Self { background, contiguous, measure, tolerance, softness }) + } +} + +fn colors_error(cmd: &str) -> crate::EngineError { + bad(cmd, "`colors` must list 1 to 16 colors, each hex (#rrggbb or #rgb) or black, white, red, green or blue") +} + +/// The colors `v` lists to command `cmd`: an array of strings, or one string of them split by +/// commas or spaces. Each is read as [`Color::from_hex`] reads it; one with an alpha part is refused. +fn colors(v: &Value, cmd: &str) -> Result<Vec<[u8; 3]>> { + // One past the most is enough to tell a list that is too long. + let texts: Vec<&str> = match v { + Value::String(s) => s.split([',', ' ', '\t', '\n']).filter(|t| !t.is_empty()).take(MAX_COLORS + 1).collect(), + Value::Array(a) => a.iter().take(MAX_COLORS + 1).map(Value::as_str).collect::<Option<_>>().ok_or_else(|| colors_error(cmd))?, + _ => return Err(colors_error(cmd)), + }; + if texts.is_empty() || texts.len() > MAX_COLORS { + return Err(colors_error(cmd)); + } + texts.into_iter().map(|t| rgb8(t).ok_or_else(|| colors_error(cmd))).collect() +} + +/// The 8-bit RGB of the color `t` writes. +fn rgb8(t: &str) -> Option<[u8; 3]> { + if hex_with_alpha(t) { + return None; + } + let [r, g, b] = Color::from_hex(t)?.to_rgb_uncalibrated(); + Some([r, g, b].map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8)) +} + +fn remove_background(s: &mut Session, p: &Value) -> Result<Value> { + let settings = Settings::read(p, C)?; + // A preview step keeps the pixels it decodes for the next step; other runs keep none. + let mut kept = std::mem::take(&mut s.decoded_images); + let previewing = s.previewing; + let found = changes(s, p, &settings, previewing.then_some(&mut kept)); + s.decoded_images = kept; + let changes = found?; + let ids: Vec<u64> = changes.iter().map(|(id, ..)| id.0).collect(); + let made_clear: u64 = changes.iter().map(|(_, out, _)| out.cleared).sum(); + if !changes.is_empty() { + s.edit("Remove Background", |d, _| { + for (id, out, xf) in changes { + let key = out.blob.content_key(); + d.images.entry(key.clone()).or_insert(out.blob); + if let Some(NodeKind::Image(im)) = d.node_mut(id).map(|n| &mut n.kind) { + im.key = key; + (im.width, im.height, im.xf) = (out.width, out.height, xf); + im.link = None; + } + } + Ok(()) + })?; + } + Ok(json!({ "changed": ids.len(), "ids": ids, "cleared": made_clear })) +} + +/// The images `p` names (`ids`, or the selected images) whose pixels change, each with its pixels +/// cleared as `settings` say and the transform that keeps its place and size. Decoded pixels are +/// taken from and kept in `kept` when it is given. +fn changes(s: &Session, p: &Value, settings: &Settings, mut kept: Option<&mut DecodedImages>) -> Result<Vec<(NodeId, Cleared, Affine)>> { + let images = images(s, p, C)?; + // The result has an alpha channel, which a grayscale image colorized with a process color + // can't take. The pixels that are cleared are checked, the image's own, not the ones a color + // mask shows. + let st = s.doc()?; + for (id, _, blob) in &images { + if blob.gray_source().is_some() && st.doc.node(*id).is_some_and(|n| colorized_with_process(&st.doc, n)) { + return Err(bad(C, PROCESS_ON_TRANSPARENCY)); + } + } + // Each image's pixels once, however many objects show them. + let mut cleared: HashMap<&str, Option<Cleared>> = HashMap::new(); + let mut changes = vec![]; + for (id, im, blob) in images { + let out = match cleared.get(im.key.as_str()) { + Some(out) => out.clone(), + None => { + let out = clear(blob, settings, kept.as_deref_mut(), C)?; + cleared.insert(&im.key, out.clone()); + out + } + }; + if let Some(out) = out { + // A file read at another size than the object's keeps the object's place and size. + let xf = if (out.width, out.height) == (im.width, im.height) { + im.xf + } else { + im.xf * Affine::scale_non_uniform(f64::from(im.width) / f64::from(out.width), f64::from(im.height) / f64::from(out.height)) + }; + changes.push((id, out, xf)); + } + } + Ok(changes) +} + +/// The image objects command `cmd` acts on (`ids`, each once, or the selected images), each with +/// its pixels, all checked before any is decoded: an object that is not an image, missing pixels, +/// a linked image that shows its preview and a CMYK image are errors, as is no image at all. +fn images<'a>(s: &'a Session, p: &Value, cmd: &str) -> Result<Vec<(NodeId, &'a ImageObject, &'a ImageBlob)>> { + let st = s.doc()?; + let mut images = vec![]; + for id in targets(s, p, cmd)? { + let Some(NodeKind::Image(im)) = st.doc.node(id).map(|n| &n.kind) else { continue }; + let blob = st.doc.images.get(&im.key).ok_or_else(|| bad(cmd, "the image's pixels are missing"))?; + // The preview stands in for a file that hasn't been read, or that is kept at its preview. + if im.link.is_some() && blob.is_proxy() { + return Err(bad(cmd, "the linked image shows its preview: embed or relink it first")); + } + if blob.is_cmyk() { + return Err(cmyk_refusal(cmd)); + } + images.push((id, &**im, blob)); + } + Ok(images) +} + +/// The image objects command `cmd` acts on: `ids`, each once, or the selected images. An object in +/// `ids` that is not an image is an error, as is no image at all. +fn targets(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> { + let st = s.doc()?; + let ids: Vec<NodeId> = if p.get("ids").is_some_and(|v| !v.is_null()) { + // Each image once, however often `ids` names it. + let mut given = HashSet::new(); + let ids: Vec<NodeId> = checked_ids_param(s, p, "ids", cmd)?.into_iter().filter(|id| given.insert(*id)).collect(); + if let Some(id) = ids.iter().find(|id| !matches!(st.doc.node(**id).map(|n| &n.kind), Some(NodeKind::Image(_)))) { + return Err(bad(cmd, format!("object {} is not an image", id.0))); + } + ids + } else { + st.selection.objects.iter().copied().filter(|id| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Image(_)))).collect() + }; + if ids.is_empty() { + return Err(bad(cmd, "select an image")); + } + Ok(ids) +} + +/// Whether `cmd` is one of Color Mask's commands, which hide pixels instead of clearing them. +fn masks(cmd: &str) -> bool { + matches!(cmd, mask::COLOR_MASK | mask::REMOVE_COLOR_MASK | mask::APPLY_COLOR_MASK) +} + +/// Command `cmd`'s refusal of a CMYK image. +fn cmyk_refusal(cmd: &str) -> crate::EngineError { + if masks(cmd) { bad(cmd, "a CMYK image can't take a color mask") } else { bad(cmd, "a CMYK image has no transparency to set") } +} + +/// An image with its background cleared: its PNG, its size in pixels, and how many of its pixels +/// were made fully clear. +#[derive(Clone, Debug)] +pub(crate) struct Cleared { + pub blob: ImageBlob, + pub width: u32, + pub height: u32, + pub cleared: u64, +} + +/// An image's pixels as straight RGBA, at 8 or 16 bits a sample. +#[derive(Clone)] +enum Pixels { + Eight(image::RgbaImage), + Sixteen(ImageBuffer<Rgba<u16>, Vec<u16>>), +} + +/// The most bytes of decoded pixels and ICC profiles [`DecodedImages`] keeps (128 MiB, or 32 MiB in +/// the web app). +const KEEP_BYTES: u64 = MAX_RASTER_ALLOC / 16; + +/// The images Remove Background decoded during an interaction's preview steps, the most recently +/// used first, at most [`KEEP_BYTES`] in all. The next preview step runs the command again on the +/// same bytes and takes their pixels from here instead of decoding them again. The session holds +/// it and empties it when the interaction ends (OK or Cancel). A run that is not a preview step +/// does not read or fill it. +#[derive(Default)] +pub(crate) struct DecodedImages(Vec<Decoded>); + +/// An image decoded by [`clear`]: the bytes it was decoded from (held weakly, so they are not kept +/// alive for it, and an entry whose bytes are gone is dropped), its pixels, whether it was gray, +/// and its ICC profile. +struct Decoded { + source: Weak<Vec<u8>>, + pixels: Arc<Pixels>, + gray: bool, + icc: Option<Vec<u8>>, +} + +#[cfg(test)] +thread_local! { + /// How many times this thread decoded an image in [`clear`]. + pub(crate) static DECODES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; +} + +impl DecodedImages { + /// Drops every image kept. + pub(crate) fn empty(&mut self) { + self.0.clear(); + } + + /// How many images are kept. + #[cfg(test)] + pub(crate) fn len(&self) -> usize { + self.0.len() + } + + /// The pixels, gray flag and ICC profile kept for `bytes`, if they are kept. Images whose bytes + /// are gone are dropped first. + fn get(&mut self, bytes: &Arc<Vec<u8>>) -> Option<(Arc<Pixels>, bool, Option<Vec<u8>>)> { + self.0.retain(|d| d.source.strong_count() > 0); + let at = self.0.iter().position(|d| std::ptr::eq(d.source.as_ptr(), Arc::as_ptr(bytes)))?; + let d = self.0.remove(at); + let found = (Arc::clone(&d.pixels), d.gray, d.icc.clone()); + self.0.insert(0, d); + Some(found) + } + + /// Keeps `pixels` decoded from `bytes` first, in place of anything kept for the same bytes, and + /// drops images whose bytes are gone and the least recently used past [`KEEP_BYTES`]. + fn keep(&mut self, bytes: &Arc<Vec<u8>>, pixels: Arc<Pixels>, gray: bool, icc: Option<Vec<u8>>) { + self.0.retain(|d| d.source.strong_count() > 0 && !std::ptr::eq(d.source.as_ptr(), Arc::as_ptr(bytes))); + self.0.insert(0, Decoded { source: Arc::downgrade(bytes), pixels, gray, icc }); + let mut total = 0u64; + self.0.retain(|d| { + total = total.saturating_add(d.bytes()); + total <= KEEP_BYTES + }); + } +} + +impl Decoded { + /// How many bytes the entry keeps: its pixels and its ICC profile. + fn bytes(&self) -> u64 { + self.pixels.bytes().saturating_add(self.icc.as_ref().map_or(0, |icc| icc.len() as u64)) + } +} + +impl Pixels { + /// How many bytes the pixels take. + fn bytes(&self) -> u64 { + match self { + Self::Eight(img) => img.as_raw().len() as u64, + Self::Sixteen(img) => img.as_raw().len() as u64 * 2, + } + } + + /// The width and height in pixels. + fn dimensions(&self) -> (u32, u32) { + match self { + Self::Eight(img) => img.dimensions(), + Self::Sixteen(img) => img.dimensions(), + } + } + + /// Pixel `i` (row by row from the top left) at 16 bits a sample (an 8-bit sample `v` is + /// `v * 257`). + fn rgba16(&self, i: usize) -> [u16; 4] { + let mut out = [0u16; 4]; + match self { + Self::Eight(img) => { + for (o, v) in out.iter_mut().zip(img.as_raw().get(i * 4..i * 4 + 4).unwrap_or_default()) { + *o = u16::from(*v) * 257; + } + } + Self::Sixteen(img) => { + for (o, v) in out.iter_mut().zip(img.as_raw().get(i * 4..i * 4 + 4).unwrap_or_default()) { + *o = *v; + } + } + } + out + } +} + +/// `blob` with its background cleared as `settings` say, or `None` when no pixel changes. A CMYK +/// image, one that can't be decoded or is too large to change, and a result with no pixel left are +/// errors of command `cmd`. The PNG keeps the source's ICC profile and resolution. The decoded +/// pixels are taken from and kept in `kept` when it is given. +pub(crate) fn clear(blob: &ImageBlob, settings: &Settings, mut kept: Option<&mut DecodedImages>, cmd: &str) -> Result<Option<Cleared>> { + if blob.is_cmyk() { + return Err(cmyk_refusal(cmd)); + } + let found = kept.as_deref_mut().and_then(|k| k.get(&blob.bytes)); + let (source, gray, icc) = match found { + Some(found) => found, + None => decode(blob, kept, cmd)?, + }; + // The pixels kept for the next run stay as they are; ones not kept are worked on in place. + let mut px = Arc::try_unwrap(source).unwrap_or_else(|kept| Pixels::clone(&kept)); + let (w, h) = px.dimensions(); + let levels = levels(w as usize, h as usize, &|i| px.rgba16(i), settings); + let Some(cleared) = apply(&mut px, &levels) else { return Ok(None) }; + let left = match &px { + Pixels::Eight(img) => img.pixels().any(|p| p.0[3] > 0), + Pixels::Sixteen(img) => img.pixels().any(|p| p.0[3] > 0), + }; + if !left { + return Err(if masks(cmd) { + bad(cmd, "the mask would hide every pixel") + } else { + bad(cmd, "every pixel matches the background: no image would be left") + }); + } + let out = match (px, gray) { + (Pixels::Eight(img), false) => DynamicImage::ImageRgba8(img), + (Pixels::Sixteen(img), false) => DynamicImage::ImageRgba16(img), + (Pixels::Eight(img), true) => { + DynamicImage::ImageLumaA8(ImageBuffer::from_fn(w, h, |x, y| LumaA([img.get_pixel(x, y).0[0], img.get_pixel(x, y).0[3]]))) + } + (Pixels::Sixteen(img), true) => { + DynamicImage::ImageLumaA16(ImageBuffer::from_fn(w, h, |x, y| LumaA([img.get_pixel(x, y).0[0], img.get_pixel(x, y).0[3]]))) + } + }; + let mut png = Vec::new(); + let mut encoder = image::codecs::png::PngEncoder::new(&mut png); + if let Some(icc) = icc { + use image::ImageEncoder as _; + encoder.set_icc_profile(icc).map_err(|e| bad(cmd, e.to_string()))?; + } + out.write_with_encoder(encoder).map_err(|e| bad(cmd, e.to_string()))?; + // The resolution the file declares, which sizes the image at 100% when it is replaced or relinked. + if let Some(r) = ppi::resolution(&blob.bytes) { + png = ppi::with_png_resolution(&png, r); + } + Ok(Some(Cleared { blob: ImageBlob::png(png), width: w, height: h, cleared })) +} + +/// `blob`'s pixels as straight RGBA, whether they were gray, and its ICC profile. An image that +/// can't be decoded or is too large to change is an error. The pixels are kept in `kept`, when it +/// is given, if a copy of them fits the decode allowance beside the work. Errors are command `cmd`'s. +fn decode(blob: &ImageBlob, kept: Option<&mut DecodedImages>, cmd: &str) -> Result<(Arc<Pixels>, bool, Option<Vec<u8>>)> { + let reader = || { + image::ImageReader::new(Cursor::new(blob.bytes.as_slice())).with_guessed_format().map_err(|_| bad(cmd, "the image's pixels can't be read")) + }; + let mut decoder = reader()?.into_decoder().map_err(|e| bad(cmd, format!("the image's pixels can't be read: {e}")))?; + // The ICC profile the colors are in goes with them into the PNG. + let (w, h, kind, icc) = { + use image::ImageDecoder as _; + let (w, h) = decoder.dimensions(); + (w, h, decoder.color_type(), decoder.icc_profile().ok().flatten()) + }; + drop(decoder); + // The file's pixels, those worked on (as many again for the PNG made of them) and the work, + // checked from the header before anything is decoded. + let deep = kind.bytes_per_pixel() > kind.channel_count(); + let per_pixel = u64::from(kind.bytes_per_pixel()) + 2 * if deep { 8 } else { 4 } + WORK_BYTES; + if u64::from(w).checked_mul(u64::from(h)).and_then(|n| n.checked_mul(per_pixel)).is_none_or(|n| n > MAX_RASTER_ALLOC) { + return Err(bad(cmd, format!("an image of {w} × {h} pixels is too large to change"))); + } + let mut reader = reader()?; + let mut limits = image::Limits::default(); + limits.max_alloc = Some(MAX_RASTER_ALLOC); + reader.limits(limits); + let img = reader.decode().map_err(|e| bad(cmd, format!("the image's pixels can't be read: {e}")))?; + #[cfg(test)] + DECODES.with(|c| c.set(c.get() + 1)); + let gray = matches!(img.color(), image::ColorType::L8 | image::ColorType::La8 | image::ColorType::L16 | image::ColorType::La16); + let px = Arc::new(if deep { Pixels::Sixteen(img.into_rgba16()) } else { Pixels::Eight(img.into_rgba8()) }); + // A kept copy is worked on as a copy: one more set of the pixels worked on. + let with_copy = per_pixel + if deep { 8 } else { 4 }; + if let Some(kept) = kept + && u64::from(w).checked_mul(u64::from(h)).and_then(|n| n.checked_mul(with_copy)).is_some_and(|n| n <= MAX_RASTER_ALLOC) + && px.bytes().saturating_add(icc.as_ref().map_or(0, |icc| icc.len() as u64)) <= KEEP_BYTES + { + kept.keep(&blob.bytes, Arc::clone(&px), gray, icc.clone()); + } + Ok((px, gray, icc)) +} + +/// Each pixel's alpha scaled by its level (255 keeps it). Returns how many pixels were made fully +/// clear, or `None` when no pixel changed. +fn apply(px: &mut Pixels, levels: &[u8]) -> Option<u64> { + let (mut changed, mut cleared) = (false, 0u64); + match px { + Pixels::Eight(img) => { + for (p, &l) in img.pixels_mut().zip(levels) { + let a = ((u32::from(p.0[3]) * u32::from(l) + 127) / 255) as u8; + changed |= a != p.0[3]; + cleared += u64::from(a == 0 && p.0[3] != 0); + p.0[3] = a; + } + } + Pixels::Sixteen(img) => { + for (p, &l) in img.pixels_mut().zip(levels) { + let a = ((u32::from(p.0[3]) * u32::from(l) + 127) / 255) as u16; + changed |= a != p.0[3]; + cleared += u64::from(a == 0 && p.0[3] != 0); + p.0[3] = a; + } + } + } + changed.then_some(cleared) +} + +/// How much of each of the `w` × `h` pixels `px` gives (row by row, straight RGBA at 16 bits a +/// sample) stays, from 0 (cleared) to 255 (kept), as `settings` say. Each pixel's distance to the +/// background is worked out once. A pixel past the first `u32::MAX` is left kept by the edge search. +pub(crate) fn levels(w: usize, h: usize, px: &dyn Fn(usize) -> [u16; 4], settings: &Settings) -> Vec<u8> { + let n = w.saturating_mul(h); + let refs: Vec<[u16; 3]> = match &settings.background { + Background::Colors(refs) => refs.iter().map(|c| c.map(|v| u16::from(v) * 257)).collect(), + Background::Edges => match edge_color(w, h, px) { + Some(edge) => vec![edge], + None => return vec![255; n], + }, + Background::Corners => match corner_color(w, h, px) { + Some(corner) => vec![corner], + None => return vec![255; n], + }, + }; + let mut out: Vec<u8> = (0..n) + .map(|i| { + let [r, g, b, _] = px(i); + level([r, g, b], &refs, settings) + }) + .collect(); + if settings.contiguous { + // Out from the edges, through clear pixels and pixels that lose some alpha; the pixels it + // doesn't reach are kept. + let reaches = |out: &[u8], i: usize| out.get(i).is_some_and(|l| *l < 255) || px(i)[3] == 0; + let mut seen = vec![false; n]; + let mut stack: Vec<u32> = vec![]; + for i in border(w, h).filter(|&i| reaches(&out, i)) { + if let (Some(s), Ok(at)) = (seen.get_mut(i), u32::try_from(i)) { + *s = true; + stack.push(at); + } + } + while let Some(at) = stack.pop() { + let i = at as usize; + let (x, y) = (i % w, i / w); + let next = [(x > 0).then(|| i - 1), (x + 1 < w).then(|| i + 1), (y > 0).then(|| i - w), (y + 1 < h).then(|| i + w)]; + for j in next.into_iter().flatten() { + if let Some(s) = seen.get_mut(j) + && !*s + && reaches(&out, j) + && let Ok(at) = u32::try_from(j) + { + *s = true; + stack.push(at); + } + } + } + for (l, s) in out.iter_mut().zip(&seen) { + if !*s { + *l = 255; + } + } + } + out +} + +/// The level of a pixel of color `c`: 0 within the tolerance of the nearest of `refs`, 255 from +/// the tolerance plus the softness on, and in proportion between them. +fn level(c: [u16; 3], refs: &[[u16; 3]], settings: &Settings) -> u8 { + let Settings { tolerance, softness, measure, .. } = *settings; + let d = percent(refs.iter().map(|r| gap(c, *r, measure)).fold(f64::INFINITY, f64::min), measure); + if d <= tolerance { + 0 + } else if d >= tolerance + softness { + 255 + } else { + ((d - tolerance) / softness * 255.0).round().clamp(0.0, 255.0) as u8 + } +} + +/// How far apart `a` and `b` are, measured as `measure` says, before `percent` converts it: the +/// squared RGB distance, or the largest difference on one channel. +fn gap(a: [u16; 3], b: [u16; 3], measure: Match) -> f64 { + match measure { + Match::Distance => a.iter().zip(b).map(|(x, y)| (f64::from(*x) - f64::from(y)).powi(2)).sum(), + Match::Channels => f64::from(a.iter().zip(b).map(|(x, y)| x.abs_diff(y)).max().unwrap_or(0)), + } +} + +/// A `gap` as a percentage: of the largest RGB distance (black to white) with distance, or of the +/// channel's range with channels. A difference of `k` 8-bit steps on one channel is exactly +/// `k / 255 × 100` with channels. +fn percent(gap: f64, measure: Match) -> f64 { + match measure { + Match::Distance => gap.sqrt() / (65_535.0 * 3f64.sqrt()) * 100.0, + Match::Channels => gap / 65_535.0 * 100.0, + } +} + +/// The pixels on the edges of a `w` × `h` image, each once. +fn border(w: usize, h: usize) -> impl Iterator<Item = usize> { + let top = (0..w).filter(move |_| h > 0); + let bottom = (0..w).filter(move |_| h > 1).map(move |x| (h - 1) * w + x); + let sides = (1..h.saturating_sub(1)).flat_map(move |y| [Some(y * w), (w > 1).then(|| y * w + w - 1)].into_iter().flatten()); + top.chain(bottom).chain(sides) +} + +/// The most common color along an image's edges: its edge pixels grouped by 16 levels a channel, +/// with the clear ones as a group of their own, as the average of the largest group. `None` when +/// the clear edge pixels are at least as many as that group: the background is already cleared. +fn edge_color(w: usize, h: usize, px: &dyn Fn(usize) -> [u16; 4]) -> Option<[u16; 3]> { + let mut groups: HashMap<[u16; 3], (u64, [u64; 3])> = HashMap::new(); + let mut clear = 0u64; + for i in border(w, h) { + let [r, g, b, a] = px(i); + if a == 0 { + clear += 1; + continue; + } + let e = groups.entry([r >> 12, g >> 12, b >> 12]).or_default(); + e.0 += 1; + for (s, v) in e.1.iter_mut().zip([r, g, b]) { + *s += u64::from(v); + } + } + // Equal groups go by color, so the result doesn't depend on the map's order. + let (_, (n, sums)) = groups.into_iter().max_by(|a, b| a.1.0.cmp(&b.1.0).then(b.0.cmp(&a.0)))?; + if clear >= n { + return None; + } + Some(sums.map(|s| ((s + n / 2) / n.max(1)) as u16)) +} + +/// The average of the four corner pixels of a `w` × `h` image that are not clear (a corner of a +/// one-pixel-wide image counts twice). `None` when all four are clear: the background is already +/// cleared. +fn corner_color(w: usize, h: usize, px: &dyn Fn(usize) -> [u16; 4]) -> Option<[u16; 3]> { + if w == 0 || h == 0 { + return None; + } + let corners = [0, w - 1, (h - 1) * w, (h - 1) * w + w - 1]; + let (mut n, mut sums) = (0u64, [0u64; 3]); + for [r, g, b, a] in corners.map(px) { + if a > 0 { + n += 1; + for (s, v) in sums.iter_mut().zip([r, g, b]) { + *s += u64::from(v); + } + } + } + (n > 0).then(|| sums.map(|s| ((s + n / 2) / n) as u16)) +} diff --git a/crates/engine/src/cmd/addons/image/mask.rs b/crates/engine/src/cmd/addons/image/mask.rs new file mode 100644 index 0000000000..786effbd2e --- /dev/null +++ b/crates/engine/src/cmd/addons/image/mask.rs @@ -0,0 +1,443 @@ +//! Image Tools › Color Mask (`addon.image.colorMask`, `addon.image.removeColorMask`, +//! `addon.image.applyColorMask`): colors of the selected images are hidden while their pixels +//! stay as they are. The colors are matched as Remove Background matches them ([`super::clear`]); +//! the image keeps its own pixels, and the mask's settings and the masked pixels are kept with it +//! ([`vectorcraft_doc::color_mask`]), so the mask can be changed, removed, or applied to the +//! pixels later. When an image's own pixels are replaced (a link updated or relinked, the image +//! cropped or recolored), its mask is applied to the new pixels ([`refresh`]). + +#[cfg(test)] +mod tests; + +use std::collections::HashMap; +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_doc::color_mask::{ColorMask, MaskBackground, MaskMatch}; +use vectorcraft_doc::{Document, ImageBlob, Node, NodeId, NodeKind}; +use vectorcraft_geom::Affine; + +use super::super::super::paint::{PROCESS_ON_TRANSPARENCY, colorized_with_process}; +use super::super::super::{CommandSpec, Result, Session, bad, cmd}; +use super::{Background, DecodedImages, MAX_COLORS, Match, Settings, clear, images, targets}; + +/// Color Mask's command. +pub const COLOR_MASK: &str = "addon.image.colorMask"; +/// Remove Color Mask's command. +pub const REMOVE_COLOR_MASK: &str = "addon.image.removeColorMask"; +/// Apply Color Mask's command. +pub const APPLY_COLOR_MASK: &str = "addon.image.applyColorMask"; + +/// The params that set a mask; with none of them, Color Mask only reports. +const SETTINGS: [&str; 6] = ["background", "colors", "contiguous", "match", "tolerance", "softness"]; + +pub fn specs() -> Vec<CommandSpec> { + vec![ + cmd!( + "addon.image.colorMask", + "Color Mask…", + ["Object", "Plug-ins", "Image Tools"], + None, + "{background?: \"edges\" (default: the most common color along the image's edges) | \"corners\" (the average of the image's four corner pixels that are not clear) | \"colors\" (the colors in `colors`), colors?: [color…] or one string of them split by commas or spaces (1 to 16 hex colors or black, white, red, green and blue, as addon.image.removeBackground takes them; needed with background: colors), contiguous?: bool (true: only matching pixels that reach in from an edge are hidden; false: wherever they are; true), match?: \"distance\" (default: a color's RGB distance from a hidden color) | \"channels\" (its largest difference on one of red, green and blue), tolerance?: 0..100 (% as addon.image.removeBackground measures it; a pixel this near a hidden color is hidden; 10), softness?: 0..100 (% past the tolerance over which pixels fade from hidden to shown; 10), ids?: [id…] (default: the selected images)} hide colors of each image without changing its pixels, as one undo step: the image keeps its own pixels, and the mask (these settings, and the image's pixels with the hidden colors made clear, made as Remove Background makes them) is kept with the image and saved with the document; the canvas, printing and separations, PDF, SVG, EPS, raster formats, DXF, EMF, WMF, the legacy .ai and the .ai editing data, copy and paste, and placing a document show the masked pixels, and a click on any part of the image's frame selects it (the Eyedropper, Object Mosaic, Create Gradient Mesh, Crop Image's trim and Image Trace read the image's own pixels); setting the mask again replaces it, and an image whose mask does not change is left as it is (no undo step when none changes); when the image's own pixels are replaced later (Update Link, Relink, Crop Image, a recolor, a linked file read again on open), the mask is made again for the new pixels; an object in `ids` that is not an image, a CMYK image, a linked image that shows its preview (embed or relink it first), an image too large to change, a mask that would hide every pixel, and a mask that would hide pixels of a grayscale image colorized with a process color (masked gray pixels have transparency, which only a spot color, black or white colorizes; each image is checked on the pixels its new mask shows) are refused. With none of background, colors, contiguous, match, tolerance and softness given, nothing changes and the mask settings of the first image (or the defaults when it has no mask) are returned → {changed: the images changed, ids, hidden: the pixels made fully clear in them} or {background, colors, contiguous, match, tolerance, softness, masked}", + super::has_image, + color_mask + ), + cmd!( + "addon.image.removeColorMask", + "Remove Color Mask", + ["Object", "Plug-ins", "Image Tools"], + None, + "{ids?: [id…] (default: the selected images)} take the color mask off each image, as one undo step: the image shows its own pixels again; images without a mask are left as they are (no undo step when none has one), and an object in `ids` that is not an image is refused → {changed, ids}", + has_color_mask, + remove_color_mask + ), + cmd!( + "addon.image.applyColorMask", + "Apply Color Mask", + ["Object", "Plug-ins", "Image Tools"], + None, + "{ids?: [id…] (default: the selected images)} make each image's color mask part of its pixels, as one undo step: the masked pixels become the image's own, embedded as a PNG with an alpha channel (a linked image is embedded), and the mask is taken off; a mask that hides nothing is only taken off (the image keeps its pixels and its link); images without a mask are left as they are (no undo step when none has one), and an object in `ids` that is not an image, and a mask made again for new pixels that would give a grayscale image colorized with a process color an alpha channel, are refused → {changed, ids}", + has_color_mask, + apply_color_mask + ), + ] +} + +/// Enabled when a selected image has a color mask. +fn has_color_mask(s: &Session) -> std::result::Result<(), String> { + let st = s.active().ok_or("no document open")?; + if st.selection.objects.iter().any(|id| st.doc.node(*id).and_then(Document::color_mask_of).is_some()) { + Ok(()) + } else { + Err("select an image with a color mask".into()) + } +} + +impl Settings { + /// The settings a mask was made with, `None` when a file gave ones out of range. + fn of(m: &ColorMask) -> Option<Self> { + let percent = |v: f64| v.is_finite() && (0.0..=100.0).contains(&v); + if !percent(m.tolerance) || !percent(m.softness) { + return None; + } + let background = match m.background { + MaskBackground::Edges => Background::Edges, + MaskBackground::Corners => Background::Corners, + MaskBackground::Colors if (1..=MAX_COLORS).contains(&m.colors.len()) => Background::Colors(m.colors.clone()), + MaskBackground::Colors => return None, + }; + let measure = match m.measure { + MaskMatch::Distance => Match::Distance, + MaskMatch::Channels => Match::Channels, + }; + Some(Self { background, contiguous: m.contiguous, measure, tolerance: m.tolerance, softness: m.softness }) + } + + /// A mask with these settings whose masked pixels are `key`, made from the pixels `from`. + fn mask(&self, key: String, from: String) -> ColorMask { + let (background, colors) = match &self.background { + Background::Edges => (MaskBackground::Edges, vec![]), + Background::Corners => (MaskBackground::Corners, vec![]), + Background::Colors(c) => (MaskBackground::Colors, c.clone()), + }; + let measure = match self.measure { + Match::Distance => MaskMatch::Distance, + Match::Channels => MaskMatch::Channels, + }; + ColorMask { key, from, background, colors, contiguous: self.contiguous, measure, tolerance: self.tolerance, softness: self.softness } + } +} + +/// The masked pixels of `blob` (`None`: no pixel is hidden, the image's own pixels show) as +/// `settings` say, with errors of command `cmd`. +fn masked(blob: &ImageBlob, settings: &Settings, kept: Option<&mut DecodedImages>, cmd: &str) -> Result<Option<(String, ImageBlob, u64)>> { + Ok(clear(blob, settings, kept, cmd)?.map(|out| (out.blob.content_key(), out.blob, out.cleared))) +} + +fn color_mask(s: &mut Session, p: &Value) -> Result<Value> { + if !SETTINGS.iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) { + return report(s, p); + } + let settings = Settings::read(p, COLOR_MASK)?; + // A preview step keeps the pixels it decodes for the next step; other runs keep none. + let mut kept = std::mem::take(&mut s.decoded_images); + let previewing = s.previewing; + let found = mask_changes(s, p, &settings, previewing.then_some(&mut kept)); + s.decoded_images = kept; + let changes = found?; + let ids: Vec<u64> = changes.iter().map(|c| c.0.0).collect(); + let hidden: u64 = changes.iter().map(|c| c.3).sum(); + if !changes.is_empty() { + s.edit("Color Mask", |d, _| { + for (id, mask, blob, _) in changes { + if let Some(blob) = blob { + d.images.entry(mask.key.clone()).or_insert(blob); + } + if let Some(n) = d.node_mut(id) { + n.extras_mut().color_mask = Some(Box::new(mask)); + } + } + Ok(()) + })?; + } + Ok(json!({ "changed": ids.len(), "ids": ids, "hidden": hidden })) +} + +/// The images `p` names whose mask changes, each with its new mask, the masked pixels to add (when +/// the document doesn't have them) and how many pixels they hide. +type MaskChange = (NodeId, ColorMask, Option<ImageBlob>, u64); + +fn mask_changes(s: &Session, p: &Value, settings: &Settings, mut kept: Option<&mut DecodedImages>) -> Result<Vec<MaskChange>> { + let st = s.doc()?; + // Each image's pixels once, however many objects show them. + let mut made: HashMap<&str, (String, Option<ImageBlob>, u64)> = HashMap::new(); + let mut out = vec![]; + for (id, im, blob) in images(s, p, COLOR_MASK)? { + let (key, pixels, hidden) = match made.get(im.key.as_str()) { + Some(m) => m.clone(), + None => { + let m = match masked(blob, settings, kept.as_deref_mut(), COLOR_MASK)? { + Some((key, blob, hidden)) => (key, Some(blob), hidden), + None => (im.key.clone(), None, 0), + }; + made.insert(&im.key, m.clone()); + m + } + }; + let mask = settings.mask(key, im.key.clone()); + if st.doc.node(id).and_then(Document::color_mask_of) == Some(&mask) { + continue; + } + // Masked pixels that hide something have an alpha channel, which a grayscale image + // colorized with a process color can't take. The pixels the new mask shows are checked, + // made from the image's own pixels, not the ones an earlier mask shows. + let shown = pixels.as_ref().or_else(|| st.doc.images.get(&mask.key)); + if st.doc.node(id).is_some_and(|n| refused_colorize(&st.doc, n, shown)) { + return Err(bad(COLOR_MASK, PROCESS_ON_TRANSPARENCY)); + } + let pixels = pixels.filter(|_| !st.doc.images.contains_key(&mask.key)); + out.push((id, mask, pixels, hidden)); + } + Ok(out) +} + +/// Whether masked pixels `shown`, made for image node `n`, have transparency that `n`'s colorize +/// color can't take: gray pixels with an alpha channel and a process color +/// ([`colorized_with_process`]). +fn refused_colorize(doc: &Document, n: &Node, shown: Option<&ImageBlob>) -> bool { + shown.and_then(ImageBlob::gray_source).is_some_and(|g| g.alpha) && colorized_with_process(doc, n) +} + +/// Color Mask without settings: the first image's mask settings, or the defaults. It reads them +/// for images a change would refuse too (CMYK, a linked image at its preview), so the dialog opens. +fn report(s: &Session, p: &Value) -> Result<Value> { + let st = s.doc()?; + let first = targets(s, p, COLOR_MASK)?.first().and_then(|id| st.doc.node(*id)).and_then(Document::color_mask_of).cloned(); + let m = first.as_ref(); + let hex = |c: &[u8; 3]| format!("#{:02x}{:02x}{:02x}", c[0], c[1], c[2]); + let colors = + m.filter(|m| !m.colors.is_empty()).map_or_else(|| "#ffffff".to_string(), |m| m.colors.iter().map(hex).collect::<Vec<_>>().join(", ")); + let name = |v: Value| v.as_str().map(str::to_string).unwrap_or_default(); + Ok(json!({ + "background": name(serde_json::to_value(m.map_or(MaskBackground::Edges, |m| m.background)).unwrap_or_default()), + "colors": colors, + "contiguous": m.is_none_or(|m| m.contiguous), + "match": name(serde_json::to_value(m.map_or(MaskMatch::Distance, |m| m.measure)).unwrap_or_default()), + "tolerance": m.map_or(10.0, |m| m.tolerance), + "softness": m.map_or(10.0, |m| m.softness), + "masked": m.is_some(), + })) +} + +/// The image objects `p` names ([`targets`]: `ids`, or the selected images) that have a color mask. +fn masked_images(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> { + let st = s.doc()?; + Ok(targets(s, p, cmd)?.into_iter().filter(|id| st.doc.node(*id).and_then(Document::color_mask_of).is_some()).collect()) +} + +fn remove_color_mask(s: &mut Session, p: &Value) -> Result<Value> { + let ids = masked_images(s, p, REMOVE_COLOR_MASK)?; + if !ids.is_empty() { + s.edit("Remove Color Mask", |d, _| { + for id in &ids { + if let Some(n) = d.node_mut(*id) { + n.extras_mut().color_mask = None; + } + } + Ok(()) + })?; + } + Ok(json!({ "changed": ids.len(), "ids": ids.iter().map(|id| id.0).collect::<Vec<_>>() })) +} + +fn apply_color_mask(s: &mut Session, p: &Value) -> Result<Value> { + let ids = masked_images(s, p, APPLY_COLOR_MASK)?; + // Each image's masked pixels, made again first when its own pixels changed since. A mask that + // hides nothing (its masked pixels are the image's own) is only taken off: the image keeps its + // pixels and its link. + let mut made = vec![]; + { + let st = s.doc()?; + for id in &ids { + let Some(n) = st.doc.node(*id) else { continue }; + let (NodeKind::Image(im), Some(m)) = (&n.kind, Document::color_mask_of(n)) else { continue }; + let mask = match fresh(&st.doc, n, APPLY_COLOR_MASK) { + Some(Ok(fresh)) => fresh, + Some(Err(e)) => return Err(e), + None => (m.clone(), None), + }; + if mask.0.key == im.key { + made.push((*id, None)); + continue; + } + let shown = st.doc.images.get(&mask.0.key).or(mask.1.as_ref()); + if refused_colorize(&st.doc, n, shown) { + return Err(bad(APPLY_COLOR_MASK, PROCESS_ON_TRANSPARENCY)); + } + let size = mask_size(shown, im.width, im.height); + made.push((*id, Some((mask, size)))); + } + } + if !made.is_empty() { + s.edit("Apply Color Mask", |d, _| { + for (id, applied) in made { + let Some(n) = d.node_mut(id) else { continue }; + n.extras_mut().color_mask = None; + let Some(((mask, blob), (w, h))) = applied else { continue }; + if let Some(blob) = blob { + d.images.entry(mask.key.clone()).or_insert(blob); + } + let Some(n) = d.node_mut(id) else { continue }; + if let NodeKind::Image(im) = &mut n.kind { + // Masked pixels of another size than the object's keep its place and size. + if (w, h) != (im.width, im.height) { + im.xf *= Affine::scale_non_uniform(f64::from(im.width) / f64::from(w), f64::from(im.height) / f64::from(h)); + (im.width, im.height) = (w, h); + } + im.key = mask.key; + im.link = None; + } + } + Ok(()) + })?; + } + Ok(json!({ "changed": ids.len(), "ids": ids.iter().map(|id| id.0).collect::<Vec<_>>() })) +} + +/// The size in pixels of masked pixels `blob` (from its header), or the object's when it can't be +/// read. +fn mask_size(blob: Option<&ImageBlob>, width: u32, height: u32) -> (u32, u32) { + blob.and_then(|b| image::ImageReader::new(std::io::Cursor::new(b.bytes.as_slice())).with_guessed_format().ok()?.into_dimensions().ok()) + .filter(|(w, h)| *w > 0 && *h > 0) + .unwrap_or((width, height)) +} + +/// The mask of image node `n` made again for the image's own pixels, with the masked pixels when +/// `doc` doesn't have them: `None` when the mask is up to date (or `n` has none), an error when the +/// pixels can't be masked (missing, CMYK, a linked preview, too large, every pixel hidden, or +/// settings a file gave out of range). +fn fresh(doc: &Document, n: &Node, cmd: &str) -> Option<Result<(ColorMask, Option<ImageBlob>)>> { + let (NodeKind::Image(im), Some(m)) = (&n.kind, Document::color_mask_of(n)) else { return None }; + if !stale_mask(doc, n) { + return None; + } + let made = || -> Result<(ColorMask, Option<ImageBlob>)> { + let settings = Settings::of(m).ok_or_else(|| bad(cmd, "the color mask's settings are out of range"))?; + let blob = doc.images.get(&im.key).ok_or_else(|| bad(cmd, "the image's pixels are missing"))?; + if im.link.is_some() && blob.is_proxy() { + return Err(bad(cmd, "the linked image shows its preview: embed or relink it first")); + } + Ok(match masked(blob, &settings, None, cmd)? { + Some((key, blob, _)) => { + let blob = (!doc.images.contains_key(&key)).then_some(blob); + (settings.mask(key, im.key.clone()), blob) + } + None => (settings.mask(im.key.clone(), im.key.clone()), None), + }) + }; + Some(made()) +} + +/// After an edit from `before` (`None`: everything is new, as after a document's links are read): +/// the color masks of images in `doc`'s art ([`Document::art_roots`]: layers, symbols, graph +/// designs, patterns and the original of the pattern being edited, opacity mask art included) +/// whose own pixels were replaced are made again for the new pixels ([`Refresh::made`]). Only the +/// art that changed since `before` is looked at. +pub(crate) fn refresh(before: Option<&Document>, doc: &mut Document) { + let old: Vec<&Arc<Node>> = before.map(|b| b.art_roots().collect()).unwrap_or_default(); + let mut pass = Refresh { doc: &*doc, made: HashMap::new(), blobs: vec![] }; + let mut fixed = vec![]; + for (i, root) in doc.art_roots().enumerate() { + let counterpart = old.get(i).copied().filter(|o| o.id == root.id); + if stale_in(doc, root, counterpart) { + let mut root = root.clone(); + pass.fix(Arc::make_mut(&mut root)); + fixed.push((i, root)); + } + } + let blobs = pass.blobs; + if fixed.is_empty() { + return; + } + for (key, blob) in blobs { + doc.images.entry(key).or_insert(blob); + } + let mut fixed = fixed.into_iter().peekable(); + for (i, root) in doc.art_roots_mut().enumerate() { + if fixed.peek().is_some_and(|(at, _)| *at == i) + && let Some((_, new)) = fixed.next() + { + *root = new; + } + } +} + +/// Whether `n`, or anything in it (opacity-mask art included), is an image whose mask is out of +/// date ([`stale_mask`]). What is the same as in `old`, `n`'s counterpart before an edit, is not +/// looked at. +fn stale_in(doc: &Document, n: &Arc<Node>, old: Option<&Arc<Node>>) -> bool { + if old.is_some_and(|o| Arc::ptr_eq(o, n)) { + return false; + } + if stale_mask(doc, n) { + return true; + } + let old_mask = old.and_then(|o| o.extras().mask.as_ref()).map(|m| &m.art); + if n.extras().mask.as_ref().is_some_and(|m| stale_in(doc, &m.art, old_mask)) { + return true; + } + let Some(children) = n.children() else { return false }; + let before = old.and_then(|o| o.children()).map_or(&[][..], Vec::as_slice); + let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None; + children.iter().enumerate().any(|(i, c)| { + let b = match before.get(i) { + Some(b) if b.id == c.id => Some(b), + _ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&c.id).copied(), + }; + stale_in(doc, c, b) + }) +} + +/// Whether `n` is an image whose color mask was not made from its own pixels (or whose masked +/// pixels `doc` doesn't have). A mask that hides nothing (its masked pixels are the image's own) +/// is up to date while the image's key stays the same, even when its pixels are missing. +fn stale_mask(doc: &Document, n: &Node) -> bool { + matches!((&n.kind, Document::color_mask_of(n)), (NodeKind::Image(im), Some(m)) + if im.pixels.is_none() && !(m.made_for(im) && (m.key == im.key || doc.images.contains_key(&m.key)))) +} + +/// One [`refresh`] pass: the masks made so far, by the image's pixels, the mask's settings and +/// whether a process color colorizes the image (an image shown by many objects is decoded once), +/// and the masked pixels to add to the document. +struct Refresh<'a> { + doc: &'a Document, + made: HashMap<(String, String, bool), ColorMask>, + blobs: Vec<(String, ImageBlob)>, +} + +impl Refresh<'_> { + /// Make the masks out of date in `n` (a copy of the document's art) again. + fn fix(&mut self, n: &mut Node) { + if let Some(mask) = self.made(n) { + n.extras_mut().color_mask = Some(Box::new(mask)); + } + if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) + && stale_in(self.doc, &m.art, None) + { + self.fix(Arc::make_mut(&mut m.art)); + } + for c in n.children_mut().into_iter().flatten() { + if stale_in(self.doc, c, None) { + self.fix(Arc::make_mut(c)); + } + } + } + + /// The mask of image node `n` made again for the image's own pixels ([`fresh`]), `None` when + /// it is up to date. A mask that can't be made for them (every pixel hidden, CMYK pixels, a + /// linked preview, too large, gray pixels with transparency under a process color) keeps its + /// settings and hides nothing: the image shows its own pixels, and setting the mask again + /// reports why. + fn made(&mut self, n: &Node) -> Option<ColorMask> { + let (NodeKind::Image(im), Some(m)) = (&n.kind, Document::color_mask_of(n)) else { return None }; + if !stale_mask(self.doc, n) { + return None; + } + let settings = ColorMask { key: String::new(), from: String::new(), ..m.clone() }; + let at = (im.key.clone(), format!("{settings:?}"), colorized_with_process(self.doc, n)); + if let Some(made) = self.made.get(&at) { + return Some(made.clone()); + } + let hides_nothing = || ColorMask { key: im.key.clone(), from: im.key.clone(), ..m.clone() }; + let mask = match fresh(self.doc, n, COLOR_MASK)? { + Ok((mask, blob)) if refused_colorize(self.doc, n, blob.as_ref().or_else(|| self.doc.images.get(&mask.key))) => hides_nothing(), + Ok((mask, blob)) => { + self.blobs.extend(blob.map(|b| (mask.key.clone(), b))); + mask + } + Err(_) => hides_nothing(), + }; + self.made.insert(at, mask.clone()); + Some(mask) + } +} diff --git a/crates/engine/src/cmd/addons/image/mask/tests.rs b/crates/engine/src/cmd/addons/image/mask/tests.rs new file mode 100644 index 0000000000..b9b56a5e4a --- /dev/null +++ b/crates/engine/src/cmd/addons/image/mask/tests.rs @@ -0,0 +1,1007 @@ +use std::io::Cursor; + +use image::DynamicImage; +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::color_mask::{ColorMask, MaskBackground}; +use vectorcraft_doc::{Document, ImageBlob, ImageObject, Node, NodeId, NodeKind}; +use vectorcraft_geom::Rect; + +use super::{APPLY_COLOR_MASK, COLOR_MASK, REMOVE_COLOR_MASK}; +use crate::Session; + +const WHITE: [u8; 4] = [255, 255, 255, 255]; +const RED: [u8; 4] = [200, 0, 0, 255]; + +fn png(img: DynamicImage) -> Vec<u8> { + let mut out = Vec::new(); + img.write_to(&mut Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out +} + +/// 12 × 10 pixels: white, with a red block from (3, 3) to (9, 7) that holds one white pixel at +/// (6, 5). +fn framed() -> Vec<u8> { + png(DynamicImage::ImageRgba8(image::RgbaImage::from_fn(12, 10, |x, y| { + let block = (3..9).contains(&x) && (3..7).contains(&y); + image::Rgba(if block && (x, y) != (6, 5) { RED } else { WHITE }) + }))) +} + +/// Hide white wherever it is, exactly. +fn hide_white() -> Value { + json!({"background": "colors", "colors": "#ffffff", "contiguous": false, "tolerance": 0, "softness": 0}) +} + +/// A session with `bytes` opened as a document, its image selected. +fn open(bytes: &[u8]) -> (Session, NodeId) { + let mut s = Session::new(); + s.execute("document.open", &json!({"name": "art.png", "dataBase64": vectorcraft_format::base64_encode(bytes)})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + let id = s.doc().unwrap().selection.objects[0]; + (s, id) +} + +fn doc(s: &Session) -> &Document { + &s.doc().unwrap().doc +} + +fn image_of(d: &Document, id: NodeId) -> ImageObject { + let NodeKind::Image(im) = &d.node(id).unwrap().kind else { panic!("an image") }; + (**im).clone() +} + +fn mask_of(d: &Document, id: NodeId) -> Option<ColorMask> { + Document::color_mask_of(d.node(id).unwrap()).cloned() +} + +fn undo_len(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +/// The straight RGBA of pixel (`x`, `y`) of image `id` as `d` draws it, on nothing. +fn drawn(d: &Document, id: NodeId, x: u32, y: u32) -> [u8; 4] { + drawn_at(d, pixel_at(d, id, x, y)) +} + +/// Where the center of pixel (`x`, `y`) of image `id` is in `d`. +fn pixel_at(d: &Document, id: NodeId, x: u32, y: u32) -> vectorcraft_geom::Point { + image_of(d, id).xf * vectorcraft_geom::Point::new(f64::from(x) + 0.5, f64::from(y) + 0.5) +} + +/// The straight RGBA that `d` draws at `at`, on nothing. +fn drawn_at(d: &Document, at: vectorcraft_geom::Point) -> [u8; 4] { + let r = vectorcraft_render::Renderer::new().render_region(d, Rect::new(at.x - 0.5, at.y - 0.5, at.x + 0.5, at.y + 0.5), 1.0, false); + let px = r.to_straight(); + [px[0], px[1], px[2], px[3]] +} + +#[test] +fn the_mask_hides_the_chosen_colors_while_the_pixels_stay() { + let (mut s, id) = open(&framed()); + let before = (image_of(doc(&s), id), doc(&s).images[&image_of(doc(&s), id).key].bytes.clone(), undo_len(&s)); + assert_eq!(drawn(doc(&s), id, 0, 0), WHITE); + let r = s.execute(COLOR_MASK, &hide_white()).unwrap(); + assert_eq!(r, json!({"changed": 1, "ids": [id.0], "hidden": 12 * 10 - 6 * 4 + 1})); + let d = doc(&s); + assert_eq!(image_of(d, id), before.0, "the image object is as it was"); + assert_eq!(d.images[&before.0.key].bytes, before.1, "its pixels are as they were"); + let m = mask_of(d, id).unwrap(); + assert_eq!((m.from.as_str(), m.background, m.contiguous), (before.0.key.as_str(), MaskBackground::Colors, false)); + assert_eq!(drawn(d, id, 0, 0)[3], 0, "white is hidden"); + assert_eq!(drawn(d, id, 6, 5)[3], 0, "inside the block too"); + assert_eq!(drawn(d, id, 4, 4), RED, "the red shows"); + assert_eq!(undo_len(&s), before.2 + 1, "one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(mask_of(doc(&s), id), None); + assert_eq!(drawn(doc(&s), id, 0, 0), WHITE); +} + +#[test] +fn the_mask_is_edited_reported_and_removed() { + let (mut s, id) = open(&framed()); + let r = s.execute(COLOR_MASK, &json!({})).unwrap(); + assert_eq!( + r, + json!({"background": "edges", "colors": "#ffffff", "contiguous": true, "match": "distance", "tolerance": 10.0, "softness": 10.0, "masked": false}) + ); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + let steps = undo_len(&s); + // The same settings again: nothing changes. + assert_eq!(s.execute(COLOR_MASK, &hide_white()).unwrap()["changed"], 0); + assert_eq!(undo_len(&s), steps, "no undo step"); + // Contiguous: the white inside the block shows again. + let r = s.execute(COLOR_MASK, &json!({"background": "colors", "colors": "#ffffff", "tolerance": 0, "softness": 0})).unwrap(); + assert_eq!(r["changed"], 1); + assert_eq!((drawn(doc(&s), id, 0, 0)[3], drawn(doc(&s), id, 6, 5)), (0, WHITE)); + let r = s.execute(COLOR_MASK, &json!({})).unwrap(); + assert_eq!( + r, + json!({"background": "colors", "colors": "#ffffff", "contiguous": true, "match": "distance", "tolerance": 0.0, "softness": 0.0, "masked": true}) + ); + let steps = undo_len(&s); + assert_eq!(s.execute(REMOVE_COLOR_MASK, &json!({})).unwrap(), json!({"changed": 1, "ids": [id.0]})); + assert_eq!(undo_len(&s), steps + 1); + assert_eq!((mask_of(doc(&s), id), drawn(doc(&s), id, 0, 0)), (None, WHITE)); + // Nothing left to remove: the command is not enabled, and adds no undo step. + let e = s.execute(REMOVE_COLOR_MASK, &json!({})).unwrap_err(); + assert!(e.to_string().contains("select an image with a color mask"), "{e}"); + assert_eq!(undo_len(&s), steps + 1); +} + +#[test] +fn applying_the_mask_makes_it_part_of_the_pixels() { + let (mut s, id) = open(&framed()); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + let m = mask_of(doc(&s), id).unwrap(); + let steps = undo_len(&s); + assert_eq!(s.execute(APPLY_COLOR_MASK, &json!({})).unwrap(), json!({"changed": 1, "ids": [id.0]})); + let d = doc(&s); + assert_eq!((image_of(d, id).key, mask_of(d, id)), (m.key.clone(), None)); + let px = image::load_from_memory(&d.images[&m.key].bytes).unwrap().to_rgba8(); + assert_eq!((px.get_pixel(0, 0).0[3], px.get_pixel(4, 4).0), (0, RED)); + assert_eq!(drawn(d, id, 0, 0)[3], 0); + assert_eq!(undo_len(&s), steps + 1); + assert!(s.execute(APPLY_COLOR_MASK, &json!({})).is_err(), "no mask left"); +} + +/// The bytes of the first `data:image/png;base64,` image in `svg`. +fn svg_image(svg: &str) -> DynamicImage { + let at = svg.find("data:image/png;base64,").expect("an embedded PNG") + "data:image/png;base64,".len(); + let end = at + svg[at..].find('"').unwrap(); + image::load_from_memory(&vectorcraft_format::base64_decode(&svg[at..end]).unwrap()).unwrap() +} + +#[test] +fn outputs_write_the_masked_pixels() { + let (mut s, _) = open(&framed()); + let export = + |s: &Session, format: &str| crate::cmd::fileio::encode_all(doc(s), format, &json!({"useArtboards": true})).unwrap().files.remove(0).1; + let (png0, svg0, pdf0, eps0) = (export(&s, "png"), export(&s, "svg"), export(&s, "pdf"), export(&s, "eps")); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + let alpha = |bytes: &[u8]| image::load_from_memory(bytes).unwrap().to_rgba8().get_pixel(0, 0).0[3]; + assert_eq!((alpha(&png0), alpha(&export(&s, "png"))), (255, 0), "PNG"); + let svg_alpha = |bytes: &[u8]| svg_image(std::str::from_utf8(bytes).unwrap()).to_rgba8().get_pixel(0, 0).0[3]; + assert_eq!((svg_alpha(&svg0), svg_alpha(&export(&s, "svg"))), (255, 0), "SVG"); + let has = |bytes: &[u8], what: &[u8]| bytes.windows(what.len()).any(|w| w == what); + assert!(!has(&pdf0, b"/SMask") && has(&export(&s, "pdf"), b"/SMask"), "PDF: the image with an alpha channel"); + assert!(!has(&eps0, b"/MaskColor") && has(&export(&s, "eps"), b"/MaskColor"), "EPS: the hidden pixels masked out"); +} + +#[test] +fn the_mask_saves_and_opens_again() { + let (mut s, id) = open(&framed()); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + let saved = vectorcraft_format::save_file(doc(&s)); + let back = vectorcraft_format::load(&saved).unwrap(); + assert_eq!(mask_of(&back, id), mask_of(doc(&s), id)); + let m = mask_of(&back, id).unwrap(); + assert_eq!(back.images[&m.key].bytes, doc(&s).images[&m.key].bytes, "the masked pixels are saved with it"); + assert_eq!(back.images[&m.from].bytes, doc(&s).images[&m.from].bytes, "and the image's own"); + assert_eq!(drawn(&back, id, 0, 0)[3], 0); +} + +#[test] +fn copy_and_paste_carry_the_mask() { + let (mut s, _) = open(&framed()); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + super::super::DECODES.with(|c| c.set(0)); + s.execute("edit.paste", &json!({})).unwrap(); + assert_eq!(super::super::DECODES.with(|c| c.get()), 0, "the masked pixels come along, so nothing is decoded to make them again"); + let id = s.doc().unwrap().selection.objects[0]; + let d = doc(&s); + let m = mask_of(d, id).expect("the pasted image keeps its mask"); + assert!(m.made_for(&image_of(d, id)) && d.images.contains_key(&m.key), "with its masked pixels"); + assert_eq!(drawn(d, id, 0, 0)[3], 0); + assert_eq!(drawn(d, id, 4, 4), RED); +} + +#[test] +fn new_pixels_take_the_mask_again() { + let (mut s, id) = open(&framed()); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + // Crop Image replaces the image's own pixels: the mask is made for the cropped ones. + let r = s.execute("object.cropImage", &json!({"rect": [0, 0, 6, 5]})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap_or(id.0)); + let d = doc(&s); + let (im, m) = (image_of(d, id), mask_of(d, id).unwrap()); + assert_eq!(m.from, im.key, "made for the cropped pixels"); + assert_eq!((drawn(d, id, 0, 0)[3], drawn(d, id, 4, 4)), (0, RED)); + // Pixels put in place by any edit (a link read again) take it too. + let blue = png(DynamicImage::ImageRgba8(image::RgbaImage::from_fn(6, 5, |x, _| image::Rgba(if x < 3 { WHITE } else { [0, 0, 200, 255] })))); + s.edit("Swap", |d, _| { + let blob = ImageBlob::png(blue); + let key = blob.content_key(); + d.images.insert(key.clone(), blob); + if let NodeKind::Image(im) = &mut d.node_mut(id).unwrap().kind { + im.key = key; + } + Ok(()) + }) + .unwrap(); + let d = doc(&s); + assert_eq!(mask_of(d, id).unwrap().from, image_of(d, id).key); + assert_eq!((drawn(d, id, 0, 0)[3], drawn(d, id, 4, 0)), (0, [0, 0, 200, 255])); +} + +#[test] +fn a_document_read_with_new_pixels_takes_the_mask_again() { + let (mut s, id) = open(&framed()); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + let mut d = doc(&s).clone(); + let blob = ImageBlob::png(png(DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(4, 4, image::Rgba(WHITE))))); + let red = ImageBlob::png(png(DynamicImage::ImageRgba8(image::RgbaImage::from_fn(4, 4, |x, _| image::Rgba(if x == 0 { WHITE } else { RED }))))); + let key = red.content_key(); + d.images.insert(key.clone(), red); + if let NodeKind::Image(im) = &mut d.node_mut(id).unwrap().kind { + im.key = key.clone(); + } + assert_eq!(drawn(&d, id, 0, 0), WHITE, "until the mask is made again, the image's own pixels"); + super::refresh(None, &mut d); + assert_eq!(mask_of(&d, id).unwrap().from, key); + assert_eq!(drawn(&d, id, 0, 0)[3], 0); + // Pixels the mask would hide entirely: the mask stays, hiding nothing. + let all = blob.content_key(); + d.images.insert(all.clone(), blob); + if let NodeKind::Image(im) = &mut d.node_mut(id).unwrap().kind { + im.key = all.clone(); + } + super::refresh(None, &mut d); + let m = mask_of(&d, id).unwrap(); + assert_eq!((m.key.as_str(), m.from.as_str(), m.colors.as_slice()), (all.as_str(), all.as_str(), &[[255, 255, 255]][..])); + assert_eq!(drawn(&d, id, 0, 0), WHITE); +} + +/// A new document with a selected 12 × 10 image of `blob` under `key`, linked to `/nowhere/art.png`. +fn linked(key: &str, blob: ImageBlob) -> (Session, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let key = key.to_string(); + let id = s + .edit("Place", |d, sel| { + d.images.insert(key.clone(), blob); + let id = d.alloc_id(); + let im = ImageObject { + key, + width: 12, + height: 10, + xf: Default::default(), + link: Some(vectorcraft_doc::LinkInfo::new("/nowhere/art.png")), + placement: Default::default(), + pixels: None, + }; + d.insert(d.default_layer(), 0, vectorcraft_doc::Node::new(id, NodeKind::Image(Box::new(im))))?; + sel.set([id]); + Ok(id) + }) + .unwrap(); + (s, id) +} + +/// A linked image keeps its link; outputs that refer to linked files write its masked pixels, and +/// applying the mask embeds it. +#[test] +fn a_linked_image_stays_linked_and_outputs_its_masked_pixels() { + let (mut s, id) = linked("linked", ImageBlob::png(framed())); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + let d = doc(&s); + assert_eq!((image_of(d, id).key.as_str(), image_of(d, id).link.map(|l| l.path)), ("linked", Some("/nowhere/art.png".to_string()))); + assert_eq!(drawn(d, id, 0, 0)[3], 0); + // Images written as files beside the SVG: the masked pixels are written, not a link to the + // linked file. + let r = s.execute("document.serialize", &json!({"format": "svg", "images": "link"})).unwrap(); + let text = r["text"].as_str().unwrap(); + assert!(!text.contains("/nowhere/art.png"), "{text}"); + assert_eq!(r["linked"].as_array().map(Vec::len), Some(1), "{r}"); + let r = s.execute("document.serialize", &json!({"format": "svg"})).unwrap(); + assert_eq!(svg_image(r["text"].as_str().unwrap()).to_rgba8().get_pixel(0, 0).0[3], 0); + let m = mask_of(doc(&s), id).unwrap(); + s.execute(APPLY_COLOR_MASK, &json!({})).unwrap(); + let im = image_of(doc(&s), id); + assert_eq!((im.key, im.link), (m.key, None), "applied: the masked pixels, embedded"); +} + +/// A mask that hides nothing (no pixel matches) leaves a linked image linked in outputs, and +/// applying it only takes it off: the image keeps its pixels and its link. +#[test] +fn a_mask_that_hides_nothing_keeps_the_link() { + let (mut s, id) = linked("linked", ImageBlob::png(framed())); + let r = s.execute(COLOR_MASK, &json!({"background": "colors", "colors": "#0000ff", "contiguous": false, "tolerance": 0, "softness": 0})).unwrap(); + assert_eq!((r["changed"].as_u64(), r["hidden"].as_u64()), (Some(1), Some(0))); + assert_eq!(mask_of(doc(&s), id).unwrap().key, "linked", "the masked pixels are the image's own"); + let r = s.execute("document.serialize", &json!({"format": "svg", "images": "link"})).unwrap(); + assert!(r["text"].as_str().unwrap().contains("/nowhere/art.png"), "{r}"); + assert_eq!(s.execute(APPLY_COLOR_MASK, &json!({})).unwrap()["changed"], 1); + let im = image_of(doc(&s), id); + assert_eq!((im.key.as_str(), im.link.map(|l| l.path), mask_of(doc(&s), id)), ("linked", Some("/nowhere/art.png".to_string()), None)); +} + +/// Color Mask refuses a linked image that shows its preview and an image too large to change, +/// with its own command's errors. +#[test] +fn color_mask_refuses_previews_and_images_too_large() { + let preview = std::sync::Arc::new(framed()); + let (mut s, id) = linked("missing", ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview) }); + let e = s.execute(COLOR_MASK, &hide_white()).unwrap_err().to_string(); + assert!(e.contains(COLOR_MASK) && e.contains("the linked image shows its preview: embed or relink it first"), "{e}"); + assert_eq!(mask_of(doc(&s), id), None); + // Without settings, the dialog's query reads the settings and opens on the defaults. + assert_eq!(s.execute(COLOR_MASK, &json!({})).unwrap()["masked"], json!(false)); + let (mut s, _) = open(&crate::tests_linkspanel::png_header(10_632, 10_631)); + let e = s.execute(COLOR_MASK, &hide_white()).unwrap_err().to_string(); + assert!(e.contains(COLOR_MASK) && e.contains("an image of 10632 × 10631 pixels is too large to change"), "{e}"); +} + +/// Crop Image off the pixel grid cuts the image's own pixels, so the hidden colors stay in them +/// and show again once the mask is removed. +#[test] +fn cropping_off_the_pixel_grid_keeps_the_hidden_colors_in_the_pixels() { + let (mut s, id) = open(&framed()); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + s.execute("object.cropImage", &json!({"rect": [0.5, 0.5, 6, 5]})).unwrap(); + let d = doc(&s); + let (im, m) = (image_of(d, id), mask_of(d, id).unwrap()); + assert_eq!(m.from, im.key, "the mask is made for the cut pixels"); + let own = image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_rgba8(); + assert!(own.pixels().all(|p| p.0[3] == 255), "the cut pixels are the image's own, white included"); + assert_eq!(drawn(d, id, 0, 0)[3], 0, "white is hidden"); + s.execute(REMOVE_COLOR_MASK, &json!({"ids": [id.0]})).unwrap(); + assert_eq!(drawn(doc(&s), id, 0, 0)[3], 255); +} + +/// Apply Color Mask on a mask made for older pixels makes it again for the image's own pixels, +/// and masked pixels of another size than the object records keep its place and size. +#[test] +fn applying_a_mask_made_for_older_pixels_makes_it_again_and_keeps_the_size() { + let (mut s, id) = open(&framed()); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + let before = doc(&s).node(id).unwrap().geometric_bounds().unwrap(); + // Pixels twice the size, put in place without an edit, so no refresh has run. + let big = ImageBlob::png(png(DynamicImage::ImageRgba8(image::RgbaImage::from_fn(24, 20, |x, y| { + let block = (6..18).contains(&x) && (6..14).contains(&y); + image::Rgba(if block { RED } else { WHITE }) + })))); + let key = big.content_key(); + let st = s.doc_mut().unwrap(); + let d = std::sync::Arc::make_mut(&mut st.doc); + d.images.insert(key.clone(), big); + if let NodeKind::Image(im) = &mut d.node_mut(id).unwrap().kind { + im.key = key.clone(); + } + assert_eq!(s.execute(APPLY_COLOR_MASK, &json!({})).unwrap()["changed"], 1); + let d = doc(&s); + let im = image_of(d, id); + assert_ne!(im.key, key, "the masked pixels of the new pixels"); + assert_eq!((im.width, im.height, mask_of(d, id)), (24, 20, None)); + let after = d.node(id).unwrap().geometric_bounds().unwrap(); + assert!((after.width() - before.width()).abs() < 1e-9 && (after.height() - before.height()).abs() < 1e-9, "{before:?} {after:?}"); + let px = image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_rgba8(); + assert_eq!((px.get_pixel(0, 0).0[3], px.get_pixel(10, 10).0), (0, RED)); +} + +/// A 12 × 10 grayscale image without alpha: white, with a black block from (3, 3) to (9, 7). +fn gray_framed() -> Vec<u8> { + png(DynamicImage::ImageLuma8(image::GrayImage::from_fn(12, 10, |x, y| { + image::Luma([if (3..9).contains(&x) && (3..7).contains(&y) { 0 } else { 255 }]) + }))) +} + +/// Masked pixels have an alpha channel: a grayscale image colorized with a process color can't +/// take a mask, and a masked one can't take a process color. +#[test] +fn a_process_color_does_not_colorize_masked_gray_pixels() { + const REFUSED: &str = "a process color can't colorize a grayscale image with transparency"; + let (mut s, id) = open(&gray_framed()); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + assert!(doc(&s).node(id).unwrap().extras().colorize.is_some(), "a gray image without alpha takes a process color"); + let (before, steps) = (doc(&s).clone(), undo_len(&s)); + let e = s.execute(COLOR_MASK, &hide_white()).unwrap_err().to_string(); + assert!(e.contains(REFUSED), "{e}"); + assert_eq!((doc(&s), undo_len(&s)), (&before, steps)); + // Black colorizes gray pixels with alpha: the mask is set, then a process color is refused. + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + assert_eq!(s.execute(COLOR_MASK, &hide_white()).unwrap()["changed"], 1); + let e = s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap_err().to_string(); + assert!(e.contains(REFUSED), "{e}"); +} + +/// Another image that already has an alpha channel and a process colorize color, as an opened file +/// can hold, neither lets a grayscale image colorized with a process color take a mask nor stops a +/// mask on an image that can take one. +#[test] +fn another_image_colorized_with_transparency_does_not_change_the_refusal() { + const REFUSED: &str = "a process color can't colorize a grayscale image with transparency"; + let (mut s, id) = open(&gray_framed()); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let held = ImageBlob::png(png(DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_pixel(2, 2, image::LumaA([128, 100]))))); + s.edit("Place", |d, _| { + let key = held.content_key(); + d.images.insert(key.clone(), held.clone()); + let other = d.alloc_id(); + let im = ImageObject { key, width: 2, height: 2, xf: Default::default(), link: None, placement: Default::default(), pixels: None }; + let mut n = Node::new(other, NodeKind::Image(Box::new(im))); + n.extras_mut().colorize = Some(Box::new(Paint::solid(Color::rgb8(255, 0, 0)))); + d.insert(d.default_layer(), 0, n)?; + Ok(()) + }) + .unwrap(); + assert_eq!(s.doc().unwrap().selection.objects, vec![id], "only the gray image is selected"); + let (before, steps) = (doc(&s).clone(), undo_len(&s)); + let e = s.execute(COLOR_MASK, &hide_white()).unwrap_err().to_string(); + assert!(e.contains(COLOR_MASK) && e.contains(REFUSED), "{e}"); + assert_eq!((doc(&s), undo_len(&s)), (&before, steps), "with another image refused already, nothing changes"); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + assert_eq!(s.execute(COLOR_MASK, &hide_white()).unwrap()["changed"], 1, "an image colorized with black takes the mask beside the other"); + let m = mask_of(doc(&s), id).unwrap(); + let masked = image::load_from_memory(&doc(&s).images[&m.key].bytes).unwrap().to_luma_alpha8(); + assert_eq!((masked.get_pixel(0, 0).0[1], masked.get_pixel(4, 4).0[1]), (0, 255), "white is hidden and black shows"); +} + +/// The mask is made from the image's own pixels: a grayscale image colorized with a process color +/// is refused even when an earlier mask, as an opened file can hold, shows color pixels. +#[test] +fn a_gray_image_whose_earlier_mask_shows_color_pixels_is_refused() { + let (mut s, id) = open(&gray_framed()); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let rgb = ImageBlob::png(framed()); + s.edit("Mask", |d, _| { + let key = rgb.content_key(); + d.images.insert(key.clone(), rgb.clone()); + let from = image_of(d, id).key; + let mask = ColorMask { key, from, ..mask_of_settings() }; + d.node_mut(id).unwrap().extras_mut().color_mask = Some(Box::new(mask)); + Ok(()) + }) + .unwrap(); + let (before, steps) = (doc(&s).clone(), undo_len(&s)); + let e = s.execute(COLOR_MASK, &hide_white()).unwrap_err().to_string(); + assert!(e.contains("a process color can't colorize a grayscale image with transparency"), "{e}"); + assert_eq!((doc(&s), undo_len(&s)), (&before, steps)); +} + +/// Remove Background clears the image's own pixels: a grayscale image colorized with a process +/// color is refused even when an earlier mask, as an opened file can hold, shows color pixels. +#[test] +fn remove_background_refuses_a_gray_image_whose_earlier_mask_shows_color_pixels() { + let (mut s, id) = open(&gray_framed()); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let rgb = ImageBlob::png(framed()); + let key = rgb.content_key(); + s.edit("Mask", |d, _| { + d.images.insert(key.clone(), rgb.clone()); + let from = image_of(d, id).key; + let mask = ColorMask { key: key.clone(), from, ..mask_of_settings() }; + d.node_mut(id).unwrap().extras_mut().color_mask = Some(Box::new(mask)); + Ok(()) + }) + .unwrap(); + let d = doc(&s); + let n = d.node(id).unwrap(); + let NodeKind::Image(im) = &n.kind else { panic!("an image") }; + assert_eq!(d.shown_image(n, im).key, key, "the image shows the color pixels"); + let (before, steps) = (doc(&s).clone(), undo_len(&s)); + let e = s.execute(super::super::REMOVE_BACKGROUND, &hide_white()).unwrap_err().to_string(); + assert!(e.contains("a process color can't colorize a grayscale image with transparency"), "{e}"); + assert_eq!((doc(&s), undo_len(&s)), (&before, steps)); +} + +/// A mask that hides nothing leaves the image's own pixels without transparency, so a grayscale +/// image colorized with a process color takes it. +#[test] +fn a_mask_that_hides_nothing_on_a_gray_image_colorized_with_a_process_color_is_set() { + let (mut s, id) = open(&gray_framed()); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let none = json!({"background": "colors", "colors": "#808080", "contiguous": false, "tolerance": 0, "softness": 0}); + let r = s.execute(COLOR_MASK, &none).unwrap(); + assert_eq!((r["changed"].as_u64(), r["hidden"].as_u64()), (Some(1), Some(0))); + let (m, im) = (mask_of(doc(&s), id).unwrap(), image_of(doc(&s), id)); + assert_eq!(m.key, im.key, "the masked pixels are the image's own"); + assert!(doc(&s).node(id).unwrap().extras().colorize.is_some(), "the image stays colorized"); +} + +/// New gray pixels whose colors a mask hides would take transparency, which a process color can't +/// colorize: the mask made again for them hides nothing, and Apply Color Mask refuses them. +#[test] +fn new_gray_pixels_under_a_process_color_are_not_masked() { + const REFUSED: &str = "a process color can't colorize a grayscale image with transparency"; + let gray = json!({"background": "colors", "colors": "#808080", "contiguous": false, "tolerance": 0, "softness": 0}); + let swapped = + || ImageBlob::png(png(DynamicImage::ImageLuma8(image::GrayImage::from_fn(12, 10, |x, _| image::Luma([if x < 6 { 128 } else { 0 }]))))); + let setup = || { + let (mut s, id) = open(&gray_framed()); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + assert_eq!(s.execute(COLOR_MASK, &gray).unwrap()["hidden"], 0, "no pixel is gray yet"); + (s, id) + }; + // Pixels put in place by an edit: the mask is made again for them and hides nothing. + let (mut s, id) = setup(); + s.edit("Swap", |d, _| { + let blob = swapped(); + let key = blob.content_key(); + d.images.insert(key.clone(), blob); + if let NodeKind::Image(im) = &mut d.node_mut(id).unwrap().kind { + im.key = key; + } + Ok(()) + }) + .unwrap(); + let d = doc(&s); + let (im, m) = (image_of(d, id), mask_of(d, id).unwrap()); + assert_eq!((m.from.as_str(), m.key.as_str()), (im.key.as_str(), im.key.as_str()), "the mask hides nothing"); + assert_eq!(crate::cmd::paint::check_colorized(d), Ok(())); + // Pixels put in place without an edit: Apply Color Mask makes the mask again and refuses it. + let (mut s, id) = setup(); + let blob = swapped(); + let key = blob.content_key(); + let st = s.doc_mut().unwrap(); + let d = std::sync::Arc::make_mut(&mut st.doc); + d.images.insert(key.clone(), blob); + if let NodeKind::Image(im) = &mut d.node_mut(id).unwrap().kind { + im.key = key; + } + let (before, steps) = (doc(&s).clone(), undo_len(&s)); + let e = s.execute(APPLY_COLOR_MASK, &json!({})).unwrap_err().to_string(); + assert!(e.contains(APPLY_COLOR_MASK) && e.contains(REFUSED), "{e}"); + assert_eq!((doc(&s), undo_len(&s)), (&before, steps)); +} + +/// A mask that hides white, made for another document's image (only its settings are of use). +fn mask_of_settings() -> ColorMask { + let (mut s, id) = open(&framed()); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + mask_of(doc(&s), id).unwrap() +} + +/// Images outside the layers (a symbol's art, opacity-mask art) take their masks again too when +/// their own pixels are replaced, as Update Link replaces them there. +#[test] +fn masks_outside_the_layers_are_made_again() { + let (mut s, id) = open(&framed()); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + let mut d = doc(&s).clone(); + let masked = d.node(id).unwrap().clone(); + let red = ImageBlob::png(png(DynamicImage::ImageRgba8(image::RgbaImage::from_fn(4, 4, |x, _| image::Rgba(if x == 0 { WHITE } else { RED }))))); + let key = red.content_key(); + d.images.insert(key.clone(), red); + let mut moved = masked.clone(); + if let NodeKind::Image(im) = &mut moved.kind { + im.key = key.clone(); + } + d.symbols.push(vectorcraft_doc::Symbol { name: "Logo".into(), art: std::sync::Arc::new(moved.clone()), dynamic: false }); + let holder_id = d.alloc_id(); + let mut holder = vectorcraft_doc::Node::new(holder_id, NodeKind::Group { children: vec![], clip: false }); + holder.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(moved, false))); + d.insert(d.default_layer(), 0, holder).unwrap(); + super::refresh(None, &mut d); + let from = |n: &vectorcraft_doc::Node| Document::color_mask_of(n).unwrap().from.clone(); + assert_eq!(from(&d.symbols.last().unwrap().art), key, "in the symbol's art"); + let art = &d.node(holder_id).unwrap().extras().mask.as_ref().unwrap().art; + assert_eq!(from(art), key, "in the opacity mask's art"); + let m = Document::color_mask_of(art).unwrap(); + let px = image::load_from_memory(&d.images[&m.key].bytes).unwrap().to_rgba8(); + assert_eq!((px.get_pixel(0, 0).0[3], px.get_pixel(1, 0).0), (0, RED)); +} + +/// `ids` stand in for the selection: an image that is not selected is changed by its id. +#[test] +fn images_given_by_id_need_not_be_selected() { + let (mut s, id) = open(&framed()); + s.execute("select.none", &json!({})).unwrap(); + assert_eq!( + s.execute(COLOR_MASK, &json!({"ids": [id.0], "background": "colors", "colors": "#fff", "tolerance": 0, "softness": 0})).unwrap()["changed"], + 1 + ); + assert_eq!(s.execute(REMOVE_COLOR_MASK, &json!({"ids": [id.0]})).unwrap()["changed"], 1); + s.execute(COLOR_MASK, &json!({"ids": [id.0], "background": "colors", "colors": "#fff", "tolerance": 0, "softness": 0})).unwrap(); + assert_eq!(s.execute(APPLY_COLOR_MASK, &json!({"ids": [id.0]})).unwrap()["changed"], 1); + assert_eq!(mask_of(doc(&s), id), None); +} + +#[test] +fn what_cannot_be_masked_is_refused_and_nothing_changes() { + let (mut s, id) = open(&framed()); + let steps = undo_len(&s); + let e = s.execute(COLOR_MASK, &json!({"tolerance": 101})).unwrap_err(); + assert!(e.to_string().contains("`tolerance` must be from 0 to 100"), "{e}"); + let e = s + .execute(COLOR_MASK, &json!({"background": "colors", "colors": "#fff, #c80000", "contiguous": false, "tolerance": 0, "softness": 0})) + .unwrap_err(); + assert!(e.to_string().contains("the mask would hide every pixel"), "{e}"); + assert_eq!((mask_of(doc(&s), id), undo_len(&s)), (None, steps)); + let inks = vectorcraft_doc::cmyk::Inks::new(4, 2, [0, 0, 0, 0].repeat(8)).unwrap(); + let (mut s, _) = open(&ImageBlob::cmyk_tiff(&inks).unwrap().bytes); + let e = s.execute(COLOR_MASK, &hide_white()).unwrap_err(); + assert!(e.to_string().contains("a CMYK image can't take a color mask"), "{e}"); + // Without settings, the dialog's query reads the settings and opens on the defaults. + assert_eq!(s.execute(COLOR_MASK, &json!({})).unwrap()["masked"], json!(false)); +} + +/// Remove Color Mask and Apply Color Mask refuse an object in `ids` that is not an image, as +/// Color Mask does. +#[test] +fn an_object_that_is_not_an_image_is_refused() { + let (mut s, id) = open(&framed()); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + let rect = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 4, "height": 4})).unwrap()["id"].as_u64().unwrap(); + let steps = undo_len(&s); + for cmd in [COLOR_MASK, REMOVE_COLOR_MASK, APPLY_COLOR_MASK] { + let mut p = if cmd == COLOR_MASK { hide_white() } else { json!({}) }; + p["ids"] = json!([id.0, rect]); + let e = s.execute(cmd, &p).unwrap_err().to_string(); + assert!(e.contains(&format!("object {rect} is not an image")), "{cmd}: {e}"); + } + assert!(mask_of(doc(&s), id).is_some()); + assert_eq!(undo_len(&s), steps); +} + +/// A mask that can't be made for the image's pixels (they are missing) is not made again on every +/// later edit: the art holding it is left as it is. +#[test] +fn a_mask_that_cannot_be_made_is_not_made_again_on_every_edit() { + let (mut s, id) = open(&framed()); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + let mut d = doc(&s).clone(); + if let NodeKind::Image(im) = &mut d.node_mut(id).unwrap().kind { + im.key = "gone".into(); + } + super::refresh(None, &mut d); + assert_eq!(mask_of(&d, id).unwrap().key, "gone", "it hides nothing"); + let layer = d.layers[0].clone(); + super::refresh(None, &mut d); + assert!(std::sync::Arc::ptr_eq(&layer, &d.layers[0]), "the second pass changes nothing"); +} + +/// The original of a pattern being edited takes its masks again too. +#[test] +fn the_pattern_being_edited_takes_its_masks_again() { + let (mut s, id) = open(&framed()); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + let mut d = doc(&s).clone(); + let mut art = d.node(id).unwrap().clone(); + let red = ImageBlob::png(png(DynamicImage::ImageRgba8(image::RgbaImage::from_fn(4, 4, |x, _| image::Rgba(if x == 0 { WHITE } else { RED }))))); + let key = red.content_key(); + d.images.insert(key.clone(), red); + if let NodeKind::Image(im) = &mut art.kind { + im.key = key.clone(); + } + let original = vectorcraft_doc::PatternDef::new("Tile", vec![std::sync::Arc::new(art)]); + d.pattern_edit = Some(vectorcraft_doc::PatternEdit { pattern: "Tile".into(), layer: NodeId(999_999), original: Some(original) }); + super::refresh(None, &mut d); + let original = d.pattern_edit.as_ref().and_then(|e| e.original.as_ref()).unwrap(); + assert_eq!(Document::color_mask_of(&original.art[0]).unwrap().from, key); +} + +/// A linked file read again as the document opens (Update Links: Automatically) takes the mask +/// for its new pixels. +#[test] +fn a_linked_file_read_again_on_open_takes_the_mask_again() { + let dir = crate::tests_links::Folder::new("color-mask"); + let pic = dir.file("art.png"); + crate::tests_links::write(&pic, &framed()); + let mut s = crate::tests_links::session(); + let id = crate::tests_links::place(&mut s, &pic); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + let saved = dir.file("art.vectorcraft"); + crate::tests_links::save(&mut s, &saved); + // New pixels in the file: blue where the block was red. + let blue = png(DynamicImage::ImageRgba8(image::RgbaImage::from_fn(12, 10, |x, y| { + image::Rgba(if (3..9).contains(&x) && (3..7).contains(&y) { [0, 0, 200, 255] } else { WHITE }) + }))); + crate::tests_links::write(&pic, &blue); + s.execute("prefs.set", &json!({"key": "updateLinks", "value": "automatically"})).unwrap(); + let r = crate::tests_links::open(&mut s, &saved); + assert_eq!(r["updatedLinks"][0]["ids"], json!([id.0]), "{r}"); + let d = doc(&s); + let (im, m) = (image_of(d, id), mask_of(d, id).unwrap()); + assert_eq!(m.from, im.key, "made for the file's new pixels"); + let px = image::load_from_memory(&d.images[&m.key].bytes).unwrap().to_rgba8(); + assert_eq!((px.get_pixel(0, 0).0[3], px.get_pixel(4, 4).0), (0, [0, 0, 200, 255])); +} + +/// The bytes of every file `format` writes for `d` with `p`. +fn written(d: &Document, format: &str, p: Value) -> Vec<Vec<u8>> { + crate::cmd::fileio::encode_all(d, format, &p).unwrap().files.into_iter().map(|f| f.1).collect() +} + +/// `out` for the opened image without a mask, with one hiding its red block, and with the mask +/// removed again: the mask changes what is written, and removing it gives the same output as +/// before. (Outputs that flatten see-through pixels over the white page show the hidden block as +/// white.) +fn written_with_the_mask<T: PartialEq + std::fmt::Debug>(out: impl Fn(&Document) -> T) { + let (mut s, _) = open(&framed()); + let plain = out(doc(&s)); + s.execute(COLOR_MASK, &json!({"background": "colors", "colors": "#c80000", "contiguous": false, "tolerance": 0, "softness": 0})).unwrap(); + let masked = out(doc(&s)); + s.execute(REMOVE_COLOR_MASK, &json!({})).unwrap(); + assert_ne!(plain, masked, "the masked pixels are written"); + assert_eq!(out(doc(&s)), plain, "without the mask, the image's own"); +} + +#[test] +fn dxf_writes_the_masked_pixels() { + written_with_the_mask(|d| written(d, "dxf", json!({}))); +} + +#[test] +fn emf_and_wmf_write_the_masked_pixels() { + written_with_the_mask(|d| written(d, "emf", json!({}))); + written_with_the_mask(|d| written(d, "wmf", json!({}))); +} + +#[test] +fn legacy_ai_writes_the_masked_pixels() { + written_with_the_mask(|d| written(d, "ai", json!({"aiVersion": 7}))); +} + +#[test] +fn ai_editing_data_writes_the_masked_pixels() { + let o = vectorcraft_eps::AiEditingOptions { title: "art".into(), created: Some(0) }; + written_with_the_mask(|d| vectorcraft_eps::export_ai_editing(d, &o).unwrap().program); +} + +/// PDF/X-1a and PDF/X-3 flatten a masked image, whose hidden pixels are transparency, and write no +/// soft mask. +#[test] +fn pdf_x1a_and_x3_flatten_the_hidden_pixels() { + for standard in ["pdfX1a", "pdfX3"] { + let (mut s, _) = open(&framed()); + let export = |s: &mut Session| { + let v = s.execute("document.exportPdf", &json!({"standard": standard, "compression": {"compressText": false}})).unwrap(); + let bytes = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap(); + (String::from_utf8_lossy(&bytes).into_owned(), v["warnings"].to_string()) + }; + let (_, warnings) = export(&mut s); + assert!(!warnings.contains("flattened"), "{standard}, an opaque image: {warnings}"); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + let (text, warnings) = export(&mut s); + assert!(warnings.contains("flattened"), "{standard}: {warnings}"); + assert!(!text.contains("/SMask"), "{standard}"); + } +} + +/// The legacy .ai flattens a masked image, whose hidden pixels are transparency, as it flattens an +/// image whose background was removed, and `transparentImages: "omit"` leaves both out. +#[test] +fn legacy_ai_flattens_a_masked_image_as_a_see_through_one() { + let warnings = |s: &Session, p: &Value| crate::cmd::fileio::encode_all(doc(s), "ai", p).unwrap().notes(); + let (mut masked, _) = open(&framed()); + masked.execute(COLOR_MASK, &hide_white()).unwrap(); + let (mut cleared, _) = open(&framed()); + cleared.execute(super::super::REMOVE_BACKGROUND, &hide_white()).unwrap(); + for (p, said) in [(json!({"aiVersion": 7}), "are flattened"), (json!({"aiVersion": 7, "transparentImages": "omit"}), "are left out")] { + let w = warnings(&masked, &p); + assert!(w.iter().any(|w| w.contains("transparent images") && w.contains(said)), "{p}: {w:?}"); + assert_eq!(w, warnings(&cleared, &p), "{p}"); + } +} + +/// A live color adjustment recolors the masked pixels too: the hidden colors stay hidden on the +/// canvas and in outputs that apply the adjustment. +#[test] +fn a_live_color_adjustment_keeps_the_hidden_colors_hidden() { + let (mut s, id) = open(&framed()); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + s.execute("effect.apply", &json!({"effect": "adjust.hueSaturation", "params": {"hue": 120}})).unwrap(); + let d = doc(&s); + assert_eq!(drawn(d, id, 1, 1)[3], 0, "the hidden white"); + let block = drawn(d, id, 4, 4); + assert!(block[3] == 255 && block != RED, "the red block, recolored: {block:?}"); + let r = s.execute("document.serialize", &json!({"format": "svg"})).unwrap(); + let px = svg_image(r["text"].as_str().unwrap()).to_rgba8(); + assert_eq!(px.get_pixel(1, 1).0[3], 0, "SVG: the hidden white"); + assert!(px.get_pixel(4, 4).0[3] == 255 && px.get_pixel(4, 4).0 != RED, "SVG: the red block, recolored"); +} + +/// An image whose masked pixels are missing from the document is drawn and expanded from its own +/// pixels with a live color adjustment, as it is drawn without one. +#[test] +fn a_live_color_adjustment_recolors_the_image_when_its_masked_pixels_are_missing() { + let (mut s, id) = open(&framed()); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + s.execute("effect.apply", &json!({"effect": "adjust.hueSaturation", "params": {"hue": 120}})).unwrap(); + let mut d = doc(&s).clone(); + let masked = mask_of(&d, id).unwrap().key; + assert!(d.images.remove(&masked).is_some(), "the masked pixels were in the document"); + assert_eq!(drawn(&d, id, 1, 1), WHITE, "the white shows"); + let block = drawn(&d, id, 4, 4); + assert!(block[3] == 255 && block != RED, "the red block, recolored: {block:?}"); + let node = d.node(id).unwrap().clone(); + let out = vectorcraft_render::effects::adjust_in_document(&mut d, &node, None).unwrap(); + let NodeKind::Image(im) = &out.kind else { panic!("an image") }; + assert_ne!(im.key, image_of(&d, id).key, "the expanded image is recolored"); + assert_eq!(Document::color_mask_of(&out), None, "the expanded image has no mask to make again from the recolored pixels"); + let px = image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_rgba8(); + assert_eq!(px.get_pixel(1, 1).0, WHITE, "the expanded image shows the white"); +} + +/// An envelope warp draws the image's masked pixels in its pieces. +#[test] +fn an_envelope_warp_draws_the_masked_pixels() { + let (mut s, id) = open(&framed()); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + let (white, red) = (pixel_at(doc(&s), id, 1, 1), pixel_at(doc(&s), id, 4, 4)); + s.execute("object.envelope.makeWithWarp", &json!({"style": "arch", "bend": 0})).unwrap(); + assert_eq!(drawn_at(doc(&s), white)[3], 0, "the hidden white"); + assert!(drawn_at(doc(&s), red)[3] > 0, "the red block"); +} + +/// A geometry effect draws the image's masked pixels, and Expand Appearance keeps the mask on the +/// image it makes. +#[test] +fn a_transform_effect_keeps_the_mask() { + let (mut s, id) = open(&framed()); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + let moved = |p: vectorcraft_geom::Point| vectorcraft_geom::Point::new(p.x + 30.0, p.y); + let (white, red) = (moved(pixel_at(doc(&s), id, 1, 1)), moved(pixel_at(doc(&s), id, 4, 4))); + s.execute("effect.apply", &json!({"ids": [id.0], "effect": "distort.transform", "params": {"moveH": 30}})).unwrap(); + assert_eq!(drawn_at(doc(&s), white)[3], 0, "the hidden white"); + assert_eq!(drawn_at(doc(&s), red), RED, "the red block"); + s.execute("effect.expandAppearance", &json!({})).unwrap(); + let mut masks = vec![]; + doc(&s).walk(|n| masks.extend(Document::color_mask_of(n).cloned())); + assert_eq!(masks.len(), 1, "the expanded image keeps its mask"); +} + +/// A pattern whose tile holds a masked image counts as one with a see-through image, so outputs +/// without transparency expand it before they flatten. +#[test] +fn a_pattern_tile_with_a_masked_image_counts_as_see_through() { + let href = format!("data:image/png;base64,{}", vectorcraft_format::base64_encode(&framed())); + let svg = format!( + r##"<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100" height="100" viewBox="0 0 100 100"><defs><pattern id="p" patternUnits="userSpaceOnUse" width="12" height="10"><image width="12" height="10" xlink:href="{href}"/></pattern></defs><rect width="100" height="100" fill="url(#p)"/></svg>"## + ); + let mut s = Session::new(); + s.execute("document.open", &json!({"name": "p.svg", "dataBase64": vectorcraft_format::base64_encode(svg.as_bytes())})).unwrap(); + let mut d = doc(&s).clone(); + let see_through = + |d: &Document| crate::cmd::expand::has_transparent_image_patterns(d, &crate::cmd::flatten::see_through_images(d), &|_, _| false); + assert!(!see_through(&d), "an opaque tile"); + let hidden = png(DynamicImage::ImageRgba8(image::RgbaImage::from_fn(12, 10, |x, _| image::Rgba(if x == 0 { [0; 4] } else { RED })))); + d.images.insert("masked".into(), ImageBlob::png(hidden)); + fn image_in(n: &mut vectorcraft_doc::Node) -> Option<&mut vectorcraft_doc::Node> { + if matches!(n.kind, NodeKind::Image(_)) { + return Some(n); + } + n.children_mut()?.iter_mut().find_map(|c| image_in(std::sync::Arc::make_mut(c))) + } + let node = d.patterns.iter_mut().flat_map(|p| p.art.iter_mut()).find_map(|a| image_in(std::sync::Arc::make_mut(a))).unwrap(); + let NodeKind::Image(im) = &node.kind else { panic!("the tile's image") }; + let from = im.key.clone(); + node.extras_mut().color_mask = Some(Box::new(ColorMask { + key: "masked".into(), + from, + background: MaskBackground::Colors, + colors: vec![[255, 255, 255]], + contiguous: false, + measure: vectorcraft_doc::color_mask::MaskMatch::Distance, + tolerance: 0.0, + softness: 0.0, + })); + assert!(see_through(&d), "the tile shows its masked pixels"); +} + +/// SVG writes a colorized gray image with a mask as the coverage of its masked pixels, shared by +/// the objects that show it. +#[test] +fn svg_writes_a_colorized_masked_image_as_it_shows() { + let (mut s, _) = open(&gray_framed()); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute(COLOR_MASK, &json!({"background": "colors", "colors": "#000000", "contiguous": false, "tolerance": 0, "softness": 0})).unwrap(); + s.execute("edit.duplicate", &json!({})).unwrap(); + let r = s.execute("document.serialize", &json!({"format": "svg"})).unwrap(); + let text = r["text"].as_str().unwrap(); + assert_eq!(text.matches("data:image/png;base64,").count(), 1, "one shared image: {text}"); + assert_eq!(svg_image(text).to_rgba8().get_pixel(4, 4).0[3], 0, "the hidden black block covers nothing"); +} + +/// The opened masked image moved into what `wrap` makes of it (given the document, to take ids +/// from, and the image node). +fn wrapped(wrap: impl FnOnce(&mut Document, vectorcraft_doc::Node) -> vectorcraft_doc::Node) -> (Session, NodeId) { + let (mut s, id) = open(&framed()); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + s.edit("Wrap", |d, _| { + let (parent, index, _) = d.position(id).unwrap(); + let image = (*d.remove(id)?).clone(); + let holder = wrap(d, image); + d.insert(parent, index, holder)?; + Ok(()) + }) + .unwrap(); + (s, id) +} + +/// The rectangle of the opened image's frame (12 × 10 at the origin) filled with `fill`. +fn frame(d: &mut Document, fill: vectorcraft_color::Paint) -> vectorcraft_doc::Node { + let rect = vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 12.0, 10.0)); + vectorcraft_doc::Node::path(d.alloc_id(), rect, vectorcraft_doc::Appearance::basic(fill, vectorcraft_color::Paint::None, 0.0)) +} + +/// An image in a clip group of its own frame, which the canvas draws straight into the clipping +/// path, shows its masked pixels. +#[test] +fn a_clipped_image_draws_its_masked_pixels() { + let (s, id) = wrapped(|d, image| { + let clip = frame(d, vectorcraft_color::Paint::None); + vectorcraft_doc::Node::new( + d.alloc_id(), + NodeKind::Group { children: vec![std::sync::Arc::new(clip), std::sync::Arc::new(image)], clip: true }, + ) + }); + assert_eq!((drawn(doc(&s), id, 0, 0)[3], drawn(doc(&s), id, 4, 4)), (0, RED)); +} + +/// An image whose opacity mask is one white shape, which the canvas draws straight into the +/// shape, shows its masked pixels. +#[test] +fn an_image_masked_by_a_white_shape_draws_its_masked_pixels() { + let (s, id) = wrapped(|d, image| { + let white = frame(d, vectorcraft_color::Paint::solid(vectorcraft_color::Color::WHITE)); + image.with_mask(Some(Box::new(vectorcraft_doc::OpacityMask::new(white, true)))) + }); + assert_eq!((drawn(doc(&s), id, 0, 0)[3], drawn(doc(&s), id, 4, 4)), (0, RED)); +} + +/// Pasting into a document that has other pixels under the image's names renames them, and the +/// mask follows: the masked pixels come along under their new name, nothing is decoded again. +#[test] +fn paste_renames_the_masked_pixels_with_the_image() { + let (mut s, id) = open(&framed()); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + let m = mask_of(doc(&s), id).unwrap(); + let masked = doc(&s).images[&m.key].bytes.clone(); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let other = ImageBlob::png(png(DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(2, 2, image::Rgba(RED))))); + s.edit("Taken names", |d, _| { + d.images.insert(m.key.clone(), other.clone()); + d.images.insert(m.from.clone(), other.clone()); + Ok(()) + }) + .unwrap(); + super::super::DECODES.with(|c| c.set(0)); + s.execute("edit.paste", &json!({})).unwrap(); + assert_eq!(super::super::DECODES.with(|c| c.get()), 0, "nothing is decoded to make the mask again"); + let id = s.doc().unwrap().selection.objects[0]; + let d = doc(&s); + let (im, pasted) = (image_of(d, id), mask_of(d, id).unwrap()); + assert!(pasted.key != m.key && pasted.from != m.from, "renamed: {pasted:?}"); + assert!(pasted.made_for(&im)); + assert_eq!(d.images[&pasted.key].bytes, masked); + assert_eq!((drawn(d, id, 0, 0)[3], drawn(d, id, 4, 4)), (0, RED)); +} + +/// Placing a document (as an editable copy) whose image has a mask brings the masked pixels, and +/// the mask follows names the placing document already uses for other pixels. +#[test] +fn placing_a_document_brings_the_masked_pixels() { + let (mut s, id) = open(&framed()); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + let m = mask_of(doc(&s), id).unwrap(); + let file = vectorcraft_format::save_file(doc(&s)); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let other = ImageBlob::png(png(DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(2, 2, image::Rgba(RED))))); + s.edit("Taken names", |d, _| { + d.images.insert(m.from.clone(), other.clone()); + Ok(()) + }) + .unwrap(); + super::super::DECODES.with(|c| c.set(0)); + let r = + s.execute("file.place", &json!({"name": "art.vectorcraft", "dataBase64": vectorcraft_format::base64_encode(&file), "link": false})).unwrap(); + assert_eq!(super::super::DECODES.with(|c| c.get()), 0, "nothing is decoded to make the mask again: {r}"); + let d = doc(&s); + let mut found = vec![]; + for root in d.art_roots() { + root.walk(&mut |n| { + if let (NodeKind::Image(im), Some(m)) = (&n.kind, Document::color_mask_of(n)) { + found.push(((**im).clone(), m.clone())); + } + }); + } + let [(im, placed)] = found.as_slice() else { panic!("one masked image: {found:?}") }; + assert!(placed.made_for(im) && placed.from != m.from, "the image was renamed and the mask follows: {placed:?}"); + let px = image::load_from_memory(&d.images[&placed.key].bytes).unwrap().to_rgba8(); + assert_eq!((px.get_pixel(0, 0).0[3], px.get_pixel(4, 4).0), (0, RED)); +} diff --git a/crates/engine/src/cmd/addons/image/tests.rs b/crates/engine/src/cmd/addons/image/tests.rs new file mode 100644 index 0000000000..ae59efad87 --- /dev/null +++ b/crates/engine/src/cmd/addons/image/tests.rs @@ -0,0 +1,529 @@ +use std::io::Cursor; +use std::sync::Arc; + +use image::{DynamicImage, ImageBuffer, Luma, LumaA, Rgb}; +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{ImageBlob, ImageObject, LinkInfo, Node, NodeId, NodeKind}; +use vectorcraft_geom::Affine; + +use super::{Background, Match, REMOVE_BACKGROUND as C, Settings, level, levels}; +use crate::Session; +use crate::cmd::fileio::ppi; + +const WHITE: [u8; 4] = [255, 255, 255, 255]; +const RED: [u8; 4] = [200, 0, 0, 255]; + +/// The command's defaults with `background`. +fn settings(background: Background) -> Settings { + Settings { background, contiguous: true, measure: Match::Distance, tolerance: 10.0, softness: 10.0 } +} + +fn png(img: DynamicImage) -> Vec<u8> { + let mut out = Vec::new(); + img.write_to(&mut Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out +} + +/// 12 × 10 pixels: white, with a red block from (3, 3) to (9, 7) that holds one white pixel at +/// (6, 5), which no white edge pixel reaches. +fn framed() -> image::RgbaImage { + image::RgbaImage::from_fn(12, 10, |x, y| { + let block = (3..9).contains(&x) && (3..7).contains(&y); + image::Rgba(if block && (x, y) != (6, 5) { RED } else { WHITE }) + }) +} + +/// A session with `bytes` opened as a document, its image selected. +fn open(bytes: &[u8]) -> (Session, NodeId) { + let mut s = Session::new(); + s.execute("document.open", &json!({"name": "art.png", "dataBase64": vectorcraft_format::base64_encode(bytes)})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + let id = s.doc().unwrap().selection.objects[0]; + (s, id) +} + +fn image_of(s: &Session, id: NodeId) -> ImageObject { + let NodeKind::Image(im) = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("an image") }; + (**im).clone() +} + +fn bytes_of(s: &Session, id: NodeId) -> Arc<Vec<u8>> { + s.doc().unwrap().doc.images[&image_of(s, id).key].bytes.clone() +} + +fn pixels(s: &Session, id: NodeId) -> DynamicImage { + image::load_from_memory(&bytes_of(s, id)).unwrap() +} + +fn alpha(img: &DynamicImage, x: u32, y: u32) -> u8 { + img.to_rgba8().get_pixel(x, y).0[3] +} + +fn undo_len(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +#[test] +fn the_edge_colors_are_cleared_where_they_reach_in_from_an_edge() { + let (mut s, id) = open(&png(DynamicImage::ImageRgba8(framed()))); + let before = (image_of(&s, id), undo_len(&s)); + let r = s.execute(C, &json!({})).unwrap(); + assert_eq!(r, json!({"changed": 1, "ids": [id.0], "cleared": 12 * 10 - 6 * 4})); + let out = pixels(&s, id); + assert_eq!(out.color(), image::ColorType::Rgba8); + assert_eq!((alpha(&out, 0, 0), alpha(&out, 11, 9), alpha(&out, 2, 4)), (0, 0, 0), "the white around the block"); + assert_eq!(out.to_rgba8().get_pixel(4, 4).0, RED, "the block"); + assert_eq!(alpha(&out, 6, 5), 255, "white inside the block, which no edge reaches"); + let after = image_of(&s, id); + assert_eq!((after.width, after.height, after.xf), (12, 10, before.0.xf), "the same place and size"); + assert_eq!(undo_len(&s), before.1 + 1, "one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(image_of(&s, id), before.0); +} + +/// Picked colors, like the other backgrounds, are cleared where they reach in from an edge, and with +/// `contiguous: false` wherever they are. +#[test] +fn picked_colors_are_cleared_from_the_edges_or_wherever_they_are() { + let (mut s, id) = open(&png(DynamicImage::ImageRgba8(framed()))); + s.execute(C, &json!({"background": "colors", "colors": ["#fff"], "tolerance": 0, "softness": 0})).unwrap(); + let out = pixels(&s, id); + assert_eq!((alpha(&out, 0, 0), alpha(&out, 6, 5), alpha(&out, 4, 4)), (0, 255, 255), "not inside the block"); + let (mut s, id) = open(&png(DynamicImage::ImageRgba8(framed()))); + s.execute(C, &json!({"background": "colors", "colors": ["#fff"], "contiguous": false, "tolerance": 0, "softness": 0})).unwrap(); + let out = pixels(&s, id); + assert_eq!((alpha(&out, 0, 0), alpha(&out, 6, 5), alpha(&out, 4, 4)), (0, 0, 255), "inside the block too; the red stays"); +} + +/// With `contiguous: false` the edge color is cleared inside the subject too. +#[test] +fn the_edge_color_can_be_cleared_wherever_it_is() { + let (mut s, id) = open(&png(DynamicImage::ImageRgba8(framed()))); + let r = s.execute(C, &json!({"contiguous": false})).unwrap(); + assert_eq!(r["cleared"], 12 * 10 - 6 * 4 + 1); + let out = pixels(&s, id); + assert_eq!((alpha(&out, 0, 0), alpha(&out, 6, 5), alpha(&out, 4, 4)), (0, 0, 255)); +} + +/// `colors` as one string split by commas and spaces, written as other color params take them. +#[test] +fn picked_colors_can_be_one_string_of_colors() { + for colors in ["#00ff00, ffffff", "green white", "#0f0,#FFF"] { + let (mut s, id) = open(&png(DynamicImage::ImageRgba8(framed()))); + s.execute(C, &json!({"background": "colors", "colors": colors, "contiguous": false, "tolerance": 0, "softness": 0})).unwrap(); + let out = pixels(&s, id); + assert_eq!((alpha(&out, 0, 0), alpha(&out, 6, 5), alpha(&out, 4, 4)), (0, 0, 255), "{colors}"); + } +} + +/// A subject along a whole edge stays: only the most common edge color is the background. +#[test] +fn a_subject_along_one_edge_is_not_the_background() { + let img = image::RgbaImage::from_fn(10, 10, |_, y| image::Rgba(if y >= 7 { RED } else { WHITE })); + let (mut s, id) = open(&png(DynamicImage::ImageRgba8(img))); + s.execute(C, &json!({})).unwrap(); + let out = pixels(&s, id); + assert_eq!((alpha(&out, 5, 0), alpha(&out, 5, 9), alpha(&out, 0, 8)), (0, 255, 255)); +} + +/// The preview steps of one interaction, as the dialog's are, decode an image once and give what a +/// run on freshly decoded pixels gives. The pixels are kept only until the interaction ends (OK or +/// Cancel), and a run that is not a preview step keeps none. +#[test] +fn preview_steps_on_the_same_pixels_decode_them_once() { + let decodes = || super::DECODES.with(std::cell::Cell::get); + let (mut s, id) = open(&png(DynamicImage::ImageRgba8(framed()))); + let start = decodes(); + let p = json!({"background": "colors", "colors": "#c80000", "contiguous": false, "tolerance": 0, "softness": 0}); + s.begin_interaction("Remove Background").unwrap(); + s.preview(C, &json!({"tolerance": 0, "softness": 0})).unwrap(); + s.preview(C, &json!({"tolerance": 20, "softness": 0})).unwrap(); + s.preview(C, &p).unwrap(); + assert_eq!((decodes() - start, s.decoded_images.len()), (1, 1), "decoded once for three preview steps"); + s.commit_interaction().unwrap(); + assert_eq!(s.decoded_images.len(), 0, "OK lets the pixels go"); + let (mut fresh, fresh_id) = open(&png(DynamicImage::ImageRgba8(framed()))); + fresh.execute(C, &p).unwrap(); + assert_eq!((decodes() - start, fresh.decoded_images.len()), (2, 0), "a run that is not a preview step keeps nothing"); + assert_eq!(bytes_of(&s, id), bytes_of(&fresh, fresh_id), "the same result"); + assert_eq!((alpha(&pixels(&s, id), 4, 4), alpha(&pixels(&s, id), 0, 0)), (0, 255), "the red cleared, the white kept"); + s.execute("edit.undo", &json!({})).unwrap(); + s.begin_interaction("Remove Background").unwrap(); + s.preview(C, &json!({})).unwrap(); + assert_eq!(s.decoded_images.len(), 1); + s.cancel_interaction().unwrap(); + assert_eq!(s.decoded_images.len(), 0, "Cancel lets the pixels go"); + s.execute(C, &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute(C, &json!({})).unwrap(); + assert_eq!(decodes() - start, 5, "each run that is not a preview step decodes"); +} + +/// Pixels a preview step takes from the step before keep what they were decoded with: a 16-bit gray +/// image with an ICC profile comes out as a run on freshly decoded pixels gives it. +#[test] +fn reused_pixels_keep_their_depth_gray_and_profile() { + use image::{ImageDecoder as _, ImageEncoder as _}; + let icc = b"a profile's bytes".to_vec(); + let gray16 = ImageBuffer::from_fn(8, 8, |x, y| Luma([if (2..6).contains(&x) && (2..6).contains(&y) { 7_000u16 } else { 61_000 }])); + let mut bytes = Vec::new(); + let mut encoder = image::codecs::png::PngEncoder::new(&mut bytes); + encoder.set_icc_profile(icc.clone()).unwrap(); + DynamicImage::ImageLuma16(gray16).write_with_encoder(encoder).unwrap(); + let decodes = || super::DECODES.with(std::cell::Cell::get); + let (mut s, id) = open(&bytes); + let start = decodes(); + s.begin_interaction("Remove Background").unwrap(); + s.preview(C, &json!({"tolerance": 0, "softness": 0})).unwrap(); + s.preview(C, &json!({})).unwrap(); + assert_eq!(decodes() - start, 1, "the second step took the pixels of the first"); + let (mut fresh, fresh_id) = open(&bytes); + fresh.execute(C, &json!({})).unwrap(); + assert_eq!(bytes_of(&s, id), bytes_of(&fresh, fresh_id), "the same result"); + let DynamicImage::ImageLumaA16(out) = pixels(&s, id) else { panic!("16-bit gray with alpha") }; + assert_eq!((out.get_pixel(0, 0).0, out.get_pixel(3, 3).0), ([61_000, 0], [7_000, 65_535])); + let result = bytes_of(&s, id); + let mut decoder = image::codecs::png::PngDecoder::new(Cursor::new(result.as_slice())).unwrap(); + assert_eq!(decoder.icc_profile().unwrap(), Some(icc)); +} + +/// Once the background is cleared, most edge pixels are clear and a second run clears nothing: the +/// subject's color along an edge is not taken for the background. +#[test] +fn a_second_run_leaves_the_subject() { + let img = image::RgbaImage::from_fn(10, 10, |x, y| { + image::Rgba(if y >= 7 { + RED + } else if (4..6).contains(&x) && (3..5).contains(&y) { + [0, 0, 200, 255] + } else { + WHITE + }) + }); + let (mut s, id) = open(&png(DynamicImage::ImageRgba8(img))); + s.execute(C, &json!({})).unwrap(); + let (first, steps) = (image_of(&s, id), undo_len(&s)); + let r = s.execute(C, &json!({})).unwrap(); + assert_eq!(r, json!({"changed": 0, "ids": [], "cleared": 0})); + assert_eq!((image_of(&s, id), undo_len(&s)), (first, steps), "no change and no undo step"); + let out = pixels(&s, id); + assert_eq!((alpha(&out, 5, 0), alpha(&out, 5, 9), alpha(&out, 4, 3)), (0, 255, 255), "the red and the blue stay"); +} + +#[test] +fn tolerance_and_softness_set_how_near_a_color_is_cleared() { + // White; 1.96 % from white; 21.6 % from white. + let px = [WHITE, [250, 250, 250, 255], [200, 200, 200, 255]]; + let at = |i: usize| px[i].map(|v| u16::from(v) * 257); + let run = |tolerance, softness| levels(3, 1, &at, &Settings { tolerance, softness, ..settings(Background::Colors(vec![[255; 3]])) }); + assert_eq!(run(0.0, 0.0), [0, 255, 255], "only white itself at 0"); + assert_eq!(run(2.0, 0.0), [0, 0, 255]); + assert_eq!(run(0.0, 10.0), [0, 50, 255], "1.96 % into a 10 % fade"); + assert_eq!(run(100.0, 0.0), [0, 0, 0], "everything at 100"); +} + +#[test] +fn a_result_with_no_pixel_left_is_refused_and_changes_nothing() { + let (mut s, id) = open(&png(DynamicImage::ImageRgba8(framed()))); + let before = (image_of(&s, id), undo_len(&s)); + let e = s.execute(C, &json!({"background": "colors", "colors": "#ffffff", "tolerance": 100})).unwrap_err(); + assert!(e.to_string().contains("every pixel matches the background"), "{e}"); + assert_eq!((image_of(&s, id), undo_len(&s)), before); +} + +#[test] +fn an_image_whose_pixels_do_not_change_is_left_with_no_undo_step() { + let (mut s, id) = open(&png(DynamicImage::ImageRgba8(framed()))); + let before = (image_of(&s, id), undo_len(&s)); + let r = s.execute(C, &json!({"background": "colors", "colors": "#00ff00", "tolerance": 0, "softness": 0})).unwrap(); + assert_eq!(r, json!({"changed": 0, "ids": [], "cleared": 0})); + assert_eq!((image_of(&s, id), undo_len(&s)), before); + // An image whose edges and corners are already clear has no edge or corner color to clear, + // whatever color the clear pixels hold. + let ring = + image::RgbaImage::from_fn(6, 6, |x, y| image::Rgba(if (1..5).contains(&x) && (1..5).contains(&y) { WHITE } else { [255, 255, 255, 0] })); + for p in [json!({}), json!({"background": "corners", "contiguous": false})] { + let (mut s, _) = open(&png(DynamicImage::ImageRgba8(ring.clone()))); + assert_eq!(s.execute(C, &p).unwrap()["changed"], 0, "{p}"); + } +} + +/// The corners' color: 40 × 30 pixels of light gray around a red block, cleared within 5 steps on +/// each channel (`match: channels`, a tolerance of `5 / 255 × 100`, no softness), from the edges +/// or wherever it is. +#[test] +fn the_corners_color_is_cleared() { + let img = image::RgbaImage::from_fn(40, 30, |x, y| { + image::Rgba(if (10..30).contains(&x) && (8..22).contains(&y) { [200, 40, 40, 255] } else { [240, 240, 240, 255] }) + }); + for contiguous in [false, true] { + let (mut s, id) = open(&png(DynamicImage::ImageRgba8(img.clone()))); + let p = json!({"background": "corners", "contiguous": contiguous, "match": "channels", "tolerance": 5.0 / 255.0 * 100.0, "softness": 0}); + let r = s.execute(C, &p).unwrap(); + assert_eq!(r["cleared"], 40 * 30 - 14 * 20, "{p}"); + let out = pixels(&s, id).to_rgba8(); + assert_eq!((out.get_pixel(0, 0).0[3], out.get_pixel(15, 15).0), (0, [200, 40, 40, 255]), "{p}"); + } + // A clear corner is left out of the average: the other three are white, and white is cleared. + let mut img = image::RgbaImage::from_pixel(8, 8, image::Rgba(WHITE)); + img.put_pixel(0, 0, image::Rgba([0; 4])); + img.put_pixel(4, 4, image::Rgba(RED)); + let (mut s, id) = open(&png(DynamicImage::ImageRgba8(img))); + let r = s.execute(C, &json!({"background": "corners", "tolerance": 0, "softness": 0})).unwrap(); + let out = pixels(&s, id); + assert_eq!((alpha(&out, 7, 7), alpha(&out, 3, 3), alpha(&out, 4, 4)), (0, 0, 255)); + assert_eq!(r["cleared"], 8 * 8 - 2, "the pixels made clear, not the corner that was clear already"); +} + +/// One picked color matched by channel at a tolerance of 0: cleared wherever it is, and a pixel a +/// long way from it kept. +#[test] +fn one_picked_color_is_cleared_by_channel() { + let mut img = image::RgbaImage::from_pixel(4, 4, image::Rgba([10, 20, 30, 255])); + img.put_pixel(2, 2, image::Rgba([250, 250, 250, 255])); + let (mut s, id) = open(&png(DynamicImage::ImageRgba8(img))); + let p = json!({"background": "colors", "colors": "#0a141e", "contiguous": false, "match": "channels", "tolerance": 0, "softness": 0}); + assert_eq!(s.execute(C, &p).unwrap()["cleared"], 15); + let out = pixels(&s, id); + assert_eq!((alpha(&out, 0, 0), alpha(&out, 2, 2)), (0, 255)); +} + +/// With `match: channels`, a tolerance of `t / 255 × 100` clears a color `k` 8-bit steps from the +/// background on one channel exactly when `k ≤ t`, for every `t` and `k` from 0 to 255; with +/// `distance` the same color is nearer when the others match. +#[test] +fn channels_match_the_largest_difference_on_one_channel() { + for t in 0..=255u16 { + let s = Settings { measure: Match::Channels, tolerance: f64::from(t) / 255.0 * 100.0, softness: 0.0, ..settings(Background::Edges) }; + for k in 0..=255u16 { + for c in [[k * 257, 0, 0], [0, k * 257, 0], [0, 0, k * 257]] { + assert_eq!(level(c, &[[0; 3]], &s) == 0, k <= t, "t {t}, k {k}"); + } + } + } + let at = |measure| { + level([0, 40 * 257, 0], &[[0; 3]], &Settings { measure, tolerance: 32.0 / 255.0 * 100.0, softness: 0.0, ..settings(Background::Edges) }) + }; + assert_eq!((at(Match::Channels), at(Match::Distance)), (255, 0), "40 steps on green: past 32 on one channel; 9 % of the RGB distance"); +} + +#[test] +fn sixteen_bit_and_gray_images_keep_their_depth_and_channels() { + let deep = ImageBuffer::from_fn(8, 8, |x, y| Rgb(if (2..6).contains(&x) && (2..6).contains(&y) { [51_400, 0, 1] } else { [65_535; 3] })); + let (mut s, id) = open(&png(DynamicImage::ImageRgb16(deep))); + s.execute(C, &json!({})).unwrap(); + let DynamicImage::ImageRgba16(out) = pixels(&s, id) else { panic!("16-bit RGBA") }; + assert_eq!(out.get_pixel(0, 0).0[3], 0); + assert_eq!(out.get_pixel(3, 3).0, [51_400, 0, 1, 65_535], "16-bit samples kept as they were"); + // Samples one 8-bit step apart are told apart: only the background is cleared at 0. + let near = ImageBuffer::from_fn(4, 4, |x, y| Rgb(if (1..3).contains(&x) && (1..3).contains(&y) { [65_280; 3] } else { [65_535; 3] })); + let (mut s, id) = open(&png(DynamicImage::ImageRgb16(near))); + s.execute(C, &json!({"tolerance": 0, "softness": 0})).unwrap(); + let DynamicImage::ImageRgba16(out) = pixels(&s, id) else { panic!("16-bit RGBA") }; + assert_eq!((out.get_pixel(0, 0).0[3], out.get_pixel(1, 1).0[3]), (0, 65_535)); + let gray = ImageBuffer::from_fn(8, 8, |x, y| Luma([if (2..6).contains(&x) && (2..6).contains(&y) { 30u8 } else { 240 }])); + let (mut s, id) = open(&png(DynamicImage::ImageLuma8(gray))); + s.execute(C, &json!({})).unwrap(); + let DynamicImage::ImageLumaA8(out) = pixels(&s, id) else { panic!("gray with alpha") }; + assert_eq!((out.get_pixel(0, 0).0, out.get_pixel(3, 3).0), ([240, 0], [30, 255])); + let gray16 = ImageBuffer::from_fn(8, 8, |x, y| Luma([if (2..6).contains(&x) && (2..6).contains(&y) { 7_000u16 } else { 61_000 }])); + let (mut s, id) = open(&png(DynamicImage::ImageLuma16(gray16))); + s.execute(C, &json!({})).unwrap(); + let DynamicImage::ImageLumaA16(out) = pixels(&s, id) else { panic!("16-bit gray with alpha") }; + assert_eq!((out.get_pixel(0, 0).0, out.get_pixel(3, 3).0), ([61_000, 0], [7_000, 65_535])); +} + +/// A process color can't colorize a grayscale image with transparency, so a gray image colorized +/// with one keeps its pixels. Black, white and spot colors can, so those images are cleared. +#[test] +fn a_gray_image_colorized_with_a_process_color_is_refused() { + let gray = || { + png(DynamicImage::ImageLuma8(ImageBuffer::from_fn(8, 8, |x, y| Luma([if (2..6).contains(&x) && (2..6).contains(&y) { 30u8 } else { 240 }])))) + }; + let (mut s, id) = open(&gray()); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + assert!(s.doc().unwrap().doc.node(id).unwrap().extras().colorize.is_some(), "the fill colorizes the image"); + let (before, steps) = (s.doc().unwrap().doc.clone(), undo_len(&s)); + let e = s.execute(C, &json!({})).unwrap_err(); + assert!(e.to_string().contains("a process color can't colorize a grayscale image with transparency"), "{e}"); + assert_eq!((&s.doc().unwrap().doc, undo_len(&s)), (&before, steps), "the document and its undo steps are unchanged"); + // Another image that already has an alpha channel and a process colorize color, as an opened + // file can hold, neither lets this one through nor stops a run on an image that can be cleared. + let held = ImageBlob::png(png(DynamicImage::ImageLumaA8(ImageBuffer::from_pixel(2, 2, LumaA([128u8, 100]))))); + let other = place_linked(&mut s, "held", held, (2, 2)); + s.edit("Embed and colorize", |d, _| { + let n = d.node_mut(other).unwrap(); + n.extras_mut().colorize = Some(Box::new(Paint::solid(Color::rgb8(255, 0, 0)))); + if let NodeKind::Image(im) = &mut n.kind { + im.link = None; + } + Ok(()) + }) + .unwrap(); + let (before, steps) = (s.doc().unwrap().doc.clone(), undo_len(&s)); + let e = s.execute(C, &json!({"ids": [id.0]})).unwrap_err(); + assert!(e.to_string().contains("a process color can't colorize a grayscale image with transparency"), "{e}"); + assert_eq!((&s.doc().unwrap().doc, undo_len(&s)), (&before, steps), "with another image refused already, nothing changes"); + s.execute("paint.setFill", &json!({"color": "#000000", "ids": [id.0]})).unwrap(); + assert_eq!(s.execute(C, &json!({"ids": [id.0]})).unwrap()["changed"], 1, "an image colorized with black is cleared beside the other"); + let DynamicImage::ImageLumaA8(out) = pixels(&s, id) else { panic!("gray with alpha") }; + assert_eq!(out.get_pixel(0, 0).0[1], 0, "the background is cleared"); + assert!(s.doc().unwrap().doc.node(id).unwrap().extras().colorize.is_some(), "the image stays colorized"); + for fill in [json!({"color": "#000000"}), json!({"color": "#ffffff"}), json!({"swatch": "Ink"})] { + let (mut s, id) = open(&gray()); + s.execute("swatch.new", &json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 100, "k": 0}, "spot": true})).unwrap(); + s.execute("paint.setFill", &fill).unwrap(); + assert!(s.doc().unwrap().doc.node(id).unwrap().extras().colorize.is_some(), "{fill} colorizes the image"); + s.execute(C, &json!({})).unwrap(); + let DynamicImage::ImageLumaA8(out) = pixels(&s, id) else { panic!("gray with alpha") }; + assert_eq!(out.get_pixel(0, 0).0[1], 0, "{fill}: the background is cleared"); + assert!(s.doc().unwrap().doc.node(id).unwrap().extras().colorize.is_some(), "{fill} still colorizes the image"); + } +} + +/// The ICC profile the colors are in stays with them. +#[test] +fn the_color_profile_is_kept() { + use image::{ImageDecoder as _, ImageEncoder as _}; + let icc = b"a profile's bytes".to_vec(); + let mut bytes = Vec::new(); + let mut encoder = image::codecs::png::PngEncoder::new(&mut bytes); + encoder.set_icc_profile(icc.clone()).unwrap(); + DynamicImage::ImageRgba8(framed()).write_with_encoder(encoder).unwrap(); + let blob = ImageBlob::png(bytes); + let out = super::clear(&blob, &settings(Background::Edges), None, super::C).unwrap().unwrap(); + let mut decoder = image::codecs::png::PngDecoder::new(Cursor::new(out.blob.bytes.as_slice())).unwrap(); + assert_eq!(decoder.icc_profile().unwrap(), Some(icc)); +} + +/// The resolution the file declares stays with the pixels, so a later Replace or relink sizes the +/// image as before. +#[test] +fn the_resolution_is_kept() { + let bytes = ppi::with_png_resolution(&png(DynamicImage::ImageRgba8(framed())), (300.0, 150.0)); + let (mut s, id) = open(&bytes); + s.execute(C, &json!({})).unwrap(); + let (x, y) = ppi::resolution(&bytes_of(&s, id)).expect("a resolution"); + assert_eq!((x.round(), y.round()), (300.0, 150.0)); +} + +#[test] +fn a_cmyk_image_is_refused() { + let inks = vectorcraft_doc::cmyk::Inks::new(4, 2, [0, 0, 0, 0].repeat(8)).unwrap(); + let tiff = ImageBlob::cmyk_tiff(&inks).unwrap(); + let (mut s, id) = open(&tiff.bytes); + let before = (image_of(&s, id), undo_len(&s)); + let e = s.execute(C, &json!({})).unwrap_err(); + assert!(e.to_string().contains("a CMYK image has no transparency to set"), "{e}"); + assert_eq!((image_of(&s, id), undo_len(&s)), before); +} + +/// A linked image of `blob`, `width` × `height` pixels as the object records it, beside the open +/// document's image. +fn place_linked(s: &mut Session, key: &str, blob: ImageBlob, (width, height): (u32, u32)) -> NodeId { + s.edit("Place", |d, sel| { + d.images.insert(key.into(), blob); + let id = d.alloc_id(); + let im = ImageObject { + key: key.into(), + width, + height, + xf: Default::default(), + link: Some(LinkInfo::new("/nowhere/art.png")), + placement: Default::default(), + pixels: None, + }; + d.insert(d.default_layer(), 0, Node::new(id, NodeKind::Image(Box::new(im))))?; + sel.set([id]); + Ok(id) + }) + .unwrap() +} + +#[test] +fn a_linked_image_is_embedded_and_one_that_shows_its_preview_is_refused() { + let bytes = png(DynamicImage::ImageRgba8(framed())); + let (mut s, _) = open(&bytes); + let linked = place_linked(&mut s, "linked", ImageBlob::png(bytes.clone()), (12, 10)); + let clip = vectorcraft_doc::links::PlacementOptions { clip: true, ..Default::default() }; + s.edit("Placement", |d, _| { + if let Some(NodeKind::Image(im)) = d.node_mut(linked).map(|n| &mut n.kind) { + im.placement = clip; + } + Ok(()) + }) + .unwrap(); + let r = s.execute(C, &json!({"ids": [linked.0, linked.0]})).unwrap(); + assert_eq!(r, json!({"changed": 1, "ids": [linked.0], "cleared": 12 * 10 - 6 * 4}), "an image named twice changes once"); + let im = image_of(&s, linked); + assert_eq!((im.link, alpha(&pixels(&s, linked), 0, 0)), (None, 0), "embedded, with its background cleared"); + assert_eq!(im.placement, clip, "its Placement Options kept, as Embed keeps them"); + // Pixels the file wasn't read for: the preview, as an image whose file is missing shows it. + let preview = Arc::new(bytes); + let missing = place_linked(&mut s, "missing", ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview) }, (12, 10)); + let before = (image_of(&s, missing), undo_len(&s)); + let e = s.execute(C, &json!({})).unwrap_err(); + assert!(e.to_string().contains("the linked image shows its preview: embed or relink it first"), "{e}"); + assert_eq!((image_of(&s, missing), undo_len(&s)), before); +} + +/// An object whose pixels were read at another size than it records keeps its place and size. +#[test] +fn an_image_read_at_another_size_keeps_its_place_and_size() { + let bytes = png(DynamicImage::ImageRgba8(framed())); + let (mut s, _) = open(&bytes); + let id = place_linked(&mut s, "linked", ImageBlob::png(bytes), (24, 20)); + s.execute(C, &json!({"ids": [id.0]})).unwrap(); + let im = image_of(&s, id); + assert_eq!((im.width, im.height, im.xf), (12, 10, Affine::scale_non_uniform(2.0, 2.0))); +} + +#[test] +fn bad_params_are_refused_and_change_nothing() { + let (mut s, id) = open(&png(DynamicImage::ImageRgba8(framed()))); + let rect = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap()["id"].clone(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let before = (image_of(&s, id), undo_len(&s)); + // With `ids`, the command is available when one of them is an image. + let not_image = format!("object {rect} is not an image"); + let cases: [(Value, &str); 18] = [ + (json!({"background": "sky"}), "`background` must be edges, corners or colors"), + (json!({"background": 5}), "`background` must be a string"), + (json!({"match": "rgb"}), "`match` must be distance or channels"), + (json!({"match": true}), "`match` must be a string"), + (json!({"contiguous": "yes"}), "`contiguous` must be true or false"), + (json!({"contiguous": 1}), "`contiguous` must be true or false"), + (json!({"tolerance": 101}), "`tolerance` must be from 0 to 100"), + (json!({"softness": -1}), "`softness` must be from 0 to 100"), + (json!({"tolerance": "5"}), "`tolerance` must be a number"), + (json!({"background": "colors"}), "`colors` must list 1 to 16 colors, each hex (#rrggbb or #rgb) or black, white, red, green or blue"), + (json!({"background": "colors", "colors": []}), "`colors` must list"), + (json!({"background": "colors", "colors": "#12"}), "`colors` must list"), + (json!({"background": "colors", "colors": "#ffffff80"}), "`colors` must list"), + (json!({"colors": ["#ffffff", 7]}), "`colors` must list"), + (json!({"background": "colors", "colors": vec!["#000"; 17]}), "`colors` must list"), + (json!({"background": "colors", "colors": "#000 ".repeat(100_000)}), "`colors` must list"), + (json!({"ids": [id.0, rect]}), ¬_image), + (json!({"ids": [rect]}), "select an image"), + ]; + for (p, msg) in cases { + let e = s.execute(C, &p).unwrap_err().to_string(); + assert!(e.contains(msg), "{p}: {e}"); + } + assert_eq!((image_of(&s, id), undo_len(&s)), before); +} + +#[test] +fn an_image_too_large_to_change_is_refused_before_it_is_decoded() { + let run = |w: u32, h: u32| { + let (mut s, _) = open(&crate::tests_linkspanel::png_header(w, h)); + s.execute(C, &json!({})).unwrap_err().to_string() + }; + // As gray samples, RGBA worked on and kept for the PNG, and the work: 19 bytes a pixel. + let over = run(10_632, 10_631); + assert!(over.contains("an image of 10632 × 10631 pixels is too large to change"), "{over}"); + // Within the allowance it is decoded, and its missing rows can't be read. + let within = run(10_631, 10_631); + assert!(within.contains("the image's pixels can't be read"), "{within}"); +} diff --git a/crates/engine/src/cmd/addons/shapes.rs b/crates/engine/src/cmd/addons/shapes.rs index 24d0e4c3ac..87549e3694 100644 --- a/crates/engine/src/cmd/addons/shapes.rs +++ b/crates/engine/src/cmd/addons/shapes.rs @@ -131,6 +131,8 @@ fn insert_custom(s: &mut Session, label: &str, live: Option<LiveShape>, cs: Cust && let Some(n) = std::sync::Arc::make_mut(&mut st.doc).node_mut(NodeId(raw_id)) { cs.write_to_node(n); + // A shape drawn pixel-aligned (Align New Objects to Pixel Grid) snaps its stored outline. + super::super::object::snap_if_aligned(n); } Ok(val) } @@ -270,6 +272,7 @@ fn box3d(s: &mut Session, p: &Value) -> Result<Value> { && let Some(n) = std::sync::Arc::make_mut(&mut st.doc).node_mut(NodeId(raw_id)) { cs.write_to_node(n); + super::super::object::snap_if_aligned(n); } Ok(val) } diff --git a/crates/engine/src/cmd/addons/typetools.rs b/crates/engine/src/cmd/addons/typetools.rs index bc1d4e4f25..10a00b1b45 100644 --- a/crates/engine/src/cmd/addons/typetools.rs +++ b/crates/engine/src/cmd/addons/typetools.rs @@ -21,7 +21,7 @@ use super::super::menucmds::whole_or; use super::super::object::choice; use super::super::textedit::{CharChange, text_mut, text_ref, type_ranges}; use super::super::typecmd::refresh_bounds; -use super::super::typemenu::text_ids; +use super::super::typemenu::{bake_dynamic_text, text_ids}; use super::super::{CommandSpec, bad, cmd, has_selection, number_or, switch_or, targets}; use crate::{EngineError, Result, Session}; @@ -61,7 +61,7 @@ pub fn specs() -> Vec<CommandSpec> { "Release Type on a Path…", ["Object", "Plug-ins", "Type Tools"], None, - "{mode?: \"both\" (point type and the path) | \"path\" (the path only) | \"text\" (point type only) (\"both\"), keepOriginal?: false (true: the type on a path stays and the released objects go just above it), ids?: [id…], id? (instead of ids; neither: the selection)} split each type on a path among the objects (inside groups too) into point type and the path it was set on. The point type holds the same text with the same character and paragraph attributes, on one straight line whose baseline starts where the first character sat on the path; Type on a Path Options (effect, align to path, spacing, flip, brackets) don't apply to point type and are dropped. The path keeps its exact shape (open or closed, anchors and handles, the object's transform) and comes out with no fill and no stroke, in the type's layer and place in the stacking order. Other objects are left alone, and with no type on a path among them nothing changes and no undo step is made. One undo step; the released objects are selected → {ids (released, bottom to top), paths, texts}", + "{mode?: \"both\" (point type and the path) | \"path\" (the path only) | \"text\" (point type only) (\"both\"), keepOriginal?: false (true: the type on a path stays and the released objects go just above it), ids?: [id…], id? (instead of ids; neither: the selection)} split each type on a path among the objects (inside groups too) into point type and the path it was set on. The point type holds the same text with the same character and paragraph attributes, on one straight line whose baseline starts where the first character sat on the path; Type on a Path Options (effect, align to path, spacing, flip, brackets) don't apply to point type and are dropped; type with Dynamic Text on (type.dynamicText) comes out with it off, at the sizes it was drawn at. The path keeps its exact shape (open or closed, anchors and handles, the object's transform) and comes out with no fill and no stroke, in the type's layer and place in the stacking order. Other objects are left alone, and with no type on a path among them nothing changes and no undo step is made. One undo step; the released objects are selected → {ids (released, bottom to top), paths, texts}", has_selection, release_path ), @@ -139,7 +139,8 @@ fn text_tweaker(s: &mut Session, p: &Value) -> Result<Value> { let mut run = 0; for (i, at) in chars.into_iter().enumerate() { let random = if shape == "random" { unit(&mut rng) } else { 0.0 }; - let value = from + (to - from) * amount(shape, i, n, random); + // Rounding can carry a value a hair past the range's ends. + let value = (from + (to - from) * amount(shape, i, n, random)).clamp(lo, hi); let mut change = CharChange::parse(&json!({ key: value }), C, &setup)?; change.localize(&t, C)?; while ends.get(run).is_some_and(|&e| e <= at) { @@ -230,8 +231,9 @@ fn first_pen(lay: &vectorcraft_text::TextLayout) -> Option<Point> { /// `t`, type on a path, as point type on one straight line: the same runs and character and /// paragraph attributes, its baseline starting where its first character sat on the path (in the -/// object's own text space, so its transform stays). Type on a Path Options are dropped. None for -/// other type, or when it can't be placed. +/// object's own text space, so its transform stays). Type on a Path Options are dropped, and +/// Dynamic Text is turned off at the sizes it draws the text at. None for other type, or when it +/// can't be placed. fn released_text(t: &TextObject) -> Option<TextObject> { let TextKind::OnPath { path, .. } = &t.kind else { return None }; let db = vectorcraft_text::FontDb::global(); @@ -244,6 +246,8 @@ fn released_text(t: &TextObject) -> Option<TextObject> { (p.x.is_finite() && p.y.is_finite()).then_some(p) })?; let mut out = t.clone(); + // Point type has no brackets to fit: it keeps the sizes the path drew it at. + bake_dynamic_text(&mut out); out.kind = TextKind::Point; out.path_effect = Default::default(); out.path_align = Default::default(); diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 2dfeb497d0..79a203c421 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -19,12 +19,15 @@ //! shape that a Convert to Shape or Outline Object effect on them gives them, below or above the //! image as its Contents row says; new ones go right below that row. -use std::sync::Arc; +use std::{ + collections::{HashMap, HashSet}, + sync::Arc, +}; use serde_json::{Value, json}; use vectorcraft_color::{BlendMode, Paint}; use vectorcraft_doc::appearance::SharedStack; -use vectorcraft_doc::{Appearance, AppearanceItem, CharStyle, FillLayer, Node, NodeKind, ParaStyle, StrokeLayer}; +use vectorcraft_doc::{Appearance, AppearanceItem, CharStyle, Document, FillLayer, Node, NodeKind, ParaStyle, StrokeLayer}; use vectorcraft_geom::Rect; use super::edit::{outermost, roots_of, selected_roots}; @@ -32,8 +35,8 @@ use super::opacitymask::percent; use super::paint::paint_from; use super::{AppearanceAttrs, EyedropperAttrs, FillAttrs, StrokeAttrs}; use super::{ - CommandSpec, NodeId, Result, Session, bad, check_numbers, check_switches, cmd, has_doc, has_selection, id_param, ids_param, index, leaf_targets, - ok, paint_targets, str_param, switch_or, targets, + CommandSpec, NodeId, Result, Session, bad, check_numbers, check_switches, cmd, has_doc, has_selection, ids_param, index, leaf_targets, + object_param, ok, paint_targets, str_param, switch_or, targets, }; use crate::EngineError; @@ -45,7 +48,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. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)", + "{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 (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)", has_doc, |s, p| add_item(s, p, true) ), @@ -54,7 +57,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. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)", + "{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 (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)", has_doc, |s, p| add_item(s, p, false) ), @@ -63,7 +66,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. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md)", + "{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 (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md)", has_doc, clear_appearance ), @@ -72,7 +75,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. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)", + "{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 (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)", has_doc, reduce_basic ), @@ -81,7 +84,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. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)", + "{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 (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)", has_doc, set_item ), @@ -90,7 +93,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. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)", + "{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 (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)", has_doc, remove_item ), @@ -108,7 +111,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. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)", + "{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 (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)", has_doc, duplicate_item ), @@ -117,7 +120,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. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md) → {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 (a series group's id stands for those paths, except with from \"contents\", which moves the group's own row), the graph also stores the paint, weight, opacity and blend mode 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 +129,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); 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 fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and 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, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md) → {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 using effective character dimensions while preserving target transforms) 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 fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and 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, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md) → {ids}", has_doc, copy_from ), @@ -144,7 +147,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. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md) → {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 (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md) → {ids}", has_doc, show_all_hidden ), @@ -162,7 +165,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. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md) → {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 (a series group's id stands for those paths; as `source`, when the group has no effect, opacity, blend mode, isolation, knockout or style link of its own, the topmost one is read and a move clears them all; as `target` each takes the appearance and the group is cleared, a `source` among them keeps its look, and a `source` that is the group's only path is an error), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md) → {source, target}", has_doc, transfer ), @@ -416,9 +419,87 @@ pub(crate) fn appearance_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> if targets_contents(p)? { leaf_targets(s, &roots) } else { Ok(roots) } } -/// [`appearance_targets`] of `cmd`, which needs at least one. -fn require_targets(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> { +/// `ids` with each graph series group that has no fill or stroke row of its own replaced by the paths directly inside +/// it ([`super::graph::series_group_marks`]). A series group with rows, as a document saved earlier can hold, stays: +/// the Appearance panel lists those rows and edits them by index. +pub(crate) fn rowless_series_marks(d: &Document, ids: &[NodeId]) -> Vec<NodeId> { + super::graph::series_group_marks_where(d, ids, |group| group.appearance.items.is_empty()) +} + +/// Whether series group `group` holds nothing of its own, as the graph draws it: no fill or stroke row, no effect, the +/// default opacity, blend mode, isolation and knockout, and no graphic style link. +fn holds_no_look(group: &Node) -> bool { + let ap = &group.appearance; + ap.items.is_empty() + && ap.effects.is_empty() + && group.opacity == 1.0 + && group.blend == BlendMode::Normal + && !group.isolate + && group.knockout == Default::default() + && !group.knockout_shape + && group.extras().graphic_style.is_none() +} + +/// The objects whose appearance a command reads for `id`: a graph series group that holds nothing of its own +/// ([`holds_no_look`]) gives the paths directly inside it, backmost first. A series group with an effect, an opacity or +/// another attribute of its own is read itself, with that attribute. +fn look_holders(d: &Document, id: NodeId) -> Vec<NodeId> { + super::graph::series_group_marks_where(d, &[id], holds_no_look) +} + +/// The object whose appearance a command reads for `n`: a graph series group that holds nothing of its own stands for +/// the topmost path directly inside it ([`look_holders`]). +pub(crate) fn look_holder<'a>(d: &'a Document, n: &'a Node) -> &'a Node { + look_holders(d, n.id).last().and_then(|id| d.node(*id)).unwrap_or(n) +} + +/// Objects whose fill and stroke rows a command edits: the [`appearance_targets`], with a graph series group standing +/// for the paths directly inside it ([`rowless_series_marks`]), so the graph can store the edit. +pub(crate) fn row_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> { let ids = appearance_targets(s, p)?; + Ok(rowless_series_marks(&s.doc()?.doc, &ids)) +} + +/// Objects whose whole appearance a command edits: the [`row_targets`], then each graph series group they stand for, +/// which can hold effects and a graphic style link of its own. +pub(crate) fn whole_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> { + let own = appearance_targets(s, p)?; + let mut ids = rowless_series_marks(&s.doc()?.doc, &own); + let groups = stood_for(&own, &ids); + ids.extend(groups); + Ok(ids) +} + +/// The series groups among `own` that `ids` ([`rowless_series_marks`] of `own`) replaced with their paths. +pub(crate) fn stood_for(own: &[NodeId], ids: &[NodeId]) -> Vec<NodeId> { + let kept: HashSet<NodeId> = ids.iter().copied().collect(); + own.iter().copied().filter(|id| !kept.contains(id)).collect() +} + +/// Clear Appearance on each series group a command gave a whole new appearance through its paths, so the group's own +/// opacity, blend mode, isolation, knockout, effects and style link do not stay on top of it. +pub(crate) fn clear_stood_for(d: &mut Document, groups: &[NodeId]) { + for id in groups { + if let Some(n) = d.node_mut(*id) { + clear(n); + (n.isolate, n.knockout, n.knockout_shape) = (false, Default::default(), false); + n.extras_mut().graphic_style = None; + } + } +} + +/// [`whole_targets`] of `cmd`, which needs at least one. +fn require_whole_targets(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> { + let ids = whole_targets(s, p)?; + if ids.is_empty() { + return Err(bad(cmd, "select objects or give ids")); + } + Ok(ids) +} + +/// [`row_targets`] of `cmd`, which needs at least one. +fn require_targets(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> { + let ids = row_targets(s, p)?; if ids.is_empty() { return Err(bad(cmd, "select objects or give ids")); } @@ -616,7 +697,7 @@ fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result<Value> { } fn clear_appearance(s: &mut Session, p: &Value) -> Result<Value> { - let ids = require_targets(s, p, "appearance.clear")?; + let ids = require_whole_targets(s, p, "appearance.clear")?; // When every object is cleared already, the document and its undo history stay as they are. let before = s.doc()?.doc.clone(); super::overprint::edit_counted(s, "Clear Appearance", |d| { @@ -726,41 +807,70 @@ fn clear(n: &mut Node) { fn transfer(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "appearance.transfer"; - let source = id_param(p, "source").ok_or_else(|| bad(C, "missing `source` id"))?; - let target = id_param(p, "target").ok_or_else(|| bad(C, "missing `target` id"))?; + let source = object_param(p, "source", C)?.ok_or_else(|| bad(C, "missing `source` id"))?; + let target = object_param(p, "target", C)?.ok_or_else(|| bad(C, "missing `target` id"))?; if source == target { return Err(bad(C, "`source` and `target` are the same object")); } let copy = switch_or(p, "copy", false, C)?; + // A graph series group stands for the paths directly inside it: as the source, the topmost of them is read and a + // move clears them all; as the target, each of them other than a source takes the appearance. + let sources = look_holders(&s.doc()?.doc, source); + let read = sources.last().copied().unwrap_or(source); + let from: Vec<NodeId> = sources.iter().copied().chain(stood_for(&[source], &sources)).collect(); + let marks = rowless_series_marks(&s.doc()?.doc, &[target]); + let stands = !marks.contains(&target); + let within: HashSet<NodeId> = from.iter().copied().collect(); + let mut targets: Vec<NodeId> = marks.iter().copied().filter(|id| !within.contains(id)).collect(); + if targets.is_empty() { + if stands { + return Err(bad(C, "`source` is the only path in series group `target`")); + } + targets.push(target); + } + // A source that is one of the target group's paths keeps its look: the group stands for it too. + let part: HashSet<NodeId> = if stands { marks.into_iter().collect() } else { HashSet::new() }; + let from: Vec<NodeId> = stood_for(&from, &targets); + let cleared: Vec<NodeId> = if copy { vec![] } else { from.iter().copied().filter(|id| !part.contains(id)).collect() }; + // The group its paths stand for loses its own opacity, blend mode and effects, which would stay on top of them. + let group: Vec<NodeId> = if stands { vec![target] } else { vec![] }; // When both objects come out as they were, the document and its undo history stay as they are. let before = s.doc()?.doc.clone(); super::overprint::edit_counted(s, if copy { "Copy Appearance" } else { "Move Appearance" }, |d| { - let src = d.node(source).cloned().ok_or(EngineError::NoNode(source))?; - let to = d.node_mut(target).ok_or(EngineError::NoNode(target))?; - let mut ap = src.appearance.clone(); - if let (Some(f), Some(t)) = (src.geometric_bounds(), to.geometric_bounds()) { - ap.rebase_gradients(f, t); + d.node(source).ok_or(EngineError::NoNode(source))?; + let src = d.node(read).cloned().ok_or(EngineError::NoNode(read))?; + for id in &targets { + let to = d.node_mut(*id).ok_or(EngineError::NoNode(*id))?; + let mut ap = src.appearance.clone(); + if let (Some(f), Some(t)) = (src.geometric_bounds(), to.geometric_bounds()) { + ap.rebase_gradients(f, t); + } + // Only groups, layers, type and images have a Contents (Characters) row to keep a slot for. + if to.contents_label().is_none() { + ap.contents_index = None; + } + 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); } - // Only groups, layers, type and images have a Contents (Characters) row to keep a slot for. - if to.contents_label().is_none() { - ap.contents_index = None; + clear_stood_for(d, &group); + for id in &cleared { + if let Some(n) = d.node_mut(*id) { + clear(n); + (n.isolate, n.knockout, n.knockout_shape) = (false, Default::default(), false); + super::object::snap_if_aligned(n); + } } - 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 changed: Vec<NodeId> = cleared.iter().chain(&targets).copied().collect(); let kept = super::graph::capture_series_opacity(d, &both_kinds(&changed)); - // The target last: on marks of one series, its paint is the one the series keeps. + // The targets last: on marks of one series, their paint is the one the series keeps. let mut rows = top_paint_changed(&before, d, &changed); - rows.extend(painted_rows(d, both_kinds(&[target]))); + rows.extend(painted_rows(d, both_kinds(&targets))); let painted = super::graph::capture_series_top_paints(d, &rows); let object = super::graph::capture_series_object_opacity(d, &changed); - Ok(count_changed(d, &before, &[source, target]) + usize::from(kept || painted || object)) + let all: Vec<NodeId> = from.iter().chain(&targets).chain(&group).copied().collect(); + Ok(count_changed(d, &before, &all) + usize::from(kept || painted || object)) })?; s.active_appearance_item = None; Ok(json!({ "source": source.0, "target": target.0 })) @@ -772,7 +882,7 @@ fn is_group(n: &Node) -> bool { } fn reduce_basic(s: &mut Session, p: &Value) -> Result<Value> { - let ids = require_targets(s, p, "appearance.reduceToBasic")?; + let ids = require_whole_targets(s, p, "appearance.reduceToBasic")?; // When every object comes out as it was, the document and its undo history stay as they are. let before = s.doc()?.doc.clone(); // The Appearance panel's active row (a row of the first selected object's stack, and in each @@ -828,7 +938,7 @@ fn set_item(s: &mut Session, p: &Value) -> Result<Value> { check_numbers(p, &["weight", "opacity"], "appearance.setItem")?; check_switches(p, &["visible"], "appearance.setItem")?; let paint = paint_from(s, p)?; - let ids = appearance_targets(s, p)?; + let ids = row_targets(s, p)?; if ids.is_empty() { return Err(bad("appearance.setItem", "select objects or give ids")); } @@ -1039,7 +1149,7 @@ 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 roots = require_whole_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 @@ -1069,11 +1179,16 @@ fn show_all_hidden(s: &mut Session, p: &Value) -> Result<Value> { fn move_item(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "appearance.moveItem"; let to = index_param(p, "to", C)?; - let ids = require_targets(s, p, C)?; let aligned = aligned(p, C)?; if p.get("from").and_then(Value::as_str) == Some("contents") { + // A graph series group's own Contents row, not its paths, which have none. + let ids = appearance_targets(s, p)?; + if ids.is_empty() { + return Err(bad(C, "select objects or give ids")); + } return move_contents(s, &ids, to); } + let ids = require_targets(s, p, C)?; // Where an aligned row would go in each of several different stacks isn't one place. if aligned && appearances_differ(&s.doc()?.doc, &ids) { return Err(bad(C, "rows of objects whose appearances differ can't be reordered together")); @@ -1198,10 +1313,10 @@ fn target_contents(s: &mut Session, p: &Value) -> Result<Value> { Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() })) } -/// Sample enabled attributes, refusing object transparency that a text range cannot store. +/// Sample enabled attributes with transform-aware character dimensions and atomic validation. fn copy_from(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "appearance.copyFrom"; - let clicked = id_param(p, "source").ok_or_else(|| bad(C, "missing `source` id"))?; + let clicked = object_param(p, "source", C)?.ok_or_else(|| bad(C, "missing `source` id"))?; let (reverse, append) = (switch_or(p, "reverse", false, C)?, switch_or(p, "append", false, C)?); let defaults_only = switch_or(p, "defaultsOnly", false, C)?; if defaults_only && (reverse || append || p.get("ids").is_some()) { @@ -1270,9 +1385,6 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> { None => s.eyedropper_sample.clone().ok_or_else(|| bad(C, "select the object to copy from"))?, }; let picked = Picked::of(&node); - if !reverse && !defaults_only { - s.eyedropper_sample = Some(node); - } // The highlighted characters' type objects and ranges: after Select All in threaded text, all // the text of every frame of the story, except a frame the attributes come from, in place of // the object selection. @@ -1285,6 +1397,15 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> { Some((id, start, end)) if targets.contains(&id) => vec![(id, Some((start, end)))], _ => vec![], }; + let target_ids = || targets.iter().copied().filter(|_| ranges.is_empty()).chain(ranges.iter().map(|(id, _)| *id)); + // Prepare every dimensional copy before changing defaults or the remembered sample. A bad + // source or target transform must refuse the entire pick, including a multi-frame range. + let characters = if attrs.character && !append { + let d = &s.doc()?.doc; + copied_character_styles(&node, target_ids().filter_map(|id| d.node(id)))? + } else { + HashMap::new() + }; // Character styles cannot represent object transparency. Refuse before even changing // paint defaults; applying it to the object would also alter the unselected characters. if attrs.appearance.transparency { @@ -1298,11 +1419,33 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> { } } } - if !reverse { - picked.to_defaults(s, &attrs.appearance); - } + // The session's bounds check follows the selection. Check text targets reached through + // explicit IDs, a reverse pick, or a highlighted story as well. Paragraph changes can + // move point text even when character copying is disabled. + let text_ids: Vec<_> = if attrs.paragraph && !append && picked.text.is_some() { + let d = &s.doc()?.doc; + target_ids().filter(|id| d.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Text(_)))).collect() + } else { + characters.keys().copied().collect() + }; + let check_text_bounds = |d: &Document| { + if !text_ids.is_empty() && !crate::sanity::objects_in_range(d, &text_ids) { + return Err(bad(C, "sampled text would exceed the canvas (coordinates out of range)")); + } + Ok(()) + }; + // Remember the pick only after the document edit has passed its own validation. + let finish = |s: &mut Session, ids: &[NodeId]| { + if !reverse { + if !defaults_only { + s.eyedropper_sample = Some(node); + } + picked.to_defaults(s, &attrs.appearance); + } + json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }) + }; if (targets.is_empty() && ranges.is_empty()) || attrs.is_empty() { - return Ok(json!({ "ids": [] })); + return Ok(finish(s, &[])); } if !ranges.is_empty() { let ids: Vec<NodeId> = ranges.iter().map(|(f, _)| *f).collect(); @@ -1312,40 +1455,44 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> { let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(id)) }; let (start, end) = range.unwrap_or((0, vectorcraft_text::edit::runs_len(&t.runs))); let placed = picked.placed(Some(t.local_bounds())); - vectorcraft_text::edit::style_range(&mut t.runs, start, end, |st| picked.run(st, &placed, &attrs)); + vectorcraft_text::edit::style_range(&mut t.runs, start, end, |st| Picked::run(st, &placed, &attrs, characters.get(&id))); if let Some((_, para)) = picked.text.as_ref().filter(|_| attrs.paragraph) { t.edit_paras(Some(t.paragraphs_in(start, end)), |p| *p = para.clone()); } super::typecmd::refresh_bounds(t); } + check_text_bounds(d)?; Ok(count_changed(d, &before, &ids)) })?; - return Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() })); + return Ok(finish(s, &ids)); } // When every target comes out as it was, the document and its undo history stay as they are. let before = s.doc()?.doc.clone(); super::overprint::edit_counted(s, "Eyedropper", |d| { for id in &targets { if let Some(n) = d.node_mut(*id) { - picked.apply(n, &attrs, append); + picked.apply(n, &attrs, append, characters.get(id)); } } + check_text_bounds(d)?; // 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()); + // A whole pick replaces the stack: it removes the rows of a kind the source has no row of. + let whole = fill == FillAttrs::ALL && stroke == StrokeAttrs::ALL; 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)), + (fill.transparency && (whole || source_has(true)), stroke.transparency && (whole || 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 rows_written = append || whole; 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()) @@ -1359,6 +1506,9 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> { .collect() }; let mut opacity_rows = top_opacity_changed(&before, d, &targets); + // A written row that had paint before the pick counts too when the pick left it without paint, as in + // `capture_series_writes`. + opacity_rows.extend(painted_rows(&before, written(opacities))); opacity_rows.extend(painted_rows(d, written(opacities))); let mut rows = top_paint_changed(&before, d, &targets); rows.extend(painted_rows(d, written(paints))); @@ -1369,7 +1519,59 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> { let object = super::graph::capture_series_object_opacity(d, &objects); Ok(count_changed(d, &before, &targets) + usize::from(kept || painted || object)) })?; - Ok(json!({ "ids": targets.iter().map(|i| i.0).collect::<Vec<_>>() })) + Ok(finish(s, &targets)) +} + +/// Read source typography in document space, then compensate for each target's transform. +/// Paint stays in its existing sampling path; character scale never changes object placement. +fn copied_character_styles<'a>(source: &Node, targets: impl Iterator<Item = &'a Node>) -> Result<HashMap<NodeId, CharStyle>> { + const C: &str = "appearance.copyFrom"; + let mut styles = HashMap::new(); + let NodeKind::Text(source) = &source.kind else { return Ok(styles) }; + let Some(run) = source.runs.first() else { return Ok(styles) }; + let mut targets = targets + .filter_map(|n| match &n.kind { + NodeKind::Text(t) => Some((n.id, t)), + _ => None, + }) + .peekable(); + if targets.peek().is_none() { + return Ok(styles); + } + let effective = source.effective_char_style(&run.style).ok_or_else(|| bad(C, "source text transform is collapsed or unrepresentable"))?; + if !copied_dimensions_fit(&run.style, &effective) { + return Err(bad(C, "character dimensions cannot be represented with the source text transform")); + } + for (id, text) in targets { + let scale = text.style_scale().ok_or_else(|| bad(C, "target text transform is collapsed or unrepresentable"))?; + let mut local = effective.clone(); + local.size /= scale.points; + local.leading = local.leading.map(|v| v / scale.points); + local.baseline_shift /= scale.points; + local.tcy_up_down /= scale.points; + local.tcy_left_right /= scale.points; + local.h_scale /= scale.horizontal; + // As with dimensional type commands, reject overflow and underflow before layout. + if !copied_dimensions_fit(&effective, &local) { + return Err(bad(C, "character dimensions cannot be represented with the target text transform")); + } + styles.insert(id, local); + } + Ok(styles) +} + +/// Bound each converted type dimension and refuse loss to zero before layout reads it. +fn copied_dimensions_fit(from: &CharStyle, to: &CharStyle) -> bool { + [ + (from.size, to.size), + (from.leading.unwrap_or(0.0), to.leading.unwrap_or(0.0)), + (from.baseline_shift, to.baseline_shift), + (from.tcy_up_down, to.tcy_up_down), + (from.tcy_left_right, to.tcy_left_right), + (from.h_scale, to.h_scale), + ] + .iter() + .all(|(from, to)| to.is_finite() && to.abs() <= crate::MAX_COORD && (*from == 0.0 || *to != 0.0)) } /// What the Eyedropper picks up from an object. @@ -1422,14 +1624,17 @@ impl Picked { /// Copy character attributes and the enabled paint attributes through the same path for /// whole text objects and highlighted character ranges. - fn run(&self, st: &mut CharStyle, placed: &Appearance, a: &EyedropperAttrs) { - if let Some((cs, _)) = self.text.as_ref().filter(|_| a.character) { + fn run(st: &mut CharStyle, placed: &Appearance, a: &EyedropperAttrs, character: Option<&CharStyle>) { + if let Some(cs) = character { *st = CharStyle { fill: std::mem::take(&mut st.fill), stroke: std::mem::take(&mut st.stroke), stroke_width: st.stroke_width, overprint_fill: st.overprint_fill, overprint_stroke: st.overprint_stroke, + // The space before a line's first character belongs to where the character is, + // not to how it looks: a sample from one doesn't move the target's (#5111). + kerning_before: st.kerning_before, ..cs.clone() }; } @@ -1439,7 +1644,7 @@ impl Picked { /// Apply attributes `a` to `n`. `append` adds the fills and strokes (and effects) on top of its /// stack instead. Type takes the paints on its characters, and character and paragraph /// attributes from type. - fn apply(&self, n: &mut Node, a: &EyedropperAttrs, append: bool) { + fn apply(&self, n: &mut Node, a: &EyedropperAttrs, append: bool, character: Option<&CharStyle>) { let ap = &a.appearance; if ap.transparency { n.opacity = self.opacity; @@ -1456,7 +1661,7 @@ impl Picked { let placed = self.placed(Some(t.local_bounds())); let text = self.text.as_ref(); for r in &mut t.runs { - self.run(&mut r.style, &placed, a); + Self::run(&mut r.style, &placed, a, character); } if let Some((_, para)) = text.filter(|_| a.paragraph) { // The source's first paragraph's attributes, on every paragraph. diff --git a/crates/engine/src/cmd/arrowheads.rs b/crates/engine/src/cmd/arrowheads.rs new file mode 100644 index 0000000000..340cf98459 --- /dev/null +++ b/crates/engine/src/cmd/arrowheads.rs @@ -0,0 +1,480 @@ +//! Custom arrowheads (Stroke panel menu › Edit Arrowheads…). The arrowheads file is a native +//! document kept next to the preferences ([`Session::attach_arrowheads_file`]). Each of its symbols +//! is one arrowhead, listed by the symbol's name after the built-in heads in the Stroke panel's +//! arrowhead menus. A head points right (+x): the symbol's registration point is its tip, and the +//! art's height (its extent across the line) is drawn as wide as the built-in heads, four times +//! the head's weight. A head covers what its art paints: the visible fills, and the visible +//! strokes outlined, of the paths, compound paths and groups in it, and its gradient meshes, with +//! their geometry effects applied and clip groups clipped. A head is one solid shape in the stroke's paint: art at 0 % +//! opacity is left out, and other opacities, blend modes and opacity masks do not change the +//! shape. Saving the file reloads the heads. A stroke that uses a custom head carries a copy of its art +//! ([`vectorcraft_doc::CustomArrowhead`]), so its document draws it anywhere. + +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, AppearanceItem, CustomArrowhead, Document, Node, NodeId, NodeKind, Symbol, SymbolRegistration}; +use vectorcraft_geom::{Affine, FillRule, PathData, Point, SubPath}; +use vectorcraft_pathops::BoolOp; + +use super::{CommandSpec, EngineError, Result, Session, always, bad, cmd}; + +/// The arrowheads file's name, in the folder of the preferences. +pub const FILE_NAME: &str = "Arrowheads.vectorcraft"; +/// The largest arrowheads file read, and the most its document or its images may unpack to when +/// compressed. +pub const MAX_FILE_BYTES: u64 = 64 << 20; +/// The most heads read from the file; symbols past it are skipped. +pub const MAX_HEADS: usize = 256; +/// The most anchors a symbol's art, and the shapes it paints, may have; a symbol past it is skipped. +pub const MAX_ART_ANCHORS: usize = 16 * CustomArrowhead::MAX_ANCHORS; + +pub fn specs() -> Vec<CommandSpec> { + vec![ + cmd!( + query "stroke.arrowheads.list", + "Arrowheads", + [], + None, + "{} → {arrowheads: [{name (stroke.set `startArrow`/`endArrow` as {custom: name}), reach, halfWidth (in head weights)}], file: the arrowheads file's path or null (no file here, as on the web, or the file is outside the automation read roots), skipped: [{name, reason}] symbols of the file that are not heads, error: why the file could not be read (naming the file by its file name outside the read roots), or null} the custom arrowheads, listed after the built-in ones in the Stroke panel's arrowhead menus", + always, + list + ), + cmd!( + "stroke.arrowheads.edit", + "Edit Arrowheads", + [], + None, + "{} open the arrowheads file (a native document next to the preferences; created first with one example head when it is missing). Each symbol in it is one custom arrowhead named after the symbol: it points right, its registration point is the tip, and its height is drawn as wide as the built-in heads; its visible fills and outlined strokes make the head. Saving the file reloads the heads. Under automation read roots, a file outside them is an error, and nothing is made or opened → {path, created: whether the file was made now}", + has_file, + edit + ), + cmd!( + "stroke.arrowheads.reload", + "Reload Arrowheads", + [], + None, + "{} read the arrowheads file again (a save of it from VectorCraft does this already; under automation read roots, a file outside them is an error and is not read) → {count, skipped: [{name, reason}]}", + has_file, + reload + ), + ] +} + +/// The custom arrowheads read from the arrowheads file. +#[derive(Default)] +pub struct Arrowheads { + path: Option<String>, + heads: Vec<Arc<CustomArrowhead>>, + skipped: Vec<(String, String)>, + error: Option<String>, +} + +impl Arrowheads { + /// The arrowheads file's path; `None` without one (the web, runs without preferences). + pub fn path(&self) -> Option<&str> { + self.path.as_deref() + } + /// The heads, in the order of the file's symbols. + pub fn heads(&self) -> &[Arc<CustomArrowhead>] { + &self.heads + } + /// Head `name`. + pub fn get(&self, name: &str) -> Option<Arc<CustomArrowhead>> { + self.heads.iter().find(|h| h.name == name).cloned() + } + fn set(&mut self, read: Read) { + (self.heads, self.skipped) = (read.heads.into_iter().map(Arc::new).collect(), read.skipped); + self.error = None; + } +} + +/// The heads a document holds, and the symbols that are not heads with the reason. +#[derive(Debug, Default)] +pub struct Read { + pub heads: Vec<CustomArrowhead>, + pub skipped: Vec<(String, String)>, +} + +/// The heads of document `doc`: one per symbol, up to [`MAX_HEADS`] (see the module docs). +pub fn heads_of(doc: &Document) -> Read { + let mut d = doc.clone(); + let brushes = vectorcraft_brush::library(&d); + let mut out = Read::default(); + for (i, sym) in doc.symbols.iter().enumerate() { + if i >= MAX_HEADS { + out.skipped.push((sym.name.clone(), format!("only the first {MAX_HEADS} symbols are read"))); + continue; + } + if out.heads.iter().any(|h| h.name == sym.name) { + out.skipped.push((sym.name.clone(), "another symbol has this name".into())); + continue; + } + match head(&mut d, &brushes, sym) { + Ok(h) => out.heads.push(h), + Err(why) => out.skipped.push((sym.name.clone(), why.into())), + } + } + out +} + +/// Symbol `sym` of `d` as a head. +fn head(d: &mut Document, brushes: &[vectorcraft_brush::Brush], sym: &Symbol) -> std::result::Result<CustomArrowhead, &'static str> { + const TOO_DETAILED: &str = "its art is too long or too detailed for a head"; + const UNITED: &str = "its shapes could not be combined into one"; + if art_anchors(&sym.art) > MAX_ART_ANCHORS { + return Err(TOO_DETAILED); + } + let art = baked_art(d, sym); + let mut shapes = Shapes::default(); + painted(d, brushes, &art, &mut shapes); + if shapes.too_detailed { + return Err(TOO_DETAILED); + } + if shapes.failed { + return Err(UNITED); + } + let area = shapes.united().ok_or(UNITED)?; + let b = area.bounds().filter(|b| b.height() > 1e-9 && b.is_finite()).ok_or("its art paints nothing")?; + let tip = b.center() + d.symbol_registration(&sym.name).offset_from_center(b.width(), b.height()); + // Head units: x back from the tip, y across to the right of +x, 4 units to the art's height. + let k = 4.0 / b.height(); + let local = Affine::new([-k, 0.0, 0.0, k, k * tip.x, -k * tip.y]); + let h = CustomArrowhead::new(sym.name.clone(), area.transformed(local)); + if h.path.subpaths.is_empty() { + return Err(TOO_DETAILED); + } + Ok(h) +} + +/// The anchors of the paths in `n` and of the pieces of its gradient meshes ([`mesh_anchors`]), its +/// members' included. +fn art_anchors(n: &Node) -> usize { + let own = match &n.kind { + NodeKind::Mesh(m) => mesh_anchors(m), + _ => n.path_data().map_or(0, PathData::anchor_count), + }; + n.children().map_or(own, |c| c.iter().fold(own, |sum, c| sum.saturating_add(art_anchors(c)))) +} + +/// The art of symbol `sym` of `d` with every geometry effect in it applied (its objects', fills', +/// strokes' and groups'), as the canvas draws it: the art baked as for export, on a copy of `d`. +fn baked_art(d: &Document, sym: &Symbol) -> Node { + // A plain new layer, so the file's own layers' effects stay out of the art. + let mut tmp = d.clone(); + tmp.layers = Document::new(1.0, 1.0).layers; + let Some(children) = tmp.layers.first_mut().and_then(|l| Arc::make_mut(l).children_mut()) else { return (*sym.art).clone() }; + *children = vec![sym.art.clone()]; + let baked = vectorcraft_render::effects::bake_document(&tmp); + baked.as_ref().and_then(|b| b.layers.first()?.children()?.first().map(|c| (**c).clone())).unwrap_or_else(|| (*sym.art).clone()) +} + +/// The shapes a symbol's art paints, up to [`MAX_ART_ANCHORS`] anchors in all. +#[derive(Default)] +struct Shapes { + list: Vec<(PathData, FillRule)>, + anchors: usize, + /// More anchors were asked for than fit; the shapes past the limit were not made. + too_detailed: bool, + /// A clip group's art could not be combined or clipped, so a shape it paints is missing. + failed: bool, +} + +impl Shapes { + /// Whether `anchors` more fit; when they do not, the shapes are too detailed. + fn room(&mut self, anchors: usize) -> bool { + self.too_detailed |= self.anchors.saturating_add(anchors) > MAX_ART_ANCHORS; + !self.too_detailed + } + fn push(&mut self, shape: (PathData, FillRule)) { + if self.room(shape.0.anchor_count()) { + self.anchors += shape.0.anchor_count(); + self.list.push(shape); + } + } + /// The shapes united, or `None` when one of them could not be (the union would miss it). + fn united(&self) -> Option<PathData> { + let refs: Vec<(&PathData, FillRule)> = self.list.iter().map(|(p, r)| (p, *r)).collect(); + vectorcraft_pathops::try_unite_all(&refs).ok() + } + /// The shapes of `inside` clipped to `outline` (filled under `rule`), added as one. + fn push_clipped(&mut self, inside: Shapes, outline: &PathData, rule: FillRule) { + if inside.too_detailed || !self.room(inside.anchors) { + self.too_detailed = true; + return; + } + self.failed |= inside.failed; + let clip = |art: PathData| { + vectorcraft_pathops::try_boolean(&art, FillRule::NonZero, outline, rule, BoolOp::Intersect, vectorcraft_pathops::DEFAULT_PRECISION).ok() + }; + let Some(clipped) = inside.united().and_then(clip) else { + self.failed = true; + return; + }; + if !clipped.subpaths.is_empty() { + self.push((clipped, FillRule::NonZero)); + } + } +} + +/// The shapes the shown paths and compound paths in `n` (baked art) paint: their filled areas and +/// their strokes' outlines, its groups' members included (baking has already made a group's own +/// fills and strokes art among its members), and the areas its gradient meshes cover. A clip +/// group's clipped art is clipped to +/// its clipping path, whose own fill and stroke paint unclipped, as on the canvas; a group used as +/// the clipping path paints nothing ([`clip_paint`]). Hidden or fully +/// transparent art is left out. +fn painted(d: &mut Document, brushes: &[vectorcraft_brush::Brush], n: &Node, out: &mut Shapes) { + if !n.visible || n.opacity <= 0.0 || out.too_detailed { + return; + } + match &n.kind { + NodeKind::Path { guide: true, .. } => {} + NodeKind::Path { .. } | NodeKind::Compound { .. } => { + fills(n, out); + // The outline holds a copy of the path for each fill too, which adds nothing new. + if let Some(o) = super::pathops::outline_strokes(d, brushes, n) { + fills_in(&o, out); + } + } + NodeKind::Group { children, clip: true } => { + let Some((clip, rest)) = children.split_first() else { return }; + clip_paint(clip).iter().for_each(|part| painted(d, brushes, part, out)); + // Nothing to clip by hides the clipped art, as on the canvas. + let Some((outline, rule)) = vectorcraft_render::effects::clip_outline(clip) else { return }; + let mut inside = Shapes { anchors: out.anchors, ..Default::default() }; + rest.iter().for_each(|c| painted(d, brushes, c, &mut inside)); + inside.anchors -= out.anchors; + out.push_clipped(inside, &PathData::from_bezpath(&outline), rule); + } + NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => children.iter().for_each(|c| painted(d, brushes, c, out)), + NodeKind::Mesh(_) => mesh_area(n, out), + _ => {} + } +} + +/// What clipping path `clip` paints ([`Node::clip_paint`]): its fills and its strokes, each as a +/// copy of it keeping only those. A group or another object that does not paint as a clipping +/// path gives neither. +fn clip_paint(clip: &Node) -> Vec<Node> { + let paint = clip.clip_paint(); + [paint.fill, paint.stroke].into_iter().flatten().collect() +} + +/// The areas the shown paths and gradient meshes in `n` (an outlined stroke) fill, clipped by its +/// clip groups, whose clipping paths' own fills paint unclipped. A stroke with a gradient along or +/// across it is outlined as gradient meshes clipped to the stroke's outline. +fn fills_in(n: &Node, out: &mut Shapes) { + if !n.visible || n.opacity <= 0.0 || out.too_detailed { + return; + } + match &n.kind { + NodeKind::Mesh(_) => mesh_area(n, out), + NodeKind::Group { children, clip: true } => { + let Some((clip, rest)) = children.split_first() else { return }; + clip_paint(clip).iter().for_each(|part| fills_in(part, out)); + let Some((outline, rule)) = vectorcraft_render::effects::clip_outline(clip) else { return }; + let mut inside = Shapes { anchors: out.anchors, ..Default::default() }; + rest.iter().for_each(|c| fills_in(c, &mut inside)); + inside.anchors -= out.anchors; + out.push_clipped(inside, &PathData::from_bezpath(&outline), rule); + } + _ => match n.children() { + Some(children) => children.iter().for_each(|c| fills_in(c, out)), + None => fills(n, out), + }, + } +} + +/// The anchors [`mesh_area`] makes at most of mesh `m`: its outline's, one a patch along each side, +/// when no point of it is fully transparent, else four by four quads of four anchors a patch. +fn mesh_anchors(m: &vectorcraft_doc::GradientMesh) -> usize { + let (rows, cols) = (m.rows as usize, m.cols as usize); + if opaque(m) { rows.saturating_add(cols).saturating_mul(2) } else { rows.saturating_mul(cols).saturating_mul(64) } +} + +fn opaque(m: &vectorcraft_doc::GradientMesh) -> bool { + m.points.iter().all(|p| p.opacity > 0.0) +} + +/// The area gradient mesh `n` paints: its outline when no point of it is fully transparent, else +/// the pieces of it that are not fully transparent (four by four quads a patch). A mesh whose +/// pieces do not fit in `out` makes the shapes too detailed. +fn mesh_area(n: &Node, out: &mut Shapes) { + let NodeKind::Mesh(m) = &n.kind else { return }; + if !out.room(mesh_anchors(m)) { + return; + } + if opaque(m) { + let outline = m.outline(); + if !outline.subpaths.is_empty() { + out.push((outline, FillRule::NonZero)); + } + return; + } + for q in m.quads(4) { + if q.opacity > 0.0 || q.corners.iter().any(|(_, o)| *o > 0.0) { + out.push((PathData::single(SubPath::polyline(&q.pts, true)), FillRule::NonZero)); + } + } +} + +/// The area path `n` fills, when a shown fill paints it. +fn fills(n: &Node, out: &mut Shapes) { + let paints = |i: &AppearanceItem| matches!(i, AppearanceItem::Fill(f) if f.visible && f.opacity > 0.0 && !f.paint.is_none()); + if n.appearance.items.iter().any(paints) + && let Some(shape) = super::pathops::node_path(n) + { + out.push(shape); + } +} + +/// The document a missing arrowheads file starts as: one example head, a solid triangle. +pub fn starter() -> Document { + let mut doc = Document::new(612.0, 792.0); + doc.title = "Arrowheads".into(); + let name = "Example Arrowhead"; + let tri = SubPath::polyline(&[Point::new(-10.0, -8.0), Point::new(10.0, 0.0), Point::new(-10.0, 8.0)], true); + let art = Node::path(NodeId(0), PathData::single(tri), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 1.0)); + let art = doc.reid(&art); + doc.symbols.push(Symbol { name: name.into(), art: Arc::new(art), dynamic: false }); + // The tip is the right edge's middle. + doc.set_symbol_registration(name, SymbolRegistration(5)); + let id = doc.alloc_id(); + let instance = Node::new(id, NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::translate((306.0, 396.0)) }); + let layer = doc.layers.first().map(|l| l.id); + let _ = doc.insert(layer, 0, instance); + doc +} + +impl Session { + /// Keep the custom arrowheads in the file at `path` and read the heads it holds (none while it + /// is missing; an unreadable file is reported by `stroke.arrowheads.list`). + pub fn attach_arrowheads_file(&mut self, path: String) { + self.arrowheads.path = Some(path); + self.reload_arrowheads(); + } + + /// Read the arrowheads file again. + fn reload_arrowheads(&mut self) { + let Some(path) = self.arrowheads.path.clone() else { return }; + match read(&path) { + Ok(Some(doc)) => self.arrowheads.set(heads_of(&doc)), + Ok(None) => self.arrowheads.set(Read::default()), + Err(e) => { + self.arrowheads.set(Read::default()); + self.arrowheads.error = Some(e); + } + } + } + + /// A document was saved to `path`: when that is the arrowheads file, its heads are read back + /// from what was written. + pub(crate) fn arrowheads_saved(&mut self, path: &str) { + if self.arrowheads.path.as_deref().is_some_and(|a| same_file(a, path)) { + self.reload_arrowheads(); + } + } +} + +fn same_file(a: &str, b: &str) -> bool { + let canon = |p: &str| std::fs::canonicalize(p).unwrap_or_else(|_| std::path::PathBuf::from(p)); + std::path::Path::new(a) == std::path::Path::new(b) || canon(a) == canon(b) +} + +/// The document in the arrowheads file at `path`; `None` when there is no file. +fn read(path: &str) -> std::result::Result<Option<Document>, String> { + let size = match std::fs::metadata(path) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(format!("{path}: {e}")), + Ok(m) if !m.is_file() => return Err(format!("{path}: not a file")), + Ok(m) => m.len(), + }; + if size > MAX_FILE_BYTES { + return Err(format!("{path}: larger than {} MB", MAX_FILE_BYTES >> 20)); + } + let bytes = crate::file_access::unconfined(|| super::fileio::read_file(path)).map_err(|e| e.to_string())?; + // A compressed file's document, and its images, may unpack to no more than an uncompressed + // file may hold. + let parse = || vectorcraft_format::load_file_capped(&bytes, MAX_FILE_BYTES).map(|f| f.doc).map_err(|e| format!("{path}: {e}")); + crate::guard::catch_panic(parse).map_err(|_| format!("{path}: could not be read"))?.map(Some) +} + +fn has_file(s: &Session) -> std::result::Result<(), String> { + if s.arrowheads.path.is_some() { Ok(()) } else { Err("no arrowheads file here".into()) } +} + +fn skipped(s: &Session) -> Vec<Value> { + s.arrowheads.skipped.iter().map(|(name, reason)| json!({"name": name, "reason": reason})).collect() +} + +/// The arrowheads file at `path` checked for reading against the automation roots in force: an agent +/// confined to read roots reaches the file only inside them. The error names the file by its file +/// name outside them. +fn may_reach(path: &str) -> Result<()> { + crate::file_access::check_read(path).map_err(|e| super::fileio::naming_in_error(EngineError::Other(e), path)) +} + +/// `msg`, an error about the arrowheads file at `path`, as the request being served may see it: the +/// file named whole inside the read roots, else by its file name. +fn shown_error(msg: &str, path: Option<&str>) -> String { + let Some(path) = path else { return msg.to_string() }; + match super::fileio::naming_in_error(EngineError::Other(msg.to_string()), path) { + EngineError::Other(m) => m, + e => e.to_string(), + } +} + +fn list(s: &mut Session, _: &Value) -> Result<Value> { + let heads: Vec<Value> = s.arrowheads.heads.iter().map(|h| json!({"name": h.name, "reach": h.reach(), "halfWidth": h.half_width()})).collect(); + let path = s.arrowheads.path.as_deref(); + let file = path.filter(|p| crate::file_access::check_read(p).is_ok()); + let error = s.arrowheads.error.as_deref().map(|e| shown_error(e, path)); + Ok(json!({"arrowheads": heads, "file": file, "skipped": skipped(s), "error": error})) +} + +fn reload(s: &mut Session, _: &Value) -> Result<Value> { + const C: &str = "stroke.arrowheads.reload"; + if let Some(path) = &s.arrowheads.path { + may_reach(path)?; + } + s.reload_arrowheads(); + if let Some(e) = &s.arrowheads.error { + return Err(bad(C, e.clone())); + } + Ok(json!({"count": s.arrowheads.heads.len(), "skipped": skipped(s)})) +} + +fn edit(s: &mut Session, _: &Value) -> Result<Value> { + const C: &str = "stroke.arrowheads.edit"; + let path = s.arrowheads.path.clone().ok_or_else(|| bad(C, "no arrowheads file here"))?; + // Checked before anything is made, brought to the front or opened. + may_reach(&path)?; + if let Some(dir) = std::path::Path::new(&path).parent() { + let dir = dir.to_string_lossy(); + std::fs::create_dir_all(&*dir).map_err(|e| super::fileio::naming_in_error(bad(C, format!("{dir}: {e}")), &dir))?; + } + // Made only when no file is there, also when another run makes one at the same moment. + let bytes = vectorcraft_format::save_file(&starter()); + let created = match crate::file_access::unconfined(|| super::fileio::write_new_file(&path, &bytes)) { + Ok(()) => true, + Err(_) if std::path::Path::new(&path).exists() => false, + Err(e) => return Err(bad(C, e.to_string())), + }; + if created { + s.reload_arrowheads(); + } + // Already open: that document comes to the front. + let open = s.documents().iter().position(|st| st.path.as_deref().is_some_and(|p| same_file(p, &path))); + match open { + Some(i) => { + s.set_active(i); + } + None => { + // Opened in the request's own scope, so the document keeps the roots it was opened under. + s.execute("document.open", &json!({ "path": path }))?; + } + } + Ok(json!({"path": path, "created": created})) +} diff --git a/crates/engine/src/cmd/artboardalign.rs b/crates/engine/src/cmd/artboardalign.rs new file mode 100644 index 0000000000..541ec94a4e --- /dev/null +++ b/crates/engine/src/cmd/artboardalign.rs @@ -0,0 +1,271 @@ +//! Align and Distribute for artboards: what the Align panel's buttons run while the Artboard tool +//! is chosen. + +use serde_json::{Value, json}; +use vectorcraft_doc::Scaling; +use vectorcraft_geom::{Rect, Vec2}; + +use super::object::choice; +use super::panelcmds::{artboard_index, artboards_art, locked_and_hidden, named_or_selected, note_artboards}; +use super::{Affine, CommandSpec, NodeId, Result, Session, bad, check_switches, cmd, has_doc, switch_or}; +use crate::EngineError; + +pub fn specs() -> Vec<CommandSpec> { + vec![ + cmd!( + "artboard.align", + "Align", + [], + None, + "{index? | indices?: [n…], selectedArtboards?: [n…] (as artboard.duplicate; default: the artboards the Artboard tool has selected, else its active one), horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\" (one of the two is needed), to?: \"selection\"|\"artboard\" (default \"selection\": the bounds of the artboards together; \"artboard\": artboard `artboard`, which stays where it is), artboard?: n (0-based; the artboard to align to with to: \"artboard\"; default: the Artboard tool's active one; it need not be one of the artboards aligned), activeArtboard?: n (the journal records that default here, for a replay; `artboard` goes ahead of it), moveArt?: bool (the art fully inside each artboard moves with it, art inside two of them with the first by index, which may stay; default: the Artboard tool's Move Artwork with Artboard option), patterns?: bool, lockedAndHidden?: bool (as artboard.move)} (Align panel › Align Objects with the Artboard tool chosen) each artboard moves until its edge or center is on that edge or center of what it aligns to, with its guides, in one undo step; a locked artboard stays where it is and still counts in the bounds, and the call fails with `the artboard is locked` when every artboard it names is locked; when no artboard moves, no undo step is recorded → {moved: [index…]}", + has_doc, + align + ), + cmd!( + "artboard.distribute", + "Distribute", + [], + None, + "{index? | indices?, selectedArtboards? (as artboard.align), horizontal?: \"left\"|\"center\"|\"right\" | vertical?: \"top\"|\"center\"|\"bottom\" (one is needed; horizontal goes first), to?: \"selection\"|\"artboard\", artboard?: n, activeArtboard?: n (as artboard.align; with `spacing` the artboard must be one of those distributed), spacing?: pt (used with to: \"artboard\"), moveArt?, patterns?, lockedAndHidden? (as artboard.align)} (Align panel › Distribute Objects with the Artboard tool chosen) the named edges or centers of the artboards are spaced evenly between the first and the last along the axis, which stay where they are (three or more artboards); with to: \"artboard\", the artboards are spaced the same way and then moved together so that artboard `artboard`, when it is one of them, stays where it is; with to: \"artboard\" and `spacing`, that artboard stays and the edges or centers are placed `spacing` apart, outward from it in their order (two or more); a locked artboard stays where it is and keeps its place in the order, and the call fails with `the artboard is locked` when every artboard it names is locked; a spacing that would move an artboard past the canvas is an error; with fewer artboards, or when none moves, no undo step is recorded → {moved: [index…]}", + has_doc, + distribute + ), + cmd!( + "artboard.distributeSpacing", + "Distribute Spacing", + [], + None, + "{index? | indices?, selectedArtboards? (as artboard.align), axis?: \"horizontal\"|\"vertical\" (default horizontal), to?: \"selection\"|\"artboard\", artboard?: n, activeArtboard?: n (as artboard.distribute), spacing?: pt (used with to: \"artboard\"), moveArt?, patterns?, lockedAndHidden? (as artboard.align)} (Align panel › Distribute Spacing with the Artboard tool chosen) the gaps between the artboards along the axis become equal, the first and the last staying where they are (three or more artboards); with to: \"artboard\", the gaps become equal the same way and the artboards then move together so that artboard `artboard`, when it is one of them, stays where it is; with to: \"artboard\" and `spacing`, that artboard stays and the others are placed with a gap of `spacing` between neighbors (two or more; a negative spacing overlaps them); a locked artboard stays where it is and keeps its place in the order, and the call fails with `the artboard is locked` when every artboard it names is locked; a spacing that would move an artboard past the canvas is an error; with fewer artboards, or when none moves, no undo step is recorded → {moved: [index…]}", + has_doc, + distribute_spacing + ), + ] +} + +/// What an artboard Align or Distribute command acts on, read from its params. +struct Boards { + /// The artboards named, in artboard order, each with its rectangle. + items: Vec<(usize, Rect)>, + /// With `to: "artboard"`, the artboard to align to and its rectangle. + reference: Option<(usize, Rect)>, + /// Whether the art inside each artboard moves with it. + move_art: bool, + /// Whether locked and hidden art moves too. + locked_art: bool, +} + +/// Reads the params that `artboard.align`, `artboard.distribute` and `artboard.distributeSpacing` +/// (command `cmd`) share, and adds the artboards and the art choice to the journal entry. The +/// artboard to align to is `artboard`, else `activeArtboard` (a replay of the journal), else the +/// Artboard tool's active one, which the journal entry then records as `activeArtboard`. It fails +/// when every artboard named is locked. +fn boards(s: &mut Session, p: &Value, cmd: &str) -> Result<Boards> { + check_switches(p, &["patterns"], cmd)?; + let to_artboard = choice(p, cmd, "to", &["selection", "artboard"])? == Some("artboard"); + let indices = named_or_selected(s, p, cmd)?; + let given = |key: &str| -> Result<Option<usize>> { + match p.get(key).filter(|v| !v.is_null()) { + Some(v) => artboard_index(&s.doc()?.doc, &json!({ "index": v }), cmd).map(Some), + None => Ok(None), + } + }; + let (named, recorded) = (given("artboard")?, given("activeArtboard")?); + let move_art = switch_or(p, "moveArt", s.tool_options_of("artboard")["moveArt"].as_bool().unwrap_or(true), cmd)?; + let locked_art = locked_and_hidden(s, p, move_art, cmd)?; + note_artboards(s, p, &indices); + s.note_journal("moveArt", json!(move_art)); + let reference = match (to_artboard, named.or(recorded)) { + (false, _) => None, + (true, Some(i)) => Some(i), + (true, None) => { + let active = s.tool_options_of("artboard")["active"].clone(); + Some(artboard_index(&s.doc()?.doc, &json!({ "index": active }), cmd)?) + } + }; + if let Some(i) = reference.filter(|_| named.is_none()) { + s.note_journal("activeArtboard", json!(i)); + } + let d = &s.doc()?.doc; + let rect = |i: usize| d.artboards.get(i).map(|a| (i, a.rect)).ok_or_else(|| EngineError::Other("no such artboard".into())); + let items = indices.iter().map(|i| rect(*i)).collect::<Result<Vec<_>>>()?; + if indices.iter().all(|i| d.artboards.get(*i).is_some_and(|a| a.locked)) { + return Err(EngineError::Other("the artboard is locked".into())); + } + Ok(Boards { items, reference: reference.map(rect).transpose()?, move_art, locked_art }) +} + +/// `spacing` of the Distribute commands: a finite number, or `None` when it is missing or null. +fn spacing(p: &Value, cmd: &str) -> Result<Option<f64>> { + p.get("spacing") + .filter(|v| !v.is_null()) + .map(|v| v.as_f64().filter(|g| g.is_finite()).ok_or_else(|| bad(cmd, "`spacing` must be a number"))) + .transpose() +} + +/// The place in `items` of the artboard `b` aligns to, which the Distribute commands keep where it +/// is. `None` without one, or when it is not one of `items`; with a `gap` that is an error +/// (`no such artboard`), since the gap is measured from it. +fn kept(b: &Boards, items: &[(usize, Rect)], gap: Option<f64>) -> Result<Option<usize>> { + let Some((reference, _)) = b.reference else { return Ok(None) }; + match items.iter().position(|(i, _)| *i == reference) { + None if gap.is_some() => Err(EngineError::Other("no such artboard".into())), + at => Ok(at), + } +} + +/// Moves each artboard of `moves` by its offset as undo step `label`, with its guides and, when +/// `b` says so, the art inside it; art inside two of the artboards `b` names goes with the one +/// first in artboard order, and stays when that one stays. Locked artboards stay where they are. +/// When no artboard moves +/// more than 1e-9 pt on either axis, the document and its undo history stay as they are. The edit +/// fails with nothing changed when an artboard would end up past the canvas, as every edit does. +fn apply(s: &mut Session, label: &str, p: &Value, b: &Boards, moves: &[(usize, Vec2)]) -> Result<Value> { + let d = &s.doc()?.doc; + let mut moves: Vec<(usize, Vec2)> = + moves.iter().copied().filter(|(i, dv)| (dv.x.abs() > 1e-9 || dv.y.abs() > 1e-9) && d.artboards.get(*i).is_some_and(|a| !a.locked)).collect(); + // In artboard order, as the other artboard edits take them, whatever order the Distribute + // commands spaced them in. + moves.sort_by_key(|(i, _)| *i); + let moved: Vec<usize> = moves.iter().map(|(i, _)| *i).collect(); + if moves.is_empty() { + return Ok(json!({ "moved": moved })); + } + // The art of every artboard named, those that stay included, so that art on overlapping + // artboards goes with the first by index; then that of the artboards that move. + let named: Vec<usize> = b.items.iter().map(|(i, _)| *i).collect(); + let arts: Vec<(usize, Vec<NodeId>)> = + artboards_art(s, &named, b.move_art, b.locked_art, true)?.into_iter().filter(|(i, _)| moved.contains(i)).collect(); + let ids: Vec<NodeId> = arts.iter().flat_map(|(_, a)| a.iter().copied()).collect(); + let sc = Scaling { patterns: super::object::transform_patterns(s, p, &ids)?, ..Scaling::default() }; + s.edit(label, |d, _| { + for ((i, dv), (_, art)) in moves.iter().zip(&arts) { + let a = d.artboards.get_mut(*i).ok_or_else(|| EngineError::Other("no such artboard".into()))?; + a.rect = a.rect + *dv; + let id = a.id; + d.move_artboard_guides(id, *dv); + for id in art { + if let Some(n) = d.node_mut(*id) { + n.transform(Affine::translate(*dv), sc); + super::object::keep_pixel_aligned(n, sc); + } + } + } + Ok(()) + })?; + Ok(json!({ "moved": moved })) +} + +fn align(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "artboard.align"; + let h = choice(p, C, "horizontal", &["left", "center", "right"])?; + let v = choice(p, C, "vertical", &["top", "center", "bottom"])?; + if h.is_none() && v.is_none() { + return Err(bad(C, "give horizontal or vertical")); + } + let b = boards(s, p, C)?; + let Some(r) = b.reference.map(|(_, r)| r).or_else(|| b.items.iter().map(|(_, r)| *r).reduce(|a, b| a.union(b))) else { + return Ok(json!({ "moved": [] })); + }; + let moves: Vec<(usize, Vec2)> = b + .items + .iter() + .map(|(i, a)| { + let dx = match h { + Some("left") => r.x0 - a.x0, + Some("center") => r.center().x - a.center().x, + Some("right") => r.x1 - a.x1, + _ => 0.0, + }; + let dy = match v { + Some("top") => r.y0 - a.y0, + Some("center") => r.center().y - a.center().y, + Some("bottom") => r.y1 - a.y1, + _ => 0.0, + }; + (*i, Vec2::new(dx, dy)) + }) + .collect(); + apply(s, "Align", p, &b, &moves) +} + +fn distribute(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "artboard.distribute"; + let h = choice(p, C, "horizontal", &["left", "center", "right"])?; + let v = choice(p, C, "vertical", &["top", "center", "bottom"])?; + let (horiz, line): (bool, fn(&Rect) -> f64) = match (h, v) { + (Some("left"), _) => (true, |r| r.x0), + (Some("right"), _) => (true, |r| r.x1), + (Some(_), _) => (true, |r| r.center().x), + (None, Some("top")) => (false, |r| r.y0), + (None, Some("bottom")) => (false, |r| r.y1), + (None, Some(_)) => (false, |r| r.center().y), + (None, None) => return Err(bad(C, "give horizontal or vertical")), + }; + let gap = spacing(p, C)?; + let b = boards(s, p, C)?; + let mut items = b.items.clone(); + items.sort_by(|x, y| line(&x.1).total_cmp(&line(&y.1))); + let kept = kept(&b, &items, gap)?; + // With a spacing: the place in the order and the line of the artboard it is measured from. + let from = kept.zip(gap).and_then(|(at, gap)| items.get(at).map(|(_, r)| (at, gap, line(r)))); + let n = items.len(); + // Two artboards are the ends already; with a spacing the second is placed from the first. + if n < if from.is_some() { 2 } else { 3 } { + return Ok(json!({ "moved": [] })); + } + let (Some((_, first)), Some((_, last))) = (items.first(), items.last()) else { return Ok(json!({ "moved": [] })) }; + let (first, last) = (line(first), line(last)); + let deltas: Vec<f64> = items + .iter() + .enumerate() + .map(|(k, (_, r))| { + let target = match from { + Some((at, gap, origin)) => origin + gap * (k as f64 - at as f64), + None => first + (last - first) * k as f64 / (n - 1) as f64, + }; + target - line(r) + }) + .collect(); + // The artboard aligned to stays where it is, and the others keep their places from it. + let hold = kept.and_then(|at| deltas.get(at)).copied().unwrap_or(0.0); + let moves: Vec<(usize, Vec2)> = items.iter().zip(&deltas).map(|((i, _), d)| (*i, along(horiz, d - hold))).collect(); + apply(s, "Distribute", p, &b, &moves) +} + +fn distribute_spacing(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "artboard.distributeSpacing"; + let horiz = choice(p, C, "axis", &["horizontal", "vertical"])? != Some("vertical"); + let gap = spacing(p, C)?; + let b = boards(s, p, C)?; + let start = |r: &Rect| if horiz { r.x0 } else { r.y0 }; + let size = |r: &Rect| if horiz { r.width() } else { r.height() }; + let mut items = b.items.clone(); + items.sort_by(|x, y| start(&x.1).total_cmp(&start(&y.1))); + let kept = kept(&b, &items, gap)?; + let gap = gap.filter(|_| kept.is_some()); + let n = items.len(); + if n < if gap.is_some() { 2 } else { 3 } { + return Ok(json!({ "moved": [] })); + } + let (Some((_, first)), Some((_, last))) = (items.first(), items.last()) else { return Ok(json!({ "moved": [] })) }; + let (lo, hi) = (start(first), start(last) + size(last)); + let gap = gap.unwrap_or_else(|| (hi - lo - items.iter().map(|(_, r)| size(r)).sum::<f64>()) / (n - 1) as f64); + let mut pos = lo; + let mut deltas = Vec::with_capacity(n); + for (i, r) in &items { + deltas.push((*i, pos - start(r))); + pos += size(r) + gap; + } + // The artboard aligned to stays where it is, and the others keep their places from it. + let hold = kept.and_then(|at| deltas.get(at)).map_or(0.0, |d| d.1); + let moves: Vec<(usize, Vec2)> = deltas.into_iter().map(|(i, d)| (i, along(horiz, d - hold))).collect(); + apply(s, "Distribute Spacing", p, &b, &moves) +} + +/// An offset of `d` along the axis: x when `horiz`, else y. +fn along(horiz: bool, d: f64) -> Vec2 { + if horiz { Vec2::new(d, 0.0) } else { Vec2::new(0.0, d) } +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/artboardalign/tests.rs b/crates/engine/src/cmd/artboardalign/tests.rs new file mode 100644 index 0000000000..526a50db31 --- /dev/null +++ b/crates/engine/src/cmd/artboardalign/tests.rs @@ -0,0 +1,310 @@ +//! Align and Distribute for artboards. + +use serde_json::{Value, json}; +use vectorcraft_doc::NodeId; + +use crate::Session; +use crate::tooling::ViewInfo; + +/// A document with three artboards, each with a 10 pt square 5 pt inside its top-left corner: +/// 0 at (0, 0) 100 × 100, 1 at (150, 40) 60 × 80 and 2 at (400, 10) 100 × 50 → the squares' ids. +fn three_boards() -> (Session, [u64; 3]) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("artboard.new", &json!({"x": 150, "y": 40, "width": 60, "height": 80})).unwrap(); + s.execute("artboard.new", &json!({"x": 400, "y": 10, "width": 100, "height": 50})).unwrap(); + let mut sq = |x: u64, y: u64| s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + let ids = [sq(5, 5), sq(155, 45), sq(405, 15)]; + s.execute("select.none", &json!({})).unwrap(); + (s, ids) +} + +/// The top-left corner of each artboard. +fn corners(s: &Session) -> Vec<(f64, f64)> { + s.doc().unwrap().doc.artboards.iter().map(|a| (a.rect.x0, a.rect.y0)).collect() +} + +/// The top-left corner of object `id`. +fn corner(s: &Session, id: u64) -> (f64, f64) { + let b = s.doc().unwrap().doc.node(NodeId(id)).unwrap().geometric_bounds().unwrap(); + (b.x0, b.y0) +} + +fn undo_steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +const ALL: [u64; 3] = [0, 1, 2]; + +/// Align Objects lines the artboards up on the bounds of all of them, each with the art inside +/// it, in one undo step. +#[test] +fn align_moves_the_artboards_to_their_common_edge_with_their_art() { + let (mut s, [a, b, c]) = three_boards(); + let before = corners(&s); + let steps = undo_steps(&s); + let out = s.execute("artboard.align", &json!({"indices": ALL, "vertical": "top"})).unwrap(); + assert_eq!(out, json!({"moved": [1, 2]})); + assert_eq!(corners(&s), [(0.0, 0.0), (150.0, 0.0), (400.0, 0.0)]); + assert_eq!([corner(&s, a), corner(&s, b), corner(&s, c)], [(5.0, 5.0), (155.0, 5.0), (405.0, 5.0)], "each square stays on its artboard"); + assert_eq!(undo_steps(&s), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((corners(&s), corner(&s, b)), (before, (155.0, 45.0)), "one undo step"); + s.execute("artboard.align", &json!({"indices": ALL, "horizontal": "right", "vertical": "bottom"})).unwrap(); + assert_eq!(corners(&s), [(400.0, 20.0), (440.0, 40.0), (400.0, 70.0)], "the right edges at 500 and the bottom edges at 120"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("artboard.align", &json!({"indices": ALL, "horizontal": "center", "moveArt": false})).unwrap(); + assert_eq!(corners(&s), [(200.0, 0.0), (220.0, 40.0), (200.0, 10.0)], "the centers at 250"); + assert_eq!(corner(&s, a), (5.0, 5.0), "moveArt false leaves the art"); +} + +/// Align to an artboard: that artboard stays where it is and the others line up on it. It need not +/// be one of the artboards aligned. +#[test] +fn align_to_an_artboard_keeps_that_artboard_in_place() { + let (mut s, _) = three_boards(); + let out = s.execute("artboard.align", &json!({"indices": ALL, "horizontal": "left", "to": "artboard", "artboard": 2})).unwrap(); + assert_eq!(out, json!({"moved": [0, 1]})); + assert_eq!(corners(&s), [(400.0, 0.0), (400.0, 40.0), (400.0, 10.0)]); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("artboard.align", &json!({"index": 0, "vertical": "center", "to": "artboard", "artboard": 1})).unwrap(); + assert_eq!(corners(&s), [(0.0, 30.0), (150.0, 40.0), (400.0, 10.0)], "artboard 1's center is at y 80"); +} + +/// With no artboard named, the commands act on the artboards the Artboard tool has selected and +/// align to its active one; the journal records both for a replay, and an action leaves them out. +#[test] +fn the_artboard_tools_selection_is_the_default_and_is_recorded() { + let (mut s, [_, _, c]) = three_boards(); + s.select_tool("artboard", ViewInfo::default()).unwrap(); + s.set_tool_option("selected", &json!([1, 2])); + let start = s.journal.len(); + assert_eq!(s.execute("artboard.align", &json!({"horizontal": "left"})).unwrap(), json!({"moved": [2]})); + assert_eq!(corners(&s), [(0.0, 0.0), (150.0, 40.0), (150.0, 10.0)]); + assert_eq!(corner(&s, c), (155.0, 15.0), "the tool's Move Artwork with Artboard option is on"); + let recorded = json!({"horizontal": "left", "selectedArtboards": [1, 2], "moveArt": true, "lockedAndHidden": false}); + assert_eq!(s.journal.last().unwrap(), &("artboard.align".to_string(), recorded)); + assert_eq!( + s.journal_for_action(start), + [("artboard.align".to_string(), json!({"horizontal": "left", "moveArt": true, "lockedAndHidden": false}))] + ); + s.execute("artboard.align", &json!({"vertical": "top", "to": "artboard"})).unwrap(); + assert_eq!(corners(&s)[2], (150.0, 40.0), "artboard 2 lines up on the active artboard, 1"); + assert_eq!(s.journal.last().unwrap().1["activeArtboard"], json!(1)); + assert_eq!(s.journal_for_action(start)[1].1.get("activeArtboard"), None, "an action aligns to the artboard active when it plays"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("artboard.align", &json!({"vertical": "top", "to": "artboard", "activeArtboard": 0})).unwrap(); + assert_eq!(corners(&s)[1..], [(150.0, 0.0), (150.0, 0.0)], "a replay aligns to the artboard it recorded, 0"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("artboard.align", &json!({"vertical": "bottom", "to": "artboard", "artboard": 0, "activeArtboard": 2})).unwrap(); + assert_eq!(corners(&s)[1..], [(150.0, 20.0), (150.0, 50.0)], "`artboard` goes ahead of the recorded one"); + let action = s.journal_for_action(start); + let entry = &action.last().unwrap().1; + assert_eq!((entry.get("artboard"), entry.get("activeArtboard")), (Some(&json!(0)), None), "an action keeps the artboard a call named"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("artboard.align", &json!({"vertical": "top", "to": "artboard"})).unwrap(); + s.set_tool_option("moveArt", &json!(false)); + s.execute("artboard.align", &json!({"horizontal": "right"})).unwrap(); + assert_eq!((corners(&s)[1], corner(&s, c)), ((190.0, 40.0), (155.0, 45.0)), "with the option off the art stays"); +} + +/// A command that moves no artboard leaves the document and its undo history as they are. +#[test] +fn nothing_to_move_records_no_undo_step() { + let (mut s, _) = three_boards(); + s.execute("artboard.align", &json!({"indices": ALL, "vertical": "top"})).unwrap(); + let (steps, before) = (undo_steps(&s), corners(&s)); + for (id, p) in [ + ("artboard.align", json!({"indices": ALL, "vertical": "top"})), + ("artboard.align", json!({"index": 1, "horizontal": "left", "vertical": "bottom"})), + ("artboard.align", json!({"index": 1, "horizontal": "center", "to": "artboard", "artboard": 1})), + ("artboard.distribute", json!({"indices": [0, 2], "horizontal": "center"})), + ("artboard.distribute", json!({"index": 2, "vertical": "top", "to": "artboard", "artboard": 2, "spacing": 30})), + ("artboard.distributeSpacing", json!({"indices": [0, 1], "axis": "horizontal"})), + ("artboard.distributeSpacing", json!({"indices": [1], "axis": "vertical"})), + ] { + assert_eq!(s.execute(id, &p).unwrap(), json!({"moved": []}), "{id} {p}"); + assert_eq!((undo_steps(&s), corners(&s)), (steps, before.clone()), "{id} {p}"); + } +} + +/// A locked artboard stays where it is and still counts in the bounds and in the order. When every +/// artboard named is locked, the command fails. +#[test] +fn a_locked_artboard_stays_where_it_is() { + let (mut s, _) = three_boards(); + s.execute("artboard.setProps", &json!({"index": 1, "locked": true})).unwrap(); + assert_eq!(s.execute("artboard.align", &json!({"indices": ALL, "vertical": "bottom"})).unwrap(), json!({"moved": [0, 2]})); + assert_eq!(corners(&s), [(0.0, 20.0), (150.0, 40.0), (400.0, 70.0)], "the bottom edges at 120, the locked artboard's"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.execute("artboard.distributeSpacing", &json!({"indices": ALL})).unwrap(), json!({"moved": []}), "the middle artboard is locked"); + let out = + s.execute("artboard.distribute", &json!({"indices": ALL, "horizontal": "left", "to": "artboard", "artboard": 0, "spacing": 100})).unwrap(); + assert_eq!((out, corners(&s)), (json!({"moved": [2]}), vec![(0.0, 0.0), (150.0, 40.0), (200.0, 10.0)]), "the third left edge goes to 200"); + s.execute("edit.undo", &json!({})).unwrap(); + let (steps, before) = (undo_steps(&s), corners(&s)); + for (id, p) in [ + ("artboard.align", json!({"index": 1, "horizontal": "left", "to": "artboard", "artboard": 0})), + ("artboard.distribute", json!({"index": 1, "horizontal": "left"})), + ("artboard.distributeSpacing", json!({"indices": [1]})), + ] { + assert_eq!(s.execute(id, &p).unwrap_err().to_string(), "the artboard is locked", "{id}"); + assert_eq!((undo_steps(&s), corners(&s)), (steps, before.clone()), "{id}"); + } +} + +/// Distribute Objects spaces the named edges or centers evenly between the outermost artboards; +/// with a spacing and an artboard to align to, it places them that far apart from that artboard. +#[test] +fn distribute_spaces_the_edges_or_centers() { + let (mut s, [_, b, _]) = three_boards(); + assert_eq!(s.execute("artboard.distribute", &json!({"indices": ALL, "horizontal": "center"})).unwrap(), json!({"moved": [1]})); + assert_eq!(corners(&s), [(0.0, 0.0), (220.0, 40.0), (400.0, 10.0)], "the centers at 50, 250 and 450"); + assert_eq!(corner(&s, b), (225.0, 45.0)); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("artboard.distribute", &json!({"indices": ALL, "vertical": "bottom"})).unwrap(); + assert_eq!(corners(&s), [(0.0, -10.0), (150.0, 40.0), (400.0, 10.0)], "the bottom edges at 60, 90 and 120"); + s.execute("edit.undo", &json!({})).unwrap(); + let p = json!({"indices": ALL, "horizontal": "left", "to": "artboard", "artboard": 1, "spacing": 100}); + assert_eq!(s.execute("artboard.distribute", &p).unwrap(), json!({"moved": [0, 2]})); + assert_eq!(corners(&s), [(50.0, 0.0), (150.0, 40.0), (250.0, 10.0)], "the left edges 100 apart, artboard 1 in place"); + s.execute("edit.undo", &json!({})).unwrap(); + let two = json!({"indices": [0, 2], "horizontal": "right", "to": "artboard", "artboard": 2, "spacing": 150}); + assert_eq!(s.execute("artboard.distribute", &two).unwrap(), json!({"moved": [0]})); + assert_eq!(corners(&s)[0], (250.0, 0.0), "two artboards are enough with a spacing: the right edges at 350 and 500"); + s.execute("edit.undo", &json!({})).unwrap(); + let held = json!({"indices": ALL, "horizontal": "center", "to": "artboard", "artboard": 1}); + assert_eq!(s.execute("artboard.distribute", &held).unwrap(), json!({"moved": [0, 2]})); + assert_eq!(corners(&s), [(-70.0, 0.0), (150.0, 40.0), (330.0, 10.0)], "the centers 200 apart, artboard 1 in place"); +} + +/// Distribute Spacing makes the gaps between the artboards equal; with a spacing and an artboard +/// to align to, the gaps are that wide and that artboard stays. +#[test] +fn distribute_spacing_makes_the_gaps_equal() { + let (mut s, _) = three_boards(); + assert_eq!(s.execute("artboard.distributeSpacing", &json!({"indices": ALL})).unwrap(), json!({"moved": [1]})); + assert_eq!(corners(&s), [(0.0, 0.0), (220.0, 40.0), (400.0, 10.0)], "gaps of 120 between 0 and 500"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("artboard.distributeSpacing", &json!({"indices": ALL, "axis": "vertical"})).unwrap(); + assert_eq!(corners(&s), [(0.0, 0.0), (150.0, 40.0), (400.0, 45.0)], "top to bottom: artboards 0, 2 and 1, overlapping by 55"); + s.execute("edit.undo", &json!({})).unwrap(); + let p = json!({"indices": ALL, "axis": "horizontal", "to": "artboard", "artboard": 1, "spacing": 20}); + assert_eq!(s.execute("artboard.distributeSpacing", &p).unwrap(), json!({"moved": [0, 2]})); + assert_eq!(corners(&s), [(30.0, 0.0), (150.0, 40.0), (230.0, 10.0)], "gaps of 20 on both sides of artboard 1"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("artboard.distributeSpacing", &json!({"indices": [0, 2], "to": "artboard", "artboard": 0, "spacing": -25})).unwrap(); + assert_eq!(corners(&s)[2], (75.0, 10.0), "a negative spacing overlaps them"); + s.execute("edit.undo", &json!({})).unwrap(); + let held = json!({"indices": ALL, "to": "artboard", "artboard": 1}); + assert_eq!(s.execute("artboard.distributeSpacing", &held).unwrap(), json!({"moved": [0, 2]})); + assert_eq!(corners(&s), [(-70.0, 0.0), (150.0, 40.0), (330.0, 10.0)], "gaps of 120, artboard 1 in place"); +} + +/// A value outside what a param takes is an error, and nothing changes. +#[test] +fn bad_params_are_errors() { + let (mut s, _) = three_boards(); + let (steps, before) = (undo_steps(&s), corners(&s)); + let with = |extra: Value| { + let mut p = json!({"indices": ALL, "horizontal": "left"}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + p + }; + let shared = [ + json!({"horizontal": "middle"}), + json!({"horizontal": 1}), + json!({"to": "key"}), + json!({"to": "artboard", "artboard": 9}), + json!({"artboard": "1"}), + json!({"artboard": -1}), + json!({"moveArt": "yes"}), + json!({"patterns": 1}), + json!({"lockedAndHidden": "no"}), + json!({"indices": [9]}), + json!({"indices": []}), + json!({"indices": "0"}), + ]; + for id in ["artboard.align", "artboard.distribute", "artboard.distributeSpacing"] { + let axis = if id == "artboard.distributeSpacing" { json!({"horizontal": null, "axis": "horizontal"}) } else { json!({}) }; + for extra in &shared { + let mut p = with(axis.clone()); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + if id == "artboard.distributeSpacing" && extra.get("horizontal").is_some() { + p = json!({"indices": ALL, "axis": extra["horizontal"]}); + } + assert!(s.execute(id, &p).is_err(), "{id} {p}"); + } + } + for (id, p) in [ + ("artboard.align", json!({"indices": ALL})), + ("artboard.align", json!({"indices": ALL, "vertical": "middle"})), + ("artboard.distribute", json!({"indices": ALL})), + ("artboard.distribute", with(json!({"spacing": "10"}))), + ("artboard.distribute", with(json!({"spacing": true}))), + ("artboard.distribute", json!({"indices": [0, 1], "horizontal": "left", "to": "artboard", "artboard": 2, "spacing": 10})), + ("artboard.distributeSpacing", json!({"indices": ALL, "spacing": [10]})), + ("artboard.distributeSpacing", json!({"indices": [0, 1], "to": "artboard", "artboard": 2, "spacing": 10})), + ] { + assert!(s.execute(id, &p).is_err(), "{id} {p}"); + } + // Spacings that would put an artboard past the canvas, or overflow to infinity. + for (id, p) in [ + ("artboard.distribute", with(json!({"to": "artboard", "artboard": 0, "spacing": 1e9}))), + ("artboard.distribute", with(json!({"to": "artboard", "artboard": 1, "spacing": 1e308}))), + ("artboard.distributeSpacing", json!({"indices": ALL, "to": "artboard", "artboard": 0, "spacing": 1e9})), + ("artboard.distributeSpacing", json!({"indices": ALL, "to": "artboard", "artboard": 1, "spacing": 1e308})), + ] { + let e = s.execute(id, &p).unwrap_err().to_string(); + assert!(e.contains("exceed the canvas"), "{id} {p}: {e}"); + } + assert_eq!((undo_steps(&s), corners(&s)), (steps, before)); +} + +/// Art inside two overlapping artboards moves with the one first in artboard order, as with the +/// other artboard edits, even when Distribute spaces the other one first: artboard 2 at x 140 is +/// left of artboard 1 at x 200, and the square inside both goes with artboard 1. +#[test] +fn art_on_overlapping_artboards_moves_with_the_first_by_index() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("artboard.new", &json!({"x": 200, "y": 0, "width": 100, "height": 100})).unwrap(); + s.execute("artboard.new", &json!({"x": 140, "y": 0, "width": 100, "height": 100})).unwrap(); + let sq = s.execute("shape.rectangle", &json!({"x": 210, "y": 10, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let p = json!({"indices": ALL, "to": "artboard", "artboard": 0, "spacing": 10}); + assert_eq!(s.execute("artboard.distributeSpacing", &p).unwrap(), json!({"moved": [1, 2]})); + assert_eq!(corners(&s), [(0.0, 0.0), (220.0, 0.0), (110.0, 0.0)]); + assert_eq!(corner(&s, sq), (230.0, 10.0), "with artboard 1, 20 pt to the right"); +} + +/// Art inside an artboard that stays and a later one that moves stays with the first: artboard 2 +/// overlaps artboard 0, and aligning it to artboard 0 leaves the square inside both in place. +#[test] +fn art_shared_with_an_artboard_that_stays_stays() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("artboard.new", &json!({"x": 200, "y": 0, "width": 100, "height": 100})).unwrap(); + s.execute("artboard.new", &json!({"x": 60, "y": 0, "width": 100, "height": 100})).unwrap(); + let sq = s.execute("shape.rectangle", &json!({"x": 70, "y": 10, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let p = json!({"indices": [0, 2], "horizontal": "left", "to": "artboard", "artboard": 0}); + assert_eq!(s.execute("artboard.align", &p).unwrap(), json!({"moved": [2]})); + assert_eq!(corners(&s)[2], (0.0, 0.0)); + assert_eq!(corner(&s, sq), (70.0, 10.0), "with artboard 0, which stays"); +} + +/// An artboard's own guides move with it. +#[test] +fn an_artboards_guides_move_with_it() { + let (mut s, _) = three_boards(); + s.execute("guide.add", &json!({"vertical": true, "pos": 160, "artboard": 1})).unwrap(); + s.execute("artboard.align", &json!({"indices": [0, 1], "horizontal": "left"})).unwrap(); + let d = &s.doc().unwrap().doc; + let positions: Vec<f64> = d.ruler_guides().iter().map(|g| g.pos).collect(); + assert_eq!(positions, [10.0], "the guide stays 10 pt inside artboard 1"); +} diff --git a/crates/engine/src/cmd/brushlib.rs b/crates/engine/src/cmd/brushlib.rs index 300d9f6aa1..16ab1c76d4 100644 --- a/crates/engine/src/cmd/brushlib.rs +++ b/crates/engine/src/cmd/brushlib.rs @@ -11,7 +11,9 @@ use std::collections::HashSet; use std::sync::{Arc, LazyLock}; use serde_json::{Value, json}; -use vectorcraft_brush::{self as brush, ArtBrush, Brush, BrushKind, Calligraphic, Colorization, PatternBrush, PatternFit, Scatter, Variation}; +use vectorcraft_brush::{ + self as brush, ArtBrush, Bristle, BristleShape, Brush, BrushKind, Calligraphic, Colorization, PatternBrush, PatternFit, Scatter, Variation, +}; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeId, NodeKind, PatternDef, Symbol}; use vectorcraft_geom::{Affine, FillRule, PathData, Point, Rect, SubPath, shapes}; @@ -168,11 +170,14 @@ pub struct BuiltinBrushLibrary { /// The built-in brush libraries, in menu order: original brushes generated in code. pub const BUILTIN: &[BuiltinBrushLibrary] = &[ BuiltinBrushLibrary { id: "art-ribbons", name: "Art Ribbons", make: art_ribbons }, + BuiltinBrushLibrary { id: "ink-and-wash", name: "Ink and Wash", make: ink_and_wash }, BuiltinBrushLibrary { id: "calligraphic-nibs", name: "Calligraphic Nibs", make: calligraphic_nibs }, + BuiltinBrushLibrary { id: "bristle-brushes", name: "Bristle Brushes", make: bristle_brushes }, BuiltinBrushLibrary { id: "pattern-borders", name: "Pattern Borders", make: pattern_borders }, BuiltinBrushLibrary { id: "scatter-shapes", name: "Scatter Shapes", make: scatter_shapes }, BuiltinBrushLibrary { id: "game-trails", name: "Game Trails", make: game_trails }, BuiltinBrushLibrary { id: "energy-beams", name: "Energy Beams", make: energy_beams }, + BuiltinBrushLibrary { id: "dry-media", name: "Dry Media", make: dry_media }, ]; /// Built-in library `id`, made once. @@ -264,6 +269,78 @@ fn art_ribbons() -> BrushLibrary { built("Art Ribbons", doc, brushes) } +/// A band between the edges y = `top(x)` and y = `bottom(x)` for x in `from`..`to`, in `n` steps. +fn between(from: f64, to: f64, n: usize, top: impl Fn(f64) -> f64, bottom: impl Fn(f64) -> f64) -> PathData { + let xs: Vec<f64> = (0..=n).map(|i| from + (to - from) * i as f64 / n as f64).collect(); + let mut pts: Vec<Point> = xs.iter().map(|&x| Point::new(x, top(x))).collect(); + pts.extend(xs.iter().rev().map(|&x| Point::new(x, bottom(x)))); + PathData::single(SubPath::polyline(&pts, true)) +} + +/// Path `p` filled with gray `hex` at `opacity`: one layer of a wash. +fn wash(p: PathData, hex: &str, opacity: f32) -> Node { + let mut n = filled(p, Paint::solid(Color::from_hex(hex).unwrap_or(Color::BLACK))); + n.opacity = opacity; + n +} + +/// How much of a wash's width is left at x: rounded ends, full width from 8 pt in. +fn wash_ends(x: f64) -> f64 { + let ends = ((x / 8.0).min(1.0) * ((100.0 - x) / 8.0).min(1.0)).max(0.0); + 0.4 + 0.6 * ends.sqrt() +} + +/// Ink and Wash: Tapered Ink, broad near its start and thinning to a fine tip; Brush Pen, a +/// rounded nib whose size follows the pen pressure; and two washes of translucent grays, Soft Wash +/// with faint edges and Pooling Wash with a darker rim and two light breaks. Black and grays take +/// the stroke color as tints of it. +fn ink_and_wash() -> BrushLibrary { + let tapered = { + let half = |x: f64| 3.0 * (x / 22.0).min(1.0).powf(0.6) * ((100.0 - x) / 78.0).min(1.0).powf(1.4); + black(between(0.0, 100.0, 48, |x| -0.85 * half(x), |x| 1.15 * half(x))) + }; + let pen = Brush { + name: "Brush Pen".into(), + kind: BrushKind::Calligraphic(Calligraphic { + angle: 40.0, + roundness: 75.0, + size: 5.0, + variation: [0.0, 0.0, 2.5], + modes: Some([Variation::Fixed, Variation::Fixed, Variation::Pressure]), + }), + }; + let soft = { + let top = |x: f64| -(4.5 + 0.5 * (x * 0.21).sin() + 0.3 * (x * 0.57 + 1.3).sin()) * wash_ends(x); + let bottom = |x: f64| (4.5 + 0.45 * (x * 0.26 + 2.1).sin() + 0.3 * (x * 0.69 + 0.4).sin()) * wash_ends(x); + group(vec![ + wash(between(0.0, 100.0, 40, top, bottom), "#404040", 0.4), + wash(between(2.0, 98.0, 32, |x| top(x) - 0.7 - 0.3 * (x * 0.43).sin().abs(), |x| top(x) + 0.5), "#404040", 0.2), + wash(between(3.0, 97.0, 32, |x| bottom(x) - 0.5, |x| bottom(x) + 0.6 + 0.35 * (x * 0.37 + 1.0).sin().abs()), "#404040", 0.18), + wash(shapes::ellipse(Rect::new(21.0, -2.4, 39.0, 0.8)), "#e6e6e6", 0.22), + wash(shapes::ellipse(Rect::new(61.0, -0.3, 75.0, 2.3)), "#e6e6e6", 0.18), + ]) + }; + let pooling = { + let top = |x: f64| -(4.0 + 0.4 * (x * 0.18 + 0.7).sin() + 0.2 * (x * 0.53).sin()) * wash_ends(x); + let bottom = |x: f64| (4.0 + 0.35 * (x * 0.23 + 1.9).sin() + 0.25 * (x * 0.61 + 0.2).sin()) * wash_ends(x); + let rim = |x: f64, k: f64, phase: f64| 0.35 + k * (0.5 + 0.5 * (x * 0.29 + phase).sin()); + group(vec![ + wash(between(0.0, 100.0, 40, top, bottom), "#4d4d4d", 0.35), + wash(between(1.0, 99.0, 40, top, |x| top(x) + rim(x, 0.45, 0.0)), "#262626", 0.55), + wash(between(1.0, 99.0, 40, |x| bottom(x) - rim(x, 0.5, 1.1), bottom), "#262626", 0.55), + wash(polygon(&[(34.0, -2.6), (39.0, -2.8), (36.0, 2.7), (31.0, 2.5)]), "#e6e6e6", 0.2), + wash(polygon(&[(70.0, -2.4), (74.0, -2.5), (72.0, 2.6), (68.0, 2.4)]), "#e6e6e6", 0.18), + ]) + }; + let brushes = vec![ + art("Tapered Ink", tapered, Colorization::Tints), + pen, + art("Soft Wash", soft, Colorization::Tints), + art("Pooling Wash", pooling, Colorization::Tints), + ]; + built("Ink and Wash", Document::new(100.0, 100.0), brushes) +} + fn nib(name: &str, angle: f64, roundness: f64, size: f64) -> Brush { Brush { name: name.into(), kind: BrushKind::Calligraphic(Calligraphic { angle, roundness, size, ..Default::default() }) } } @@ -290,6 +367,31 @@ fn calligraphic_nibs() -> BrushLibrary { built("Calligraphic Nibs", Document::new(100.0, 100.0), brushes) } +/// A bristle brush: `shape`, then size (pt), bristle length, density, thickness, paint opacity +/// and stiffness (%). +fn bristle(name: &str, shape: BristleShape, [size, length, density, thickness, opacity, stiffness]: [f64; 6]) -> Brush { + Brush { name: name.into(), kind: BrushKind::Bristle(Bristle { shape, size, length, density, thickness, opacity, stiffness }) } +} + +/// Bristle Brushes: one bristle brush for each tip shape, from a fine liner to wide fans for +/// blending and texture. +fn bristle_brushes() -> BrushLibrary { + use BristleShape::*; + let brushes = vec![ + bristle("Fine Liner", RoundPoint, [2.0, 140.0, 30.0, 30.0, 90.0, 75.0]), + bristle("Pointed Flat", FlatPoint, [5.0, 120.0, 55.0, 35.0, 80.0, 60.0]), + bristle("Stubby Round", RoundBlunt, [8.0, 60.0, 70.0, 50.0, 85.0, 80.0]), + bristle("Dry Scrub", FlatBlunt, [10.0, 40.0, 25.0, 60.0, 60.0, 95.0]), + bristle("Soft Dome", RoundCurve, [12.0, 160.0, 85.0, 20.0, 45.0, 25.0]), + bristle("Filbert", FlatCurve, [9.0, 110.0, 65.0, 40.0, 70.0, 45.0]), + bristle("Angled Round", RoundAngle, [7.0, 130.0, 50.0, 35.0, 75.0, 55.0]), + bristle("Angled Flat", FlatAngle, [11.0, 100.0, 60.0, 45.0, 80.0, 65.0]), + bristle("Fan Blender", RoundFan, [16.0, 220.0, 40.0, 15.0, 35.0, 20.0]), + bristle("Grass Fan", FlatFan, [20.0, 260.0, 15.0, 25.0, 65.0, 35.0]), + ]; + built("Bristle Brushes", Document::new(100.0, 100.0), brushes) +} + fn border(name: &str, side: Node, corner: Option<Node>, fit: PatternFit) -> Brush { let kind = BrushKind::Pattern(PatternBrush { side, outer_corner: corner.clone(), inner_corner: corner, fit, ..Default::default() }); Brush { name: name.into(), kind } @@ -446,6 +548,170 @@ fn energy_beams() -> BrushLibrary { built("Energy Beams", Document::new(100.0, 100.0), brushes) } +/// The fixed-seed number source of the Dry Media grain: integer steps and plain arithmetic, so the +/// art is the same on every run and every platform. +struct Grain(u64); + +impl Grain { + /// The next number in 0..1. + fn next(&mut self) -> f64 { + self.0 = self.0.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); + (self.0 >> 11) as f64 / (1u64 << 53) as f64 + } + /// The next number in `a`..`b`. + fn range(&mut self, a: f64, b: f64) -> f64 { + a + (b - a) * self.next() + } +} + +/// `floor` at x = `x0` and `x1`, rising smoothly to 1 within `ramp` pt of each. +fn ends(x: f64, x0: f64, x1: f64, ramp: f64, floor: f64) -> f64 { + let t = ((x - x0).min(x1 - x) / ramp).clamp(0.0, 1.0); + floor + (1.0 - floor) * t * t * (3.0 - 2.0 * t) +} + +/// A closed band from x = `x0` to `x1` in `n` steps, at most `half` pt either side of y = 0 times +/// `taper(x)`; each edge point is pulled in by up to `rough` of that. +fn rough_band(g: &mut Grain, (x0, x1): (f64, f64), n: usize, half: f64, rough: f64, taper: impl Fn(f64) -> f64) -> PathData { + let xs: Vec<f64> = (0..=n).map(|i| x0 + (x1 - x0) * i as f64 / n as f64).collect(); + let mut pts: Vec<Point> = xs.iter().map(|&x| Point::new(x, -half * taper(x) * (1.0 - rough * g.next()))).collect(); + let bottom: Vec<Point> = xs.iter().rev().map(|&x| Point::new(x, half * taper(x) * (1.0 - rough * g.next()))).collect(); + pts.extend(bottom); + PathData::single(SubPath::polyline(&pts, true)) +} + +/// A small four-cornered fleck around (`cx`, `cy`), at most `w` × `h` pt either side; one corner +/// in each direction, so its outline never crosses itself. +fn fleck(g: &mut Grain, cx: f64, cy: f64, w: f64, h: f64) -> PathData { + let mut side = |a: f64, b: f64| g.range(a, b); + let pts = [ + (cx - w * side(0.6, 1.0), cy + h * side(-0.3, 0.3)), + (cx + w * side(-0.3, 0.3), cy - h * side(0.6, 1.0)), + (cx + w * side(0.6, 1.0), cy + h * side(-0.3, 0.3)), + (cx + w * side(-0.3, 0.3), cy + h * side(0.6, 1.0)), + ]; + polygon(&pts) +} + +/// `body` with `holes` (inside it, apart from each other) cut out, even-odd, in gray `k`: what +/// lies under the stroke shows through the holes. +fn holed(body: PathData, holes: Vec<PathData>, k: f32) -> Node { + let children = std::iter::once(body).chain(holes).map(|p| Arc::new(Node::path(NodeId(0), p, Appearance::default()))).collect(); + let mut n = Node::new(NodeId(0), NodeKind::Compound { children, rule: FillRule::EvenOdd }); + n.appearance = Appearance { items: vec![AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::gray(k))))], ..Default::default() }.into(); + n +} + +/// Path `p` filled with gray `k` (1 is black). +fn ink(p: PathData, k: f32) -> Node { + filled(p, Paint::solid(Color::gray(k))) +} + +/// Slivers `w` × `h` pt (ranges) in `count` slots along x = 6..94 inside a band `half` pt wide +/// times `taper`. Each stays within `reach` of the band's half width from y = 0, taken where the +/// band is narrowest over the sliver and the 3 pt either side of it, so with `reach` below the +/// band's roughness margin no sliver touches the band's edge or another sliver. +fn slivers(g: &mut Grain, count: usize, half: f64, reach: f64, (w, h): ((f64, f64), (f64, f64)), taper: impl Fn(f64) -> f64) -> Vec<PathData> { + let slot = 88.0 / count as f64; + (0..count) + .map(|i| { + let cx = 6.0 + slot * (i as f64 + 0.5); + let (w, h) = (g.range(w.0, w.1), g.range(h.0, h.1)); + let room = reach * half * taper(cx - w - 3.0).min(taper(cx + w + 3.0)); + let cy = g.range(-1.0, 1.0) * (room - h).max(0.0); + fleck(g, cx, cy, w, h) + }) + .collect() +} + +/// Dry Media: art brushes of grainy dry drawing marks, chalk, pencil, crayon and charcoal (original +/// vector grain from fixed seeds; every brush 100 pt long, black and grays that take the stroke +/// color as tints, gaps cut out so the paper shows). +pub(crate) fn dry_media() -> BrushLibrary { + // Chalk Grain, 100 × 8 pt: a soft band with narrow scratches and chips along its edges. + let chalk = { + let mut g = Grain(0x0c4a_1c0a); + let taper = |x: f64| ends(x, 0.0, 100.0, 10.0, 0.35); + let body = rough_band(&mut g, (0.0, 100.0), 36, 4.0, 0.25, taper); + let scratches = slivers(&mut g, 14, 4.0, 0.7, ((1.2, 2.4), (0.15, 0.3)), taper); + let mut parts = vec![holed(body, scratches, 0.8)]; + for i in 0..18 { + let cx = 3.0 + 94.0 * (i as f64 + g.range(0.2, 0.8)) / 18.0; + let side = if i % 2 == 0 { -1.0 } else { 1.0 }; + let cy = side * 4.0 * taper(cx) * g.range(0.7, 0.95); + let (w, h) = (g.range(0.3, 0.7), g.range(0.25, 0.5)); + let f = fleck(&mut g, cx, cy, w, h); + parts.push(ink(f, 1.0)); + } + group(parts) + }; + // Graphite Pencil, 100 × 2.5 pt: a solid tapered core with fine slanted hatching at its edges. + let pencil = { + let mut g = Grain(0x009e_4c11); + let core = rough_band(&mut g, (0.0, 100.0), 40, 0.8, 0.12, |x| ends(x, 0.0, 100.0, 18.0, 0.25)); + let mut parts = vec![ink(core, 1.0)]; + for i in 0..24 { + let x0 = 2.0 + 92.0 * (i as f64 + g.range(0.0, 0.4)) / 24.0; + let len = g.range(1.5, 3.0); + let t = g.range(0.12, 0.2); + let slant = g.range(0.1, 0.3); + let y0 = if i % 2 == 0 { -g.range(0.85, 1.05) } else { g.range(0.85, 1.25) - t - slant }; + parts.push(ink(polygon(&[(x0, y0 + slant), (x0 + len, y0), (x0 + len, y0 + t), (x0, y0 + slant + t)]), 0.6)); + } + group(parts) + }; + // Wax Crayon, 100 × 6 pt: a dense band with small gaps in its middle and short overlapping + // marks along both edges. + let crayon = { + let mut g = Grain(0x00c0_a7e5); + let taper = |x: f64| ends(x, 0.0, 100.0, 6.0, 0.5); + let body = rough_band(&mut g, (0.0, 100.0), 30, 2.6, 0.2, taper); + let gaps = slivers(&mut g, 16, 2.6, 0.34, ((0.6, 1.6), (0.15, 0.3)), taper); + let mut parts = vec![holed(body, gaps, 0.9)]; + for i in 0..36 { + let w = g.range(1.0, 2.2); + let cx = (1.0 + w).max(98.0 * (i as f64 + g.range(0.0, 1.0)) / 36.0).min(99.0 - w); + let side = if i % 2 == 0 { -1.0 } else { 1.0 }; + let h = g.range(0.4, 0.6); + // Clear of the gaps, which stay within 0.9 pt of the middle. + let inner = 0.9 + h; + let cy = side * g.range(inner, (2.4 * taper(cx)).max(inner)); + let f = fleck(&mut g, cx, cy, w, h); + parts.push(ink(f, 1.0)); + } + group(parts) + }; + // Charcoal Dust, 100 × 7 pt: a dark band broken into pieces, with flecks of dust either side. + let dust = { + let mut g = Grain(0xc4a2_c0a1); + let mut parts = vec![]; + let mut x0 = 0.0; + while x0 < 100.0 { + let x1 = (x0 + g.range(14.0, 24.0)).min(100.0); + let x1 = if 100.0 - x1 < 8.0 { 100.0 } else { x1 }; + let piece = rough_band(&mut g, (x0, x1), 10, 2.0, 0.3, |x| ends(x, 0.0, 100.0, 8.0, 0.4) * ends(x, x0, x1, 2.0, 0.3)); + parts.push(ink(piece, 1.0)); + x0 = x1 + g.range(1.5, 3.0); + } + for i in 0..30 { + let cx = 2.0 + 96.0 * (i as f64 + g.range(0.2, 0.8)) / 30.0; + let side = if g.next() < 0.5 { -1.0 } else { 1.0 }; + let s = g.range(0.15, 0.3); + let cy = side * g.range(2.3, 3.5 - s); + let f = fleck(&mut g, cx, cy, s, s); + parts.push(ink(f, if i % 3 == 0 { 0.7 } else { 1.0 })); + } + group(parts) + }; + let brushes = vec![ + art("Chalk Grain", chalk, Colorization::Tints), + art("Graphite Pencil", pencil, Colorization::Tints), + art("Wax Crayon", crayon, Colorization::Tints), + art("Charcoal Dust", dust, Colorization::Tints), + ]; + built("Dry Media", Document::new(100.0, 100.0), brushes) +} + // ---------- commands ---------- fn builtin_info(b: &BuiltinBrushLibrary) -> LibraryInfo { diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index b4b231a22b..50c63b59cd 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -33,10 +33,10 @@ mod symbols; pub(crate) use brushes::{apply_brush, brush_targets, stroke_paint}; 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, + brush_apply, brush_delete, brush_duplicate, brush_freehand, brush_get, brush_list, brush_move, brush_new, brush_options, brush_place_art, + brush_remove, brush_replace_art, brush_selection_art, brush_set_current, brush_unused, expand_brush, }; -pub(crate) use dynamic::{edit_part, part_only, selected_part}; +pub(crate) use dynamic::{edit_part, fit_parts, part_only, selected_part}; use dynamic::{symbol_instance_reset, symbol_instance_select_part, symbol_instance_set_appearance}; use symbols::selected_instances; pub(crate) use symbols::{ @@ -67,6 +67,24 @@ pub fn specs() -> Vec<CommandSpec> { has_doc, brush_selection_art ), + cmd!( + "brush.placeArt", + "Place Brush Art", + [], + None, + "{name, x?, y?} place a copy of the art a scatter, art or pattern brush is made of, centered on (x, y) (default: the center of the first artboard), and select it, as dragging the brush from the Brushes panel onto an empty part of the canvas does; a pattern brush places its tiles left to right (side, outer corner, inner corner, start, end; the ones it has art for) 10 pt apart, each in a group named Side Tile, Outer Corner Tile, Inner Corner Tile, Start Tile or End Tile, with an unpainted rectangle at the back of a tile that has a repeat frame marking that frame; a calligraphic or bristle brush is refused → {id}", + has_doc, + brush_place_art + ), + cmd!( + "brush.replaceArt", + "Replace Brush Art", + [], + None, + "{name, ids?|id?, applyToStrokes?: true} make the selected art (several objects become one group, as in brush.new) the art of a scatter, art or pattern brush, keeping its other options, as Alt-dragging (Option-dragging on macOS) art onto the brush in the Brushes panel does; a pattern brush takes a group named for one of its tiles, or a group of such groups (as brush.placeArt places them), tile by tile (of two named for one tile, the frontmost), each with the repeat frame an unpainted rectangle at its back marks (other tiles stay as they are), and other art as its side tile; when strokes use the brush and applyToStrokes is false, the brush and its strokes stay as they were and a copy of the brush with the new art, named `<name> copy`, goes after it and becomes the current brush; otherwise the strokes redraw with the new art; one undo step; refused for a calligraphic or bristle brush, with nothing selected, and for art (or a tile) with no width → {name: the brush that has the new art}", + has_doc, + brush_replace_art + ), cmd!( "brush.apply", "Apply Brush", @@ -144,7 +162,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° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°), rotation_relative_to_path. 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}", + "{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°), rotation_relative_to_path. art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest; tilt: width with the pen lying flat to width_max upright; bearing and rotation: width at −180° to width_max at 180°; half way on a stroke drawn without that input), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}", has_doc, brush_options ), @@ -181,7 +199,7 @@ pub fn specs() -> Vec<CommandSpec> { "New Symbol…", [], None, - "{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type)} make a symbol from the selection and replace it with an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions 0..1 of the natural size (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions → {name, id, registration, exportType, nineSlice, type}", + "{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type)} make a symbol from the selection and replace it with an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions of the natural size in from each edge, each -16..16 (below 0 or above 1 puts a guide outside the art), with left + right < 1 and top + bottom < 1 (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions → {name, id, registration, exportType, nineSlice, type}", has_selection, symbol_new ), @@ -190,7 +208,7 @@ pub fn specs() -> Vec<CommandSpec> { "Symbol Options…", [], None, - "{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic} rename a symbol and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions 0..1) and Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes); default name: current → {name, registration, exportType, nineSlice, type}", + "{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic} rename a symbol (its instances and the graphics mapped onto 3D objects follow the new name) and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions in from each edge, each -16..16, with left + right < 1 and top + bottom < 1) and Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes); default name: current → {name, registration, exportType, nineSlice, type}", has_doc, symbol_options ), @@ -308,7 +326,7 @@ pub fn specs() -> Vec<CommandSpec> { "Select All Unused", [], None, - "{} → {names: [the symbols nothing places, in panel order]} (the Symbols panel selects them): instances in the art (opacity masks included), graph designs, pattern tiles (with the tiles that pattern editing's Cancel puts back) and brush art count, and so do instances in the art of a symbol that is used", + "{} → {names: [the symbols nothing places, in panel order]} (the Symbols panel selects them): instances in the art (opacity masks included), graphics mapped onto 3D objects (threeD.mapGraphic), graph designs, pattern tiles (with the tiles that pattern editing's Cancel puts back) and brush art count, and so do instances in the art of a symbol that is used", has_doc, symbol_unused ), diff --git a/crates/engine/src/cmd/brushsym/brushes.rs b/crates/engine/src/cmd/brushsym/brushes.rs index cf5dedb6bd..1f63076cfd 100644 --- a/crates/engine/src/cmd/brushsym/brushes.rs +++ b/crates/engine/src/cmd/brushsym/brushes.rs @@ -239,7 +239,7 @@ pub(super) fn brush_new(s: &mut Session, p: &Value) -> Result<Value> { && v.get(k).is_none() { let art = selection_art(s, p)?.ok_or_else(|| bad(C, format!("{ty} brushes need selected art (or params.{k})")))?; - if art.geometric_bounds().is_none_or(|b| b.width() <= 1e-6) { + if !has_width(&art, &s.doc()?.doc.symbol_boxes()) { return Err(bad(C, "the selected art has no width")); } v[k] = serde_json::to_value(&art).unwrap_or_default(); @@ -249,6 +249,12 @@ pub(super) fn brush_new(s: &mut Session, p: &Value) -> Result<Value> { Ok(json!({ "name": name })) } +/// Whether art `n` has width for a brush to be made of, with symbol instances measured by their +/// symbols' art in `symbols`. +fn has_width(n: &Node, symbols: &vectorcraft_doc::SymbolBoxes) -> bool { + n.geometric_bounds_with(symbols).is_some_and(|b| b.width() > 1e-6) +} + /// Refuses `name` for a bristle brush when it has more than [`Bristle::MAX_NAME_CHARS`] characters. fn bristle_name_fits(cmd: &str, name: &str) -> Result<()> { let (count, max) = (name.chars().count(), Bristle::MAX_NAME_CHARS); @@ -367,6 +373,12 @@ fn art_brushes(n: &Node, out: &mut Vec<String>) { pub(super) fn brush_unused(s: &mut Session, _: &Value) -> Result<Value> { let d = &s.doc()?.doc; let lib = brush::library(d); + let names = brush_unused_in(d, &lib); + Ok(json!({ "names": names })) +} + +/// The brushes of `lib` no stroke in `d` paints with, in library order ([`brush_unused`]). +fn brush_unused_in(d: &Document, lib: &[Brush]) -> Vec<String> { let mut todo = vec![]; let trees = d.layers.iter().chain(d.symbols.iter().map(|s| &s.art)).chain(d.graph_designs.iter().map(|g| &g.art)); let patterns = d.patterns.iter().chain(d.pattern_edit.iter().filter_map(|pe| pe.original.as_ref())); @@ -379,8 +391,7 @@ pub(super) fn brush_unused(s: &mut Session, _: &Value) -> Result<Value> { used.insert(name); } } - let names: Vec<&str> = lib.iter().map(|b| b.name.as_str()).filter(|n| !used.contains(*n)).collect(); - Ok(json!({ "names": names })) + lib.iter().map(|b| b.name.clone()).filter(|n| !used.contains(n)).collect() } pub(super) fn brush_options(s: &mut Session, p: &Value) -> Result<Value> { @@ -483,6 +494,217 @@ pub(super) fn brush_options(s: &mut Session, p: &Value) -> Result<Value> { Ok(json!({ "name": out })) } +/// The name `brush.placeArt` gives each pattern brush tile it places, by tile, in the order it +/// places them; `brush.replaceArt` reads a group of that name as that tile. +const TILE_NAMES: [&str; 5] = ["Side Tile", "Outer Corner Tile", "Inner Corner Tile", "Start Tile", "End Tile"]; + +/// The space between the pattern brush tiles `brush.placeArt` places, in points. +const TILE_GAP: f64 = 10.0; + +/// The message for a brush that is not made of art. +fn no_art(name: &str) -> String { + format!("`{name}` has no art (only scatter, art and pattern brushes do)") +} + +/// Tile `i` of `p` ([`TILE_NAMES`] order): its art and its repeat frame, when it has art. +fn tile(p: &brush::PatternBrush, i: usize) -> Option<(&Node, Option<vectorcraft_geom::Rect>)> { + match i { + 0 => Some((&p.side, p.side_frame)), + 1 => p.outer_corner.as_ref().map(|n| (n, p.outer_corner_frame)), + 2 => p.inner_corner.as_ref().map(|n| (n, p.inner_corner_frame)), + 3 => p.start.as_ref().map(|n| (n, p.start_frame)), + _ => p.end.as_ref().map(|n| (n, p.end_frame)), + } +} + +/// Gives tile `i` of `p` ([`TILE_NAMES`] order) the art `art` and the repeat frame `frame`. The tile +/// no longer comes from a pattern swatch, and a corner draws its own art. +fn set_tile(p: &mut brush::PatternBrush, i: usize, art: Node, frame: Option<vectorcraft_geom::Rect>) { + match i { + 0 => (p.side, p.side_frame, p.side_swatch) = (art, frame, None), + 1 => (p.outer_corner, p.outer_corner_frame, p.outer_corner_swatch, p.outer_source) = (Some(art), frame, None, None), + 2 => (p.inner_corner, p.inner_corner_frame, p.inner_corner_swatch, p.inner_source) = (Some(art), frame, None, None), + 3 => (p.start, p.start_frame, p.start_swatch) = (Some(art), frame, None), + _ => (p.end, p.end_frame, p.end_swatch) = (Some(art), frame, None), + } +} + +/// The art `brush.placeArt` places for brush `b`, in the brush's own coordinates: a scatter or art +/// brush's art, or a pattern brush's tiles in a row, each in a group named for its tile +/// ([`TILE_NAMES`]), with an unpainted rectangle at the back of a tile that has a repeat frame +/// marking that frame. `None` for a brush that is not made of art. Symbol instances in the art are +/// measured by their symbols' art in `symbols`. +fn placed_art(b: &Brush, symbols: &vectorcraft_doc::SymbolBoxes) -> Option<Node> { + match &b.kind { + BrushKind::Scatter(sc) => Some(sc.art.clone()), + BrushKind::Art(a) => Some(a.art.clone()), + BrushKind::Pattern(pb) => { + let mut tiles = vec![]; + let mut x = 0.0; + for (i, tile_name) in TILE_NAMES.iter().enumerate() { + let Some((art, frame)) = tile(pb, i) else { continue }; + let mut children = vec![]; + if let Some(f) = frame { + let marker = Node::path( + NodeId(0), + vectorcraft_geom::shapes::rectangle(f), + vectorcraft_doc::Appearance::basic(Paint::None, Paint::None, 1.0), + ); + children.push(Arc::new(marker)); + } + children.push(Arc::new(art.clone())); + let mut g = Node::group(NodeId(0), children); + g.name = Some((*tile_name).to_string()); + let Some(r) = g.geometric_bounds_with(symbols) else { continue }; + // Each tile sits right of the one before it, centered on the line y = 0. + g.transform(vectorcraft_geom::Affine::translate((x - r.x0, -r.center().y)), false); + x += r.width() + TILE_GAP; + tiles.push(Arc::new(g)); + } + Some(Node::group(NodeId(0), tiles)) + } + BrushKind::Calligraphic(_) | BrushKind::Bristle(_) => None, + } +} + +/// `brush.placeArt`: a copy of the art brush `name` is made of, centered on (`x`, `y`) (default: the +/// center of the first artboard) in the layer new art goes into, and selected, as one undo step. +/// Scatter and art brushes place their art; pattern brushes place their tiles ([`placed_art`]). +pub(super) fn brush_place_art(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "brush.placeArt"; + let name = name_param(p, C)?.to_string(); + let d = &s.doc()?.doc; + let center = d.artboards.first().map(|a| a.rect.center()).unwrap_or(super::Point::ZERO); + let at = super::Point::new(super::number_or(p, "x", center.x, C)?, super::number_or(p, "y", center.y, C)?); + let b = brush::find(d, &name).ok_or_else(|| bad(C, format!("no brush named `{name}`")))?; + let symbols = d.symbol_boxes(); + let mut art = placed_art(&b, &symbols).ok_or_else(|| bad(C, no_art(&name)))?; + if let Some(r) = art.geometric_bounds_with(&symbols) { + art.transform(vectorcraft_geom::Affine::translate(at - r.center()), false); + } + let parent = s.doc()?.target_parent()?; + let id = s.edit("Place Brush Art", |d, sel| { + let art = d.reid(&art); + let id = art.id; + d.insert(parent, usize::MAX, art)?; + sel.set([id]); + Ok(id) + })?; + Ok(json!({ "id": id.0 })) +} + +/// The repeat frame an unpainted rectangle at the back of a tile group marks ([`placed_art`]): the +/// rectangle's bounds, when `n` is a path of one closed subpath through the four corners of its +/// bounds, without curves, whose fills and strokes paint nothing and that has no other appearance. +fn frame_marker(n: &Node) -> Option<vectorcraft_geom::Rect> { + let NodeKind::Path { path, guide: false, clipping: false, .. } = &n.kind else { return None }; + let unpainted = n.appearance.effects.is_empty() + && n.appearance.items.iter().all(|i| match i { + AppearanceItem::Fill(f) => f.paint.is_none(), + AppearanceItem::Stroke(st) => st.paint.is_none(), + }); + let [sp] = path.subpaths.as_slice() else { return None }; + let r = n.geometric_bounds()?; + let corners = [(r.x0, r.y0), (r.x1, r.y0), (r.x1, r.y1), (r.x0, r.y1)]; + let at_corners = sp.anchors.len() == 4 + && sp.anchors.iter().all(|a| a.h_in == a.p && a.h_out == a.p) + && corners.iter().all(|c| sp.anchors.iter().any(|a| (a.p.x, a.p.y) == *c)); + (unpainted && sp.closed && at_corners && r.width() > 1e-9 && r.height() > 1e-9).then_some(r) +} + +/// The tiles in `art` for a pattern brush, by tile ([`TILE_NAMES`] order), with their repeat frames: +/// a group named for a tile, as `brush.placeArt` places them, is the art of its tile (an unpainted +/// rectangle at its back marks the tile's frame, [`frame_marker`], and is left out of the art; a +/// group left with one member gives that member), and so is each member of a group whose members +/// are all such groups; any other art is the side tile. +fn tiles_of(art: Node) -> Vec<(usize, Node, Option<vectorcraft_geom::Rect>)> { + let named = |c: &Node| matches!(c.kind, NodeKind::Group { clip: false, .. }) && c.name.as_deref().is_some_and(|n| TILE_NAMES.contains(&n)); + let tiles = match &art.kind { + _ if named(&art) => vec![Arc::new(art)], + NodeKind::Group { children, clip: false } if !children.is_empty() && children.iter().all(|c| named(c)) => children.clone(), + _ => return vec![(0, art, None)], + }; + let mut out: Vec<(usize, Node, Option<vectorcraft_geom::Rect>)> = vec![]; + for t in tiles { + let Some(i) = t.name.as_deref().and_then(|n| TILE_NAMES.iter().position(|x| *x == n)) else { continue }; + let mut g = (*t).clone(); + let mut frame = None; + if let NodeKind::Group { children, .. } = &mut g.kind + && let Some(f) = children.first().and_then(|c| frame_marker(c)) + { + frame = Some(f); + children.remove(0); + } + g.name = None; + // The group `brush.placeArt` put around the tile's art: the art itself goes back, so a + // tile does not gain a group each time it goes out and back. + if let NodeKind::Group { children, clip: false } = &g.kind + && let [only] = children.as_slice() + && g == Node::group(g.id, children.clone()) + { + g = (**only).clone(); + } + // A tile named twice: the frontmost one counts. + out.retain(|(j, ..)| *j != i); + out.push((i, g, frame)); + } + out +} + +/// `brush.replaceArt`: the selected art (or `ids`/`id`; several objects become one group, as in +/// `brush.new`) becomes the art of scatter, art or pattern brush `name`, keeping its other options, +/// as one undo step. A pattern brush takes the tiles `brush.placeArt` places by their names +/// ([`tiles_of`]) and other art as its side tile. When strokes use the brush and `applyToStrokes` is +/// false, the brush and its strokes stay as they were and a copy of the brush with the new art is +/// added after it and becomes the current brush; otherwise the strokes redraw with the new art. +pub(super) fn brush_replace_art(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "brush.replaceArt"; + let name = name_param(p, C)?.to_string(); + let apply = super::switch_or(p, "applyToStrokes", true, C)?; + let mut lib = brush::library(&s.doc()?.doc); + let i = lib.iter().position(|b| b.name == name).ok_or_else(|| bad(C, format!("no brush named `{name}`")))?; + if lib[i].art().is_empty() { + return Err(bad(C, no_art(&name))); + } + let art = selection_art(s, p)?.ok_or_else(|| bad(C, "nothing selected"))?; + let d = &s.doc()?.doc; + let symbols = d.symbol_boxes(); + let check = |n: &Node| if has_width(n, &symbols) { Ok(()) } else { Err(bad(C, "the selected art has no width")) }; + let mut b = lib[i].clone(); + match &mut b.kind { + BrushKind::Scatter(sc) => { + check(&art)?; + sc.art = art; + } + BrushKind::Art(a) => { + check(&art)?; + a.art = art; + } + BrushKind::Pattern(pb) => { + for (t, art, frame) in tiles_of(art) { + check(&art)?; + set_tile(pb, t, art, frame); + } + } + BrushKind::Calligraphic(_) | BrushKind::Bristle(_) => return Err(bad(C, no_art(&name))), + } + let used = !brush_unused_in(d, &lib).contains(&name); + if apply || !used { + lib[i] = b; + save_library(s, "Replace Brush Art", lib, &[])?; + return Ok(json!({ "name": name })); + } + b.name = brush::unique_name(&lib, &format!("{} copy", name.trim())); + let copy = b.name.clone(); + lib.insert(i + 1, b); + s.edit("Replace Brush Art", |d, _| { + d.unknown.insert(brush::CURRENT_KEY.into(), json!(copy)); + brush::store(d, &lib); + Ok(()) + })?; + Ok(json!({ "name": copy })) +} + pub(super) fn expand_brush(s: &mut Session, p: &Value) -> Result<Value> { let ids = brush_targets(&s.doc()?.doc, &roots(s, p)?); let ids: Vec<NodeId> = ids.into_iter().filter(|id| s.doc().ok().and_then(|st| st.doc.node(*id)).is_some_and(brush::has_brush)).collect(); diff --git a/crates/engine/src/cmd/brushsym/dynamic.rs b/crates/engine/src/cmd/brushsym/dynamic.rs index 888e450085..f5cef8351e 100644 --- a/crates/engine/src/cmd/brushsym/dynamic.rs +++ b/crates/engine/src/cmd/brushsym/dynamic.rs @@ -2,7 +2,7 @@ //! appearance of objects in the symbol's art and stays linked to the symbol //! (`symbol.instance.setAppearance`, `symbol.instance.reset`). The changes live on the instance //! ([`vectorcraft_doc::symbol_overrides`]); editing the symbol keeps those whose object is still -//! there ([`fit_overrides`]). +//! there and draws them ([`fit_overrides`]). use std::sync::Arc; @@ -27,7 +27,7 @@ pub(super) fn type_id(dynamic: bool) -> &'static str { } /// Fit the appearance changes of instances `ids` to their symbols: an instance of a static (or -/// missing) symbol keeps none, an instance of a dynamic one those naming an object of its art. +/// missing) symbol keeps none, an instance of a dynamic one those its art still draws ([`fit_parts`]). pub(super) fn fit_overrides(d: &mut Document, ids: &[NodeId]) { for id in ids { let art = match d.node(*id) { @@ -40,7 +40,7 @@ pub(super) fn fit_overrides(d: &mut Document, ids: &[NodeId]) { let Some(n) = d.node_mut(*id) else { continue }; let mut e = n.extras_mut(); match art { - Some(art) => symbol_overrides::retain_parts(&mut e.symbol_overrides, &art), + Some(art) => fit_parts(&mut e.symbol_overrides, &art), None => e.symbol_overrides.clear(), } } @@ -177,17 +177,42 @@ fn check_paint_kinds(p: &Value, art: &Node, path: &[u32], cmd: &str) -> Result<( fn solid_fill_check(p: &Value, art: &Node, path: &[u32], fill: Option<&vectorcraft_color::Paint>, cmd: &str) -> Result<()> { let asked = p.get("fill").is_some_and(|v| !v.is_null()); let is_instance = symbol_overrides::part(art, path).is_some_and(|n| matches!(n.kind, NodeKind::SymbolInstance { .. })); - let draws_nothing = |f: &vectorcraft_color::Paint| match f { - vectorcraft_color::Paint::Gradient(_) => true, - vectorcraft_color::Paint::Pattern { .. } => true, - vectorcraft_color::Paint::None | vectorcraft_color::Paint::Solid { .. } => false, - }; - if asked && is_instance && fill.is_some_and(draws_nothing) { + if asked && is_instance && fill.is_some_and(|f| !stains(f)) { return Err(bad(cmd, "fill on a symbol instance must be a solid color or none")); } Ok(()) } +/// Can a symbol instance's fill be `f`? An instance stains its art with a solid fill only. +fn stains(f: &vectorcraft_color::Paint) -> bool { + match f { + vectorcraft_color::Paint::Gradient(_) => false, + vectorcraft_color::Paint::Pattern { .. } => false, + vectorcraft_color::Paint::None | vectorcraft_color::Paint::Solid { .. } => true, + } +} + +/// Keep the appearance changes `overrides` that name an object of `art` (a symbol's new art), each +/// without a fill or stroke that object does not draw ([`paint_refusal`], [`stains`]); a change +/// left with nothing in it is dropped. +pub(crate) fn fit_parts(overrides: &mut Vec<SymbolOverride>, art: &Node) { + symbol_overrides::retain_parts(overrides, art); + for o in overrides.iter_mut() { + let Some(n) = symbol_overrides::part(art, &o.path) else { continue }; + let instance = matches!(n.kind, NodeKind::SymbolInstance { .. }); + if paint_refusal(n, "fill", FIT).is_some() || (instance && o.fill.as_ref().is_some_and(|f| !stains(f))) { + o.fill = None; + } + if paint_refusal(n, "stroke", FIT).is_some() { + o.stroke = None; + } + } + overrides.retain(|o| !o.is_empty()); +} + +/// The command name [`fit_parts`] gives [`paint_refusal`], whose refusal it does not show. +const FIT: &str = "symbol.update"; + /// `fill` or `stroke` of `p` for override `o`: absent leaves it, null clears it, a colour string or /// an object of `paint.setFill`'s paint params sets it. fn paint_change(s: &Session, p: &Value, key: &str, cmd: &str) -> Result<Option<Option<vectorcraft_color::Paint>>> { diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index b789f600b4..2fb31c5f6b 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -47,21 +47,20 @@ fn export_type_param(p: &Value, cmd: &str) -> Result<Option<SymbolExportType>> { } /// `nineSlice` (bool) and `nineSliceGuides` ([left, top, right, bottom] fractions of the natural -/// size): `None` leaves the symbol alone, `Some(None)` turns 9-slice off, `Some(Some(g))` turns it -/// on with guides `g` (the symbol's current ones, else a quarter in from each edge, when none are -/// given). +/// size, below 0 or above 1 for a guide outside the art): `None` leaves the symbol alone, +/// `Some(None)` turns 9-slice off, `Some(Some(g))` turns it on with guides `g` (the symbol's +/// current ones, else a quarter in from each edge, when none are given). fn nine_slice_param(p: &Value, cmd: &str, current: Option<SymbolNineSlice>) -> Result<Option<Option<SymbolNineSlice>>> { let on = match p.get("nineSlice") { None | Some(Value::Null) => None, Some(v) => Some(v.as_bool().ok_or_else(|| bad(cmd, "nineSlice must be true or false"))?), }; - let guides = - match p.get("nineSliceGuides") { - None | Some(Value::Null) => None, - Some(v) => Some(SymbolNineSlice::from_value(v).ok_or_else(|| { - bad(cmd, "nineSliceGuides must be [left, top, right, bottom], each 0..1, with left + right < 1 and top + bottom < 1") - })?), - }; + let guides = match p.get("nineSliceGuides") { + None | Some(Value::Null) => None, + Some(v) => Some(SymbolNineSlice::from_value(v).ok_or_else(|| { + bad(cmd, "nineSliceGuides must be [left, top, right, bottom], each -16..16, with left + right < 1 and top + bottom < 1") + })?), + }; Ok(match (on, guides) { (Some(false), _) => Some(None), (None, None) => None, @@ -115,6 +114,8 @@ fn art_symbols(n: &Node, out: &mut Vec<String>) { if let NodeKind::SymbolInstance { symbol, .. } = &m.kind { out.push(symbol.clone()); } + // A graphic on a 3D object draws its symbol's art too. + out.extend(vectorcraft_render::effects::graphic_symbols(m)); }); } @@ -129,6 +130,8 @@ pub(super) fn symbol_unused(s: &mut Session, _: &Value) -> Result<Value> { let patterns = d.patterns.iter().chain(d.pattern_edit.iter().filter_map(|pe| pe.original.as_ref())); let trees = d.layers.iter().map(|l| &**l).chain(d.graph_designs.iter().map(|g| &*g.art)); trees.chain(patterns.flat_map(|p| p.art.iter().map(|n| &**n))).chain(lib.iter().flat_map(|b| b.art())).for_each(|n| art_symbols(n, &mut todo)); + // A graphic in a graphic style draws its symbol's art wherever the style is applied. + todo.extend(d.graphic_styles.iter().flat_map(|g| vectorcraft_render::effects::appearance_graphic_symbols(&g.appearance))); let mut used = std::collections::BTreeSet::new(); while let Some(name) = todo.pop() { if !used.contains(&name) { @@ -290,6 +293,33 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result<Value> { *symbol = n.clone(); } } + // The graphics mapped onto 3D objects follow the new name: in the layers, the art of + // symbols, patterns, graph designs and brushes, their opacity masks, and graphic styles. + let patterns = d.patterns.iter_mut().chain(d.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut())); + let trees = d + .layers + .iter_mut() + .chain(d.symbols.iter_mut().map(|sym| &mut sym.art)) + .chain(d.graph_designs.iter_mut().map(|g| &mut g.art)) + .chain(patterns.flat_map(|p| p.art.iter_mut())); + for art in trees.filter(|art| vectorcraft_render::effects::names_graphic_symbol(art, &name)) { + vectorcraft_render::effects::rename_graphic_symbol_in(Arc::make_mut(art), &name, n); + } + let styled = |g: &vectorcraft_doc::GraphicStyle| vectorcraft_render::effects::appearance_graphic_symbols(&g.appearance).contains(&name); + if d.graphic_styles.iter().any(styled) { + for style in d.graphic_styles.iter_mut() { + vectorcraft_render::effects::rename_appearance_graphic_symbol(&mut style.appearance, &name, n); + } + } + // The brush library is stored again only when a brush's art changed. + let mut lib = brush::library(d); + let mut brushes = false; + for art in lib.iter_mut().flat_map(|b| b.art_mut()) { + brushes |= vectorcraft_render::effects::rename_graphic_symbol_in(art, &name, n); + } + if brushes { + brush::store(d, &lib); + } rename_natural_size(d, &name, n); d.rename_symbol_registration(&name, n); d.rename_symbol_export_type(&name, n); diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index d392449247..94fe55c119 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -29,8 +29,8 @@ use super::edit::{outermost, selected_roots}; use super::paint::paint_from; use super::pathops::{Beside, shape_node}; use super::{ - CommandSpec, EngineError, Result, Session, always, bad, check_numbers, cmd, color_value, f64_or, finite_numbers, has_doc, id_param, named_ids, - number_or, point_param, str_param, switch_or, + CommandSpec, EngineError, Result, Session, always, bad, check_numbers, cmd, color_value, f64_or, finite_numbers, has_doc, named_ids, number_or, + object_param, point_param, str_param, switch_or, }; mod live_paint; @@ -117,7 +117,7 @@ pub fn specs() -> Vec<CommandSpec> { "Live Paint Bucket", [], None, - "{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], color?|swatch?|gradient?|none? (default: current fill; a color in #rrggbbaa or #rgba is refused), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces → {group, face}", + "{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], points?: [[x,y]…] (a drag polyline starting at point; 1 to 4096 finite canvas points; fills every crossed face of the same group), continuation?: [[[x,y]…]…] (further path chunks of 1 to 4096 finite canvas points each; each starts at the preceding chunk's last point; requires points), color?|swatch?|gradient?|none? (default: current fill; a color in #rrggbbaa or #rgba is refused), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces → {group, face}", has_doc, lp_fill ), @@ -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), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}", + "{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, 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), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}", has_selection_or_ids, |s, p| trace_make(s, p, false) ), diff --git a/crates/engine/src/cmd/buildcmds/live_paint.rs b/crates/engine/src/cmd/buildcmds/live_paint.rs index 207182d40a..e5e7757486 100644 --- a/crates/engine/src/cmd/buildcmds/live_paint.rs +++ b/crates/engine/src/cmd/buildcmds/live_paint.rs @@ -1,7 +1,7 @@ use super::{ Appearance, Arc, Beside, Document, EDGE_NAME, EngineError, FACE_NAME, GapOptions, GapSize, LIVE_PAINT_NAME, Node, NodeId, Paint, PathData, Point, - Rect, Result, SOURCES_NAME, Selection, Session, SubPath, Value, b, bad, build_children, edge_near, face_at, finite, id_param, ids_json, - is_live_paint, json, number_or, paint_from, po, point_param, repaint_from, replace_roots, root_ids, source_nodes, source_shapes, switch_or, + Rect, Result, SOURCES_NAME, Selection, Session, SubPath, Value, b, bad, build_children, edge_near, face_at, finite, ids_json, is_live_paint, + json, number_or, object_param, paint_from, po, point_param, repaint_from, replace_roots, root_ids, source_nodes, source_shapes, switch_or, }; /// `options` as stored on a Live Paint group: none for the defaults. @@ -272,9 +272,38 @@ pub(super) fn lp_gap_options(s: &mut Session, p: &Value) -> Result<Value> { pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "livePaint.fill"; let pt = point_param(p, "point").filter(|q| finite(*q)).ok_or_else(|| bad(C, "missing point [x,y]"))?; + let parse_chunk = |input: &Value, start: Point| -> Result<Vec<Point>> { + let values = input + .as_array() + .filter(|points| !points.is_empty() && points.len() <= b::LP_FILL_CHUNK_POINTS) + .ok_or_else(|| bad(C, "each path chunk must contain 1 to 4096 points"))?; + let points: Vec<_> = values + .iter() + .map(|point| { + let pair = point.as_array().filter(|pair| pair.len() == 2).ok_or_else(|| bad(C, "points must be [x,y] pairs"))?; + let x = pair.first().and_then(Value::as_f64).ok_or_else(|| bad(C, "point x must be a number"))?; + let y = pair.get(1).and_then(Value::as_f64).ok_or_else(|| bad(C, "point y must be a number"))?; + let point = Point::new(x, y); + if !finite(point) { + return Err(bad(C, "points must be finite canvas points")); + } + Ok(point) + }) + .collect::<Result<_>>()?; + if points.first() != Some(&start) { + return Err(bad(C, "path chunks must share their boundary point")); + } + Ok(points) + }; + let points = p.get("points"); + let continuation = match p.get("continuation") { + None => &[][..], + Some(input) if points.is_some() => input.as_array().ok_or_else(|| bad(C, "continuation must be an array of path chunks"))?.as_slice(), + Some(_) => return Err(bad(C, "continuation requires points")), + }; crate::cmd::paint::check_keep_model(p, C)?; let paint = paint_from(s, p)?.unwrap_or_else(|| s.paint.fill.clone()); - let group = id_param(p, "group"); + let group = object_param(p, "group", C)?; let roots = if group.is_none() { root_ids(s, p)? } else { vec![] }; let (g, face) = s.edit("Live Paint Bucket", |d, sel| { let gid = match group { @@ -302,7 +331,33 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> { .and_then(|n| b::visible_face_at(n, pt)) .map(|f| f.id) .ok_or_else(|| EngineError::Other("no Live Paint face at that point".into()))?; - d.node_mut(fid).ok_or(EngineError::NoNode(fid))?.appearance.set_fill(paint.clone()); + let mut targets = std::collections::BTreeSet::from([fid]); + if let Some(points) = points { + let n = d.node(gid).ok_or(EngineError::NoNode(gid))?; + // Use the existing region-crossing probes, so even a face narrower than the distance + // between pointer events is filled. Reversing matches visible_face_at's front first. + let faces: Vec<_> = b::faces(n).into_iter().rev().filter(|f| f.visible).collect(); + let mut face_ids = vec![]; + let mut regions = vec![]; + for f in faces { + if let Some(path) = f.path_data() + && let Some(bounds) = path.bounds() + { + face_ids.push(f.id); + regions.push((po::Region { path: path.clone(), sources: vec![] }, path.to_bezpath(), bounds)); + } + } + let map = b::BuilderMap { regions, ..Default::default() }; + let mut last = pt; + for input in std::iter::once(points).chain(continuation) { + let chunk = parse_chunk(input, last)?; + last = chunk.last().copied().unwrap_or(last); + targets.extend(map.hits_along(&chunk, None).regions.iter().filter_map(|i| face_ids.get(*i).copied())); + } + } + for target in targets { + d.node_mut(target).ok_or(EngineError::NoNode(target))?.appearance.set_fill(paint.clone()); + } Ok((gid, fid)) })?; s.remember_paint(&paint); @@ -312,7 +367,7 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> { pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "livePaint.strokeEdge"; let pt = point_param(p, "point").filter(|q| finite(*q)).ok_or_else(|| bad(C, "missing point [x,y]"))?; - let g = id_param(p, "group").ok_or_else(|| bad(C, "missing group"))?; + let g = object_param(p, "group", C)?.ok_or_else(|| bad(C, "missing group"))?; crate::cmd::paint::check_keep_model(p, C)?; let paint = paint_from(s, p)?.unwrap_or_else(|| s.paint.stroke.clone()); let width = number_or(p, "width", s.paint.stroke_width.max(0.0), C)?; @@ -335,7 +390,10 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> { } pub(super) fn lp_info(s: &mut Session, p: &Value) -> Result<Value> { - let g = id_param(p, "group").or_else(|| id_param(p, "id")).ok_or_else(|| bad("livePaint.info", "missing group"))?; + let g = match object_param(p, "group", "livePaint.info")? { + Some(g) => g, + None => object_param(p, "id", "livePaint.info")?.ok_or_else(|| bad("livePaint.info", "missing group"))?, + }; let d = &s.doc()?.doc; let n = d.node(g).filter(|n| is_live_paint(n)).ok_or_else(|| bad("livePaint.info", format!("{g} is not a Live Paint group")))?; let faces: Vec<Value> = b::faces(n) diff --git a/crates/engine/src/cmd/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs index 9c6c28b900..11519b84be 100644 --- a/crates/engine/src/cmd/buildcmds/trace.rs +++ b/crates/engine/src/cmd/buildcmds/trace.rs @@ -527,8 +527,9 @@ fn color_groups(cmd: &str, d: &mut Document, items: Vec<Arc<Node>>) -> Result<Ve } /// 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. +/// its image, the image's encoded bytes, and the settings it is traced with. The tracer makes the +/// same paths of the same inputs, so a trace made away from the command ([`TraceRun`]) stands in +/// for the command's own. #[derive(Clone, Debug, PartialEq)] struct TraceInputs { target: NodeId, @@ -538,6 +539,9 @@ struct TraceInputs { /// Document Library: the library's colours, which the JSON leaves out /// ([`tr::TraceParams::swatches`]). swatches: Vec<[u8; 3]>, + /// The encoded image the tracer decodes: the blob under the image's key, shared with the + /// document. Two blobs are equal when they are the same allocation or hold the same bytes. + bytes: Arc<Vec<u8>>, } /// What `imageTrace.make` and `imageTrace.makeAndExpand` take from the session before they trace. @@ -549,7 +553,6 @@ struct Prepared { params_json: Value, preset_label: String, library: Vec<([u8; 3], Paint)>, - bytes: Arc<Vec<u8>>, } /// What command `c` with params `p` traces, and how, from the session: everything but the trace. @@ -597,8 +600,8 @@ fn prepare(s: &Session, c: &str, p: &Value) -> Result<Prepared> { let bytes = Arc::clone(&blob.bytes); let library = trace_library(c, s, &mut params)?; let traced_with = serde_json::to_value(¶ms).map_err(|e| EngineError::Other(e.to_string()))?; - let inputs = TraceInputs { target, image, params: traced_with, swatches: params.swatches.clone() }; - Ok(Prepared { inputs, trace: params, view, params_json, preset_label, library, bytes }) + let inputs = TraceInputs { target, image, params: traced_with, swatches: params.swatches.clone(), bytes }; + Ok(Prepared { inputs, trace: params, view, params_json, preset_label, library }) } /// What a trace made of an image: the size in pixels it was decoded at, and the paths. @@ -616,11 +619,11 @@ impl Traced { } } -/// Decode the image `bytes` and trace it with `params`, telling `steps` how far it has got -/// ([`tr::trace_watched`]); [`EngineError::Cancelled`] once `steps` answers `false`. -fn trace_now(inputs: &TraceInputs, params: &tr::TraceParams, bytes: &[u8], steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result<Traced> { +/// Decode the image bytes of `inputs` and trace them with `params`, telling `steps` how far it has +/// got ([`tr::trace_watched`]); [`EngineError::Cancelled`] once `steps` answers `false`. +fn trace_now(inputs: &TraceInputs, params: &tr::TraceParams, steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result<Traced> { // An image over the tracer's size is traced scaled down (the paths are scaled back). - let raster = tr::Raster::decode_to_fit(bytes).map_err(|e| EngineError::Other(e.to_string()))?; + let raster = tr::Raster::decode_to_fit(&inputs.bytes).map_err(|e| EngineError::Other(e.to_string()))?; if !steps(0, 0) { return Err(EngineError::Cancelled); } @@ -682,7 +685,8 @@ impl TraceRun { (self.prepared.inputs.image.width, self.prepared.inputs.image.height) } - /// Does it still apply: would the command trace the same object, image and settings now? + /// Does it still apply: would the command trace the same object, image, pixels and settings + /// now? pub fn current(&self, s: &Session) -> bool { prepare(s, self.command, &self.params).is_ok_and(|now| now.inputs == self.prepared.inputs) } @@ -691,13 +695,13 @@ impl TraceRun { /// failed or stopped ([`EngineError::Cancelled`] once `steps` answers `false`). It touches no /// document, so it can run on any thread. pub fn run(&self, steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result<Traced> { - trace_now(&self.prepared.inputs, &self.prepared.trace, &self.prepared.bytes, steps) + trace_now(&self.prepared.inputs, &self.prepared.trace, steps) } } 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 Prepared { inputs, trace, view, params_json, preset_label, library } = 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. @@ -709,7 +713,7 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val // A trace handed in for these very inputs ([`TraceRun`]), else one made now. let Traced { raster, res, .. } = match s.trace_hand_off.take() { Some(traced) if traced.inputs == inputs => traced, - _ => trace_now(&inputs, &trace, &bytes, &|_, _| true)?, + _ => trace_now(&inputs, &trace, &|_, _| true)?, }; let TraceInputs { target, image: img, .. } = inputs; let mut warnings = keep_warnings(&trace, &res); diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index 9e52454de1..446634d21c 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -88,8 +88,9 @@ pub struct Clipboard { /// The artboard the objects were copied from (none when they lie on no artboard; the first of /// [`Self::artboards`] when there are any): Paste on All Artboards keeps their offset to it. pub source_artboard: Option<Rect>, - /// Per object: the name of the layer it was copied from (Paste Remembers Layers). - pub source_layers: Vec<Option<String>>, + /// Per object: the layer or sublayer it was copied from and the layers around it (Paste + /// Remembers Layers); none when that layer has no name. + pub source_layers: Vec<Option<SourceLayer>>, /// The open document the objects came from ([`DocState::uid`]): pasting back into it uses its /// own resources as they are now. pub source_doc: Option<u64>, @@ -101,6 +102,29 @@ pub struct Clipboard { pub guides: Vec<vectorcraft_doc::Guide>, } +/// The layer an object was copied from, as Paste Remembers Layers finds it again: the top-level +/// layer first, down to the layer or sublayer that holds the object. +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] +pub struct SourceLayer { + /// The layers' ids in the source document ([`Clipboard::source_doc`]). + pub ids: Vec<NodeId>, + /// The layers' names (an unnamed layer above the one that holds the object is ""). + pub names: Vec<String>, +} + +impl SourceLayer { + /// The layers around the object `anc` ends with ([`Document::ancestry`]); none when the layer + /// that holds it has no name. + fn of(d: &Document, anc: &[NodeId]) -> Option<Self> { + let layers: Vec<&Node> = anc.iter().rev().skip(1).filter_map(|a| d.node(*a).filter(|l| l.is_layer())).collect(); + layers.first()?.name.as_ref()?; + Some(Self { + ids: layers.iter().rev().map(|l| l.id).collect(), + names: layers.iter().rev().map(|l| l.name.clone().unwrap_or_default()).collect(), + }) + } +} + /// Indices of segments selected on `sp` (either explicitly or via incident anchors). pub(crate) fn subpath_selected_segments( sp: &vectorcraft_geom::SubPath, @@ -119,17 +143,13 @@ pub(crate) fn subpath_selected_segments( let has_explicit_segs = seg_refs.is_some_and(|segments| !segments.is_empty()); if has_explicit_segs { if let Some(segments) = seg_refs { - for &(s, seg) in segments { - if s == si && seg < seg_count { - selected_segs.insert(seg); - } - } + selected_segs.extend(super::path::subpath_refs(segments, si).filter(|&seg| seg < seg_count)); } return selected_segs; } if let Some(anchors) = anchor_refs { - let sub_anchors: BTreeSet<usize> = anchors.iter().filter_map(|&(s, a)| (s == si && a < n).then_some(a)).collect(); + let sub_anchors: BTreeSet<usize> = super::path::subpath_refs(anchors, si).filter(|&a| a < n).collect(); if !sub_anchors.is_empty() { for i in 0..seg_count { let next = (i + 1) % n; @@ -256,7 +276,7 @@ impl Clipboard { let mut compound_bounds: std::collections::HashMap<NodeId, Option<vectorcraft_geom::Rect>> = std::collections::HashMap::new(); for id in roots { let (Some(n), Some(anc)) = (d.node(*id), d.ancestry(*id)) else { continue }; - let layer_name = anc.iter().rev().skip(1).find_map(|a| d.node(*a).filter(|l| l.is_layer())).and_then(|l| l.name.clone()); + let source_layer = SourceLayer::of(d, &anc); let compound_parent = anc.iter().rev().skip(1).find_map(|a| d.node(*a).filter(|p| matches!(p.kind, NodeKind::Compound { .. }))); // Gradients fitted to the compound's bounds are pinned there, as a split pins them. let gradient_box = compound_parent @@ -299,11 +319,11 @@ impl Clipboard { if direct && let Some(pieces) = extract_direct_selection(n, &st.selection) { for piece in pieces { nodes.push(inherit_appearance(piece)); - source_layers.push(layer_name.clone()); + source_layers.push(source_layer.clone()); } } else { nodes.push(inherit_appearance(n.clone())); - source_layers.push(layer_name); + source_layers.push(source_layer); } } // Symbol instances are measured by their art. diff --git a/crates/engine/src/cmd/clipboard/flavours.rs b/crates/engine/src/cmd/clipboard/flavours.rs index 9463dd8cf1..e98dbd5619 100644 --- a/crates/engine/src/cmd/clipboard/flavours.rs +++ b/crates/engine/src/cmd/clipboard/flavours.rs @@ -491,7 +491,7 @@ fn import_text(s: &mut Session, p: &Value) -> Result<Value> { if text.trim().is_empty() { return Err(bad(C, "the text is empty")); } - let style = super::super::create::new_type_style(s, &Value::Null); + let style = super::super::create::new_type_style(s, &Value::Null, C)?; let system_layout = s.doc()?.doc.setup.system_layout; let layout = |t: &mut TextObject| { t.system_layout = system_layout; diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index b1377d2fef..bdb238ce83 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -86,6 +86,10 @@ fn paint_refs(p: &Paint, f: Visit) { } fn appearance_refs(a: &Appearance, f: Visit) { + // The graphics mapped onto the faces of its 3D effects name symbols. + for s in vectorcraft_render::effects::appearance_graphic_symbols(a) { + f(Ref::Name(Res::Symbol, &s)); + } for it in &a.items { paint_refs(it.paint(), f); if let AppearanceItem::Stroke(l) = it @@ -119,6 +123,10 @@ fn node_refs(n: &Node, f: Visit) { if let Some(mask) = &m.extras().mask { node_refs(&mask.art, f); } + // A color-masked image's masked pixels go with it. + if let Some(cm) = Document::color_mask_of(m) { + f(Ref::Name(Res::Image, &cm.key)); + } match &m.kind { NodeKind::Text(t) => { for r in &t.runs { @@ -620,6 +628,17 @@ impl Relink { } } } + // A 3D effect's mapped graphics follow their symbols' names in the document. Each name is + // looked up once, so renames that chain (A to B, B to C) do not apply twice. + let items = a.items.iter_mut().flat_map(|i| i.effects_mut().iter_mut()); + for e in a.effects.iter_mut().chain(items).filter(|e| vectorcraft_render::effects::takes_graphics(&e.id)) { + let list = e.params.get_mut(vectorcraft_render::effects::GRAPHICS).and_then(Value::as_array_mut); + for g in list.into_iter().flatten() { + if let Some(Value::String(s)) = g.get_mut("symbol") { + self.name(Res::Symbol, s); + } + } + } for it in &mut a.items { self.paint(it.paint_mut()); if let AppearanceItem::Stroke(l) = it @@ -648,6 +667,10 @@ impl Relink { if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) { self.node(Arc::make_mut(&mut m.art)); } + if let Some(cm) = n.extras_if_any().and_then(|e| e.color_mask.as_deref_mut()) { + self.name(Res::Image, &mut cm.key); + self.name(Res::Image, &mut cm.from); + } match &mut n.kind { NodeKind::Text(t) => { for r in &mut t.runs { @@ -697,15 +720,6 @@ fn same_brush(r: &Relink, ours: &Brush, theirs: &Brush) -> bool { relinked(&Relink::default(), ours) == relinked(r, theirs) } -/// Does brush `b`'s art show symbols or patterns? -fn shows_definitions(b: &Brush) -> bool { - let mut found = false; - for a in b.art() { - node_refs(a, &mut |r| found |= matches!(r, Ref::Name(Res::Symbol | Res::Pattern, _))); - } - found -} - /// A symbol's Symbol Options, which its document keeps by symbol name: copied with the symbol and /// given to it under the name pasting adds it as. #[derive(Clone, Debug, PartialEq)] @@ -739,7 +753,7 @@ 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 +/// brush to place /// ([`Clipboard::import_used`]). #[derive(Clone, Copy)] enum Def<'c> { @@ -1055,49 +1069,40 @@ 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. An error, with `d` unchanged, when a pasted SVG filter finds no - /// free name ([`Self::filter_links`]). + /// pasted copies relink to them. Each style, symbol, pattern and brush is placed after those it + /// uses, as [`import_text_styles`] places them, so that a style that paints with a pattern added + /// under a free name ("Dots 2") is compared and added with that name. An error, with `d` + /// unchanged, when a pasted SVG filter finds no free name ([`Self::filter_links`]). pub(crate) fn import_into(&self, d: &mut Document, choices: &SwatchChoices, same_doc: bool) -> Result<Imported> { - self.import_used(d, &self.used(), choices, same_doc, false) + self.import_used(d, &self.used(), choices, same_doc) } - /// [`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) -> Result<Imported> { + /// [`Self::import_into`] for the resources `used` names. 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`]). Pasted back into its own document + /// (`same_doc`), each definition of a loop is the document's of its name. + fn import_used(&self, d: &mut Document, used: &Used, choices: &SwatchChoices, same_doc: bool) -> Result<Imported> { let mut out = Imported::default(); out.relink.filters = self.filter_links(d, same_doc)?; self.import_images(d, used, same_doc, &mut out); self.import_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. 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)); - } + 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![]); + 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)); + let groups: Vec<(Vec<Def<'_>>, bool)> = std::iter::once((order, false)).chain(loops).collect(); + // Styles (their colors relinked first), symbols, patterns and brushes (compared once + // relinked, symbols with their options too). The styles, symbols, patterns and brushes + // added are relinked at the end, when every new name and graphic style id is known: a loop + // of uses may place one before a definition it uses. + let (mut added_symbols, mut added_patterns, mut added_brushes, mut added_styles) = (HashSet::new(), HashSet::new(), HashSet::new(), vec![]); // Each definition, whether it is in a loop, and the loop it starts. let steps = groups .iter() @@ -1107,8 +1112,8 @@ impl Clipboard { 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. + // The document's brush library, read the first time a brush is placed 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; @@ -1116,8 +1121,9 @@ impl Clipboard { 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 { + // its definitions are compared. In its own document, each definition is the + // document's of its name, as outside a loop. + if let Some(group) = starts.filter(|_| !same_doc) { matched.clear(); match names_of_loop(d, group, &out.relink) { Some(names) => { @@ -1146,7 +1152,7 @@ impl Clipboard { 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) { + if let Some(name) = p.new_name(&def.name) { added_styles.push((r, name, def)); } out.placed(r, &def.name, &p); @@ -1200,9 +1206,6 @@ impl Clipboard { } } } - 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 }; @@ -1323,28 +1326,6 @@ impl Clipboard { } } - /// The brushes whose art shows symbols or patterns (`late`), or the others: each one the - /// document has (its art compared once relinked) is used, the others are added. → the names of - /// those added, whose art is relinked at the end. - fn import_brushes(&self, d: &mut Document, used: &Used, same_doc: bool, late: bool, out: &mut Imported) -> Vec<String> { - let brushes: Vec<&Brush> = self.brushes.iter().filter(|b| used.has(Res::Brush, &b.name) && shows_definitions(b) == late).collect(); - if brushes.is_empty() { - return vec![]; - } - let mut lib = vectorcraft_brush::library(d); - let mut added = vec![]; - for b in brushes { - let r = &out.relink; - let p = place(&mut lib, b, same_doc, |ours, theirs| same_brush(r, ours, theirs)); - added.extend(p.new_name(&b.name)); - out.placed(Res::Brush, &b.name, &p); - } - if !added.is_empty() { - vectorcraft_brush::store(d, &lib); - } - added - } - /// Global and spot colours (a name conflict merges or adds as `choices` say), then the tint /// swatches of the tints used and the gradient swatches. fn import_swatches(&self, d: &mut Document, used: &Used, choices: &SwatchChoices, same_doc: bool, out: &mut Imported) { @@ -1429,7 +1410,7 @@ pub(crate) fn import_text_styles(src: &Document, d: &mut Document, chars: bool, 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 out = clip.import_used(d, &used, &SwatchChoices::default(), false)?; 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 { diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index bbc56dbc15..b2b44a898d 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -3,7 +3,11 @@ //! shared colour visitor [`Recolor`]: fills and strokes (solid colours, gradient stops and text //! runs), gradient meshes, embedded images and pattern fills. Colours linked to a global swatch are //! unlinked when they change; Adjust Color Balance's Global mode shifts their tints instead. +//! +//! Convert to Indexed Color uses the same visitor for embedded images only, and stores each one as +//! a palette PNG. +use std::cell::Cell; use std::collections::{HashMap, HashSet}; use std::sync::Arc; @@ -15,7 +19,9 @@ use vectorcraft_doc::live::lerp_color; use vectorcraft_doc::pattern::PatternDef; pub(crate) use vectorcraft_doc::recolor::map_paint; use vectorcraft_doc::recolor::{ColorVisitor, Reach, map_links, recolor_node}; -use vectorcraft_doc::{Document, ImageBlob, Node, NodeId, NodeKind}; +use vectorcraft_doc::{Document, ImageBlob, MAX_RASTER_ALLOC, Node, NodeId, NodeKind}; +use vectorcraft_render::encode::png::{PngOptions, encode_indexed}; +use vectorcraft_render::encode::quantize::{Dither, Indexed, PaletteOptions, Reduction, quantize, quantize_to}; use super::edit::selected_roots; use super::{ @@ -66,6 +72,15 @@ pub fn specs() -> Vec<CommandSpec> { }) } ), + cmd!( + "edit.colors.toIndexed", + "Convert to Indexed Color…", + ["Edit", "Edit Colors"], + None, + "{reduction?: \"selective\" (default)|\"perceptual\"|\"adaptive\"|\"web\"|\"gray\"|\"blackWhite\" (chosen as for a PNG-8 export)|\"uniform\" (evenly spaced levels of red, green and blue: the most levels, 2 to 6, whose cube fits in `colors` with one entry left for transparency)|\"document\" (the colors of the document's swatches, at most 255), colors?: 2..256 (default 256; the most palette entries, the transparent one included; at least 9 for uniform; refused for blackWhite and document), dither?: \"diffusion\" (default)|\"pattern\"|\"noise\"|\"none\", ditherAmount?: 0..100 (default 100), ids?} store each embedded image in the selection (in groups too) as an indexed-color PNG: a palette of at most 256 RGB colors, each pixel the index of one; pixels under half opacity become one transparent entry and the others opaque, keeping their color; linked images, colorized images and the images of color glyphs in outlined type keep their pixels; each image changed becomes a new image, one undo step for all; an image that is an indexed PNG already and would show the same pixels is left as it is, and no undo step is recorded when no image changes; an image of more than 134,217,728 pixels (33,554,432 in the web app) is refused with an error and nothing changes; reduction and dither ids are read as for a PNG-8 export, ignoring case → {changed: images changed, notChanged: the locked and hidden objects Select All left out that hold an image that is not an indexed PNG yet, warning?} (as edit.colors.invert)", + has_selection, + to_indexed + ), cmd!( "edit.colors.saturate", "Saturate…", @@ -149,6 +164,13 @@ fn gray_level(c: Color) -> f32 { /// gradient stop): `(colour, link, tint)`, true when it changed them. pub(crate) type LinkMap<'a> = dyn Fn(&mut Color, &mut Option<String>, &mut f32) -> bool + 'a; +/// What a pass that remakes whole images makes of one: its new copy, `None` when it stays as it is. +type Remake<'a> = dyn Fn(&ImageBlob) -> Option<ImageBlob> + 'a; + +/// The objects a pass recolors, and the locked and hidden objects the selection left out, each +/// with whether it is hidden ([`pass_targets`]). +type Targets = (Vec<NodeId>, Vec<(NodeId, bool)>); + /// The identity colour map (a pass that only maps linked colours). fn same(c: Color) -> Color { c @@ -191,6 +213,8 @@ pub(crate) struct Recolor<'a> { scope: Scope, /// Recolored images are stored with one gray channel ([`ImageBlob::map_gray`]). gray_images: bool, + /// Makes each embedded image's new copy in place of `f` (`None`: it stays as it is). + remake: Option<&'a Remake<'a>>, /// Image key → the key of its recoloured copy (`None`: unchanged). images: HashMap<String, Option<String>>, /// Pattern name → the name of its recoloured copy (`None`: unchanged, or being recoloured). @@ -207,6 +231,7 @@ impl<'a> Recolor<'a> { links: None, scope, gray_images: false, + remake: None, images: HashMap::new(), patterns: HashMap::new(), new_images: vec![], @@ -229,7 +254,7 @@ impl<'a> Recolor<'a> { /// A pass that maps colors as this one does, with nothing recolored yet. fn again(&self) -> Self { - Self { links: self.links, gray_images: self.gray_images, ..Self::new(self.scope, self.f) } + Self { links: self.links, gray_images: self.gray_images, remake: self.remake, ..Self::new(self.scope, self.f) } } /// The entries of `objects` (ids, each with a flag) whose object this pass would change, other @@ -328,7 +353,9 @@ impl<'a> Recolor<'a> { } let f = self.f; let blob = d.images.get(key)?; - let new = if self.gray_images { + let new = if let Some(remake) = self.remake { + remake(blob) + } else if self.gray_images { blob.map_gray(|[r, g, b]| f(Color::rgb8(r, g, b)).to_rgba8(1.0)[0]) } else { blob.map_rgb(|[r, g, b]| { @@ -534,6 +561,187 @@ impl NotChanged { } } +/// The objects a pass recolors (the `ids` param's, default: the selection's) and the locked and +/// hidden objects the selection left out ([`left_out`]), each with whether it is hidden. +fn pass_targets(s: &Session, p: &Value, cmd: &str) -> Result<Targets> { + Ok(match ids_param(p, "ids", cmd)? { + Some(v) => (v, vec![]), + None => { + let roots = selected_roots(s)?; + let st = s.doc()?; + let left = left_out(&st.doc, st.isolation, &roots); + (roots, left) + } + }) +} + +/// Edit › Edit Colors › Convert to Indexed Color: the embedded images of the objects stored as +/// indexed-color PNGs ([`Indexing`]). The pass runs on a copy of the document, so no undo step is +/// recorded when no image changes. +fn to_indexed(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "edit.colors.toIndexed"; + let indexing = Indexing::of(s, p)?; + // A typing session ends here as `s.edit` would end it, before the copy is taken, so that the + // copy holds what was typed. + if !s.previewing && super::typing_in_progress(s) { + super::settle_interaction(s)?; + } + let remake = |b: &ImageBlob| indexing.convert(b); + let images = Scope { fill: false, stroke: false, images: true, patterns: false }; + let pass = Recolor { remake: Some(&remake), ..Recolor::new(images, &same) }; + // A left-out image counts as one the pass would change when it is an image that is not an + // indexed PNG yet; it is not converted to find out. The empty PNG only gives it a new key. + let would = |b: &ImageBlob| (!b.indexed_png() && b.pixel_size().is_some()).then(|| ImageBlob::png(vec![])); + let (ids, left) = pass_targets(s, p, C)?; + let st = s.doc()?; + let colorized_ok = super::paint::check_colorized(&st.doc).is_ok(); + let not_changed = NotChanged::of( + Recolor { remake: Some(&would), ..Recolor::new(images, &same) }.would_change(&st.doc, &left).into_iter().map(|(_, hidden)| hidden), + ); + let mut doc = (*st.doc).clone(); + let n = pass.run(&mut doc, &ids); + if let Some((w, h)) = indexing.too_large.get() { + return Err(bad(C, format!("an image of {w} × {h} pixels is too large to convert (at most {} pixels)", Indexing::MAX_PIXELS))); + } + if n > 0 { + s.edit("Convert to Indexed Color", |d, _| { + *d = doc; + super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(C, e)) + })?; + } + let mut out = json!({ "changed": n }); + not_changed.report(&mut out); + Ok(out) +} + +/// How Convert to Indexed Color reduces an image's colors: the palette options of a PNG-8 +/// export, with transparency kept and no matte, and the fixed palette of the uniform and document +/// reductions. +struct Indexing { + options: PaletteOptions, + fixed: Option<Vec<[u8; 3]>>, + /// The size of an image [`Self::convert`] left as it is because it has more than + /// [`Self::MAX_PIXELS`] pixels. + too_large: Cell<Option<(u32, u32)>>, +} + +impl Indexing { + /// The most pixels an image may have. Converting one holds at most about 8 bytes a pixel at + /// once: decoding (the decoded samples and the RGBA), quantizing (the RGBA, the colors and the + /// indices) and writing the PNG after the RGBA is freed (the indices, the packed and filtered + /// rows and the compressed data). 16 bytes a pixel keeps that within [`MAX_RASTER_ALLOC`] twice + /// over. + const MAX_PIXELS: u64 = MAX_RASTER_ALLOC / 16; + + /// The reduction `p` asks for (see `edit.colors.toIndexed`); a value out of range or of the + /// wrong type is an error. Reduction and dither ids are read as a PNG-8 export reads them. + fn of(s: &Session, p: &Value) -> Result<Self> { + const C: &str = "edit.colors.toIndexed"; + let reduction = text_param(p, "reduction", C)?.unwrap_or("selective"); + let colors = match p.get("colors") { + None | Some(Value::Null) => None, + Some(v) => { + Some(v.as_u64().filter(|n| (2..=256).contains(n)).ok_or_else(|| bad(C, "`colors` must be a whole number from 2 to 256"))? as u16) + } + }; + let dither = match text_param(p, "dither", C)? { + None => Dither::Diffusion, + Some(d) => Dither::from_id(d).ok_or_else(|| bad(C, format!("unknown dither `{d}` (diffusion, pattern, noise or none)")))?, + }; + let dither_amount = match p.get("ditherAmount") { + None | Some(Value::Null) => 100, + Some(v) => { + v.as_f64().filter(|x| (0.0..=100.0).contains(x)).ok_or_else(|| bad(C, "`ditherAmount` must be a number from 0 to 100"))?.round() as u8 + } + }; + let options = + |r: Reduction| PaletteOptions { colors: colors.unwrap_or(256), reduction: r, dither, dither_amount, transparency: true, matte: None }; + let refuse_colors = |name: &str| match colors { + Some(_) => Err(bad(C, format!("`colors` does not apply to the {name} reduction"))), + None => Ok(()), + }; + let fixed = |palette: Vec<[u8; 3]>| Self { options: options(Reduction::Adaptive), fixed: Some(palette), too_large: Cell::new(None) }; + Ok(match reduction.to_ascii_lowercase().as_str() { + "uniform" => { + let n = colors.unwrap_or(256); + // One entry is kept for transparent pixels. + let levels = + (2..=6u16).rev().find(|l| l.pow(3) < n).ok_or_else(|| bad(C, "`colors` must be at least 9 for the uniform reduction"))?; + let level = |i: u16| (u32::from(i) * 255 / u32::from(levels - 1)) as u8; + let mut palette = Vec::with_capacity(usize::from(levels.pow(3))); + for r in 0..levels { + for g in 0..levels { + for b in 0..levels { + palette.push([level(r), level(g), level(b)]); + } + } + } + fixed(palette) + } + "document" => { + refuse_colors("document")?; + let mut palette: Vec<[u8; 3]> = vec![]; + for c in s.doc()?.doc.swatches_iter().filter_map(|sw| sw.paint.color()) { + let [r, g, b, _] = c.to_rgba8(1.0); + if !palette.contains(&[r, g, b]) { + palette.push([r, g, b]); + } + } + if palette.is_empty() { + return Err(bad(C, "the document has no color swatches")); + } + if palette.len() > 255 { + return Err(bad(C, format!("the document's swatches hold {} colors; the document reduction takes at most 255", palette.len()))); + } + fixed(palette) + } + id => { + let r = Reduction::from_id(id).ok_or_else(|| { + bad(C, format!("unknown reduction `{reduction}` (selective, perceptual, adaptive, web, gray, blackWhite, uniform or document)")) + })?; + if r == Reduction::BlackWhite { + refuse_colors("blackWhite")?; + } + Self { options: options(r), fixed: None, too_large: Cell::new(None) } + } + }) + } + + /// Image `b` as an indexed-color PNG; `None` when it can't be decoded, when it has more than + /// [`Self::MAX_PIXELS`] pixels (noted in `too_large`), or when it is an indexed PNG already and + /// every pixel would show as it does. + fn convert(&self, b: &ImageBlob) -> Option<ImageBlob> { + let (w, h) = b.pixel_size()?; + if u64::from(w) * u64::from(h) > Self::MAX_PIXELS { + self.too_large.set(Some((w, h))); + return None; + } + let (w, h, rgba) = b.rgba()?; + let ix = match &self.fixed { + Some(palette) => quantize_to(&rgba, w, h, &self.options, palette), + None => quantize(&rgba, w, h, &self.options), + }; + if b.indexed_png() && shows_same(&ix, &rgba) { + return None; + } + // The PNG writer's buffers take the place of the pixels. + drop(rgba); + Some(ImageBlob::png(encode_indexed(&ix, &PngOptions::default()).ok()?)) + } +} + +/// Whether palette image `ix` shows every pixel of straight RGBA `rgba` as it is: transparent +/// where they are transparent, and the same color where they are opaque. +fn shows_same(ix: &Indexed, rgba: &[u8]) -> bool { + let px = rgba.as_chunks::<4>().0; + px.len() == ix.indices.len() + && px.iter().zip(&ix.indices).all(|(p, &i)| match (p[3], ix.transparent == Some(i)) { + (0, clear) => clear, + (255, false) => ix.palette.get(usize::from(i)).is_some_and(|c| c[..] == p[..3]), + _ => false, + }) +} + fn saturate(s: &mut Session, p: &Value) -> Result<Value> { let i = (f64_req(p, "intensity", "edit.colors.saturate")?.clamp(-100.0, 100.0) / 100.0) as f32; recolor(s, p, "edit.colors.saturate", "Saturate", &move |c| { diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index da7dc42ece..c94de5d3b2 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -5,7 +5,11 @@ //! Colour settings and the proof view are process-wide (`vectorcraft_color::cms::active`, //! `vectorcraft_render::proof::view`). A document's assigned profiles are stored in //! `Document::color_profiles` (files before format v3: `Document.unknown["colorProfiles"]`) and -//! become active when assigned. +//! take the place of the working spaces in the active settings while the document is in front +//! ([`use_front_profiles`]): when they are assigned, when the working settings change, and when the +//! document comes to the front or its assignment comes back (an open, a switch, a close, a revert, +//! an undo or a rollback, [`Session::sync_front_profiles`]); the working spaces stay as Edit → Color +//! Settings set them. use std::collections::BTreeMap; use std::sync::Arc; @@ -59,7 +63,7 @@ pub fn specs() -> Vec<CommandSpec> { "Assign Profile…", ["Edit"], None, - "{rgb?: profile|null, cmyk?: profile|null} tag the document with profiles (colour numbers are kept) → {rgb, cmyk}", + "{rgb?: profile|null, cmyk?: profile|null} tag the document with profiles (color numbers are kept; null: the working space). Colors then show and convert through the profiles assigned; the working spaces stay as edit.colorSettings set them → {rgb, cmyk}", has_doc, assign_profile ), @@ -86,7 +90,7 @@ pub fn specs() -> Vec<CommandSpec> { "Gamut Warning", [], None, - "{ids?|id?, colors?: [color] (#rrggbbaa and #rgba are refused)} colours that can't be printed in the working CMYK (selection, or the whole document when nothing is selected) → {checked, outOfGamut: [{hex, deltaE, count}]}", + "{ids?|id?, colors?: [color] (#rrggbbaa and #rgba are refused)} colors that can't be printed in the document's assigned CMYK profile, else the working CMYK (selection, or the whole document when nothing is selected) → {checked, outOfGamut: [{hex, deltaE, count}]}", has_doc, gamut_check ), @@ -176,9 +180,19 @@ fn touch_all(s: &mut Session) { } } +/// Make the active settings the working settings with the profiles the front document is assigned +/// in place of the working spaces (none, or no document open: the working spaces). The open +/// documents redraw when the active settings change. +pub(crate) fn use_front_profiles(s: &mut Session) { + let (rgb, cmyk) = s.active().map(|d| doc_profiles(&d.doc)).unwrap_or_default(); + if cms::use_document_profiles(rgb.as_deref(), cmyk.as_deref()) { + touch_all(s); + } +} + fn color_settings(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "edit.colorSettings"; - let mut st = cms::active_settings(); + let mut st = cms::working_settings(); let before = st.clone(); if let Some(v) = text_param(p, "rgb", C)? { st.rgb = cms::canonical_name(v).to_string(); @@ -194,6 +208,7 @@ fn color_settings(s: &mut Session, p: &Value) -> Result<Value> { cms::set_active(&st).map_err(|e| bad(C, e.to_string()))?; // Saved for the next start when the app attached a settings file (#6335). s.store_color_settings(&st); + use_front_profiles(s); touch_all(s); } Ok(settings_json(&st)) @@ -208,10 +223,18 @@ fn load_profile(s: &mut Session, p: &Value) -> Result<Value> { let info = cms::register_icc(&bytes, None).map_err(|e| bad(C, e.to_string()))?; // The bytes are kept, not the path: the file may move or go away. let remembered = s.store_profile(&info.name, &bytes); - // A new file of a working space: the active settings still hold the old one. - let working = cms::active_settings(); - if working.rgb == info.name || working.cmyk == info.name { + // A new file of a working space or of an assigned profile in use: the active settings still + // hold the old one. A profile the front document is assigned, loaded after it was removed, is + // in use again. + let (working, active) = (cms::working_settings(), cms::active_settings()); + let (rgb, cmyk) = s.active().map(|d| doc_profiles(&d.doc)).unwrap_or_default(); + let front = [rgb, cmyk].iter().any(|n| n.as_deref() == Some(info.name.as_str())); + if front || [&working.rgb, &working.cmyk, &active.rgb, &active.cmyk].contains(&&info.name) { cms::set_active(&working).map_err(|e| bad(C, e.to_string()))?; + use_front_profiles(s); + touch_all(s); + } else if proof_targets(&info.name) { + // A new file of the CMYK profile View → Proof Setup targets: redraw. touch_all(s); } Ok(json!({"name": info.name, "kind": info.kind, "remembered": remembered})) @@ -225,18 +248,32 @@ fn remove_profile(s: &mut Session, p: &Value) -> Result<Value> { if info.builtin { return Err(bad(C, format!("`{name}` is a built-in profile and stays"))); } - let working = cms::active_settings(); + let working = cms::working_settings(); if working.rgb == name || working.cmyk == name { return Err(bad(C, format!("`{name}` is a working space: choose another with edit.colorSettings first"))); } + let active = cms::active_settings(); if !cms::unregister_icc(&info.name) { return Err(bad(C, format!("no profile named `{name}`"))); } s.unstore_profile(&info.name); - touch_all(s); + // An assigned profile in use: the working space takes its place, as for any document assigned + // a profile that is not available. + if active.rgb == name || active.cmyk == name { + use_front_profiles(s); + } + // The CMYK profile View → Proof Setup targets: redraw. + if proof_targets(&info.name) { + touch_all(s); + } Ok(json!({"removed": info.name})) } +/// Whether View → Proof Setup targets the CMYK profile `name`. +fn proof_targets(name: &str) -> bool { + matches!(proof::view().setup.target, ProofTarget::Cmyk(t) if t == name) +} + #[cfg(target_arch = "wasm32")] fn load_profile(_: &mut Session, _: &Value) -> Result<Value> { Err(bad("color.loadProfile", "loading profiles from disk isn't available in the browser")) @@ -273,15 +310,9 @@ fn assign_profile(s: &mut Session, p: &Value) -> Result<Value> { d.color_profiles = profiles; Ok(()) })?; - let mut st = cms::active_settings(); - if let Some(r) = &rgb { - st.rgb = r.clone(); - } - if let Some(c) = &cmyk { - st.cmyk = c.clone(); - } - cms::set_active(&st).map_err(|e| bad(C, e.to_string()))?; - touch_all(s); + // The document draws through its profiles now, and a Document Color Mode later in the same + // batch converts through them. The working spaces stay as they are. + use_front_profiles(s); } Ok(json!({"rgb": rgb, "cmyk": cmyk})) } @@ -368,7 +399,9 @@ pub(crate) fn commit_new_art_colors(s: &mut Session) -> Result<()> { Ok(()) } -fn record_new_art_colors(s: &mut Session, before: vectorcraft_tools::PaintDefaults) -> Result<()> { +/// Record new-art paints `before` and the session's current ones with the step just made (or the +/// interaction or undo group in progress), so Undo puts `before` back and Redo the current ones. +pub(super) fn record_new_art_colors(s: &mut Session, before: vectorcraft_tools::PaintDefaults) -> Result<()> { let after = s.paint.clone(); if before != after || s.batch_stash.is_some() || s.doc()?.undo_group.is_some() { let st = s.doc_mut()?; @@ -393,7 +426,9 @@ fn record_new_art_colors(s: &mut Session, before: vectorcraft_tools::PaintDefaul Ok(()) } -fn new_art_colors_before(s: &Session) -> Result<vectorcraft_tools::PaintDefaults> { +/// The new-art paints an undo step that starts now puts back: those at the start of the undo group +/// or interaction in progress, else the session's current ones. +pub(super) fn new_art_colors_before(s: &Session) -> Result<vectorcraft_tools::PaintDefaults> { let st = s.doc()?; Ok(st.undo_group.as_ref().map(|g| &g.paint).or_else(|| st.interaction.as_ref().map(|it| &it.paint)).cloned().unwrap_or_else(|| s.paint.clone())) } @@ -760,17 +795,33 @@ fn proof_setup(s: &mut Session, p: &Value) -> Result<Value> { if let Some(on) = on_param(p, "proof", C)? { v.proof_colors = on; } - proof::set_view(v.clone()); - touch_all(s); + store_view(s, v.clone()); Ok(view_json(&v)) } +/// Make `v` the proof view and redraw every document. When `v` equals the current view, the view +/// and the revisions stay as they are; Separations Preview's visible plates are compared as a set. +fn store_view(s: &mut Session, v: proof::ProofView) { + let shown = |v: &proof::ProofView| proof::ProofView { + separations: v.separations.as_ref().map(|vis| { + let mut vis = vis.clone(); + vis.sort(); + vis.dedup(); + vis + }), + ..v.clone() + }; + if shown(&v) != shown(&proof::view()) { + proof::set_view(v); + touch_all(s); + } +} + 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, on); - proof::set_view(v.clone()); - touch_all(s); + store_view(s, v.clone()); Ok(view_json(&v)) } @@ -802,7 +853,15 @@ fn separations(s: &mut Session, p: &Value) -> Result<Value> { 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<_>>>()?); + let mut vis: Vec<String> = Vec::new(); + for n in a.iter().filter_map(Value::as_str) { + let n = check(n)?; + // A plate named twice is shown once. + if !vis.contains(&n) { + vis.push(n); + } + } + v.separations = Some(vis); } Some(_) => { let key = "plates"; @@ -821,8 +880,7 @@ fn separations(s: &mut Session, p: &Value) -> Result<Value> { vis.push(n); } } - proof::set_view(v); - touch_all(s); + store_view(s, v); Ok(plates_json(s)) } diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index f265c3ff3d..ebef729fd3 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -109,7 +109,7 @@ pub fn specs() -> Vec<CommandSpec> { "Create Text", [], None, - "{x, y, text, rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt, font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on", + "{x, y, text, rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on", has_doc, text_create ), @@ -162,7 +162,8 @@ fn constrained_turn(s: &Session, rotation: f64) -> f64 { } } -/// [`insert_look`] with the new object's bounding box turned to `bbox_angle`. +/// [`insert_look`] with the new object's bounding box turned to `bbox_angle`. A new path or +/// compound path is pixel-aligned while the document's Align New Objects to Pixel Grid is on. fn insert_look_turned( s: &mut Session, label: &str, @@ -180,6 +181,7 @@ fn insert_look_turned( let id = d.alloc_id(); let mut n = Node::new(id, kind); look.apply(d, &mut n); + super::object::align_new_object(d, &mut n); n.name = name; n.bbox_angle = bbox_angle; let mut into = None; @@ -512,6 +514,7 @@ fn flare(s: &mut Session, p: &Value) -> Result<Value> { n.name = Some(name.into()); n.blend = BlendMode::Screen; n.opacity = op; + super::object::align_new_object(d, &mut n); std::sync::Arc::new(n) }) .collect(); @@ -603,6 +606,7 @@ fn grid_group(s: &mut Session, label: &str, (paths, bbox_angle): (Vec<PathData>, Node::path(d.alloc_id(), pd, Appearance::default()) }; look.apply(d, &mut n); + super::object::align_new_object(d, &mut n); n.bbox_angle = bbox_angle; std::sync::Arc::new(n) }) @@ -735,7 +739,7 @@ fn text_create(s: &mut Session, p: &Value) -> Result<Value> { check_numbers(a, &["width", "height"], "text.create")?; } let text = str_param(p, "text").unwrap_or(""); - let mut t = TextObject::point(Point::new(x, y), text, new_type_style(s, p)); + let mut t = TextObject::point(Point::new(x, y), text, new_type_style(s, p, "text.create")?); // Turned about the point (the first baseline's start, an area's top-left corner): type set // along a Constrain Angle. let rotation = if p.get("rotation").is_some() { f64_req(p, "rotation", "text.create")? } else { 0.0 }; @@ -779,12 +783,14 @@ fn text_create(s: &mut Session, p: &Value) -> Result<Value> { /// The paragraph attributes new type gets (the Type tools, `text.create`): aligned to the start of /// each paragraph's direction (left, right for Hebrew and Arabic), Japanese punctuation composed -/// with Line-end Punctuation Half Width and Standard burasagari. Imported text keeps its own. +/// with Line-end Punctuation Half Width and Standard burasagari, and Korean words kept whole +/// (Korean Line Break Anywhere off). Imported text keeps its own. pub(crate) fn new_type_para() -> vectorcraft_doc::ParaStyle { vectorcraft_doc::ParaStyle { justify: vectorcraft_doc::Justify::Auto, mojikumi: vectorcraft_doc::Mojikumi::LineEndHalf, burasagari: vectorcraft_doc::Burasagari::Standard, + korean_line_break_anywhere: false, ..Default::default() } } @@ -842,11 +848,11 @@ pub(crate) fn new_area_fit(s: &Session, p: &Value, c: &str, t: &mut TextObject) /// The character style new type gets: `size`, `font`, `style` and `color` from `p` (an RGB /// `color` in a CMYK document as [`super::paint::new_color`] stores it), else the defaults, /// filled with the current fill unless that is None or white (black then), in the document's -/// language. -pub(crate) fn new_type_style(s: &Session, p: &Value) -> CharStyle { +/// language. A `size` outside [`super::typecmd::TYPE_SIZES`] is an error. +pub(crate) fn new_type_style(s: &Session, p: &Value, cmd: &str) -> Result<CharStyle> { let mut style = CharStyle::default(); if let Some(sz) = p.get("size").and_then(Value::as_f64) { - style.size = sz.clamp(0.1, 1296.0); + style.size = super::typecmd::given_type_size(sz, cmd)?; } if let Some(f) = str_param(p, "font") { style.font_family = f.to_string(); @@ -867,5 +873,5 @@ pub(crate) fn new_type_style(s: &Session, p: &Value) -> CharStyle { let chosen = |name: &str| vectorcraft_doc::setup::char_language(name).ok().flatten(); let document = s.doc().ok().and_then(|d| chosen(&d.doc.setup.language)); style.language = document.or_else(|| chosen(&s.prefs.hyphenation_language)).map(str::to_string); - style + Ok(style) } diff --git a/crates/engine/src/cmd/css.rs b/crates/engine/src/cmd/css.rs index ed83a01410..7cb2ff138d 100644 --- a/crates/engine/src/cmd/css.rs +++ b/crates/engine/src/cmd/css.rs @@ -7,8 +7,8 @@ use serde_json::{Value, json}; use vectorcraft_doc::NodeId; use vectorcraft_svg::{CssOptions, CssSheet, css_rules}; -use super::fileio::{default_name, encode_with_warnings, isolated, write_file}; -use super::{CommandSpec, Result, Session, bad, cmd, has_doc, str_param, targets}; +use super::fileio::{Note, default_name, encode_with_notes, isolated, note_texts, write_file}; +use super::{CommandSpec, Result, Session, bad, cmd, has_doc, named_ids, targets}; pub fn specs() -> Vec<CommandSpec> { vec![ @@ -21,13 +21,13 @@ pub fn specs() -> Vec<CommandSpec> { has_doc, selection ), - cmd!(query "css.generate", "Generate CSS", [], None, "{…options as css.selection} css.selection of every object in the document", has_doc, generate), + cmd!(query "css.generate", "Generate CSS", [], None, "{…options as css.selection} css.selection of every object in the document; ids and id are not used, and a malformed one is an error", has_doc, generate), cmd!( "css.export", "Export CSS", [], None, - "{path?, scope?: selection|all (default selection; ids? picks the objects), …options as css.selection, id?: object id (default: the selection)} write the CSS (css.selection, or css.generate for all) to path and, with rasterize, each picture its rules refer to next to it (PNG of what the object draws, with the clips, masks and effects of the groups and layers that hold it, 1 px per point) → {path, bytes, rules: n, images: [path…], warnings}; no path → {data: the CSS, name: <document>.css, rules, images: [{name, dataBase64}], warnings}; warnings are css.selection's and the pictures' as document.export gives them (an image that couldn't be decoded, type in the fallback font or that doesn't fit its frame), each once", + "{path?: string, scope?: selection|all (default selection when left out; ids? picks the objects), …options as css.selection, id?: object id (default: the selection)} a path or scope given as anything but a string, null included, is an error, and so is a malformed ids or id with scope all, which does not use them; write the CSS (css.selection, or css.generate for all) to path and, with rasterize, each picture its rules refer to next to it (PNG of what the object draws, with the clips, masks and effects of the groups and layers that hold it, 1 px per point) → {path, bytes, rules: n, images: [path…], warnings}; no path → {data: the CSS, name: <document>.css, rules, images: [{name, dataBase64}], warnings}; warnings are css.selection's and the pictures' as document.export gives them (an image that couldn't be decoded, type in the fallback font or that doesn't fit its frame), each once", has_doc, export ), @@ -77,16 +77,34 @@ fn selection(s: &mut Session, p: &Value) -> Result<Value> { Ok(result(&sheet(s, p, ids, "css.selection")?)) } +/// Checks the form of the `ids` or `id` that `p` gives a command that exports every object and does +/// not use them: a malformed one is an error, as it is for the selection. +fn unused_ids(p: &Value) -> Result<()> { + named_ids(p).map(|_| ()) +} + fn generate(s: &mut Session, p: &Value) -> Result<Value> { + unused_ids(p)?; let ids = everything(s)?; Ok(result(&sheet(s, p, ids, "css.generate")?)) } +/// The string `p` gives for `key`, or `None` when `p` leaves it out. Any value given that is not a +/// string, null included, is an error: "`{key}` must be a string". +fn given_text<'a>(p: &'a Value, key: &str, cmd: &str) -> Result<Option<&'a str>> { + p.get(key).map(|v| v.as_str().ok_or_else(|| bad(cmd, format!("`{key}` must be a string")))).transpose() +} + fn export(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "css.export"; - let ids = match str_param(p, "scope").unwrap_or("selection") { + let scope = given_text(p, "scope", C)?; + let path = given_text(p, "path", C)?; + let ids = match scope.unwrap_or("selection") { "selection" => targets(s, p)?, - "all" => everything(s)?, + "all" => { + unused_ids(p)?; + everything(s)? + } other => return Err(bad(C, format!("scope must be selection or all (got {other})"))), }; let sheet = sheet(s, p, ids, C)?; @@ -100,22 +118,24 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> { } let css = format!("{}\n", sheet.text()); let doc = &s.doc()?.doc; - // Encode the pictures of rasterized art, and add each of their warnings once. + // Encode the pictures of rasterized art, and add each of their warnings once. What CSS can't + // describe is a loss. let mut images = Vec::new(); - let mut warnings = sheet.warnings.clone(); + let mut notes: Vec<Note> = sheet.warnings.iter().cloned().map(Note::loss).collect(); for r in &sheet.rules { let Some(name) = &r.image else { continue }; let (d, _) = isolated(doc, &[r.id], name).ok_or_else(|| bad(C, format!("{} paints nothing to rasterize", r.selector)))?; - let (png, notes) = encode_with_warnings(&d, "png", &json!({}))?; + let (png, given) = encode_with_notes(&d, "png", &json!({}))?; images.push((name, png)); - for w in notes { - if !warnings.contains(&w) { - warnings.push(w); + for n in given { + if !notes.iter().any(|x| x.text == n.text) { + notes.push(n); } } } + let warnings = note_texts(¬es); let n = sheet.rules.len(); - match str_param(p, "path") { + match path { Some(path) => { write_file(path, css.as_bytes())?; let folder = std::path::Path::new(path).parent(); diff --git a/crates/engine/src/cmd/dimension.rs b/crates/engine/src/cmd/dimension.rs index e1b88d5d9f..44ac08d7ad 100644 --- a/crates/engine/src/cmd/dimension.rs +++ b/crates/engine/src/cmd/dimension.rs @@ -568,7 +568,7 @@ fn appearance(o: &DimensionOptions, mode: ColorMode, ext: bool, arrows: bool) -> ArrowStyle::Tick => Some(Arrowhead::Slash), ArrowStyle::None => None, }; - st.start_arrow = head; + st.start_arrow = head.clone(); st.end_arrow = head; st.arrow_scale = (o.arrow_scale, o.arrow_scale); st.arrow_align = vectorcraft_doc::appearance::ArrowAlign::Tip; diff --git a/crates/engine/src/cmd/distortcmds.rs b/crates/engine/src/cmd/distortcmds.rs index 17638477a9..2dbb7a9a18 100644 --- a/crates/engine/src/cmd/distortcmds.rs +++ b/crates/engine/src/cmd/distortcmds.rs @@ -15,8 +15,8 @@ use vectorcraft_tools::distort::{PinSet, arap, collect_points, mesh_for, project 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, + CommandSpec, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, f64_req, finite_numbers, has_doc, has_selection, matrix_param, + named_id, named_ids, number_or, object_param, ok, point_indices, point_param, str_param, switch_or, targets, }; use crate::EngineError; @@ -305,7 +305,7 @@ fn same_points(a: Option<&WidthProfile>, b: Option<&WidthProfile>) -> bool { fn width_point_set(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "stroke.widthPoint.set"; - let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; let t = f64_req(p, "t", C)?.clamp(0.0, 1.0); let (left, right) = (f64_req(p, "left", C)?, f64_req(p, "right", C)?); if !(left.is_finite() && right.is_finite()) || left < 0.0 || right < 0.0 || left.max(right) > 1.0e5 { @@ -362,7 +362,7 @@ fn width_point_set(s: &mut Session, p: &Value) -> Result<Value> { fn width_point_copy(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "stroke.widthPoint.copy"; - let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; let t = f64_req(p, "t", C)?.clamp(0.0, 1.0); // When the profile comes out as it was (the copy replaces a side of a discontinuous point that has // its widths already), the document and its undo history stay as they are. @@ -382,7 +382,7 @@ fn width_point_copy(s: &mut Session, p: &Value) -> Result<Value> { fn width_point_remove(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "stroke.widthPoint.remove"; - let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; let indices = match (p.get("indices"), p.get("index")) { (Some(a), _) => point_indices(a), (None, Some(i)) => point_indices(&json!([i])), diff --git a/crates/engine/src/cmd/docinfo.rs b/crates/engine/src/cmd/docinfo.rs index 7499e14943..a9fb07bdf8 100644 --- a/crates/engine/src/cmd/docinfo.rs +++ b/crates/engine/src/cmd/docinfo.rs @@ -1,7 +1,7 @@ //! Document Info panel data, its categories and the text report (Document Info › Save…, File → //! Package), and Object → Make Pixel Perfect. -use std::collections::{BTreeMap, BTreeSet, HashSet}; +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use serde_json::{Value, json}; use vectorcraft_color::Paint; @@ -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), 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), gradientObjects: [{id, name, gradients}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else Linear gradient, Radial gradient or Freeform gradient; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}", + "{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 (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient with a stop above opacity 0, at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else Linear gradient, Radial gradient or Freeform gradient; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone. brushNames, brushes, spotObjects, patternObjects and gradientObjects leave out hidden objects, objects at an opacity of 0 and the objects inside a hidden group or layer or one at an opacity of 0 (with selectionOnly too), their characters' paints and colorized images included; objects still counts them as paths, groups and the other kinds", has_doc, info ), @@ -40,7 +40,7 @@ pub const CATEGORIES: [(&str, &str); 13] = [ ("objects", "Objects"), ("graphicStyles", "Graphic Styles"), ("brushes", "Brushes"), - ("spotColors", "Spot Colors"), + ("spotColors", "Spot Color Objects"), ("patterns", "Pattern Objects"), ("gradients", "Gradient Objects"), ("symbols", "Symbols"), @@ -52,7 +52,7 @@ pub const CATEGORIES: [(&str, &str); 13] = [ ]; /// The object counts of `document.info` and their labels. -const OBJECT_LABELS: [(&str, &str); 18] = [ +pub const OBJECT_LABELS: [(&str, &str); 19] = [ ("paths", "Paths"), ("compoundPaths", "Compound Paths"), ("groups", "Groups"), @@ -63,6 +63,7 @@ const OBJECT_LABELS: [(&str, &str); 18] = [ ("symbolInstances", "Symbol Instances"), ("gradients", "Gradient Objects"), ("patterns", "Pattern Objects"), + ("spots", "Spot Color Objects"), ("meshes", "Gradient Meshes"), ("blends", "Blends"), ("envelopes", "Envelopes"), @@ -130,15 +131,18 @@ 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, the rows of its Repeat objects and the -/// rows of its objects filled or stroked with a pattern and with a gradient. +/// `document.info` reports), its fonts, its image objects, the rows of the brushes its art uses, the +/// rows of its Repeat objects and the rows of its objects filled or stroked with a spot color, with a +/// pattern and with a gradient. #[allow(clippy::too_many_arguments)] fn sections( d: &Document, info: &Value, fonts: &BTreeSet<super::fonts::UsedFont>, images: &[ImageRow], + brushes: &[(String, String)], repeats: &[(String, String)], + spot_objects: &[(String, String)], pattern_objects: &[(String, String)], gradient_objects: &[(String, String)], category: Option<&str>, @@ -182,8 +186,8 @@ fn sections( rows } "graphicStyles" => names("graphicStyleNames"), - "brushes" => names("brushNames"), - "spotColors" => names("spotColors"), + "brushes" => brushes.to_vec(), + "spotColors" => spot_objects.to_vec(), "patterns" => pattern_objects.to_vec(), "gradients" => gradient_objects.to_vec(), "symbols" => names("symbols"), @@ -273,15 +277,50 @@ fn gradient_label(p: &Paint) -> Option<String> { } } -/// The type object `n` holds and the runs its layout draws, when it uses a pattern or a gradient: -/// 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>)> { +/// The names of `d`'s spot color swatches: the swatches whose prints go to a plate of their own +/// ([`vectorcraft_doc::inks::inks`]). A name held by several swatches is the first one's, as +/// [`Document::swatch`] finds it, and the Registration swatch prints on every plate, so it is not +/// one. +fn spot_swatches(d: &Document) -> HashSet<&str> { + let mut first: BTreeMap<&str, bool> = BTreeMap::new(); + for s in d.swatches_iter() { + first.entry(s.name.as_str()).or_insert(s.spot && s.paint.color().is_some()); + } + first.into_iter().filter(|&(name, spot)| spot && name != vectorcraft_color::swatch::REGISTRATION).map(|(name, _)| name).collect() +} + +/// The spot colors paint `p` prints (`spots`: [`spot_swatches`]): the spot swatch a solid color is +/// linked to, or those a gradient's stops are linked to, each once, in the order of the stops. A +/// link at a tint of 0 prints no ink, a gradient whose stops are all at an opacity of 0 draws +/// nothing, and a color that only looks like a spot color is not linked to one. +fn spot_labels(spots: &HashSet<&str>, p: &Paint) -> Vec<String> { + let mut out: Vec<String> = vec![]; + let mut add = |swatch: &Option<String>, tint: f32| { + if let Some(name) = swatch + && tint > 0.0 + && spots.contains(name.as_str()) + && !out.contains(name) + { + out.push(name.clone()); + } + }; + match p { + Paint::Solid { swatch, tint, .. } => add(swatch, *tint), + Paint::Gradient(g) if g.gradient.stops.iter().any(|s| s.opacity > 0.0) => g.gradient.stops.iter().for_each(|s| add(&s.swatch, s.tint)), + _ => {} + } + out +} + +/// The type object `n` holds and the runs its layout draws, when it uses a spot color, a pattern or +/// a gradient (`spots`: [`spot_swatches`]): 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, spots: &HashSet<&str>, n: &'a Node) -> Option<(&'a vectorcraft_doc::TextObject, BTreeSet<usize>)> { let NodeKind::Text(t) = &n.kind else { return None }; - let is_listed = |p: &Paint| matches!(p, Paint::Pattern { .. } | Paint::Gradient(_)); + let is_listed = |p: &Paint| matches!(p, Paint::Pattern { .. } | Paint::Gradient(_)) || !spot_labels(spots, p).is_empty(); let own = n.appearance.items.iter().any(|i| match i { vectorcraft_doc::AppearanceItem::Fill(f) => is_listed(&f.paint), vectorcraft_doc::AppearanceItem::Stroke(s) => is_listed(&s.paint), @@ -289,51 +328,161 @@ fn painted_runs<'a>(d: &Document, n: &'a Node) -> Option<(&'a vectorcraft_doc::T if !own && !t.runs.iter().any(|r| is_listed(&r.style.fill) || is_listed(&r.style.stroke)) { return None; } + Some((t, drawn_runs(d, t))) +} + +/// The runs of type `t` that its layout draws: those with a glyph outline (list markers and ruby +/// included) or an underline or strikethrough bar, laid out as the renderer lays it out. +fn drawn_runs(d: &Document, t: &vectorcraft_doc::TextObject) -> BTreeSet<usize> { 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)) + painted } -/// The patterns or gradients (`label`: [`pattern_label`] or [`gradient_label`]) that `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. +/// The names a paint is listed by in a Document Info category: its spot colors, its pattern or its +/// gradient. +type PaintNames<'a> = dyn Fn(&Paint) -> Vec<String> + 'a; + +/// The spot colors, patterns or gradients (`label`: [`spot_labels`], [`pattern_label`] or +/// [`gradient_label`], each paint's names) that `n`'s own fills and strokes paint, each once. A +/// hidden fill or stroke, a fill or stroke at an opacity of 0 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_paints( d: &Document, n: &Node, members: &HashSet<*const Node>, painted_runs: Option<&(&vectorcraft_doc::TextObject, BTreeSet<usize>)>, - label: fn(&Paint) -> Option<String>, + label: &PaintNames<'_>, ) -> Vec<String> { if matches!(n.kind, NodeKind::Path { guide: true, .. }) || members.contains(&std::ptr::from_ref(n)) || painted_runs.is_some_and(|(_, r)| r.is_empty()) - || !n.appearance.items.iter().any(|i| label(i.paint()).is_some()) + || n.appearance.items.iter().all(|i| label(i.paint()).is_empty()) { return vec![]; } - // The patterns or gradients an image's shaped fills and strokes paint (their effects can - // transform the paint, so they are matched by label). + // The names an image's shaped fills and strokes paint (their effects can transform the paint, + // so they are matched by name). let shaped: Option<Vec<String>> = matches!(n.kind, NodeKind::Image(_)) - .then(|| vectorcraft_render::effects::image_paint(Some(d), n).into_iter().filter_map(|(_, _, item)| label(item.paint())).collect()); + .then(|| vectorcraft_render::effects::image_paint(Some(d), n).into_iter().flat_map(|(_, _, item)| label(item.paint())).collect()); let mut out: Vec<String> = vec![]; for item in &n.appearance.items { - let Some(name) = label(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(&name)); - if paints && !out.contains(&name) { - out.push(name); + if !item.visible() || item.opacity() <= 0.0 || matches!(item, vectorcraft_doc::AppearanceItem::Stroke(s) if s.width <= 0.0) { + continue; + } + for name in label(item.paint()) { + if shaped.as_ref().is_none_or(|s| s.contains(&name)) && !out.contains(&name) { + out.push(name); + } } } out } +/// [`pattern_label`] or [`gradient_label`] as the names [`own_paints`] takes. +fn one_label(label: fn(&Paint) -> Option<String>) -> impl Fn(&Paint) -> Vec<String> { + move |p| label(p).into_iter().collect() +} + +/// The brushes `n`'s own strokes draw with, in the order of its appearance. A hidden stroke, a +/// stroke at an opacity of 0, a stroke with no paint and a stroke with no width draw nothing, and neither does any stroke of a +/// guide (drawn in the guide color) or of a compound path's member (`members`: the compound path's +/// own strokes draw it). An image's strokes draw only where an effect gives them a shape, and only +/// paths, compound paths, type and images draw strokes of their own. +fn applied_brushes(d: &Document, n: &Node, members: &HashSet<*const Node>) -> Vec<String> { + if matches!(n.kind, NodeKind::Path { guide: true, .. }) || members.contains(&std::ptr::from_ref(n)) { + return vec![]; + } + let brush = |item: &vectorcraft_doc::AppearanceItem| match item { + vectorcraft_doc::AppearanceItem::Stroke(st) if item.visible() && st.opacity > 0.0 && !st.paint.is_none() && st.width > 0.0 => { + st.brush.clone().filter(|b| !b.is_empty()) + } + _ => None, + }; + if matches!(n.kind, NodeKind::Image(_)) { + return vectorcraft_render::effects::image_paint(Some(d), n).iter().filter_map(|(_, _, item)| brush(item)).collect(); + } + let used: Vec<String> = n.appearance.items.iter().filter_map(brush).collect(); + if used.is_empty() { + return used; + } + // A path or compound path with no segment gives its strokes nothing to follow, and neither does + // type whose layout draws nothing (spaces and line breaks without an underline or strikethrough). + let segments = |pd: &vectorcraft_geom::PathData| pd.subpaths.iter().any(|sp| sp.segment_count() > 0); + let follows = match &n.kind { + NodeKind::Path { .. } => n.path_data().is_some_and(segments), + NodeKind::Compound { children, .. } => children.iter().filter_map(|c| c.path_data()).any(segments), + NodeKind::Text(t) => !drawn_runs(d, t).is_empty(), + // A brush on any other kind of object (a layer, a group, a ruler guide) is not listed. + _ => false, + }; + if follows { used } else { vec![] } +} + +/// Whether `n` draws, as far as its own state goes: a hidden object, and an object at an opacity +/// of 0, paint no color, and neither do their members. +fn draws(n: &Node) -> bool { + n.visible && n.opacity > 0.0 +} + +/// The object of `d` at index path `path`, with whether the groups and layers around it draw +/// ([`draws`]). +fn node_and_drawn<'a>(d: &'a Document, path: &[usize]) -> Option<(&'a Node, bool)> { + let (first, rest) = path.split_first()?; + let mut at: &Node = d.layers.get(*first)?; + let mut drawn = true; + for &i in rest { + drawn &= draws(at); + at = &**at.children()?.get(i)?; + } + Some((at, drawn)) +} + +/// The spot colors, the patterns and the gradients (`spots`: [`spot_swatches`]) that object `n` +/// paints, each once: those of its own fills and strokes ([`own_paints`], `members` included), of +/// its drawn characters and, for a grayscale or 1-bit image, of the color it is colorized with. +fn object_paints(d: &Document, spots: &HashSet<&str>, members: &HashSet<*const Node>, n: &Node) -> [Vec<String>; 3] { + let (spot, pattern, gradient) = (|p: &Paint| spot_labels(spots, p), one_label(pattern_label), one_label(gradient_label)); + let labels: [&PaintNames<'_>; 3] = [&spot, &pattern, &gradient]; + let painted_runs = painted_runs(d, spots, n); + let mut used = labels.map(|label| own_paints(d, n, members, painted_runs.as_ref(), label)); + // 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) { + for (used, label) in used.iter_mut().zip(labels) { + for name in label(paint) { + if !used.contains(&name) { + used.push(name); + } + } + } + } + } + } + // A grayscale or 1-bit image colorized with a spot color prints it, while its pixels take the + // color, as the renderer draws it. + if let NodeKind::Image(im) = &n.kind + && let Some(colorize) = n.extras().colorize.as_deref() + && d.image_blob(im).is_some_and(|b| b.takes_colorize()) + { + for name in spot(colorize) { + if !used[0].contains(&name) { + used[0].insert(0, name); + } + } + } + used +} + fn info(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "document.info"; let category = str_param(p, "category"); @@ -349,8 +498,13 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> { let st = s.doc()?; let d = &st.doc; let selection_only = bool_or(p, "selectionOnly", false); - let roots: Vec<&Node> = - if selection_only { st.selection.objects.iter().filter_map(|id| d.node(*id)).collect() } else { d.layers.iter().map(|l| &**l).collect() }; + // Each root with whether the groups and layers around it draw: a selected object inside a hidden group or layer, or one + // at an opacity of 0, paints nothing. + let roots: Vec<(&Node, bool)> = if selection_only { + st.selection.objects.iter().filter_map(|id| node_and_drawn(d, &d.index_path(*id)?)).collect() + } else { + d.layers.iter().map(|l| (&**l, true)).collect() + }; let mut counts: BTreeMap<&str, usize> = BTreeMap::new(); // The paths' total length, as Document Info › Objects shows it (the length of a cut line, a // strip of LEDs along the letters, #1958). @@ -358,12 +512,29 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> { let mut fonts = BTreeSet::new(); let mut images: BTreeMap<String, Value> = BTreeMap::new(); let mut image_rows: Vec<ImageRow> = vec![]; + // Whether the request being served may read each linked file (a relative path read from the + // document's folder), checked once per file. + let mut readable: HashMap<String, bool> = HashMap::new(); + let link_doc = super::links::LinkBase::of(st).doc; + let mut may_read = |stored: &str| { + *readable.entry(stored.to_string()).or_insert_with(|| { + let resolved = super::fileio::document_path(stored, link_doc).ok(); + crate::file_access::check_read(resolved.as_deref().unwrap_or(stored)).is_ok() + }) + }; let mut patterns = BTreeSet::new(); let mut symbols = BTreeSet::new(); + // `spot_objects`, `spot_rows` and `spot` hold the `spotObjects` entries, the rows of the objects filled or stroked with a spot + // color, in walk order, and the spot colors they use. `spot_swatches` names the document's spot colors once, for every paint. + let spot_swatches = spot_swatches(d); + let mut spot_objects: Vec<Value> = vec![]; + let mut spot_rows: Vec<(String, String)> = vec![]; let mut spot = BTreeSet::new(); let mut styles: Vec<&str> = if selection_only { vec![] } else { d.graphic_styles.iter().map(|g| g.name.as_str()).collect() }; - // `brushes` holds the Brushes panel's brushes, or with selectionOnly it holds the brushes that the selected objects' strokes use. - let mut brushes: Vec<String> = if selection_only { vec![] } else { vectorcraft_brush::library(d).into_iter().map(|b| b.name).collect() }; + // `library` holds the Brushes panel's brushes, and `brushes` the brushes the visited objects' strokes draw with, each once, + // in walk order. + let library = vectorcraft_brush::library(d); + let mut brushes: Vec<String> = vec![]; // `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![]; @@ -385,10 +556,18 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> { members.extend(children.iter().map(|c| std::ptr::from_ref(&**c))); } }); - for r in roots { - r.walk(&mut |n| { + // Depth first, in paint order, as `Node::walk` visits: each object with whether it and the groups and layers around it + // draw. An object that does not draw is still counted, and its members are visited. + let mut stack: Vec<(&Node, bool)> = vec![]; + for (r, drawn) in roots { + stack.push((r, drawn)); + while let Some((n, around)) = stack.pop() { if !seen.insert(std::ptr::from_ref(n)) { - return; + continue; + } + let drawn = around && draws(n); + if let Some(ch) = n.children() { + stack.extend(ch.iter().rev().map(|c| (&**c, drawn))); } let k = match &n.kind { // The Guides row counts paths made into guides; ruler guides are not objects. @@ -411,12 +590,15 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> { Some("textObjects") } NodeKind::Image(im) => { + // A linked file outside a confined request's read roots: `link` is null, and the row + // names the file alone. + let link = im.link.as_ref().map(|l| (l, may_read(&l.path))); images.insert( im.key.clone(), - json!({ "width": im.width, "height": im.height, "linked": im.link.is_some(), "link": im.link.as_ref().map(|l| &l.path) }), + json!({ "width": im.width, "height": im.height, "linked": im.link.is_some(), "link": link.and_then(|(l, ok)| ok.then_some(&l.path)) }), ); let name = im.link.as_ref().map_or_else(|| n.display_name(), |l| l.name().to_string()); - image_rows.push((name, im.width, im.height, im.link.as_ref().map(|l| l.path.clone()))); + image_rows.push((name, im.width, im.height, link.map(|(l, ok)| if ok { l.path.clone() } else { l.name().to_string() }))); Some("images") } NodeKind::SymbolInstance { symbol, .. } => { @@ -433,37 +615,16 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> { if let Some(k) = k { *counts.entry(k).or_default() += 1; } - for item in &n.appearance.items { - if let Paint::Solid { swatch: Some(name), .. } = item.paint() - && d.swatch(name).is_some_and(|s| s.spot) - { - spot.insert(name.clone()); - } + // The spot colors, the patterns and the gradients this object paints, each once; none when it does not draw. + let [used_spots, used_patterns, used_gradients] = if drawn { object_paints(d, &spot_swatches, &members, n) } else { Default::default() }; + // Objects counts the objects that Spot Color Objects, Pattern Objects and Gradient Objects list. + if !used_spots.is_empty() { + let name = n.display_name(); + spot.extend(used_spots.iter().cloned()); + spot_rows.push((name.clone(), used_spots.join(", "))); + spot_objects.push(json!({ "id": n.id.0, "name": name, "spotColors": used_spots })); + *counts.entry("spots").or_default() += 1; } - // The patterns and the gradients this object's fills and strokes paint, each once. - let painted_runs = painted_runs(d, n); - let mut used_patterns = own_paints(d, n, &members, painted_runs.as_ref(), pattern_label); - let mut used_gradients = own_paints(d, n, &members, painted_runs.as_ref(), gradient_label); - // 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) { - for (used, label) in - [(&mut used_patterns, pattern_label as fn(&Paint) -> Option<String>), (&mut used_gradients, gradient_label)] - { - if let Some(name) = label(paint) - && !used.contains(&name) - { - used.push(name); - } - } - } - } - } - // Objects counts the objects that Pattern Objects and Gradient Objects list. if !used_patterns.is_empty() { let name = n.display_name(); patterns.extend(used_patterns.iter().cloned()); @@ -490,13 +651,10 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> { { styles.push(&g.name); } - if selection_only { - for item in &n.appearance.items { - if let vectorcraft_doc::AppearanceItem::Stroke(st) = item - && let Some(b) = &st.brush - && !brushes.contains(b) - { - brushes.push(b.clone()); + if drawn { + for b in applied_brushes(d, n, &members) { + if !brushes.contains(&b) { + brushes.push(b); } } } @@ -505,9 +663,26 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> { repeats.push(entry); repeat_rows.push(row); } - }); + } + } + // The document's fonts include those of the type in opacity masks and in the art of its + // symbols and patterns, as Find Font lists them. + if !selection_only { + fonts.extend(super::fonts::art_texts_of(d).into_iter().flat_map(|(_, t, _)| t.runs.iter().map(|r| super::fonts::font_of(&r.style)))); } let font_names: Vec<String> = fonts.iter().map(super::fonts::font_label).collect(); + // Each brush the art uses with its type, found by name in the Brushes panel as the renderer finds it (the last of two + // brushes with one name); a brush the panel does not hold draws as a plain stroke and has no type. A row names the type + // as the New Brush dialog does (`Art Brush`), and the panel translates these values when it shows them. + let kinds: HashMap<&str, &vectorcraft_brush::BrushKind> = library.iter().map(|b| (b.name.as_str(), &b.kind)).collect(); + let brush_entries: Vec<Value> = + brushes.iter().map(|name| json!({ "name": name, "type": kinds.get(name.as_str()).map(|k| k.type_id()) })).collect(); + let brush_rows: Vec<(String, String)> = brushes + .iter() + .map(|name| { + (name.clone(), kinds.get(name.as_str()).map_or_else(|| "missing from the Brushes panel".to_string(), |k| format!("{} Brush", k.label()))) + }) + .collect(); let mut out = json!({ "document": document_summary(d), "objects": counts, @@ -516,10 +691,14 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> { "images": images, "symbols": symbols, "spotColors": spot, + "spotColorNames": spot, + "spotObjects": spot_objects, "swatches": d.swatches_iter().count(), "graphicStyles": d.graphic_styles.len(), "graphicStyleNames": styles, "brushNames": brushes, + "brushes": brush_entries, + "panelBrushNames": library.iter().map(|b| b.name.as_str()).collect::<Vec<_>>(), "repeatObjects": repeats, "characterStyles": d.char_styles.len(), "paragraphStyles": d.para_styles.len(), @@ -531,7 +710,7 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> { }); // 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, &pattern_rows, &gradient_rows, category); + let sections = sections(d, &out, &fonts, &image_rows, &brush_rows, &repeat_rows, &spot_rows, &pattern_rows, &gradient_rows, category); if text { return Ok(json!({ "text": report_text(&st.title(), selection_only, §ions) })); } @@ -620,6 +799,40 @@ mod tests { assert!(i["objects"]["textObjects"].is_null() && i["objects"]["paths"] == 1); } + /// Document Info's fonts include the type in an opacity mask, in a symbol's art and in a + /// pattern swatch that nothing paints with; with `selectionOnly`, only the selected type's. + #[test] + fn info_fonts_include_masks_symbols_and_patterns() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + let id = |v: Value| NodeId(v["id"].as_u64().unwrap()); + let text = |s: &mut Session, font: &str| id(s.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi", "font": font})).unwrap()); + let rect = |s: &mut Session| id(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()); + let (masked, in_symbol) = (rect(&mut s), rect(&mut s)); + for (owner, font) in [(masked, "Mask Family"), (in_symbol, "Symbol Mask Family")] { + let t = text(&mut s, font); + s.edit("Mask", |d, _| { + let art = d.remove(t)?; + d.node_mut(owner).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*art).clone(), true))); + Ok(()) + }) + .unwrap(); + } + s.execute("symbol.new", &json!({"name": "Mark", "ids": [in_symbol.0]})).unwrap(); + let t = text(&mut s, "Pattern Family"); + s.execute("object.pattern.make", &json!({"ids": [t.0], "name": "Unused", "edit": false})).unwrap(); + s.execute("select.set", &json!({"ids": [t.0]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + let plain = text(&mut s, "Source Sans 3"); + let fonts = |s: &mut Session, p: Value| s.execute("document.info", &p).unwrap()["fonts"].clone(); + assert_eq!( + fonts(&mut s, json!({})), + json!(["Mask Family Regular", "Pattern Family Regular", "Source Sans 3 Regular", "Symbol Mask Family Regular"]) + ); + s.execute("select.set", &json!({"ids": [plain.0]})).unwrap(); + assert_eq!(fonts(&mut s, json!({"selectionOnly": true})), json!(["Source Sans 3 Regular"])); + } + /// Document Info › Objects gives the paths' total length in the document's units (#1958): an /// open line, a closed rectangle's perimeter and a compound path's pieces count, a guide doesn't. #[test] @@ -644,38 +857,129 @@ mod tests { assert_eq!(length(&mut s, json!({"selectionOnly": true})), 0.0); } - /// Document Info › Brushes lists the Brushes panel's brushes, and with Selection Only it lists - /// the brushes the selected objects' strokes use, each once. + /// Document Info › Brushes lists the brushes the art's strokes use, each once with its type, and + /// leaves out the Brushes panel's brushes no art uses (`panelBrushNames` lists those). With + /// Selection Only it lists the brushes the selected objects' strokes use. #[test] fn info_lists_the_brushes() { let mut s = Session::new(); s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); let panel: Vec<Value> = s.execute("brush.list", &json!({})).unwrap()["brushes"].as_array().unwrap().iter().map(|b| b["name"].clone()).collect(); - let i = s.execute("document.info", &json!({"category": "brushes"})).unwrap(); - assert_eq!(i["brushNames"], json!(panel)); + let brushes = |s: &mut Session, p: Value| s.execute("document.info", &p).unwrap(); + // No art uses a brush: the category is empty. + let i = brushes(&mut s, json!({"category": "brushes"})); + assert_eq!((i["brushNames"].clone(), i["brushes"].clone(), i["panelBrushNames"].clone()), (json!([]), json!([]), json!(panel))); assert_eq!((i["sections"][0]["id"].as_str(), i["sections"][0]["title"].as_str()), (Some("brushes"), Some("Brushes"))); - let rows: Vec<Value> = panel.iter().map(|n| json!([n, ""])).collect(); - assert_eq!(i["sections"][0]["rows"], json!(rows)); + assert_eq!(i["sections"][0]["rows"], json!([])); let a = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone(); let b = s.execute("shape.rectangle", &json!({"x": 20, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone(); let c = s.execute("shape.rectangle", &json!({"x": 40, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone(); s.execute("brush.apply", &json!({"ids": [a], "name": "Charcoal"})).unwrap(); - s.execute("brush.apply", &json!({"ids": [b], "name": "Arrow"})).unwrap(); + s.execute("brush.apply", &json!({"ids": [b], "name": "Dots"})).unwrap(); s.execute("brush.apply", &json!({"ids": [c], "name": "Charcoal"})).unwrap(); - let names = - |s: &mut Session| s.execute("document.info", &json!({"selectionOnly": true, "category": "brushes"})).unwrap()["brushNames"].clone(); + // The whole document: the two brushes the art uses, each once, with their types; "3 pt. Round" (a Calligraphic + // brush in the panel) is left out. + let i = brushes(&mut s, json!({"category": "brushes"})); + assert_eq!(i["brushNames"], json!(["Charcoal", "Dots"])); + assert_eq!(i["brushes"], json!([{"name": "Charcoal", "type": "art"}, {"name": "Dots", "type": "scatter"}])); + assert_eq!(i["sections"][0]["rows"], json!([["Charcoal", "Art Brush"], ["Dots", "Scatter Brush"]])); + assert!(panel.contains(&json!("3 pt. Round")) && i["panelBrushNames"] == json!(panel)); + let text = brushes(&mut s, json!({"category": "brushes", "format": "text"}))["text"].as_str().unwrap().to_string(); + assert!(text.contains("\nBRUSHES\nCharcoal: Art Brush\nDots: Scatter Brush\n") && !text.contains("3 pt. Round"), "{text}"); + assert!(!text.contains("OBJECTS"), "{text}"); + // Selection Only: the brushes the selected objects' strokes use. + let selected = |s: &mut Session| brushes(s, json!({"selectionOnly": true, "category": "brushes"})); s.execute("select.set", &json!({"ids": [a, b, c]})).unwrap(); - assert_eq!(names(&mut s), json!(["Charcoal", "Arrow"])); + assert_eq!(selected(&mut s)["brushNames"], json!(["Charcoal", "Dots"])); s.execute("select.set", &json!({"ids": [b]})).unwrap(); - assert_eq!(names(&mut s), json!(["Arrow"])); + let i = selected(&mut s); + assert_eq!( + (i["brushes"].clone(), i["sections"][0]["rows"].clone()), + (json!([{"name": "Dots", "type": "scatter"}]), json!([["Dots", "Scatter Brush"]])) + ); + let text = brushes(&mut s, json!({"selectionOnly": true, "category": "brushes", "format": "text"}))["text"].as_str().unwrap().to_string(); + assert!(text.contains("\nBRUSHES\nDots: Scatter Brush\n") && !text.contains("Charcoal"), "{text}"); // A stroke without a brush lists none. let plain = s.execute("shape.rectangle", &json!({"x": 60, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone(); s.execute("select.set", &json!({"ids": [plain]})).unwrap(); - assert_eq!(names(&mut s), json!([])); - let text = s.execute("document.info", &json!({"category": "brushes", "format": "text"})).unwrap()["text"].as_str().unwrap().to_string(); - assert!(text.contains(&format!("\nBRUSHES\n{}\n", panel[0].as_str().unwrap())), "{text}"); - assert!(text.contains("\nCharcoal\n") && text.contains("\nArrow\n") && !text.contains("OBJECTS"), "{text}"); + assert_eq!(selected(&mut s)["brushNames"], json!([])); + } + + /// Document Info › Brushes leaves out brushes on strokes that draw nothing (hidden, at an + /// opacity of 0, with no width or paint, a guide's, a compound path member's, a path's with no segment, type's that + /// draws no characters, a group's own), lists a brush the Brushes panel does + /// not hold with no type, and gives a name two panel brushes share the type the renderer uses. + #[test] + fn info_brushes_skip_undrawn_strokes_and_name_missing_brushes() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + let square = |s: &mut Session, x: f64| { + s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap() + }; + let (hidden, thin, guide, missing) = (square(&mut s, 0.0), square(&mut s, 20.0), square(&mut s, 40.0), square(&mut s, 60.0)); + let (empty, faint) = (square(&mut s, 80.0), square(&mut s, 200.0)); + s.execute("brush.apply", &json!({"ids": [hidden, thin, guide, missing, empty, faint], "name": "Charcoal"})).unwrap(); + let (p, q) = (square(&mut s, 100.0), square(&mut s, 120.0)); + s.execute("select.set", &json!({"ids": [p, q]})).unwrap(); + let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + // A compound path's member: the compound path's own stroke draws it. + let NodeKind::Compound { children, .. } = &mut d.node_mut(NodeId(compound)).unwrap().kind else { panic!("not a compound path") }; + let member = &mut std::sync::Arc::make_mut(&mut children[0]).appearance; + member.set_stroke(Paint::solid(vectorcraft_color::Color::BLACK)); + member.stroke_mut().unwrap().brush = Some("Dots".into()); + d.node_mut(NodeId(hidden)).unwrap().appearance.stroke_mut().unwrap().visible = false; + d.node_mut(NodeId(thin)).unwrap().appearance.stroke_mut().unwrap().width = 0.0; + // A stroke at an opacity of 0 draws nothing. + d.node_mut(NodeId(faint)).unwrap().appearance.stroke_mut().unwrap().opacity = 0.0; + if let NodeKind::Path { guide: g, .. } = &mut d.node_mut(NodeId(guide)).unwrap().kind { + *g = true; + } + // A path with no segment: its stroke follows nothing. + if let NodeKind::Path { path, .. } = &mut d.node_mut(NodeId(empty)).unwrap().kind { + *path = vectorcraft_geom::PathData::default(); + } + d.node_mut(NodeId(missing)).unwrap().appearance.stroke_mut().unwrap().brush = Some("Gone".into()); + let i = s.execute("document.info", &json!({"category": "brushes"})).unwrap(); + assert_eq!(i["brushes"], json!([{"name": "Gone", "type": null}])); + assert_eq!(i["sections"][0]["rows"], json!([["Gone", "missing from the Brushes panel"]])); + // A stroke with no paint draws nothing. + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + d.node_mut(NodeId(missing)).unwrap().appearance.stroke_mut().unwrap().paint = Paint::None; + assert_eq!(s.execute("document.info", &json!({"category": "brushes"})).unwrap()["brushes"], json!([])); + // Two panel brushes with one name: the type is the one the renderer draws with, the last one's. + let twin = square(&mut s, 140.0); + s.execute("brush.apply", &json!({"ids": [twin], "name": "Charcoal"})).unwrap(); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let mut lib = vectorcraft_brush::library(d); + let kinds: Vec<vectorcraft_brush::BrushKind> = + ["Charcoal", "Dots"].iter().map(|n| lib.iter().find(|b| b.name == *n).unwrap().kind.clone()).collect(); + lib.extend(kinds.into_iter().map(|kind| vectorcraft_brush::Brush { name: "Twin".into(), kind })); + vectorcraft_brush::store(d, &lib); + d.node_mut(NodeId(twin)).unwrap().appearance.stroke_mut().unwrap().brush = Some("Twin".into()); + assert_eq!(s.execute("document.info", &json!({"category": "brushes"})).unwrap()["brushes"], json!([{"name": "Twin", "type": "scatter"}])); + // Type: a brushed stroke on drawn characters is listed, one on spaces alone is not. + let blank = s.execute("text.create", &json!({"x": 10, "y": 60, "text": " "})).unwrap()["id"].as_u64().unwrap(); + let word = s.execute("text.create", &json!({"x": 10, "y": 90, "text": "Hi"})).unwrap()["id"].as_u64().unwrap(); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + for (id, name) in [(blank, "Dots"), (word, "Arrow")] { + let ap = &mut d.node_mut(NodeId(id)).unwrap().appearance; + ap.set_stroke(Paint::solid(vectorcraft_color::Color::BLACK)); + ap.stroke_mut().unwrap().brush = Some(name.into()); + } + let names = s.execute("document.info", &json!({"category": "brushes"})).unwrap()["brushNames"].clone(); + assert_eq!(names, json!(["Twin", "Arrow"])); + // A group's own stroke: the group draws its members. + let (m1, m2) = (square(&mut s, 160.0), square(&mut s, 180.0)); + s.execute("select.set", &json!({"ids": [m1, m2]})).unwrap(); + let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let ap = &mut d.node_mut(NodeId(group)).unwrap().appearance; + ap.set_stroke(Paint::solid(vectorcraft_color::Color::BLACK)); + ap.stroke_mut().unwrap().brush = Some("Leaves".into()); + let names = s.execute("document.info", &json!({"category": "brushes"})).unwrap()["brushNames"].clone(); + assert_eq!(names, json!(["Twin", "Arrow"])); } /// Document Info › Repeat Objects lists each Repeat object by name with its kind and the number @@ -786,6 +1090,11 @@ mod tests { 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(); + // Nor does a pattern fill at an opacity of 0. + let clear = square(&mut s, 220.0); + s.execute("paint.setStroke", &json!({"ids": [clear], "none": true})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [clear], "swatch": "Dots"})).unwrap(); + s.execute("appearance.setItem", &json!({"ids": [clear], "index": 0, "opacity": 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(); @@ -846,7 +1155,7 @@ mod tests { 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(); + s.execute("select.set", &json!({"ids": [d, e, clear, 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(); @@ -984,6 +1293,315 @@ mod tests { assert!(!text.contains("Spare"), "{text}"); } + /// Document Info › Spot Color Objects lists each object filled or stroked with a spot color once, + /// with the spot colors it uses, as a solid color or in a gradient's stops, one in a group and a + /// type object whose characters use one included. A spot swatch no art uses adds no row; a + /// process color that looks the same, Registration and a tint of 0 are not spot colors; paint + /// that draws nothing is left out by the rules Pattern Objects follows; and Objects counts the + /// listed objects. With Selection Only it lists the objects in the selection, each once, and the + /// report writes the same rows. + #[test] + fn info_lists_the_spot_color_objects() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + // An empty document lists none. + let i = s.execute("document.info", &json!({"category": "spotColors"})).unwrap(); + assert_eq!((i["spotObjects"].clone(), i["spotColorNames"].clone(), i["spotColors"].clone()), (json!([]), json!([]), json!([]))); + assert!(i["objects"]["spots"].is_null() && i["sections"][0]["rows"] == json!([]), "{i}"); + let text = s.execute("document.info", &json!({"category": "spotColors", "format": "text"})).unwrap()["text"].as_str().unwrap().to_string(); + assert!(text.contains("\nSPOT COLOR OBJECTS\nNone\n"), "{text}"); + let ink = |c: f64| json!({"model": "cmyk", "c": c, "m": 0.5, "y": 0.0, "k": 0.0}); + s.execute("swatch.new", &json!({"name": "Ink", "color": ink(1.0), "spot": true})).unwrap(); + s.execute("swatch.new", &json!({"name": "Gold", "color": ink(0.2), "spot": true})).unwrap(); + s.execute("swatch.new", &json!({"name": "Spare", "color": ink(0.4), "spot": true})).unwrap(); + // A global process color of the same color as Ink. + s.execute("swatch.new", &json!({"name": "Look", "color": ink(1.0), "global": true})).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 ramp = |a: &str, b: &str| json!({"kind": "linear", "stops": [{"offset": 0, "color": "#000", "swatch": a}, {"offset": 1, "color": "#fff", "swatch": b}]}); + let (a, b, c, f, g, h) = + (square(&mut s, 0.0), square(&mut s, 20.0), square(&mut s, 40.0), square(&mut s, 60.0), square(&mut s, 80.0), square(&mut s, 100.0)); + s.execute("paint.setFill", &json!({"ids": [a], "swatch": "Ink"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [a], "swatch": "Gold", "tint": 40})).unwrap(); + s.execute("layer.setProps", &json!({"id": a, "name": "Both"})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [b], "swatch": "Look"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [b], "swatch": "Ink", "tint": 50})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [c], "swatch": "Ink", "tint": 0})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [f], "gradient": ramp("Gold", "Look")})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [g], "gradient": ramp("Look", "Look")})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [h], "swatch": "[Registration]"})).unwrap(); + for id in [&c, &g, &h] { + s.execute("paint.setStroke", &json!({"ids": [id], "none": true})).unwrap(); + } + s.execute("select.set", &json!({"ids": [b, c]})).unwrap(); + let group = s.execute("object.group", &json!({})).unwrap()["id"].clone(); + // A type object whose characters are filled with a spot color. + let t = s.execute("text.create", &json!({"x": 0, "y": 200, "text": "Hi"})).unwrap()["id"].clone(); + s.execute("paint.setFill", &json!({"ids": [t], "swatch": "Ink"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [t], "none": true})).unwrap(); + s.execute("layer.setProps", &json!({"id": t, "name": "Type"})).unwrap(); + // A hidden spot fill and a spot stroke with no width paint nothing, so neither object is listed. + let (d, e) = (square(&mut s, 120.0), square(&mut s, 140.0)); + s.execute("paint.setStroke", &json!({"ids": [d], "none": true})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [d], "swatch": "Ink"})).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": "Ink"})).unwrap(); + s.execute("appearance.setItem", &json!({"ids": [e], "index": 1, "weight": 0})).unwrap(); + // Type with no characters, or of only spaces and a line break, paints nothing, and neither + // does a guide made from a path with a spot color. + let empty = s.execute("text.create", &json!({"x": 0, "y": 300, "text": ""})).unwrap()["id"].clone(); + s.execute("paint.setFill", &json!({"ids": [empty], "swatch": "Ink"})).unwrap(); + s.execute("appearance.addFill", &json!({"ids": [empty]})).unwrap(); + let blank = s.execute("text.create", &json!({"x": 0, "y": 320, "text": " \n"})).unwrap()["id"].clone(); + s.execute("paint.setFill", &json!({"ids": [blank], "swatch": "Ink"})).unwrap(); + let guide = square(&mut s, 300.0); + s.execute("paint.setFill", &json!({"ids": [guide], "swatch": "Ink"})).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 spot fill, or an image's spot fill without an + // effect that gives it a shape. + 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); + 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(); + let i = s.execute("document.info", &json!({})).unwrap(); + assert_eq!( + i["spotObjects"], + json!([ + {"id": a, "name": "Both", "spotColors": ["Ink", "Gold"]}, + {"id": b, "name": "<Rectangle>", "spotColors": ["Ink"]}, + {"id": f, "name": "<Rectangle>", "spotColors": ["Gold"]}, + {"id": t, "name": "Type", "spotColors": ["Ink"]}, + ]) + ); + assert_eq!((i["spotColorNames"].clone(), i["spotColors"].clone()), (json!(["Gold", "Ink"]), json!(["Gold", "Ink"]))); + // Objects counts the objects that Spot Color Objects lists. + assert_eq!(i["objects"]["spots"].as_u64(), Some(4), "{}", i["objects"]); + let objects = s.execute("document.info", &json!({"category": "objects"})).unwrap()["sections"][0]["rows"].clone(); + assert!(objects.as_array().unwrap().contains(&json!(["Spot Color Objects", "4"])), "{objects}"); + s.execute("select.set", &json!({"ids": [c, g, h, d, e, empty, blank, guide, compound, image.0]})).unwrap(); + let i = s.execute("document.info", &json!({"selectionOnly": true})).unwrap(); + assert!(i["objects"]["spots"].is_null() && i["spotObjects"] == json!([]) && i["spotColors"] == json!([]), "{i}"); + let i = s.execute("document.info", &json!({"category": "spotColors"})).unwrap(); + assert_eq!((i["sections"][0]["id"].as_str(), i["sections"][0]["title"].as_str()), (Some("spotColors"), Some("Spot Color Objects"))); + assert_eq!(i["sections"][0]["rows"], json!([["Both", "Ink, Gold"], ["<Rectangle>", "Ink"], ["<Rectangle>", "Gold"], ["Type", "Ink"]])); + // A selection that holds the group and the object inside it lists that object once. + for ids in [json!([group, b]), json!([b, group])] { + s.execute("select.set", &json!({"ids": ids})).unwrap(); + let i = s.execute("document.info", &json!({"selectionOnly": true, "category": "spotColors"})).unwrap(); + assert_eq!(i["sections"][0]["rows"], json!([["<Rectangle>", "Ink"]]), "{ids}"); + assert_eq!((i["objects"]["spots"].as_u64(), i["spotColorNames"].clone()), (Some(1), json!(["Ink"])), "{ids}"); + } + s.execute("select.set", &json!({"ids": [t]})).unwrap(); + let i = s.execute("document.info", &json!({"selectionOnly": true, "category": "spotColors"})).unwrap(); + assert_eq!((i["sections"][0]["rows"].clone(), i["spotColors"].clone()), (json!([["Type", "Ink"]]), json!(["Ink"]))); + let text = s.execute("document.info", &json!({"category": "spotColors", "format": "text"})).unwrap()["text"].as_str().unwrap().to_string(); + assert!(text.contains("\nSPOT COLOR OBJECTS\nBoth: Ink, Gold\n<Rectangle>: Ink\n<Rectangle>: Gold\nType: Ink\n"), "{text}"); + assert!(!text.contains("Spare") && !text.contains("Look"), "{text}"); + } + + /// Spot Color Objects lists a grayscale image colorized with a spot color, and leaves out a + /// gradient whose stops are all at an opacity of 0, which draws nothing. + #[test] + fn spot_color_objects_take_colorized_images_and_skip_clear_gradients() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + s.execute("swatch.new", &json!({"name": "Ink", "color": {"model": "cmyk", "c": 0, "m": 1, "y": 1, "k": 0}, "spot": true})).unwrap(); + let mut bytes = Vec::new(); + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(2, 1, vec![0, 255]).unwrap()) + .write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png) + .unwrap(); + let image = s + .edit("Place", |d, sel| { + d.images.insert("gray".into(), vectorcraft_doc::ImageBlob::png(bytes)); + let id = d.alloc_id(); + let im = vectorcraft_doc::ImageObject { + key: "gray".into(), + width: 2, + height: 1, + xf: Default::default(), + link: None, + placement: Default::default(), + pixels: None, + }; + d.insert(d.default_layer(), 0, Node::new(id, NodeKind::Image(Box::new(im))))?; + sel.set([id]); + Ok(id) + }) + .unwrap(); + s.execute("paint.setFill", &json!({"swatch": "Ink"})).unwrap(); + assert!(s.doc().unwrap().doc.node(image).unwrap().extras().colorize.is_some()); + let clear = s.execute("shape.rectangle", &json!({"x": 0, "y": 50, "width": 10, "height": 10})).unwrap()["id"].clone(); + let stops = + json!([{"offset": 0, "color": "#000", "swatch": "Ink", "opacity": 0}, {"offset": 1, "color": "#fff", "swatch": "Ink", "opacity": 0}]); + s.execute("paint.setFill", &json!({"ids": [clear], "gradient": {"kind": "linear", "stops": stops}})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [clear], "none": true})).unwrap(); + let i = s.execute("document.info", &json!({})).unwrap(); + let name = s.doc().unwrap().doc.node(image).unwrap().display_name(); + assert_eq!(i["spotObjects"], json!([{"id": image.0, "name": name, "spotColors": ["Ink"]}]), "{i}"); + assert_eq!(i["objects"]["spots"].as_u64(), Some(1), "{}", i["objects"]); + } + + /// Spot Color Objects leaves out a fill or stroke at an opacity of 0, which prints no ink, and + /// keeps the object while another of its fills or strokes prints the spot color. Gradient + /// Objects leaves out a clear gradient fill as well. + #[test] + fn spot_color_objects_skip_clear_fills_and_strokes() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + s.execute("swatch.new", &json!({"name": "Ink", "color": {"model": "cmyk", "c": 0, "m": 1, "y": 1, "k": 0}, "spot": true})).unwrap(); + let rect = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone(); + s.execute("paint.setFill", &json!({"ids": [rect], "swatch": "Ink"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [rect], "swatch": "Ink"})).unwrap(); + let ramp = s.execute("shape.rectangle", &json!({"x": 50, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone(); + let stops = json!([{"offset": 0, "color": "#000", "swatch": "Ink"}, {"offset": 1, "color": "#fff", "swatch": "Ink"}]); + s.execute("paint.setFill", &json!({"ids": [ramp], "gradient": {"kind": "linear", "stops": stops}})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [ramp], "none": true})).unwrap(); + let items = |s: &Session, id: &Value| s.doc().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap().appearance.items.clone(); + let spots = |s: &mut Session| { + let i = s.execute("document.info", &json!({})).unwrap(); + let mut ids: Vec<u64> = i["spotObjects"].as_array().unwrap().iter().map(|o| o["id"].as_u64().unwrap()).collect(); + ids.sort_unstable(); + (ids, i["objects"]["spots"].as_u64(), i["objects"]["gradients"].as_u64()) + }; + // The rectangle's fill at an opacity of 0: its stroke still prints the spot color. + s.execute("select.set", &json!({"ids": [rect]})).unwrap(); + let fill = items(&s, &rect).iter().position(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))).unwrap(); + s.execute("appearance.setItem", &json!({"index": fill, "opacity": 0})).unwrap(); + assert_eq!(spots(&mut s), (vec![rect.as_u64().unwrap(), ramp.as_u64().unwrap()], Some(2), Some(1))); + // Every fill and stroke of both objects at an opacity of 0. + for id in [&rect, &ramp] { + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + for index in 0..items(&s, id).len() { + s.execute("appearance.setItem", &json!({"index": index, "opacity": 0})).unwrap(); + } + } + assert_eq!(spots(&mut s), (vec![], None, None)); + } + + /// Brushes, Spot Color Objects, Pattern Objects and Gradient Objects leave out a hidden object, + /// an object at an opacity of 0 and the objects inside a hidden layer or a group at an opacity of + /// 0, with Selection Only too: their fills, strokes, characters and colorized pixels paint no + /// color. Objects still counts them. + #[test] + fn info_skips_paints_on_hidden_and_clear_objects_and_their_members() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s.execute("swatch.new", &json!({"name": "Ink", "color": {"model": "cmyk", "c": 0, "m": 1, "y": 1, "k": 0}, "spot": true})).unwrap(); + let square = |s: &mut Session, x: f64| { + s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap() + }; + let tile = square(&mut s, 0.0); + s.execute("object.pattern.make", &json!({"ids": [tile], "name": "Dots", "edit": false})).unwrap(); + // A patterned square that stays drawn, an object at an opacity of 0 and a hidden one. + let (shown, clear, hidden) = (square(&mut s, 20.0), square(&mut s, 40.0), square(&mut s, 60.0)); + s.execute("paint.setFill", &json!({"ids": [shown, clear], "swatch": "Dots"})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [hidden], "swatch": "Ink"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [shown, clear, hidden], "none": true})).unwrap(); + // A brushed square in a group. + let (brushed, other) = (square(&mut s, 80.0), square(&mut s, 100.0)); + s.execute("brush.apply", &json!({"ids": [brushed], "name": "Charcoal"})).unwrap(); + s.execute("select.set", &json!({"ids": [brushed, other]})).unwrap(); + let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + // Type whose characters are filled with the spot color. + let word = s.execute("text.create", &json!({"x": 0, "y": 200, "text": "Hi"})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"ids": [word], "swatch": "Ink"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [word], "none": true})).unwrap(); + // A grayscale image colorized with the spot color. + let mut bytes = Vec::new(); + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(2, 1, vec![0, 255]).unwrap()) + .write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png) + .unwrap(); + let image = s + .edit("Place", |d, sel| { + d.images.insert("gray".into(), vectorcraft_doc::ImageBlob::png(bytes)); + let id = d.alloc_id(); + let im = vectorcraft_doc::ImageObject { + key: "gray".into(), + width: 2, + height: 1, + xf: Default::default(), + link: None, + placement: Default::default(), + pixels: None, + }; + d.insert(d.default_layer(), 0, Node::new(id, NodeKind::Image(Box::new(im))))?; + sel.set([id]); + Ok(id) + }) + .unwrap(); + s.execute("paint.setFill", &json!({"swatch": "Ink"})).unwrap(); + // A square with a gradient on a layer of its own. + let layer = s.execute("layer.new", &json!({"name": "Back"})).unwrap()["id"].as_u64().unwrap(); + let ramp = square(&mut s, 120.0); + s.execute( + "paint.setFill", + &json!({"ids": [ramp], "gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]}}), + ) + .unwrap(); + s.execute("paint.setStroke", &json!({"ids": [ramp], "none": true})).unwrap(); + let listed = |s: &mut Session, p: Value| { + let i = s.execute("document.info", &p).unwrap(); + let ids = |k: &str| -> Vec<u64> { + let mut ids: Vec<u64> = i[k].as_array().unwrap().iter().map(|o| o["id"].as_u64().unwrap()).collect(); + ids.sort_unstable(); + ids + }; + (i["brushNames"].clone(), ids("spotObjects"), ids("patternObjects"), ids("gradientObjects"), i["objects"].clone()) + }; + // Everything drawn: each object is listed. + let (brushes, spots, patterns, gradients, before) = listed(&mut s, json!({})); + assert_eq!(brushes, json!(["Charcoal"])); + // New squares take the new spot color as their fill, the group's members included. + assert_eq!((spots, patterns, gradients), (vec![hidden, brushed, other, word, image.0], vec![shown, clear], vec![ramp])); + s.edit("hide", |d, _| { + d.node_mut(NodeId(clear)).unwrap().opacity = 0.0; + d.node_mut(NodeId(hidden)).unwrap().visible = false; + d.node_mut(NodeId(group)).unwrap().opacity = 0.0; + d.node_mut(NodeId(word)).unwrap().opacity = 0.0; + d.node_mut(image).unwrap().opacity = 0.0; + d.node_mut(NodeId(layer)).unwrap().visible = false; + Ok(()) + }) + .unwrap(); + let (brushes, spots, patterns, gradients, after) = listed(&mut s, json!({})); + assert_eq!((brushes, spots, patterns, gradients), (json!([]), vec![], vec![shown], vec![])); + // Objects counts the listed objects, and every object as before. + assert_eq!((after["spots"].clone(), after["patterns"].clone(), after["gradients"].clone()), (Value::Null, json!(1), Value::Null)); + for k in ["paths", "groups", "textObjects", "images"] { + assert_eq!(after[k], before[k], "{k}: {after}"); + } + let rows = s.execute("document.info", &json!({"category": "brushes"})).unwrap()["sections"][0]["rows"].clone(); + assert_eq!(rows, json!([])); + // Selection Only: an object selected inside a group at an opacity of 0 or a hidden layer paints nothing either. + s.execute("select.set", &json!({"ids": [brushed, ramp]})).unwrap(); + let (brushes, _, _, gradients, after) = listed(&mut s, json!({"selectionOnly": true})); + assert_eq!((brushes, gradients, after["paths"].clone()), (json!([]), vec![], json!(2))); + // Drawn again, the group's brush and the layer's gradient are listed. + s.edit("show", |d, _| { + d.node_mut(NodeId(group)).unwrap().opacity = 1.0; + d.node_mut(NodeId(layer)).unwrap().visible = true; + Ok(()) + }) + .unwrap(); + let (brushes, _, _, gradients, _) = listed(&mut s, json!({"selectionOnly": true})); + assert_eq!((brushes, gradients), (json!(["Charcoal"]), vec![ramp])); + } + /// 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. diff --git a/crates/engine/src/cmd/docmenu.rs b/crates/engine/src/cmd/docmenu.rs index db792ab1c6..ae48ba02e6 100644 --- a/crates/engine/src/cmd/docmenu.rs +++ b/crates/engine/src/cmd/docmenu.rs @@ -13,8 +13,8 @@ use super::edit::selected_roots; use super::pathops::Beside; use super::select::{first_selectable, is_selectable, selectable_ids, walk_selectable}; use super::{ - CommandSpec, EngineError, Point, Result, Session, bad, bool_or, checked_ids_param, cmd, f64_or, f64_req, has_doc, has_selection, id_param, ok, - str_param, switch_or, + CommandSpec, EngineError, Point, Result, Session, bad, checked_ids_param, cmd, f64_req, has_doc, has_selection, id_param, number_or, ok, + str_param, switch_or, text_param, }; pub fn specs() -> Vec<CommandSpec> { @@ -210,7 +210,7 @@ pub fn specs() -> Vec<CommandSpec> { "Guides", [], None, - "{} → [{index, vertical, pos, selected, artboard?: index (an artboard guide's), layer?: id (the layer it is on), shown, editable (its layer shown and unlocked)}…] the ruler guides", + "{} → [{index, id (its node, which `layer.setProps` hides or locks on its own), vertical, pos, selected, artboard?: index (an artboard guide's), layer?: id (the layer it is on), hidden, locked (its own visibility and lock), shown, editable (it and its layer shown and unlocked)}…] the ruler guides", has_doc, guide_list ), @@ -219,7 +219,7 @@ pub fn specs() -> Vec<CommandSpec> { "Select Guides", [], None, - "{indexes: [index…], toggle?: bool} select ruler guides on their own (deselecting the art); toggle adds or removes them instead, keeping the selected art (a Shift-click on a guide) → {selected: [index…]}", + "{indexes: [index…] (at most 10,000), toggle?: bool} select ruler guides on their own (deselecting the art); toggle adds or removes them instead, keeping the selected art (a Shift-click on a guide) → {selected: [index…]}", guides_unlocked, guide_select ), @@ -228,7 +228,7 @@ pub fn specs() -> Vec<CommandSpec> { "Remove Guide", [], None, - "{index?} delete ruler guide `index`, else the selected ones (as Delete / edit.clear does) → {count}", + "{index?, indexes?: [index…] (at most 10,000)} delete ruler guide `index` (or guides `indexes`, as dragging their rows onto the Layers panel's trash does), else the selected ones (as Delete / edit.clear does), in one undo step; give `index` or `indexes`, not both, and an index given twice counts once; a hidden or locked guide, or one on a hidden or locked layer, is an error → {count}", guides_unlocked, guide_remove ), @@ -246,7 +246,7 @@ pub fn specs() -> Vec<CommandSpec> { "Move Guide to Layer", [], None, - "{index?, indexes?: [index…], layer: id} put ruler guide `index` (or guides `indexes`), else the selected guides, on layer `layer` (a layer or sublayer), as dragging their rows onto that layer's row in the Layers panel does → {count}", + "{index?, indexes?: [index…] (at most 10,000), layer: id} put ruler guide `index` (or guides `indexes`), else the selected guides, on layer `layer` (a layer or sublayer), as dragging their rows onto that layer's row in the Layers panel does; give `index` or `indexes`, not both, and an index given twice counts once → {count}", guides_unlocked, guide_set_layer ), @@ -482,7 +482,7 @@ fn save_selection(s: &mut Session, p: &Value) -> Result<Value> { let st = s.doc()?; let ids = st.selection.objects.clone(); let saved = &st.doc.saved_selections; - let name = str_param(p, "name").and_then(SavedSelection::clean_name).unwrap_or_else(|| SavedSelection::default_name(saved)); + let name = text_param(p, "name", C)?.and_then(SavedSelection::clean_name).unwrap_or_else(|| SavedSelection::default_name(saved)); let existing = saved.iter().position(|x| x.name == name); if existing.is_none() && saved.len() >= SavedSelection::MAX { return Err(bad(C, format!("a document keeps at most {} saved selections", SavedSelection::MAX))); @@ -577,10 +577,12 @@ fn edit_saved(s: &mut Session, p: &Value) -> Result<Value> { for e in edits { let name = str_param(e, "name").ok_or_else(|| bad(C, "missing name"))?; let i = *index.get(name).ok_or_else(|| bad(C, format!("no saved selection `{name}`")))?; + let delete = switch_or(e, "delete", false, C)?; + let new_name = text_param(e, "newName", C)?; let Some(slot) = after.get_mut(i) else { continue }; - if bool_or(e, "delete", false) { + if delete { *slot = None; - } else if let Some(n) = str_param(e, "newName").and_then(SavedSelection::clean_name) + } else if let Some(n) = new_name.and_then(SavedSelection::clean_name) && let Some(x) = slot { x.name = n; @@ -764,7 +766,7 @@ fn clear_guides(s: &mut Session, _: &Value) -> Result<Value> { fn guide_add(s: &mut Session, p: &Value) -> Result<Value> { let pos = f64_req(p, "pos", "guide.add")?; - let vertical = bool_or(p, "vertical", false); + let vertical = switch_or(p, "vertical", false, "guide.add")?; let artboard = match p.get("artboard").filter(|v| !v.is_null()) { Some(v) => { let boards = &s.doc()?.doc.artboards; @@ -803,12 +805,17 @@ fn guide_list(s: &mut Session, _: &Value) -> Result<Value> { let row = |(i, g): (usize, &Guide)| { let selected = g.id.is_some_and(|id| st.selection.guides.contains(&id)); let mut r = json!({ "index": i, "vertical": g.vertical, "pos": g.pos, "selected": selected }); + if let Some(id) = g.id { + r["id"] = json!(id.0); + } if let Some(ab) = st.doc.artboards.iter().position(|a| Some(a.id) == g.artboard) { r["artboard"] = json!(ab); } if let Some(l) = g.layer { r["layer"] = json!(l.0); } + r["hidden"] = json!(g.hidden); + r["locked"] = json!(g.locked); r["shown"] = json!(st.doc.guide_shown(g)); r["editable"] = json!(st.doc.guide_editable(g)); r @@ -822,30 +829,47 @@ fn guide_index_in(ids: &[NodeId], v: Option<&Value>, cmd: &str) -> Result<NodeId ids.get(i).copied().ok_or_else(|| bad(cmd, format!("no guide {i}"))) } +/// The most guide indexes one `indexes` list may hold. +const MAX_GUIDE_INDEXES: usize = 10_000; + +/// `indexes` as a list of at most [`MAX_GUIDE_INDEXES`] entries. +fn guide_index_list<'a>(v: &'a Value, cmd: &str) -> Result<&'a Vec<Value>> { + let list = v.as_array().ok_or_else(|| bad(cmd, "indexes must be an array of guide indexes"))?; + if list.len() > MAX_GUIDE_INDEXES { + return Err(bad(cmd, format!("indexes may hold at most {MAX_GUIDE_INDEXES} entries"))); + } + Ok(list) +} + /// The id of ruler guide `index` of the active document (`index` validated). fn guide_index(s: &Session, v: Option<&Value>, cmd: &str) -> Result<NodeId> { guide_index_in(&guide_ids(&s.doc()?.doc), v, cmd) } -/// Is ruler guide `id` one that can be moved or deleted: not on a hidden or locked layer? +/// Is ruler guide `id` one that can be moved or deleted: not hidden or locked itself, nor on a +/// hidden or locked layer? fn check_editable_guide(s: &Session, id: NodeId) -> Result<NodeId> { let d = &s.doc()?.doc; - if !d.ruler_guide(id).is_some_and(|g| d.guide_editable(&g)) { + let guide = d.ruler_guide(id); + if guide.as_ref().is_some_and(|g| g.hidden || g.locked) { + return Err(EngineError::Other("the guide is hidden or locked".into())); + } + if !guide.is_some_and(|g| d.guide_editable(&g)) { return Err(EngineError::Other("the guide is on a hidden or locked layer".into())); } Ok(id) } -/// [`guide_index`] of a guide that can be moved or deleted: not on a hidden or locked layer. +/// [`guide_index`] of a guide that can be moved or deleted ([`check_editable_guide`]). fn editable_guide_index(s: &Session, v: Option<&Value>, cmd: &str) -> Result<NodeId> { check_editable_guide(s, guide_index(s, v, cmd)?) } fn guide_select(s: &mut Session, p: &Value) -> Result<Value> { - let list = p.get("indexes").and_then(Value::as_array).ok_or_else(|| bad("guide.select", "missing indexes"))?; + let list = guide_index_list(p.get("indexes").ok_or_else(|| bad("guide.select", "missing indexes"))?, "guide.select")?; let ids = guide_ids(&s.doc()?.doc); let picked = list.iter().map(|v| guide_index_in(&ids, Some(v), "guide.select")).collect::<Result<Vec<_>>>()?; - if bool_or(p, "toggle", false) { + if switch_or(p, "toggle", false, "guide.select")? { // Added to (or taken from) what is selected, the art included. s.select(|_, sel| { for i in picked { @@ -859,18 +883,30 @@ fn guide_select(s: &mut Session, p: &Value) -> Result<Value> { Ok(json!({ "selected": guide_indexes(&st.doc, &st.selection.guides) })) } -/// Delete ruler guide `index`, else the selected guides, in one undo step → {count}. +/// Delete ruler guide `index` (or guides `indexes`), else the selected guides, in one undo step +/// → {count}. pub(crate) fn guide_remove(s: &mut Session, p: &Value) -> Result<Value> { - let gone: Vec<NodeId> = match p.get("index") { - Some(v) => vec![editable_guide_index(s, Some(v), "guide.remove")?], - None => s.doc()?.selection.guides.clone(), + const C: &str = "guide.remove"; + let mut gone: Vec<NodeId> = match (p.get("index"), p.get("indexes")) { + (Some(_), Some(_)) => return Err(bad(C, "give index or indexes, not both")), + (Some(v), None) => vec![editable_guide_index(s, Some(v), C)?], + (None, Some(list)) => { + let list = guide_index_list(list, C)?; + let ids = guide_ids(&s.doc()?.doc); + // A set, so an index given twice deletes its guide once and the ids held never outnumber the guides. + let set = list.iter().map(|v| check_editable_guide(s, guide_index_in(&ids, Some(v), C)?)).collect::<Result<BTreeSet<_>>>()?; + set.into_iter().collect() + } + (None, None) => s.doc()?.selection.guides.clone(), }; + gone.sort_unstable(); + gone.dedup(); if gone.is_empty() { - return Err(bad("guide.remove", "no guide selected")); + return Err(bad(C, "no guide selected")); } let label = if gone.len() == 1 { "Delete Guide" } else { "Delete Guides" }; s.edit(label, |d, sel| { - d.retain_guides(sel, |g| !g.id.is_some_and(|id| gone.contains(&id))); + d.retain_guides(sel, |g| !g.id.is_some_and(|id| gone.binary_search(&id).is_ok())); Ok(()) })?; Ok(json!({ "count": gone.len() })) @@ -886,14 +922,19 @@ fn guide_set_layer(s: &mut Session, p: &Value) -> Result<Value> { if super::layer::locked_within(d, layer) { return Err(EngineError::Other("the layer or group is locked".into())); } - let moving: Vec<NodeId> = match (p.get("index"), p.get("indexes").and_then(Value::as_array)) { - (Some(v), _) => vec![editable_guide_index(s, Some(v), C)?], + let mut moving: Vec<NodeId> = match (p.get("index"), p.get("indexes")) { + (Some(_), Some(_)) => return Err(bad(C, "give index or indexes, not both")), + (Some(v), None) => vec![editable_guide_index(s, Some(v), C)?], (None, Some(list)) => { + let list = guide_index_list(list, C)?; let ids = guide_ids(&s.doc()?.doc); - list.iter().take(10_000).map(|v| check_editable_guide(s, guide_index_in(&ids, Some(v), C)?)).collect::<Result<Vec<_>>>()? + list.iter().map(|v| check_editable_guide(s, guide_index_in(&ids, Some(v), C)?)).collect::<Result<Vec<_>>>()? } (None, None) => s.doc()?.selection.guides.clone(), }; + // An index given twice moves (and counts) its guide once; the others keep their order. + let mut seen = HashSet::new(); + moving.retain(|id| seen.insert(*id)); if moving.is_empty() { return Err(bad(C, "no guide selected (or give an index)")); } @@ -924,7 +965,9 @@ pub(crate) fn guide_move(s: &mut Session, p: &Value) -> Result<Value> { if moving.is_empty() { return Err(bad("guide.move", "no guide selected (or give an index)")); } - let (dx, dy, copy) = (f64_or(p, "dx", 0.0), f64_or(p, "dy", 0.0), bool_or(p, "copy", false)); + let dx = number_or(p, "dx", 0.0, "guide.move")?; + let dy = number_or(p, "dy", 0.0, "guide.move")?; + let copy = switch_or(p, "copy", false, "guide.move")?; if !s.doc()?.selection.is_empty() { let ids = super::edit::selected_roots(s)?; return super::object::apply_transform( diff --git a/crates/engine/src/cmd/docsetup.rs b/crates/engine/src/cmd/docsetup.rs index 894d9b90ae..dadafaa1b8 100644 --- a/crates/engine/src/cmd/docsetup.rs +++ b/crates/engine/src/cmd/docsetup.rs @@ -17,7 +17,7 @@ pub fn specs() -> Vec<CommandSpec> { "Document Setup", [], None, - "{units?: \"Points\"|\"Inches\"|\"Millimeters\"|…, bleed?: pt (all sides)|[top, bottom, left, right]|{top?, bottom?, left?, right?} (0–72 pt), outlineImages?: bool (show images in Outline mode), highlightSubstitutedGlyphs?: bool (Highlight Substituted Fonts is a preference: prefs.set highlightSubstitutedFonts; a highlightSubstitutedFonts key is ignored and the reply carries a warning),gridSize?: \"small\"|\"medium\"|\"large\", gridColors?: \"Light\"|\"Medium\"|\"Dark\"|\"Red\"|\"Orange\"|\"Green\"|\"Blue\"|\"Purple\"|[colour, colour] (transparency grid; the first is also the paper colour; #rrggbbaa and #rgba are refused), simulatePaper?: bool, flattenerPreset?: \"High Resolution\"|\"Medium Resolution\"|\"Low Resolution\"|a saved preset (flattener.presets.list), discardWhiteOverprint?: bool, language?: \"English: USA\"|\"German\"|\"French\"|… (also picks its quotes), quotes?: {double?: \"“”\", single?: \"‘’\"} (beside a language: only if they differ from the current ones), typographersQuotes?: bool (typed straight quotes become the document's quotes), superscript?: {size?: %, position?: %}, subscript?: {size?: %, position?: %}, smallCapsSize?: %, exportText?: \"editable\"|\"appearance\" (SVG text as text or as outlines), backgroundContents?: \"transparent\"|\"white\" (white: raster exports are white behind the art), …the keys of its own reply (it can be passed back; the values it only reports are ignored)} change the document setup in one undo step; no params → the current setup", + "{units?: \"Points\"|\"Inches\"|\"Millimeters\"|…, bleed?: pt (all sides)|[top, bottom, left, right]|{top?, bottom?, left?, right?} (0–72 pt), outlineImages?: bool (show images in Outline mode), highlightSubstitutedGlyphs?: bool (Highlight Substituted Fonts is a preference: prefs.set highlightSubstitutedFonts; a highlightSubstitutedFonts key is ignored and the reply carries a warning),gridSize?: \"small\"|\"medium\"|\"large\", gridColors?: \"Light\"|\"Medium\"|\"Dark\"|\"Red\"|\"Orange\"|\"Green\"|\"Blue\"|\"Purple\"|[colour, colour] (transparency grid; the first is also the paper colour; #rrggbbaa and #rgba are refused), simulatePaper?: bool, flattenerPreset?: \"High Resolution\"|\"Medium Resolution\"|\"Low Resolution\"|a saved preset (flattener.presets.list), discardWhiteOverprint?: bool, language?: \"English: USA\"|\"German\"|\"French\"|… (also picks its quotes), quotes?: {double?: \"“”\", single?: \"‘’\"} (beside a language: only if they differ from the current ones), typographersQuotes?: bool (typed straight quotes become the document's quotes), superscript?: {size?: %, position?: %}, subscript?: {size?: %, position?: %}, smallCapsSize?: %, exportText?: \"editable\"|\"appearance\" (SVG text as text or as outlines), backgroundContents?: \"transparent\"|\"white\" (white: raster exports are white behind the art), alignNewObjectsToPixelGrid?: bool (Align New Objects to Pixel Grid: paths and compound paths drawn from then on are pixel-aligned, as object.setPixelAligned; art already in the document, pasted, duplicated or placed keeps its own setting), …the keys of its own reply (it can be passed back; the values it only reports are ignored)} change the document setup in one undo step; no params → the current setup", has_doc, setup )] @@ -46,6 +46,7 @@ pub(crate) fn setup_json(d: &Document) -> Value { "smallCapsSize": s.small_caps_size, "exportText": s.export_text.id(), "backgroundContents": s.background.id(), + "alignNewObjectsToPixelGrid": s.align_new_objects_to_pixel_grid, }) } @@ -140,6 +141,7 @@ fn apply(s: &mut DocSetup, units: &mut vectorcraft_doc::Unit, k: &str, v: &Value "smallCapsSize" => s.small_caps_size = percent(k, v, 1.0, vectorcraft_doc::setup::MAX_SMALL_CAPS)?, "exportText" => s.export_text = v.as_str().and_then(ExportText::parse).ok_or_else(|| bad(C, "exportText must be editable or appearance"))?, "backgroundContents" => s.background = background_param(v, C)?, + "alignNewObjectsToPixelGrid" => s.align_new_objects_to_pixel_grid = flag(k, v)?, // Read-only values `document.setup` reports. "gridColorsName" | "warnings" => {} _ => return Err(bad(C, format!("unknown setting `{k}`"))), diff --git a/crates/engine/src/cmd/draw2.rs b/crates/engine/src/cmd/draw2.rs index 7d1c1208d8..d469c7a613 100644 --- a/crates/engine/src/cmd/draw2.rs +++ b/crates/engine/src/cmd/draw2.rs @@ -18,8 +18,8 @@ use super::create::{add_look, insert_look}; use super::newart::NewArt; use super::pathops::{Beside, remove_each}; use super::{ - CommandSpec, Result, Session, bad, check_numbers, cmd, f64_or, has_anchors, has_doc, has_selection, id_param, index, number_or, ok, str_param, - switch_or, + CommandSpec, Result, Session, bad, check_numbers, cmd, f64_or, has_anchors, has_doc, has_selection, index, number_or, object_param, ok, + str_param, switch_or, }; use crate::EngineError; diff --git a/crates/engine/src/cmd/draw2/anchors.rs b/crates/engine/src/cmd/draw2/anchors.rs index dbca59b00d..5b80fcc80f 100644 --- a/crates/engine/src/cmd/draw2/anchors.rs +++ b/crates/engine/src/cmd/draw2/anchors.rs @@ -1,7 +1,7 @@ use super::common::{MAX_INPUT, path_kind, path_mut, point_entry, usize_opt, usize_req, within_input_bound}; use super::{ Anchor, BTreeSet, Beside, Color, Document, EngineError, Node, NodeId, NodeKind, Paint, PathData, Point, Result, Selection, Session, Value, Vec2, - add_look, bad, check_numbers, f64_or, id_param, json, number_or, ok, po, str_param, switch_or, + add_look, bad, check_numbers, f64_or, json, number_or, object_param, ok, po, str_param, switch_or, }; // ---------- Curvature ---------- @@ -41,7 +41,7 @@ enum CurvatureOp { pub(super) fn curvature_edit(s: &mut Session, p: &Value) -> Result<Value> { use vectorcraft_tools::draw2::{EndCurve, curvature_close, curvature_extend, curvature_insert, curvature_move}; const C: &str = "path.curvatureEdit"; - let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; let si = usize_opt(p, "subpath", C)?.unwrap_or(0); check_numbers(p, &["x", "y", "t"], C)?; let at = match (p.get("x").and_then(Value::as_f64), p.get("y").and_then(Value::as_f64)) { @@ -106,7 +106,7 @@ pub(super) fn curvature_edit(s: &mut Session, p: &Value) -> Result<Value> { pub(super) fn remove_anchor(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "path.removeAnchor"; - let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; let si = usize_opt(p, "subpath", C)?.unwrap_or(0); let ai = usize_req(p, "anchor", C)?; let curvature = switch_or(p, "curvature", false, C)?; @@ -116,8 +116,11 @@ pub(super) fn remove_anchor(s: &mut Session, p: &Value) -> Result<Value> { return Err(EngineError::Other("no such anchor".into())); } let mut emptied = Beside::replacing(d, &[id]); - let removed = remove_anchors_of(d, sel, &mut emptied, id, [(si, ai)], curvature)?; + let removed = remove_anchors_of(d, sel, &mut emptied, id, vec![(si, ai)], curvature)?; emptied.finish(d)?; + if removed { + sel.remove(id); + } Ok(removed) })?; Ok(json!({ "removedObject": removed })) @@ -136,14 +139,14 @@ pub(super) fn remove_anchors(s: &mut Session, _: &Value) -> Result<Value> { return Err(bad("path.removeAnchors", "direct-select anchor points of a path")); } let removed = s.edit("Remove Anchor Points", |d, sel| { - let mut removed = 0; + let mut gone = Vec::new(); let mut emptied = Beside::replacing(d, &jobs.iter().map(|(id, _)| *id).collect::<Vec<_>>()); for (id, anchors) in jobs { let shape: Vec<(usize, bool)> = d.node(id).and_then(Node::path_data).map(|p| p.subpaths.iter().map(|sp| (sp.anchors.len(), sp.closed)).collect()).unwrap_or_default(); let next = following_anchors(&shape, &anchors); if remove_anchors_of(d, sel, &mut emptied, id, anchors, false)? { - removed += 1; + gone.push(id); } else if !next.is_empty() { // The next anchor along is selected, so the next Remove Anchor Points goes on from // there without picking it first (#2241). @@ -151,7 +154,8 @@ pub(super) fn remove_anchors(s: &mut Session, _: &Value) -> Result<Value> { } } emptied.finish(d)?; - Ok(removed) + sel.remove_all(gone.iter().copied()); + Ok(gone.len()) })?; Ok(json!({ "removedObjects": removed })) } @@ -160,19 +164,32 @@ pub(super) fn remove_anchors(s: &mut Session, _: &Value) -> Result<Value> { /// path whose subpaths have `shape` (anchor count, closed): in each subpath, the anchor after its /// last removed one, round the end of a closed subpath, or the one before it at an open subpath's /// end. Indexes are those after the removal, without the subpaths left with fewer than two anchors. +/// `removed` is in ascending order without repeats, as a selection holds it, and each subpath reads +/// only its own pairs. fn following_anchors(shape: &[(usize, bool)], removed: &[(usize, usize)]) -> BTreeSet<(usize, usize)> { let mut next = BTreeSet::new(); let mut kept = 0; + let mut rest = removed; for (si, &(n, closed)) in shape.iter().enumerate() { - let gone: BTreeSet<usize> = removed.iter().filter(|&&(s, a)| s == si && a < n).map(|&(_, a)| a).collect(); + let (mine, after) = rest.split_at(rest.iter().take_while(|&&(s, _)| s == si).count()); + rest = after; + let gone = &mine[..mine.partition_point(|&(_, a)| a < n)]; if n - gone.len() < 2 { continue; } - if let Some(&last) = gone.last() { - let wrap = if closed { 0..last } else { 0..0 }; - let after = (last + 1..n).chain(wrap).find(|a| !gone.contains(a)); - if let Some(a) = after.or_else(|| (0..last).rev().find(|a| !gone.contains(a))) { - next.insert((kept, a - gone.range(..a).count())); + if let Some(&(_, last)) = gone.last() { + // Anchors past `last` are all left. Below it, the first one left (round a closed + // subpath's end) is past the removed run from 0, and the last one left is below the + // removed run down from `last`. + let a = if last + 1 < n { + Some(last + 1) + } else if closed { + Some(gone.iter().zip(0..).take_while(|&(&(_, g), k)| g == k).count()) + } else { + last.checked_sub(gone.iter().rev().zip((0..=last).rev()).take_while(|&(&(_, g), k)| g == k).count()) + }; + if let Some(a) = a { + next.insert((kept, a - gone.partition_point(|&(_, g)| g < a))); } } kept += 1; @@ -183,34 +200,37 @@ fn following_anchors(shape: &[(usize, bool)], removed: &[(usize, usize)]) -> BTr /// Remove `anchors` (subpath, anchor) of path `id` without opening it, refitting the curve round /// each one, or with `curvature` re-curving it as the Curvature tool curves its points /// ([`vectorcraft_tools::draw2::curvature_remove`]). A subpath left with one anchor is removed, -/// and a path left with no subpath is removed through `emptied`. True when the path went. +/// and a path left with no subpath is removed through `emptied`; the caller then takes it out of +/// the selection. True when the path went. fn remove_anchors_of( d: &mut Document, sel: &mut Selection, emptied: &mut Beside, id: NodeId, - anchors: impl IntoIterator<Item = (usize, usize)>, + mut anchors: Vec<(usize, usize)>, curvature: bool, ) -> Result<bool> { - let mut anchors: Vec<(usize, usize)> = anchors.into_iter().collect(); // The last first, so the indexes still to come stay valid. anchors.sort_unstable_by(|a, b| b.cmp(a)); anchors.dedup(); let path = path_mut(d, id)?; - for (si, ai) in anchors { - if let Some(sp) = path.subpaths.get_mut(si) { - if curvature { + let mut rest = &anchors[..]; + while let Some(&(si, _)) = rest.first() { + let (mine, after) = rest.split_at(rest.iter().take_while(|&&(s, _)| s == si).count()); + rest = after; + let Some(sp) = path.subpaths.get_mut(si) else { continue }; + if curvature { + for &(_, ai) in mine { vectorcraft_tools::draw2::curvature_remove(sp, ai); - } else { - po::remove_anchor(sp, ai); } + } else { + po::remove_anchors(sp, &mine.iter().map(|&(_, ai)| ai).collect::<Vec<_>>()); } } path.subpaths.retain(|sp| sp.anchors.len() >= 2); let gone = path.is_empty(); if gone { emptied.put(d, id, vec![])?; - sel.remove(id); } else { sel.anchors.remove(&id); sel.segments.remove(&id); @@ -220,7 +240,7 @@ fn remove_anchors_of( pub(super) fn convert_anchor(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "path.convertAnchor"; - let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; let si = usize_opt(p, "subpath", C)?.unwrap_or(0); let ai = usize_req(p, "anchor", C)?; let smooth = str_param(p, "to") == Some("smooth"); @@ -257,7 +277,7 @@ pub(super) fn convert_anchor(s: &mut Session, p: &Value) -> Result<Value> { pub(super) fn reshape_segment(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "path.reshapeSegment"; - let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; let si = usize_opt(p, "subpath", C)?.unwrap_or(0); let seg = usize_req(p, "segment", C)?; let t = number_or(p, "t", 0.5, C)?.clamp(0.05, 0.95); @@ -277,3 +297,47 @@ pub(super) fn reshape_segment(s: &mut Session, p: &Value) -> Result<Value> { })?; ok() } + +#[cfg(test)] +mod tests { + use super::*; + + /// [`following_anchors`] by its definition: for each subpath, a search of the anchors after + /// its last removed one, round a closed end, then before it. + fn following_by_search(shape: &[(usize, bool)], removed: &[(usize, usize)]) -> BTreeSet<(usize, usize)> { + let mut next = BTreeSet::new(); + let mut kept = 0; + for (si, &(n, closed)) in shape.iter().enumerate() { + let gone: BTreeSet<usize> = removed.iter().filter(|&&(s, a)| s == si && a < n).map(|&(_, a)| a).collect(); + if n - gone.len() < 2 { + continue; + } + if let Some(&last) = gone.last() { + let wrap = if closed { 0..last } else { 0..0 }; + let after = (last + 1..n).chain(wrap).find(|a| !gone.contains(a)); + if let Some(a) = after.or_else(|| (0..last).rev().find(|a| !gone.contains(a))) { + next.insert((kept, a - gone.range(..a).count())); + } + } + kept += 1; + } + next + } + + #[test] + fn following_anchors_matches_a_search_along_each_subpath() { + let mut seed = 0x2545_f491_4f6c_dd1d_u64; + let mut rnd = |m: u64| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed % m) as usize + }; + for case in 0..2000 { + let shape: Vec<(usize, bool)> = (0..rnd(5) + 1).map(|_| (rnd(9), rnd(2) == 0)).collect(); + let removed: BTreeSet<(usize, usize)> = (0..rnd(14)).map(|_| (rnd(shape.len() as u64 + 1), rnd(11))).collect(); + let removed: Vec<_> = removed.into_iter().collect(); + assert_eq!(following_anchors(&shape, &removed), following_by_search(&shape, &removed), "case {case}: {shape:?} removing {removed:?}"); + } + } +} diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index 8946aa4351..400e13baab 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -11,7 +11,7 @@ pub fn specs() -> Vec<CommandSpec> { "Pencil", [], None, - "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks), fidelity?: pt (1.5), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end; with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it", + "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end; with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it", has_doc, freehand ), diff --git a/crates/engine/src/cmd/draw2/cut.rs b/crates/engine/src/cmd/draw2/cut.rs index 126fa57a1b..645c184b14 100644 --- a/crates/engine/src/cmd/draw2/cut.rs +++ b/crates/engine/src/cmd/draw2/cut.rs @@ -4,7 +4,7 @@ use super::common::{ }; use super::{ Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, EngineError, FillRule, Join, NodeId, ParamCurve, PathData, Point, Result, Session, SubPath, - Value, bad, eraser_area, eraser_tip, f64_or, fill_contains, id_param, json, number_or, po, + Value, bad, eraser_area, eraser_tip, f64_or, fill_contains, json, number_or, object_param, po, }; /// Split a filled path into connected pieces (each outer contour with its holes). @@ -170,7 +170,7 @@ pub(in super::super) fn erase_outline(pd: &PathData, step: f64, remove: &dyn Fn( pub(super) fn split(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "path.split"; - let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; let si = usize_opt(p, "subpath", C)?.unwrap_or(0); let anchor = usize_opt(p, "anchor", C)?; let seg = usize_opt(p, "segment", C)?; diff --git a/crates/engine/src/cmd/draw2/freehand.rs b/crates/engine/src/cmd/draw2/freehand.rs index 660f52121e..31e184e195 100644 --- a/crates/engine/src/cmd/draw2/freehand.rs +++ b/crates/engine/src/cmd/draw2/freehand.rs @@ -4,7 +4,8 @@ use super::common::{ }; use super::{ Anchor, Appearance, BTreeSet, BoolOp, Cap, Color, Document, EngineError, FillRule, Join, NewArt, Node, NodeId, NodeKind, Paint, PathData, Point, - Result, Selection, Session, SimplifyOptions, SubPath, Value, bad, id_param, insert_look, json, number_or, po, remove_each, str_param, switch_or, + Result, Selection, Session, SimplifyOptions, SubPath, Value, bad, insert_look, json, number_or, object_param, po, remove_each, str_param, + switch_or, }; // ---------- Pencil / Paintbrush ---------- @@ -150,7 +151,11 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> { } let pen = PenRecord::of_samples(&samples); let mut pts: Vec<Point> = samples.into_iter().map(|s| s.pt).collect(); - let tol = number_or(p, "fidelity", 1.5, C)?.clamp(vectorcraft_tools::draw2::MIN_FIT_TOLERANCE, 100.0); + let tol = number_or(p, "fidelity", 1.5, C)?; + let (lo, hi) = (vectorcraft_tools::draw2::MIN_FIT_TOLERANCE, vectorcraft_tools::draw2::MAX_FIT_TOLERANCE); + if !(lo..=hi).contains(&tol) { + return Err(bad(C, format!("`fidelity` must be from {lo} to {hi} pt"))); + } // The tolerance the stroke is fitted at; with `fit: false` it is not fitted. let fit_tol = switch_or(p, "fit", true, C)?.then_some(tol); let closed = switch_or(p, "closed", false, C)?; @@ -158,7 +163,7 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> { let keep_selected = switch_or(p, "keepSelected", true, C)?; let filled = switch_or(p, "fill", false, C)?; if let Some(ext) = p.get("extend").filter(|v| !v.is_null()) { - let id = id_param(ext, "id").ok_or_else(|| bad(C, "extend needs id"))?; + let id = object_param(ext, "id", C)?.ok_or_else(|| bad(C, "extend needs id"))?; let at_start = str_param(ext, "end") == Some("start"); let (pd, _) = path_of(&s.doc()?.doc, id)?; let si = pd.subpaths.iter().rposition(|s| !s.closed && !s.anchors.is_empty()).ok_or_else(|| bad(C, "path has no open end"))?; @@ -179,7 +184,7 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> { // open subpath, that subpath starting at the end the stroke ends on, it ends at its end). let connect = match p.get("connect").filter(|v| !v.is_null()) { Some(cn) => { - let other = id_param(cn, "id").ok_or_else(|| bad(C, "connect needs id"))?; + let other = object_param(cn, "id", C)?.ok_or_else(|| bad(C, "connect needs id"))?; if other == id { return Err(bad(C, "connect needs a path other than the one extended")); } @@ -199,7 +204,9 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> { } None => None, }; - let close_tol = (tol * 4.0).max(6.0); + // An extending stroke that ends within four Fidelities of the path's other end closes it: + // at least 6 pt and at most 400 pt, whatever the Fidelity it is fitted at. + let close_tol = (tol * 4.0).clamp(6.0, 400.0); let closing = connect.is_none() && sp.anchors.len() >= 2 && pts.last().is_some_and(|p| p.distance(first) <= close_tol); if closing && let Some(l) = pts.last_mut() { *l = first; @@ -299,7 +306,7 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> { return Ok(json!({ "id": id.0 })); } if let Some(rd) = p.get("redraw").filter(|v| !v.is_null()) { - let id = id_param(rd, "id").ok_or_else(|| bad(C, "redraw needs id"))?; + let id = object_param(rd, "id", C)?.ok_or_else(|| bad(C, "redraw needs id"))?; let within = number_or(rd, "within", 12.0, C)?; if !within.is_finite() || within < 0.0 { return Err(bad(C, "redraw within must be a finite distance of 0 or more")); diff --git a/crates/engine/src/cmd/draw2/smooth.rs b/crates/engine/src/cmd/draw2/smooth.rs index d63bdaea77..0ac4fc8d6b 100644 --- a/crates/engine/src/cmd/draw2/smooth.rs +++ b/crates/engine/src/cmd/draw2/smooth.rs @@ -8,10 +8,22 @@ use super::{ // ---------- Smooth ---------- -/// Refit the anchors of an open run `a[lo..=hi]` keeping its end points and outer handles. -fn refit_run(anchors: &[Anchor], tol: f64) -> Vec<Anchor> { +/// The spread (points) of the Gaussian the Smooth tool smooths a path along its length with before +/// refitting it, as a share of the tool's reach: a third, so each point is averaged with the stretch +/// of path within the reach on either side of it. VectorCraft's own value. +const SMOOTH_SPREAD: f64 = 1.0 / 3.0; + +/// The options the Smooth tool refits with: the path smoothed along its length by a Gaussian of +/// spread `sigma` (none at 0), then refitted within `tol` of that and within twice the distance the +/// smoothing moved it, keeping a corner only where the path turns back on itself. +fn refit_options(tol: f64, sigma: f64) -> SimplifyOptions { + SimplifyOptions { tolerance: tol, corner_angle_deg: 179.0, straight_lines: false, smooth: sigma, smooth_moved_only: true } +} + +/// Smooth and refit the anchors of an open run `a[lo..=hi]` keeping its end points and outer handles. +fn refit_run(anchors: &[Anchor], tol: f64, sigma: f64) -> Vec<Anchor> { let piece = PathData::single(SubPath::new(anchors.to_vec(), false)); - let fitted = po::simplify_with(&piece, &SimplifyOptions { tolerance: tol, corner_angle_deg: 179.0, straight_lines: false, ..Default::default() }); + let fitted = po::simplify_with(&piece, &refit_options(tol, sigma)); let Some(mut out) = fitted.subpaths.into_iter().next().map(|s| s.anchors).filter(|a| a.len() >= 2) else { return anchors.to_vec() }; let (f, l) = (anchors[0], anchors[anchors.len() - 1]); let last = out.len() - 1; @@ -25,7 +37,7 @@ fn refit_run(anchors: &[Anchor], tol: f64) -> Vec<Anchor> { out } -fn smooth_subpath(sp: &SubPath, near: &dyn Fn(Point) -> bool, tol: f64) -> Option<SubPath> { +fn smooth_subpath(sp: &SubPath, near: &dyn Fn(Point) -> bool, tol: f64, sigma: f64) -> Option<SubPath> { let n = sp.anchors.len(); let marked: Vec<bool> = sp.anchors.iter().map(|a| near(a.p)).collect(); if n < 3 || !marked.iter().any(|m| *m) { @@ -33,11 +45,8 @@ fn smooth_subpath(sp: &SubPath, near: &dyn Fn(Point) -> bool, tol: f64) -> Optio } if sp.closed { let Some(k) = marked.iter().position(|m| !m) else { - // Everything is in range: smooth the whole closed path. - let f = po::simplify_with( - &PathData::single(sp.clone()), - &SimplifyOptions { tolerance: tol, corner_angle_deg: 179.0, straight_lines: false, ..Default::default() }, - ); + // Everything is in range: smooth the whole closed path, across its start too. + let f = po::simplify_with(&PathData::single(sp.clone()), &refit_options(tol, sigma)); return f.subpaths.into_iter().next(); }; // Rotate so an untouched anchor comes first, duplicate it at the end and treat as open. @@ -48,14 +57,14 @@ fn smooth_subpath(sp: &SubPath, near: &dyn Fn(Point) -> bool, tol: f64) -> Optio open.anchors.push(open.anchors[0]); m.push(false); open.closed = false; - let mut res = smooth_open(&open.anchors, &m, near, tol); + let mut res = smooth_open(&open.anchors, &m, near, tol, sigma); let l = res.pop()?; if let Some(r0) = res.first_mut() { r0.h_in = l.h_in; } return Some(SubPath::new(res, true)); } - Some(SubPath::new(smooth_open(&sp.anchors, &marked, near, tol), false)) + Some(SubPath::new(smooth_open(&sp.anchors, &marked, near, tol, sigma), false)) } /// The segment `c`, which ends in the drag's reach (`near`) and starts outside it, split where it @@ -84,10 +93,11 @@ fn split_at_reach(c: CubicBez, near: &dyn Fn(Point) -> bool) -> Option<(CubicBez (hi > 0.02).then(|| (part(0.0..hi), part(hi..1.0))) } -/// `anchors` with each run of `marked` ones refitted, together with the stretch of the segments -/// leading into the run that is in the drag's reach (`near`): a short drag smooths what is under -/// it, and the rest of a long segment next to it stays as it was (#1512). -fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool, tol: f64) -> Vec<Anchor> { +/// `anchors` with each run of `marked` ones smoothed by a Gaussian of spread `sigma` and refitted +/// within `tol`, together with the stretch of the segments leading into the run that is in the +/// drag's reach (`near`): a short drag smooths what is under it, and the rest of a long segment next +/// to it stays as it was (#1512). +fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool, tol: f64, sigma: f64) -> Vec<Anchor> { let n = anchors.len(); let mut runs = vec![]; let mut i = 0; @@ -127,7 +137,7 @@ fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool head = Some(Anchor { h_out: far.p1, ..*outer }); *outer = Anchor::with_handles(far.p3, far.p2, reach.p1); } - let new = refit_run(&piece, tol); + let new = refit_run(&piece, tol, sigma); out.splice(lo..=hi, head.into_iter().chain(new).chain(tail)); } out @@ -138,6 +148,7 @@ pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result<Value> { let pts = points_param(p, "points", C)?; let radius = number_or(p, "radius", 12.0, C)?.max(0.0); let tol = number_or(p, "fidelity", 2.5, C)?.clamp(vectorcraft_tools::draw2::SMOOTH_MIN_FIDELITY, 100.0); + let sigma = radius * SMOOTH_SPREAD; let st = s.doc()?; let near = |q: Point| dist_to_polyline(&pts, q) <= radius; let mut plan = vec![]; @@ -148,7 +159,7 @@ pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result<Value> { let subs: Vec<SubPath> = pd .subpaths .iter() - .map(|sp| match smooth_subpath(sp, &near, tol) { + .map(|sp| match smooth_subpath(sp, &near, tol, sigma) { Some(n) if n != *sp && n.anchors.len() >= 2 => { changed = true; n @@ -167,9 +178,13 @@ pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result<Value> { return Ok(json!({ "ids": [], "before": 0, "after": 0 })); } let ids: Vec<NodeId> = plan.iter().map(|(id, _)| *id).collect(); - s.edit("Smooth", |d, _| { + s.edit("Smooth", |d, sel| { for (id, np) in plan { *path_mut(d, id)? = np; + // The smoothed path has new anchors, so the old anchor and segment indices are + // dropped and the path stays selected whole. + sel.anchors.remove(&id); + sel.segments.remove(&id); } Ok(()) })?; diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 26d0f4d247..990ac1a1c6 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1,6 +1,6 @@ //! File (document-level) and Edit commands, plus document queries. -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::{BTreeMap, BTreeSet, HashMap}; use std::sync::Arc; use serde_json::{Value, json}; @@ -9,11 +9,11 @@ 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, 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, + CommandSpec, Result, Session, always, bad, can_clear_history, can_redo, can_undo, check_numbers, checked_ids_param, clock_date, cmd, date_param, + f64_req, finite_numbers, has_clipboard, has_doc, has_selection, has_selection_guides_or_artboard_tool, has_selection_or_guides, index, number_or, + object_param, ok, point_param, str_param, switch_or, }; -use crate::{Clipboard, EngineError, inspect}; +use crate::{Clipboard, EngineError, SourceLayer, inspect}; /// Register editing commands, including document-to-document artwork drops and their parameter contracts. pub fn specs() -> Vec<CommandSpec> { @@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> { "New…", ["File"], None, - "{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792, units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode}; the size is remembered in file.newPresets' Recent", + "{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent", always, super::newdoc::file_new ), @@ -38,7 +38,7 @@ pub fn specs() -> Vec<CommandSpec> { has_doc, doc_move ), - 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.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)} → path (the document's file; null when automation read roots are in force and the file is outside them), 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!( @@ -50,7 +50,11 @@ pub fn specs() -> Vec<CommandSpec> { 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!(query "document.json", "Document JSON", [], None, "{} → complete document model (with automation read roots, a linked or placed file outside them is named by its file name alone, without its relative path, size or date, in brush art too, and so are a data set's image value and a linked JavaScript file in svg_scripts outside them (a URL is kept); a relative path that leads outside them is left out; a stored brush entry that does not read as a brush is left out; a folder outside them is left out of export_settings)", has_doc, |s, _| { + let st = s.doc()?; + let d = super::links::with_hidden_paths_named(&st.doc, super::links::LinkBase::of(st)); + Ok(serde_json::to_value(&*d).unwrap_or(Value::Null)) + }), cmd!( "document.setUnits", "Units", @@ -175,7 +179,7 @@ pub fn specs() -> Vec<CommandSpec> { "Paste", ["Edit"], Some("Cmd+V"), - "{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers they came from (by name; made when missing). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}", + "{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}", has_clipboard, |s, p| paste(s, p, PasteMode::Offset) ), @@ -237,7 +241,7 @@ pub fn specs() -> Vec<CommandSpec> { } fn file_close(s: &mut Session, p: &Value) -> Result<Value> { - let i = p.get("index").and_then(Value::as_u64).map(index).or(s.active_index()).ok_or(EngineError::NoDocument)?; + let i = opt_u64(p, "file.close", "index")?.map(index).or(s.active_index()).ok_or(EngineError::NoDocument)?; if !s.close_document(i) { return Err(bad("file.close", "no such document")); } @@ -267,9 +271,9 @@ fn doc_move(s: &mut Session, p: &Value) -> Result<Value> { } fn doc_node(s: &mut Session, p: &Value) -> Result<Value> { - let id = id_param(p, "id").ok_or_else(|| bad("document.node", "missing id"))?; + let id = object_param(p, "id", "document.node")?.ok_or_else(|| bad("document.node", "missing id"))?; let mut opts = slice_opts(p, "document.node")?; - let summary = bool_or(p, "summary", false); + let summary = switch_or(p, "summary", false, "document.node")?; if !summary && (opts.depth.is_some() || opts.child_limit.is_some()) { // The full object JSON is never truncated: a slice without `summary` would // otherwise silently return the whole subtree. @@ -663,7 +667,8 @@ fn undo_group_begin(s: &mut Session, p: &Value) -> Result<Value> { } fn undo_group_end(s: &mut Session, p: &Value) -> Result<Value> { - s.end_undo_group(bool_or(p, "cancel", false)); + let cancel = switch_or(p, "cancel", false, "edit.undoGroup.end")?; + s.end_undo_group(cancel); ok() } @@ -672,10 +677,24 @@ fn undo_group_end(s: &mut Session, p: &Value) -> Result<Value> { /// the step before. As any new edit it ends the steps to redo, so Redo never swaps the document /// under an interaction that would then preview on, or cancel to, the document from before (#1719). /// A typing session also ends in the Type tool, whose caret and marked text (IME) must follow the -/// document. +/// document. A preview that Real-time Drawing off left unapplied is applied first, as the tool's own +/// commit applies it; when it fails, the interaction is canceled. The applied preview's warning +/// goes to the running command's result or the tool's status messages, as the tool's own commit +/// reports it ([`Session::note_settled_warning`]). pub(crate) fn settle_interaction(s: &mut Session) -> Result<()> { let typing = typing_in_progress(s); - s.commit_interaction()?; + match s.unapplied_interaction_preview().filter(|_| !s.previewing) { + Some((cmd, p)) => match s.preview(&cmd, &p) { + Ok(v) => { + if let Some(w) = v.get("warning").and_then(Value::as_str) { + s.note_settled_warning(w); + } + s.commit_interaction()? + } + Err(_) => s.cancel_interaction()?, + }, + None => s.commit_interaction()?, + } if typing { s.set_tool_option("endTyping", &Value::Bool(true)); } @@ -1077,7 +1096,7 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> { subpaths.extend(super::path::without_segments(sp, &cuts)); } else { // Picked anchors leave the path with their connections, as Clear removes them. - let gone: BTreeSet<usize> = anchor_refs.into_iter().flatten().filter_map(|&(s, a)| (s == si).then_some(a)).collect(); + let gone: BTreeSet<usize> = anchor_refs.into_iter().flat_map(|refs| super::path::subpath_refs(refs, si)).collect(); subpaths.extend(super::path::without_anchors(sp, &gone)); } } @@ -1231,6 +1250,9 @@ impl PasteMode { fn paste(s: &mut Session, p: &Value, mode: PasteMode) -> Result<Value> { let choices = SwatchChoices::parse(mode.label(), p)?; + if mode == PasteMode::Offset { + check_numbers(p, &["dx", "dy"], "edit.paste")?; + } // Taken out of the session for the edit (and put back whatever happens). let clip = std::mem::take(&mut s.clipboard); let r = paste_clip(s, p, mode, &clip, &choices); @@ -1368,6 +1390,9 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho && inside.is_none() && (st.doc.paste_remembers_layers || boards.is_some()) && parent.is_some_and(|p| st.doc.node(p).is_some_and(Node::is_layer)); + // Each object's remembered layer, found before anything is pasted: a hidden or locked one + // refuses the whole paste. + let remembered = if remember { remembered_layers(&st.doc, &clip.source_layers, same_doc)? } else { vec![] }; // Front/back: relative to the selection (top-most / bottom-most selected object); with // nothing selected, the top / bottom of the current layer. Art other than paths goes beside // the compound path that holds the selected object, not into it. @@ -1385,7 +1410,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho (_, Some((_, dv))) => vec![Affine::translate(dv)], (PasteMode::Offset | PasteMode::Library | PasteMode::Drag, None) => vec![match point_param(p, "center") { Some(c) => clip.bounds().map_or(Affine::IDENTITY, |b| Affine::translate(c - b.center())), - None => Affine::translate((f64_or(p, "dx", off), f64_or(p, "dy", off))), + None => Affine::translate((number_or(p, "dx", off, mode.label())?, number_or(p, "dy", off, mode.label())?)), }], (PasteMode::AllArtboards, None) => { let src = clip.source_artboard.or_else(|| st.doc.artboards.first().map(|a| a.rect)).map(|r| r.origin()).unwrap_or_default(); @@ -1411,7 +1436,8 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho .flat_map(|(all, dv)| all.iter().map(move |a| (a, dv))) .map(|(a, dv)| super::panelcmds::push_artboard_copy(d, a, a.rect + dv)) .collect(); - let mut layers: BTreeMap<&str, NodeId> = BTreeMap::new(); + // The layers made for remembered layers the document lacks, by parent and name. + let mut made = HashMap::new(); // Objects pasted into each parent so far (keeps their order in front and back pastes). let mut placed: BTreeMap<Option<NodeId>, usize> = BTreeMap::new(); let mut new_ids = vec![]; @@ -1425,8 +1451,9 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho // including the pattern phase, independently of transform-tool settings. 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))), + let layer = match remembered.get(k) { + Some(Some(Remembered::Layer(l))) => Some(*l), + Some(Some(Remembered::Make { parent, names })) => make_layers(d, &mut made, *parent, names)?, _ => None, }; // In a clip group or a clipping layer the bottom child is the clipping path: art pasted @@ -1545,23 +1572,117 @@ fn paste_anchor(doc: &Document, id: NodeId, can_enter_compound: bool) -> NodeId } } -/// The first unlocked layer or sublayer called `name` (topmost first), or a new top layer. -fn layer_named(d: &mut Document, name: &str) -> NodeId { - let mut found = None; - for l in d.layers.iter().rev() { - l.walk(&mut |n| { - if found.is_none() && n.is_layer() && !n.locked && n.name.as_deref() == Some(name) { - found = Some(n.id); +/// Where Paste Remembers Layers puts an object: a layer or sublayer of the document, or new +/// layers `names`, each inside the one before, the first under `parent` (none: on top). +#[derive(Clone, Debug, PartialEq)] +enum Remembered { + Layer(NodeId), + Make { parent: Option<NodeId>, names: Vec<String> }, +} + +/// [`remembered_layer`] for each object's source layer, worked out once for each layer. +fn remembered_layers(d: &Document, sources: &[Option<SourceLayer>], same_doc: bool) -> Result<Vec<Option<Remembered>>> { + let mut found: HashMap<&SourceLayer, Remembered> = HashMap::new(); + sources + .iter() + .map(|src| { + let Some(src) = src else { return Ok(None) }; + if let Some(r) = found.get(src) { + return Ok(Some(r.clone())); } - }); + let r = remembered_layer(d, src, same_doc)?; + found.insert(src, r.clone()); + Ok(Some(r)) + }) + .collect() +} + +/// The layer `src` names in `d`. In the document it was copied from, the layer that held the +/// object is kept while it is there with its name, wherever it was moved; else the layers around +/// it still where they were (by id) are kept. Below them, and in another document from the top, +/// each name is matched among the layers inside the one above (the topmost of the same name whose +/// layers match the most names, a shown and unlocked one first). The names left unmatched are +/// made. A matched layer that is hidden or locked, or inside one that is, is an error. +fn remembered_layer(d: &Document, src: &SourceLayer, same_doc: bool) -> Result<Remembered> { + let held = |id: &NodeId| d.node(*id).is_some_and(|n| n.is_layer() && n.name.as_ref() == src.names.last()); + let kept = if same_doc && src.ids.last().is_some_and(held) { + src.ids.len() + } else if same_doc { + (1..=src.ids.len()) + .rev() + .find(|&j| d.node(src.ids[j - 1]).is_some_and(Node::is_layer) && d.ancestry(src.ids[j - 1]).is_some_and(|a| a == src.ids[..j])) + .unwrap_or(0) + } else { + 0 + }; + let rest = &src.names[kept..]; + let (end, matched, _) = named_chain(d, kept.checked_sub(1).map(|j| src.ids[j]), rest); + if let Some(l) = end + && !d.ancestry(l).is_some_and(|a| a.iter().all(|i| d.node(*i).is_some_and(|n| n.visible && !n.locked))) + { + return Err(EngineError::Other("the target layer is locked or hidden".into())); } - found.unwrap_or_else(|| d.add_layer(Some(name))) + Ok(match end { + Some(l) if matched == rest.len() => Remembered::Layer(l), + parent => Remembered::Make { parent, names: rest[matched..].to_vec() }, + }) +} + +/// The deepest chain of layers inside `parent` (none: the top level) named `names` one inside the +/// other: its last layer (`parent` when none matches), how many names it matched and whether all +/// its layers are shown and unlocked. Of chains as deep, the topmost shown and unlocked one wins. +fn named_chain(d: &Document, parent: Option<NodeId>, names: &[String]) -> (Option<NodeId>, usize, bool) { + let mut best = (parent, 0, true); + let Some((name, rest)) = names.split_first() else { return best }; + let siblings = match parent { + None => Some(&d.layers), + Some(p) => d.node(p).and_then(Node::children), + }; + for l in siblings.into_iter().flatten().rev().filter(|l| l.is_layer() && l.name.as_deref() == Some(name.as_str())) { + let (end, n, open) = named_chain(d, Some(l.id), rest); + let chain = (end, n + 1, open && l.visible && !l.locked); + if (chain.1, chain.2) > (best.1, best.2) { + best = chain; + } + } + best +} + +/// Layers `names`, each inside the one before, the first under `parent` (none: on top); `made` +/// keeps the ones a paste has made, by parent and name, so they are made once. The last one, or +/// none when `names` is empty. +fn make_layers( + d: &mut Document, + made: &mut HashMap<(Option<NodeId>, String), NodeId>, + parent: Option<NodeId>, + names: &[String], +) -> Result<Option<NodeId>> { + let mut at = parent; + for name in names { + let key = (at, name.clone()); + let id = match made.get(&key) { + Some(id) => *id, + None => { + let id = match at { + None => d.add_layer(Some(name)), + Some(p) => { + let layer = super::layer::make_layer(d, Some(name)); + d.insert(Some(p), usize::MAX, layer)? + } + }; + made.insert(key, id); + id + } + }; + at = Some(id); + } + Ok(at.filter(|_| !names.is_empty())) } fn duplicate(s: &mut Session, p: &Value) -> Result<Value> { let roots = selected_roots(s)?; - let dx = f64_or(p, "dx", 0.0); - let dy = f64_or(p, "dy", 0.0); + let dx = number_or(p, "dx", 0.0, "edit.duplicate")?; + let dy = number_or(p, "dy", 0.0, "edit.duplicate")?; let ids = s.edit("Duplicate", |d, sel| duplicate_in(d, sel, &roots, Affine::translate((dx, dy))))?; Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() })) } diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index 30d927a966..17fcb63fe2 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -16,7 +16,7 @@ use vectorcraft_render::effects; use super::appearance::{ItemTarget, aligned, appearance_targets, index_param, item_indices, item_target, item_target_at}; 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}; +use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, check_switches, 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 @@ -34,8 +34,15 @@ fn svg_filter_name(s: &Session, xml: &str, cmd: &str) -> Result<String> { Ok(name) } -/// The effect commands of the Effect menu and the Appearance panel. +/// The effect commands of the Effect menu and the Appearance panel, and the 3D and Materials +/// panel's Graphics. pub fn specs() -> Vec<CommandSpec> { + let mut specs = effect_specs(); + specs.extend(graphics::specs()); + specs +} + +fn effect_specs() -> Vec<CommandSpec> { vec![ cmd!( "effect.apply", @@ -69,7 +76,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), 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}", + "{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; params are checked against the new style), 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 (any other value but null is refused, when a step plays too), 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 ), @@ -78,7 +85,7 @@ pub fn specs() -> Vec<CommandSpec> { "3D Lighting Preset", [], None, - "{index: int, preset: standard|diffuse|topLeft|right, item?: appearance item index|null (omitted: the active item, else the object's), 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)} replace an applied 3D effect's light rig and ambient with an original lighting preset; preserve shading, geometry and view; all targets must have a 3D effect at index other than Extrude & Bevel (Classic), which has no lighting presets; one undo step → {ids}", + "{index: int, preset: standard|diffuse|topLeft|right, item?: appearance item index|null (omitted: the active item, else the object's), 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)} replace an applied 3D effect's light rig and ambient with an original lighting preset; preserve shading, geometry and view; all targets must have a 3D effect at index other than Extrude & Bevel (Classic), Revolve (Classic) or Rotate (Classic), which have no lighting presets; one undo step → {ids}", has_doc, lighting_preset ), @@ -87,7 +94,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 becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. 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)}", + "{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; a symbol instance whose topmost fill or stroke is visible, has an opacity above 0 and has a geometry effect becomes a group of its art, that fill's effects reshaping the art's filled shapes and that stroke's effects reshaping its stroked shapes, as the canvas draws them. 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 becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. 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 ), @@ -123,7 +130,7 @@ pub fn specs() -> Vec<CommandSpec> { "Refresh Deferred Effects", ["Effect"], None, - "{ids?: [object id] (objects of the document; `id` names one; default: every object with a deferred stage)} run the deferred live-effect plug-in stages of those objects again (effect.deferredStatus), sharing a fresh 2,000 ms budget; a stage that gives a result is drawn with it; not an undo step. Enabled when a stage is deferred → {refreshed, stillDeferred (left out for want of time again, or not reached because the object, or a group or layer holding it, is hidden, or with a part of its input too small for the refresh's drawing), failed (timed out, failed or has no plug-in)}", + "{ids?|id?: [object id] (objects of the document, also in the art of a symbol, pattern, brush or opacity mask; an object without a deferred stage adds nothing; an id of no object is an error; `id` names one; default: every object with a deferred stage)} run the deferred live-effect plug-in stages of those objects again (effect.deferredStatus), sharing a fresh 2,000 ms budget; a stage that gives a result is drawn with it; not an undo step. Enabled when a stage is deferred → {refreshed, stillDeferred (left out for want of time again, or not reached because the object, or a group or layer holding it, is hidden, or with a part of its input too small for the refresh's drawing), failed (timed out, failed or has no plug-in)}", has_deferred, refresh_deferred ), @@ -150,16 +157,27 @@ fn stage_objects(d: &Document, fx: &vectorcraft_plugins::deferred::Deferrals) -> None => rest.push(object), } } - if rest.is_empty() { + for (id, n) in definition_objects(d, &rest) { + out.entry(id).or_insert((n, false)); + } + out +} + +/// The objects of `ids` found in the art `d` draws from outside its layers: the art of its +/// symbols, patterns and brushes, and opacity masks (in that art or in the layers). +fn definition_objects(d: &Document, ids: &[u64]) -> std::collections::HashMap<u64, Arc<Node>> { + let mut out = std::collections::HashMap::new(); + if ids.is_empty() { return out; } + let ids: std::collections::HashSet<u64> = ids.iter().copied().collect(); let brushes = vectorcraft_brush::library(d); let symbols = d.symbols.iter().map(|s| &*s.art); let patterns = d.patterns.iter().flat_map(|p| p.art.iter().map(|a| &**a)); let layers = d.layers.iter().map(|a| &**a); let mut look = |n: &Node| { - if rest.contains(&n.id.0) { - out.entry(n.id.0).or_insert_with(|| (Arc::new(n.clone()), false)); + if ids.contains(&n.id.0) { + out.entry(n.id.0).or_insert_with(|| Arc::new(n.clone())); } }; for a in symbols.chain(patterns).chain(brushes.iter().flat_map(|b| b.art())).chain(layers) { @@ -231,10 +249,19 @@ fn refresh_deferred(s: &mut Session, p: &Value) -> Result<Value> { let (doc, fx) = (st.doc.clone(), st.plugin_effects.clone()); let ids = super::named_ids(p)?; let objects = prune(&doc, &fx); - if let Some(id) = ids.iter().flatten().find(|id| doc.node(**id).is_none() && !objects.contains_key(&id.0)) { - return Err(EngineError::NoNode(*id)); + // An object of the art drawn outside the layers is valid whether or not it has a stage. + let elsewhere: Vec<u64> = ids.iter().flatten().filter(|id| doc.node(**id).is_none() && !objects.contains_key(&id.0)).map(|id| id.0).collect(); + let found = definition_objects(&doc, &elsewhere); + if let Some(id) = elsewhere.iter().find(|id| !found.contains_key(id)) { + return Err(EngineError::NoNode(NodeId(*id))); } - let ids: Option<Vec<u64>> = ids.map(|ids| ids.iter().map(|id| id.0).collect()); + // Only the objects with a stage have anything to refresh. + let ids: Option<Vec<u64>> = ids.map(|ids| { + let mut ids: Vec<u64> = ids.iter().map(|id| id.0).filter(|id| objects.contains_key(id)).collect(); + ids.sort_unstable(); + ids.dedup(); + ids + }); let counts = fx.refresh(ids.as_deref(), |targets| { let mut renderer = vectorcraft_render::Renderer::new(); let mut whole = Vec::new(); @@ -430,10 +457,14 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> { for (target, at) in targets.iter().copied().zip(item.per_target(s, &targets)) { let d = &s.doc()?.doc; let n = d.node(target).ok_or(EngineError::NoNode(target))?; - // A new effect goes after the item's others. + // A new effect goes after the item's (or the object's) others. let on = at.and_then(|at| at.effects_item(&n.appearance, C).ok()).flatten(); - let on = on.and_then(|i| Some((i, n.appearance.items.get(i)?.effects().len()))); + let on = on.and_then(|i| Some((Some(i), n.appearance.items.get(i)?.effects().len()))); + let on = on.unwrap_or((None, n.appearance.effects.len())); effects::validate_three_d_at_in(Some(d), n, id, &effect.params, on).map_err(|e| bad(C, e))?; + if let Some(name) = effects::missing_symbol(d, &effect.params, None) { + return Err(bad(C, format!("no symbol named `{name}`"))); + } if id == effects::REVOLVE && effects::has_revolve(n) { return Err(bad(C, "A profile supports one Revolve effect. Edit the existing effect's options instead.")); } @@ -619,15 +650,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![] }; - // A 3D effect whose type `threeDType` changes takes the new effect's parameters. + // A 3D effect whose type `threeDType` changes, and a Warp whose style `warpStyle` changes, take + // the new effect's parameters. let kind = three_d_type(p, C).ok().flatten(); + let warp = p.get("warpStyle").and_then(Value::as_str).filter(|style| effects::WarpStyle::from_id(style).is_some()); 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)) + Some(edited_effect_id(id, kind, warp)) }; targets.iter().filter_map(effect).collect() } +/// The id effect `id` has once `effect.setParams` sets its 3D type to `kind` or its Warp style to +/// `warp` (each when given and when `id` is an effect of that family). +fn edited_effect_id(id: &str, kind: Option<&str>, warp: Option<&str>) -> String { + let is_warp = id.strip_prefix("warp.").and_then(effects::WarpStyle::from_id).is_some(); + match (kind, warp) { + (Some(to), _) if effects::is_three_d(id) => to.to_string(), + (_, Some(style)) if is_warp => format!("warp.{style}"), + _ => id.to_string(), + } +} + /// 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"; @@ -656,12 +700,10 @@ fn lighting_preset(s: &mut Session, p: &Value) -> Result<Value> { if !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))); } - // Extrude & Bevel (Classic) has no lighting presets; its lights are set in its own options. - if effect.is_some_and(|e| e.id == effects::CLASSIC_EXTRUDE) { - return Err(bad( - C, - format!("object {}: Extrude & Bevel (Classic) at index {index} has no lighting presets; set its lights with effect.setParams", id.0), - )); + // The classic 3D effects have no lighting presets; their lights are set in their own options. + if let Some(e) = effect.filter(|e| effects::is_classic_three_d(&e.id)) { + let name = effects::effect_info(&e.id).map_or("This effect", |info| info.label.trim_end_matches('…')); + return Err(bad(C, format!("object {}: {name} at index {index} has no lighting presets; set its lights with effect.setParams", id.0))); } } let mut options = p.clone(); @@ -690,6 +732,7 @@ fn set_params(s: &mut Session, p: &Value) -> Result<Value> { Ok(format!("warp.{style}")) }) .transpose()?; + check_switches(p, &["visible"], C)?; let visible = p.get("visible").and_then(Value::as_bool); let item = item_target(s, p, C)?; let edited = set_params_effects(s, p); @@ -740,8 +783,11 @@ fn set_params(s: &mut Session, p: &Value) -> Result<Value> { if let (Some(cur), Value::Object(new)) = (prospective.as_object_mut(), effects::upgrade_params(to, ¶ms)) { cur.extend(new); } + if let Some(name) = effects::missing_symbol(d, &prospective, Some(&e.params)) { + return Err(bad(C, format!("no symbol named `{name}`"))); + } if visible != Some(false) { - effects::validate_three_d_at_in(Some(d), n, to, &prospective, target.map(|item| (item, index))).map_err(|e| bad(C, e))?; + effects::validate_three_d_at_in(Some(d), n, to, &prospective, (target, index)).map_err(|e| bad(C, e))?; } else { // Hidden, the effect draws nothing, so its object need not fit. The values given are // checked, and after a change of 3D type so is every value it keeps. @@ -817,8 +863,9 @@ fn load_texture(params: &mut Value, cmd: &str) -> Result<()> { /// Has `n` an appearance Expand Appearance turns into objects: a path that isn't basic (several /// fills or strokes, effects, transparency of a fill or stroke, a brush), a group or layer with -/// fills, strokes or effects of its own or such members, other objects with effects, or type with -/// fills or strokes of its own? +/// fills, strokes or effects of its own or such members, other objects with effects, type with +/// fills or strokes of its own, or a symbol instance whose active fill or stroke has a geometry +/// effect ([`effects::has_item_geometry`])? pub(crate) fn expandable(n: &Node) -> bool { expandable_except(n, &[]) } @@ -835,7 +882,7 @@ pub(crate) fn expandable_except(n: &Node, skip: &[NodeId]) -> bool { !n.appearance.items.is_empty() || !n.appearance.effects.is_empty() || children.iter().any(|c| expandable_except(c, skip)) } NodeKind::Text(_) => !n.appearance.items.is_empty() || !n.appearance.effects.is_empty(), - NodeKind::Image(_) => effects::has_item_geometry(n) || !n.appearance.effects.is_empty(), + NodeKind::Image(_) | NodeKind::SymbolInstance { .. } => effects::has_item_geometry(n) || !n.appearance.effects.is_empty(), _ => !n.appearance.effects.is_empty(), } } @@ -908,6 +955,38 @@ fn expand_pieces( expanded } +/// Replace each symbol instance in `m`, art an instance placed (`depth` instances deep), whose +/// active fill or stroke has a geometry effect ([`effects::has_item_geometry`]) by its art as +/// [`effects::expand_outlined`] makes it, and the instances in that art in turn, so +/// [`expand_pieces`] bakes their effects with the rest. An instance stays as it is when it is more +/// than [`vectorcraft_doc::depth::MAX_DEPTH`] instances deep, its symbol is missing, or its art +/// would take the objects placed so far past `budget`. +fn expand_nested_instances(d: &Document, m: &mut Node, depth: usize, budget: &mut u64) { + for c in m.children_mut().into_iter().flatten() { + if !matches!(c.kind, NodeKind::SymbolInstance { .. }) { + if c.children().is_some() { + expand_nested_instances(d, Arc::make_mut(c), depth, budget); + } + continue; + } + let NodeKind::SymbolInstance { symbol, .. } = &c.kind else { continue }; + if depth >= vectorcraft_doc::depth::MAX_DEPTH || !effects::has_item_geometry(c) { + continue; + } + let Some(sym) = d.symbols.iter().find(|s| s.name == *symbol) else { continue }; + let count = sym.art.count() as u64; + if count > *budget { + continue; + } + *budget -= count; + let art = vectorcraft_render::instance_art(&sym.art, c); + if let Some(mut a) = effects::expand_outlined(Some(d), c, Some(&art)) { + expand_nested_instances(d, &mut a, depth + 1, budget); + *c = Arc::new(a); + } + } +} + /// Does `n` hold an id of `seen`, or one id twice: does [`effects::fresh_ids`] give it new ids? fn repeats_an_id(n: &Node, seen: &std::collections::HashSet<NodeId>) -> bool { let mut ids = std::collections::HashSet::new(); @@ -1063,6 +1142,8 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br _ => None, }; effects::expand_outlined(Some(&*d), &v, symbol.as_ref()).map(|mut m| { + let mut budget = vectorcraft_doc::MAX_SYMBOL_NODES; + expand_nested_instances(d, &mut m, 1, &mut budget); expand_pieces(d, &mut m, true, brushes, &mut stroke_art); m }) @@ -1183,6 +1264,8 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> { Ok(out) } +mod graphics; + #[cfg(test)] mod lighting_presets_tests; diff --git a/crates/engine/src/cmd/effectcmd/graphics.rs b/crates/engine/src/cmd/effectcmd/graphics.rs new file mode 100644 index 0000000000..3f95ae0518 --- /dev/null +++ b/crates/engine/src/cmd/effectcmd/graphics.rs @@ -0,0 +1,153 @@ +//! Window › 3D and Materials › Materials › Graphics: art kept as a document symbol (Add as Single +//! Graphic) and mapped onto 3D objects (Extrude & Bevel's caps, a plane, Revolve's side). The +//! graphics an object shows are the `graphics` parameter of its 3D effect, which `effect.setParams` +//! also edits. + +use serde_json::{Map, Value, json}; +use vectorcraft_doc::{Effect, Node}; +use vectorcraft_render::effects; + +use super::super::appearance::{appearance_targets, index_param, item_target}; +use super::super::brushsym::{normalize, selection_art, store_symbol}; +use super::super::{CommandSpec, EngineError, NodeId, Result, Session, bad, cmd, has_doc, has_selection, str_param}; +use super::{effect_targets, ids_json}; + +pub(super) fn specs() -> Vec<CommandSpec> { + vec![ + cmd!( + "threeD.addGraphic", + "Add as Single Graphic", + [], + None, + "{name?: string (default Graphic; made unique), ids?|id?} keep the selection's art as a new document symbol, listed among the 3D and Materials panel's Graphics; the selection stays as it is → {name}", + has_selection, + add_graphic + ), + cmd!( + "threeD.mapGraphic", + "Map Graphic", + [], + None, + "{symbol: name of a document symbol, face?: front|back (front; Plane has only a front; the back reads left to right as seen from behind; on Revolve the front is its swept side, which is the only face), x?: pt, y?: pt (0, 0: the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on Revolve from the middle of the side unrolled flat, x around the axis and y along the profile), scale?: % (1..10000; default 100, or less so the graphic fits inside the object, on Revolve inside the half of the side seen from the front), rotation?: degrees (-360..360, 0; counterclockwise), index?: int (the 3D effect's position; default: each object's first 3D effect, its own before its fills' and strokes'), item?: appearance item index|null (refused without index; as effect.setParams), ids?|id?} add a graphic to the 3D effect of each selected object, drawn on that face turned, foreshortened and shaded with it and clipped to it (on Revolve wrapped around the side, and drawn only where its outside faces the viewer); every object's 3D effect must be Extrude & Bevel (on a solid cap), Rotate (the Plane type) or Revolve; one undo step → {ids, graphic}", + has_doc, + map_graphic + ), + ] +} + +/// `threeD.addGraphic`: stores the selection's art as a symbol without replacing it with an +/// instance. +fn add_graphic(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "threeD.addGraphic"; + if let Some(key) = p.as_object().and_then(|m| m.keys().find(|k| !["name", "ids", "id"].contains(&k.as_str()))) { + return Err(bad(C, format!("unknown parameter `{key}`"))); + } + if p.get("name").is_some_and(|v| v.as_str().is_none_or(|n| n.trim().is_empty())) { + return Err(bad(C, "`name` must be a name that is not empty")); + } + let mut art = selection_art(s, p)?.ok_or_else(|| EngineError::Other("nothing selected".into()))?; + crate::cmd::threads::keep_shown_text(&s.doc()?.doc, &mut art); + let (art, size, _) = normalize(art)?; + let name = s.doc()?.doc.unique_symbol_name(str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).unwrap_or("Graphic")); + s.edit("Add as Single Graphic", |d, _| { + store_symbol(d, &art, &name, size); + Ok(()) + })?; + Ok(json!({ "name": name })) +} + +/// The 3D effect of `n` that a graphic goes on when none is named: its own first, then its fills' +/// and strokes', as the 3D and Materials panel finds it. +fn first_three_d(n: &Node) -> Option<(Option<usize>, usize)> { + let at = |fx: &[Effect]| fx.iter().position(|e| effects::is_three_d(&e.id)); + at(&n.appearance.effects) + .map(|i| (None, i)) + .or_else(|| n.appearance.items.iter().enumerate().find_map(|(k, item)| at(item.effects()).map(|i| (Some(k), i)))) +} + +/// `threeD.mapGraphic`: appends a graphic to the 3D effect of each target, after checking that every +/// target takes it. +fn map_graphic(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "threeD.mapGraphic"; + const KEYS: [&str; 10] = ["symbol", "face", "x", "y", "scale", "rotation", "index", "item", "ids", "id"]; + if let Some(key) = p.as_object().and_then(|m| m.keys().find(|k| !KEYS.contains(&k.as_str()))) { + return Err(bad(C, format!("unknown parameter `{key}`"))); + } + // An item names where the effect is in that item's list, so it takes an index too. + if p.get("item").is_some() && p.get("index").is_none() { + return Err(bad(C, "`item` needs `index`")); + } + // The graphic's own settings, checked as the effect checks them. + let mut given = Map::new(); + for key in ["symbol", "face", "x", "y", "scale", "rotation"] { + if let Some(v) = p.get(key) { + given.insert(key.into(), v.clone()); + } + } + let base = effects::MappedGraphic::from_value(&Value::Object(given)).map_err(|e| bad(C, e))?; + let d = &s.doc()?.doc; + if !d.symbols.iter().any(|sym| sym.name == base.symbol) { + return Err(bad(C, format!("no symbol named `{}`", base.symbol))); + } + let targets: Vec<(NodeId, Option<usize>, usize)> = if p.get("index").is_some() { + let index = index_param(p, "index", C)?; + let item = item_target(s, p, C)?; + effect_targets(s, p, item, index, C)? + } else { + let mut out = vec![]; + for id in appearance_targets(s, p)? { + let (item, index) = d.node(id).and_then(first_three_d).ok_or_else(|| bad(C, format!("object {} needs a 3D effect", id.0)))?; + out.push((id, item, index)); + } + out + }; + if targets.is_empty() { + return Err(bad(C, "select an object with a 3D effect")); + } + let mut edits = Vec::with_capacity(targets.len()); + for &(id, item, index) in &targets { + let n = d.node(id).ok_or(EngineError::NoNode(id))?; + let Some(effect) = n.appearance.effects_at(item).and_then(|fx| fx.get(index)).filter(|e| effects::is_three_d(&e.id)) else { + return Err(bad(C, format!("object {} needs a 3D effect at index {index}", id.0))); + }; + if !effects::takes_graphics(&effect.id) { + return Err(bad(C, format!("object {}: {}", id.0, effects::GRAPHICS_NOT_TAKEN))); + } + // A hollow Extrude & Bevel keeps the graphics it has, to show when Cap is turned on again, + // but has no cap to show a new one on. + let merged = effects::merged_params(&effect.id, &effect.params); + let extrude = (effect.id == effects::EXTRUDE).then(|| effects::extrude_options(&merged)); + if extrude.is_some_and(|o| o.depth > 0.0 && !o.cap) { + return Err(bad(C, format!("object {}: a hollow Extrude & Bevel has no caps: turn on Cap to map a graphic", id.0))); + } + // With a depth of 0 the art is a plane, which has only a front. + if base.face == effects::PlanarFace::Back && extrude.is_some_and(|o| o.depth <= 0.0) { + return Err(bad(C, format!("object {}: with a depth of 0 the object has one face: map its graphics onto the front", id.0))); + } + let mut graphic = base.clone(); + if p.get("scale").is_none() + && let (Some(frame), Some(art)) = (effects::graphic_frame_at(Some(d), n, item, index), effects::graphic_bounds(d, &graphic.symbol)) + { + graphic.scale = frame.fitting_scale(art); + } + let params = effects::with_graphic(&effects::merged_params(&effect.id, &effect.params), &graphic); + effects::validate_three_d_at_in(Some(d), n, &effect.id, ¶ms, (item, index)).map_err(|e| bad(C, e))?; + edits.push((id, item, index, graphic)); + } + let first = edits.first().map(|(.., g)| g.to_value()); + let ids = s.edit("Map Graphic", |d, _| { + let mut done = vec![]; + for (id, item, index, graphic) in &edits { + let Some(e) = d.node_mut(*id).and_then(|n| n.appearance.effects_mut(*item)).and_then(|fx| fx.get_mut(*index)) else { continue }; + let current = effects::upgrade_params(&e.id, &e.params); + e.params = effects::with_graphic(¤t, graphic); + done.push(*id); + } + Ok(done) + })?; + Ok(json!({ "ids": ids_json(&ids), "graphic": first })) +} + +#[cfg(test)] +#[path = "graphics_tests.rs"] +mod tests; diff --git a/crates/engine/src/cmd/effectcmd/graphics_tests.rs b/crates/engine/src/cmd/effectcmd/graphics_tests.rs new file mode 100644 index 0000000000..a9d3a754ce --- /dev/null +++ b/crates/engine/src/cmd/effectcmd/graphics_tests.rs @@ -0,0 +1,314 @@ +#![allow(clippy::unwrap_used, clippy::panic)] +use serde_json::{Value, json}; +use vectorcraft_doc::NodeId; + +use crate::Session; + +/// A 100 × 100 square with `effect`, and a 10 × 20 red rectangle beside it kept as graphic "Mark". +fn setup(effect: &str) -> (Session, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width":400,"height":400})).unwrap(); + let mark = s.execute("path.create", &json!({"d":"M300 300L310 300L310 320L300 320Z"})).unwrap()["id"].clone(); + s.execute("paint.setFill", &json!({"color":"#ff0000"})).unwrap(); + let made = s.execute("threeD.addGraphic", &json!({"name": "Mark", "ids": [mark]})).unwrap(); + assert_eq!(made["name"], "Mark"); + let id = NodeId(s.execute("path.create", &json!({"d":"M100 100L200 100L200 200L100 200Z"})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"color":"#338ad6"})).unwrap(); + s.execute("effect.apply", &json!({"effect":effect,"item":null,"params":{"rotationX":0.0,"rotationY":0.0,"rotationZ":0.0}})).unwrap(); + (s, id) +} + +fn graphics(s: &Session, id: NodeId) -> Value { + s.doc().unwrap().doc.node(id).unwrap().appearance.effects[0].params["graphics"].clone() +} + +fn undo_len(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +#[test] +fn add_as_single_graphic_keeps_the_art_and_makes_a_symbol() { + let (s, _) = setup("threeD.extrude"); + let d = &s.doc().unwrap().doc; + assert!(d.symbols.iter().any(|sym| sym.name == "Mark")); + // The art stays a plain path: no instance replaced it. + let mut instances = 0; + for l in &d.layers { + l.walk(&mut |n| instances += usize::from(matches!(n.kind, vectorcraft_doc::NodeKind::SymbolInstance { .. }))); + } + assert_eq!(instances, 0); + // The 10 × 20 rectangle and its 1 pt stroke. + assert_eq!(vectorcraft_render::effects::graphic_bounds(d, "Mark").map(|r| (r.width(), r.height())), Some((11.0, 21.0))); +} + +#[test] +fn map_graphic_adds_to_the_selected_object_in_one_undo_step_and_undoes() { + let (mut s, id) = setup("threeD.extrude"); + let before = s.doc().unwrap().doc.clone(); + let history = undo_len(&s); + let r = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "x": 5.0, "rotation": 30.0})).unwrap(); + assert_eq!(r["ids"], json!([id.0])); + assert_eq!(graphics(&s, id), json!([{"symbol": "Mark", "face": "front", "x": 5.0, "y": 0.0, "scale": 100.0, "rotation": 30.0}])); + assert_eq!(undo_len(&s), history + 1); + s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "back"})).unwrap(); + assert_eq!(graphics(&s, id).as_array().unwrap().len(), 2); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.layers, before.layers); +} + +#[test] +fn a_large_graphic_starts_inside_its_object() { + let (mut s, id) = setup("threeD.rotate"); + let big = s.execute("path.create", &json!({"d":"M0 0L400 0L400 200L0 200Z"})).unwrap()["id"].clone(); + s.execute("threeD.addGraphic", &json!({"name": "Big", "ids": [big]})).unwrap(); + s.execute("threeD.mapGraphic", &json!({"symbol": "Big", "ids": [id.0]})).unwrap(); + // 401 pt wide with its stroke, in a 100 pt square. + let scale = graphics(&s, id)[0]["scale"].as_f64().unwrap(); + assert!((scale - 100.0 * 100.0 / 401.0).abs() < 1e-9, "{scale}"); +} + +#[test] +fn map_graphic_puts_a_graphic_on_the_side_of_a_revolve() { + let (mut s, id) = setup("threeD.revolve"); + let plain = vectorcraft_render::effects::revolve_art_in(Some(&s.doc().unwrap().doc), s.doc().unwrap().doc.node(id).unwrap()); + let history = undo_len(&s); + s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).unwrap(); + assert_eq!(graphics(&s, id), json!([{"symbol": "Mark", "face": "front", "x": 0.0, "y": 0.0, "scale": 100.0, "rotation": 0.0}])); + assert_eq!(undo_len(&s), history + 1); + let d = &s.doc().unwrap().doc; + assert_ne!(vectorcraft_render::effects::revolve_art_in(Some(d), d.node(id).unwrap()), plain, "the graphic is drawn"); + // A large graphic starts inside the half of the side seen from the front: 100π around the + // axis (the square's far edge is 100 from it) and 300 along the profile (its edge on the axis + // sweeps nothing). + let big = s.execute("path.create", &json!({"d":"M0 0L400 0L400 200L0 200Z"})).unwrap()["id"].clone(); + s.execute("threeD.addGraphic", &json!({"name": "Big", "ids": [big]})).unwrap(); + s.execute("threeD.mapGraphic", &json!({"symbol": "Big", "ids": [id.0]})).unwrap(); + let scale = graphics(&s, id)[1]["scale"].as_f64().unwrap(); + assert!((scale - 100.0 * 100.0 * std::f64::consts::PI / 401.0).abs() < 1e-6, "{scale}"); + // The side is its only face. + let history = undo_len(&s); + let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "back", "ids": [id.0]})).unwrap_err().to_string(); + assert!(e.contains("side"), "{e}"); + assert_eq!(undo_len(&s), history); +} + +#[test] +fn map_graphic_refuses_what_cannot_take_it_and_changes_nothing() { + let (mut s, id) = setup("threeD.inflate"); + let history = undo_len(&s); + let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).unwrap_err().to_string(); + assert!(e.contains("Plane, Extrude and Revolve"), "{e}"); + let (mut s, id) = setup("threeD.rotate"); + for (p, says) in [ + (json!({"symbol": "Gone"}), "no symbol named"), + (json!({"face": "front"}), "needs `symbol`"), + (json!({"symbol": "Mark", "face": "back"}), "one face"), + (json!({"symbol": "Mark", "scale": 0.0}), "scale"), + (json!({"symbol": "Mark", "tile": true}), "`tile`"), + (json!({"symbol": "Mark", "item": 0}), "`item` needs `index`"), + (json!({"symbol": "Mark", "item": null}), "`item` needs `index`"), + ] { + let mut p = p; + p["ids"] = json!([id.0]); + let e = s.execute("threeD.mapGraphic", &p).unwrap_err().to_string(); + assert!(e.contains(says), "{p}: {e}"); + } + assert_eq!(undo_len(&s), history); + // An object without a 3D effect. + let plain = s.execute("path.create", &json!({"d":"M0 0L10 0L10 10Z"})).unwrap()["id"].clone(); + let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [plain]})).unwrap_err().to_string(); + assert!(e.contains("3D effect"), "{e}"); + // A hollow Extrude & Bevel has no cap to show a new graphic on. + let (mut s, id) = setup("threeD.extrude"); + s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"cap": false}})).unwrap(); + let history = undo_len(&s); + let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).unwrap_err().to_string(); + assert!(e.contains("turn on Cap"), "{e}"); + assert_eq!(undo_len(&s), history); + // With a depth of 0 there is no back. + s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"cap": true, "depth": 0.0}})).unwrap(); + let history = undo_len(&s); + let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "back", "ids": [id.0]})).unwrap_err().to_string(); + assert!(e.contains("one face"), "{e}"); + assert_eq!(undo_len(&s), history); + assert!(s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).is_ok()); +} + +#[test] +fn set_params_edits_graphics_and_checks_them() { + let (mut s, id) = setup("threeD.extrude"); + s.execute("threeD.mapGraphic", &json!({"symbol": "Mark"})).unwrap(); + let moved = json!([{"symbol": "Mark", "face": "front", "x": -12.0, "y": 8.0, "scale": 150.0, "rotation": 0.0}]); + s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "params": {"graphics": moved}})).unwrap(); + assert_eq!(graphics(&s, id), moved); + let bad = json!({"ids": [id.0], "index": 0, "item": null, "params": {"graphics": [{"symbol": "Mark", "face": "top"}]}}); + assert!(s.execute("effect.setParams", &bad).is_err()); + let null = json!({"ids": [id.0], "index": 0, "item": null, "params": {"graphics": null}}); + assert!(s.execute("effect.setParams", &null).is_err()); + assert_eq!(graphics(&s, id), moved); + // Extrude to Plane keeps the graphics; to Inflate drops them. + s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "threeDType": "plane"})).unwrap(); + assert_eq!(graphics(&s, id), moved); + s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "threeDType": "inflate"})).unwrap(); + assert_eq!(graphics(&s, id), Value::Null); +} + +#[test] +fn effect_commands_refuse_an_unknown_symbol_but_keep_a_deleted_ones_graphic() { + let (mut s, id) = setup("threeD.extrude"); + let unknown = json!([{"symbol": "Nowhere"}]); + let history = undo_len(&s); + assert!(s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "params": {"graphics": unknown}})).is_err()); + s.execute("path.create", &json!({"d":"M0 0L50 0L50 50L0 50Z"})).unwrap(); + let created = undo_len(&s); + assert!(s.execute("effect.apply", &json!({"effect": "threeD.extrude", "item": null, "params": {"graphics": unknown}})).is_err()); + assert_eq!((history + 1, undo_len(&s)), (created, created)); + // A graphic whose symbol was deleted stays while the effect's other settings change. + s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).unwrap(); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).symbols.retain(|sym| sym.name != "Mark"); + s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "params": {"depth": 30.0}})).unwrap(); + assert_eq!(graphics(&s, id)[0]["symbol"], "Mark"); +} + +#[test] +fn a_symbol_a_graphic_uses_is_used_and_follows_a_rename() { + let (mut s, id) = setup("threeD.extrude"); + s.execute("threeD.mapGraphic", &json!({"symbol": "Mark"})).unwrap(); + let unused = s.execute("symbol.unused", &json!({})).unwrap(); + assert!(!unused["names"].as_array().unwrap().iter().any(|n| n == "Mark"), "{unused}"); + // A 3D object with the graphic kept in another symbol's art follows the rename too. + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("edit.paste", &json!({})).unwrap(); + s.execute("symbol.new", &json!({"name": "Holder"})).unwrap(); + s.execute("symbol.options", &json!({"name": "Mark", "newName": "Label"})).unwrap(); + assert_eq!(graphics(&s, id)[0]["symbol"], "Label"); + let d = &s.doc().unwrap().doc; + let holder = d.symbols.iter().find(|sym| sym.name == "Holder").unwrap(); + let mut held = vec![]; + holder.art.walk(&mut |n| held.extend(vectorcraft_render::effects::graphic_symbols(n))); + assert_eq!(held, vec!["Label".to_string()]); +} + +#[test] +fn a_rename_reaches_graphics_in_graph_designs_and_opacity_masks() { + let (mut s, id) = setup("threeD.extrude"); + s.execute("threeD.mapGraphic", &json!({"symbol": "Mark"})).unwrap(); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let held = d.node(id).unwrap().clone(); + d.graph_designs.push(vectorcraft_doc::GraphDesign { name: "Bars".into(), art: std::sync::Arc::new(held.clone()) }); + d.graphic_styles.push(vectorcraft_doc::GraphicStyle::new("Boxed", (*held.appearance).clone())); + let mut lib = vectorcraft_brush::library(d); + let scatter = lib.iter_mut().find(|b| !b.art().is_empty()).unwrap(); + *scatter.art_mut()[0] = held.clone(); + vectorcraft_brush::store(d, &lib); + d.node_mut(id).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(held, true))); + s.execute("symbol.options", &json!({"name": "Mark", "newName": "Label"})).unwrap(); + let d = &s.doc().unwrap().doc; + let style = d.graphic_styles.iter().find(|g| g.name == "Boxed").unwrap(); + assert_eq!(vectorcraft_render::effects::appearance_graphic_symbols(&style.appearance), vec!["Label".to_string()]); + let brush: Vec<String> = + vectorcraft_brush::library(d).iter().flat_map(|b| b.art()).flat_map(vectorcraft_render::effects::graphic_symbols).collect(); + assert_eq!(brush, vec!["Label".to_string()]); + let names = |n: &vectorcraft_doc::Node| { + let mut out = vec![]; + n.walk(&mut |c| out.extend(vectorcraft_render::effects::graphic_symbols(c))); + out + }; + assert_eq!(names(&d.graph_designs[0].art), vec!["Label".to_string()]); + let mask = d.node(id).unwrap().extras().mask.as_deref().map(|m| names(&m.art)); + assert_eq!(mask, Some(vec!["Label".to_string()])); +} + +#[test] +fn pasted_into_another_document_a_graphic_brings_its_symbol() { + let (mut s, id) = setup("threeD.extrude"); + s.execute("threeD.mapGraphic", &json!({"symbol": "Mark"})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + // The symbol the pasted object's graphic names, and the size of that symbol's art. + let pasted = |s: &mut Session| { + s.execute("edit.paste", &json!({})).unwrap(); + let st = s.doc().unwrap(); + let n = st.doc.node(st.selection.objects[0]).unwrap(); + let name = n.appearance.effects[0].params["graphics"][0]["symbol"].as_str().unwrap().to_string(); + let size = vectorcraft_render::effects::graphic_bounds(&st.doc, &name).map(|r| (r.width(), r.height())); + (name, size) + }; + // A document without the symbol gets it. + s.execute("file.new", &json!({"width":400,"height":400})).unwrap(); + assert_eq!(pasted(&mut s), ("Mark".to_string(), Some((11.0, 21.0)))); + // A document whose symbol "Mark" is other art gets the copied symbol under a free name. + s.execute("file.new", &json!({"width":400,"height":400})).unwrap(); + let other = s.execute("path.create", &json!({"d":"M0 0L50 0L50 50L0 50Z"})).unwrap()["id"].clone(); + s.execute("threeD.addGraphic", &json!({"name": "Mark", "ids": [other]})).unwrap(); + let (name, size) = pasted(&mut s); + assert_ne!(name, "Mark"); + assert_eq!(size, Some((11.0, 21.0))); +} + +#[test] +fn a_symbol_only_a_graphic_style_uses_is_used() { + let (mut s, id) = setup("threeD.extrude"); + s.execute("threeD.mapGraphic", &json!({"symbol": "Mark"})).unwrap(); + let appearance = (*s.doc().unwrap().doc.node(id).unwrap().appearance).clone(); + s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"graphics": []}})).unwrap(); + let unused = |s: &mut Session| s.execute("symbol.unused", &json!({})).unwrap()["names"].clone(); + assert!(unused(&mut s).as_array().unwrap().iter().any(|n| n == "Mark")); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).graphic_styles.push(vectorcraft_doc::GraphicStyle::new("Boxed", appearance)); + assert!(!unused(&mut s).as_array().unwrap().iter().any(|n| n == "Mark")); +} + +#[test] +fn add_graphic_refuses_bad_parameters_and_changes_nothing() { + let (mut s, _) = setup("threeD.extrude"); + let art = s.execute("path.create", &json!({"d":"M0 0L10 0L10 10Z"})).unwrap()["id"].clone(); + let (symbols, history) = (s.doc().unwrap().doc.symbols.len(), undo_len(&s)); + for p in [ + json!({"name": 5, "ids": [art]}), + json!({"name": null, "ids": [art]}), + json!({"name": "", "ids": [art]}), + json!({"name": " ", "ids": [art]}), + json!({"tile": true, "ids": [art]}), + ] { + assert!(s.execute("threeD.addGraphic", &p).is_err(), "{p}"); + } + assert_eq!((s.doc().unwrap().doc.symbols.len(), undo_len(&s)), (symbols, history)); +} + +#[test] +fn map_graphic_refuses_a_selection_with_an_object_without_a_3d_effect() { + let (mut s, id) = setup("threeD.extrude"); + let plain = s.execute("path.create", &json!({"d":"M0 0L10 0L10 10Z"})).unwrap()["id"].as_u64().unwrap(); + let history = undo_len(&s); + let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0, plain]})).unwrap_err().to_string(); + assert!(e.contains(&format!("object {plain} needs a 3D effect")), "{e}"); + assert_eq!(undo_len(&s), history); + assert_eq!(graphics(&s, id).as_array().map_or(0, Vec::len), 0); +} + +#[test] +fn the_graphic_is_drawn_on_the_object() { + let (mut s, id) = setup("threeD.extrude"); + s.execute("threeD.mapGraphic", &json!({"symbol": "Mark"})).unwrap(); + let d = &s.doc().unwrap().doc; + let art = vectorcraft_render::effects::solid_art_in(Some(d), d.node(id).unwrap()).unwrap(); + let mut red = None; + art.walk(&mut |n| { + if let (Some(p), Some(vectorcraft_doc::AppearanceItem::Fill(f))) = (n.path_data(), n.appearance.items.first()) + && f.paint.color().is_some_and(|c| c.to_rgb()[0] > 0.3 && c.to_rgb()[1] < 0.1) + { + red = p.bounds(); + } + }); + // Seen straight on, the 10 × 20 graphic sits at the center of the square. + let r = red.unwrap(); + assert!( + (r.center().x - 150.0).abs() < 1e-6 + && (r.center().y - 150.0).abs() < 1e-6 + && (r.width() - 10.0).abs() < 1e-6 + && (r.height() - 20.0).abs() < 1e-6, + "{r:?}" + ); +} diff --git a/crates/engine/src/cmd/effectcmd/lighting_presets_tests.rs b/crates/engine/src/cmd/effectcmd/lighting_presets_tests.rs index 812ce09664..2dff0d23f1 100644 --- a/crates/engine/src/cmd/effectcmd/lighting_presets_tests.rs +++ b/crates/engine/src/cmd/effectcmd/lighting_presets_tests.rs @@ -115,3 +115,32 @@ fn lighting_presets_refuse_extrude_and_bevel_classic_and_leave_a_mixed_selection let params = &s.doc().unwrap().doc.node(NodeId(classic)).unwrap().appearance.effects[0].params; assert_eq!((params["lightRotation"].as_f64(), params["lightHeight"].as_f64()), (Some(135.0), Some(45.0))); } + +#[test] +fn lighting_presets_refuse_revolve_classic() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let id = s.execute("path.create", &json!({"d":"M100 40 L130 60 L130 140 L100 160"})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"color":"#3366cc"})).unwrap(); + s.execute("effect.apply", &json!({"effect":"threeD.classicRevolve","item":null,"params":{"surface":"diffuse"}})).unwrap(); + s.doc_mut().unwrap().mark_saved(); + let before = s.doc().unwrap().doc.clone(); + let err = s.execute("effect.lightingPreset", &json!({"ids":[id],"index":0,"item":null,"preset":"topLeft"})).unwrap_err().to_string(); + assert!(err.contains(&format!("object {id}: Revolve (Classic) at index 0 has no lighting presets")), "{err}"); + assert_eq!(s.doc().unwrap().doc, before); + assert!(!s.doc().unwrap().is_dirty()); +} + +#[test] +fn lighting_presets_refuse_rotate_classic() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x":100,"y":100,"width":80,"height":60})).unwrap()["id"].as_u64().unwrap(); + s.execute("effect.apply", &json!({"effect":"threeD.classicRotate","item":null,"params":{"lightRotation":40}})).unwrap(); + s.doc_mut().unwrap().mark_saved(); + let before = s.doc().unwrap().doc.clone(); + let err = s.execute("effect.lightingPreset", &json!({"ids":[id],"index":0,"item":null,"preset":"diffuse"})).unwrap_err().to_string(); + assert!(err.contains(&format!("object {id}: Rotate (Classic) at index 0 has no lighting presets")), "{err}"); + assert_eq!(s.doc().unwrap().doc, before); + assert!(!s.doc().unwrap().is_dirty()); +} diff --git a/crates/engine/src/cmd/effectcmd/tests.rs b/crates/engine/src/cmd/effectcmd/tests.rs index e4c8d79450..306aaa4797 100644 --- a/crates/engine/src/cmd/effectcmd/tests.rs +++ b/crates/engine/src/cmd/effectcmd/tests.rs @@ -169,6 +169,44 @@ fn solid_effects_apply_to_a_group_and_its_members_stay_editable() { assert_eq!(s.doc().unwrap().doc, before, "nothing changed"); } +/// Extrude & Bevel is refused, and nothing changes, on a path whose fill's and strokes' solids each +/// fit but together pass the limit of their faces; with one stroke the effect applies. +#[test] +fn extrude_is_refused_when_its_solids_together_are_too_complex() { + use vectorcraft_doc::color::{Color, Paint}; + use vectorcraft_doc::{Appearance, AppearanceItem}; + let (mut s, id) = session_with_rect(); + let points: Vec<vectorcraft_geom::Point> = (0..16_384) + .map(|k| { + let (sin, cos) = (k as f64 * std::f64::consts::TAU / 16_384.0).sin_cos(); + vectorcraft_geom::Point::new(20_000.0 + 10_000.0 * cos, 20_000.0 + 10_000.0 * sin) + }) + .collect(); + let polygon = vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&points, true)); + let painted = |strokes: usize| { + let mut items = Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0).items; + let stroke = AppearanceItem::Stroke(vectorcraft_doc::StrokeLayer::new(Paint::solid(Color::WHITE), 20.0)); + items.extend(std::iter::repeat_n(stroke, strokes)); + items + }; + let set = |s: &mut Session, strokes: usize| { + let n = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap(); + let NodeKind::Path { path, live, .. } = &mut n.kind else { panic!("a path") }; + *path = polygon.clone(); + *live = None; + n.appearance.items = painted(strokes); + }; + // The fill's solid and each stroke's fit on their own; sixty strokes' together do not. + set(&mut s, 60); + let before = s.doc().unwrap().doc.clone(); + let err = s.execute("effect.apply", &json!({"effect": "threeD.extrude", "ids": [id.0], "item": null})).unwrap_err().to_string(); + assert!(err.contains("The 3D surface is too complex; simplify the shape"), "{err}"); + assert_eq!(s.doc().unwrap().doc, before, "nothing changed"); + set(&mut s, 1); + s.execute("effect.apply", &json!({"effect": "threeD.extrude", "ids": [id.0], "item": null})).unwrap(); + assert!(effects::solid_art(&node(&s, id)).is_some()); +} + /// A group of a clipping group (a rectangle clipped by an ellipse) and a rectangle: the session, /// the clipping group and the group. fn group_with_a_clipping_group() -> (Session, NodeId, NodeId) { @@ -626,6 +664,50 @@ fn warp_options_non_warp_target_rejection_is_atomic() { assert!(!state.is_dirty()); } +/// `effect.setParams` refuses a `visible` that is not true or false, when called and when a step +/// plays, and the effect, the document and the undo history stay as they were. `null` leaves the +/// visibility as it is. +#[test] +fn set_params_refuses_a_visible_that_is_not_true_or_false() { + let (mut s, id) = session_with_rect(); + s.execute("effect.apply", &json!({"effect": "distort.roughen", "item": null})).unwrap(); + s.doc_mut().unwrap().mark_saved(); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + for visible in [json!(1), json!(0), json!("false"), json!([])] { + let p = json!({"index": 0, "item": null, "visible": visible, "params": {"size": 9}}); + for replay in [false, true] { + let r = if replay { s.replay("effect.setParams", &p) } else { s.execute("effect.setParams", &p) }; + let err = r.err().map(|e| e.to_string()).unwrap_or_default(); + assert!(err.contains("`visible` must be true or false"), "{visible} (replay {replay}): {err}"); + let state = s.doc().unwrap(); + assert_eq!(state.doc, before, "{visible} (replay {replay})"); + assert_eq!(state.history.undo.len(), undo, "{visible} (replay {replay})"); + assert!(!state.is_dirty()); + } + } + s.execute("effect.setParams", &json!({"index": 0, "item": null, "visible": null, "params": {"size": 9}})).unwrap(); + let n = node(&s, id); + assert!(n.appearance.effects[0].visible); + assert_eq!(n.appearance.effects[0].params["size"], 9); +} + +/// The effect `effect.setParams` checks the parameters against is the one it leaves: a Warp's new +/// style and a 3D effect's new type, and the effect as it is otherwise. +#[test] +fn set_params_checks_the_effect_it_leaves() { + use super::edited_effect_id; + assert_eq!(edited_effect_id("warp.arc", None, Some("flag")), "warp.flag"); + assert_eq!(edited_effect_id("warp.arc", None, None), "warp.arc"); + assert_eq!(edited_effect_id("distort.roughen", None, Some("flag")), "distort.roughen"); + assert_eq!(edited_effect_id("threeD.extrude", Some("threeD.revolve"), None), "threeD.revolve"); + assert_eq!(edited_effect_id("warp.arc", Some("threeD.revolve"), None), "warp.arc"); + let (mut s, _) = session_with_rect(); + s.execute("effect.apply", &json!({"effect": "warp.arc", "item": null})).unwrap(); + let p = json!({"index": 0, "item": null, "warpStyle": "flag", "params": {"bend": 25}}); + assert_eq!(super::set_params_effects(&s, &p), ["warp.flag"]); +} + #[test] fn list_remove_and_set_params() { let (mut s, id) = session_with_rect(); @@ -881,3 +963,56 @@ fn move_takes_several_effects_that_land_together_in_order() { assert!(s.execute("effect.move", &json!({"from": [0, 9], "to": 0, "fromItem": null, "ids": [id.0]})).is_err()); assert_eq!(node(&s, id).appearance, before); } + +/// A 3D effect's shadow is set with `effect.setParams` in one undo step, saved in the native file, +/// drawn in exports and kept as a path by Expand Appearance; settings out of range are refused +/// without an undo step. +#[test] +fn a_3d_shadow_is_one_undo_step_saved_exported_and_expanded() { + let (mut s, id) = session_with_rect(); + s.execute("effect.apply", &json!({"effect": effects::EXTRUDE, "ids": [id.0], "item": null})).unwrap(); + let undo = s.doc().unwrap().history.undo.len(); + for (params, why) in [ + (json!({"shadowBounds": 401}), "shadowBounds must be a number from 10 to 400"), + (json!({"shadowPosition": "left"}), "shadowPosition must be behind or below"), + ] { + let before = s.doc().unwrap().doc.clone(); + let e = s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "params": params})).unwrap_err().to_string(); + assert!(e.contains(why), "{params}: {e}"); + assert_eq!(s.doc().unwrap().doc, before); + } + assert_eq!(s.doc().unwrap().history.undo.len(), undo); + let params = json!({"shadow": true, "shadowPosition": "below", "shadowDistance": 20, "shadowBounds": 150}); + s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "params": params})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + let art = effects::solid_art(&node(&s, id)).unwrap(); + let shadow = art.children().unwrap()[0].clone(); + assert!(matches!(shadow.kind, NodeKind::Path { .. })); + // Saved and opened again, the effect keeps its shadow settings and draws the same shadow. + let doc = &s.doc().unwrap().doc; + let restored = vectorcraft_format::load(&vectorcraft_format::save(doc, false)).unwrap(); + let fx = &restored.node(id).unwrap().appearance.effects[0]; + for (key, value) in params.as_object().unwrap() { + assert_eq!(fx.params.get(key), Some(value), "{key}"); + } + assert_eq!(effects::solid_art(restored.node(id).unwrap()).unwrap(), art); + // SVG export draws it: one more shape than without the shadow. + let shapes = |s: &mut Session| { + let svg = s.execute("document.serialize", &json!({"format": "svg"})).unwrap(); + let svg = svg["data"].as_str().or_else(|| svg["text"].as_str()).map(str::to_string).unwrap_or_else(|| svg.to_string()); + vectorcraft_testkit::svg_shapes(&svg) + }; + let with = shapes(&mut s); + s.execute("edit.undo", &json!({})).unwrap(); + let without = shapes(&mut s); + assert_eq!(with, without + 1); + s.execute("edit.redo", &json!({})).unwrap(); + s.execute("effect.expandAppearance", &json!({"ids": [id.0]})).unwrap(); + let mut shadows = 0; + s.doc().unwrap().doc.walk(|n| { + if n.path_data().is_some() && n.path_data() == shadow.path_data() && n.appearance.items == shadow.appearance.items { + shadows += 1; + } + }); + assert_eq!(shadows, 1); +} diff --git a/crates/engine/src/cmd/effectcmd/three_d_source_tests.rs b/crates/engine/src/cmd/effectcmd/three_d_source_tests.rs index 122d937b98..104363a142 100644 --- a/crates/engine/src/cmd/effectcmd/three_d_source_tests.rs +++ b/crates/engine/src/cmd/effectcmd/three_d_source_tests.rs @@ -4,7 +4,7 @@ use vectorcraft_doc::{NodeId, NodeKind}; use crate::Session; -const TYPES: [&str; 5] = ["threeD.extrude", "threeD.classicExtrude", "threeD.inflate", "threeD.rotate", "threeD.revolve"]; +const TYPES: [&str; 6] = ["threeD.extrude", "threeD.classicExtrude", "threeD.inflate", "threeD.rotate", "threeD.classicRotate", "threeD.revolve"]; fn id_of(v: &Value) -> NodeId { NodeId(v["id"].as_u64().unwrap()) diff --git a/crates/engine/src/cmd/expand.rs b/crates/engine/src/cmd/expand.rs index 935d5e9dc5..d4a6c60802 100644 --- a/crates/engine/src/cmd/expand.rs +++ b/crates/engine/src/cmd/expand.rs @@ -18,8 +18,8 @@ use vectorcraft_color::{BlendMode, Color, Gradient, GradientKind, GradientPaint, use vectorcraft_doc::appearance::{AppearanceItem, FillLayer}; use vectorcraft_doc::live::GradientMesh; use vectorcraft_doc::pattern::{PatternDef, place_art}; -use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, Scaling}; -use vectorcraft_geom::{Affine, PathData, Point, Rect, SubPath, Vec2, shapes}; +use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, Scaling, TextObject}; +use vectorcraft_geom::{Affine, BezPath, PathData, Point, Rect, SubPath, Vec2, shapes}; use super::dimension::EndedLink; use super::edit::selected_roots; @@ -47,7 +47,7 @@ pub fn specs() -> Vec<CommandSpec> { "Expand…", ["Object"], None, - "{object?: true (symbol instances without effects (their fills' and strokes' included) and not in perspective → their art, as Break Link to Symbol places it (the instances that art holds stay instances), type → outlines, live shapes → paths, effects baked, blends → groups of their steps, repeats → groups of their instances, Intertwine groups → groups of their objects and of the parts drawn over the others (clip groups), envelopes → their distorted content, placed documents → editable copies of their art, as placing the file without link gives, its symbols, patterns, swatches and images joining the document), fill?: true (gradient fills → `gradient` art, pattern fills → their tiles in a clip group shaped like the object), stroke?: true (strokes → filled outlines, the stroked paths that baking effects leaves included), gradient?: \"objects\" (default: `steps` solid strips, concentric ellipses for radial gradients, wedges around the center for conic ones) | \"mesh\" (a gradient mesh); both in a clip group shaped like the object (freeform gradients always become a mesh shaped like it), steps?: 1..1000 (255)} one undo step; a dimension whose art an option changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked → {ids}", + "{object?: true (symbol instances without effects (their fills' and strokes' included) and not in perspective → their art, as Break Link to Symbol places it (the instances that art holds stay instances), type → outlines, live shapes → paths, effects baked, blends → groups of their steps, repeats → groups of their instances, Intertwine groups → groups of their objects and of the parts drawn over the others (clip groups), envelopes → their distorted content, placed documents → editable copies of their art, as placing the file without link gives, its symbols, patterns, swatches and images joining the document), fill?: true (gradient fills → `gradient` art, pattern fills → their tiles in a clip group shaped like the object), stroke?: true (strokes → filled outlines, the stroked paths that baking effects leaves included), gradient?: \"objects\" (default: `steps` solid strips, concentric ellipses for radial gradients, wedges around the center for conic ones, nested squares for diamond ones) | \"mesh\" (a gradient mesh); both in a clip group shaped like the object (freeform gradients always become a mesh shaped like it), steps?: 1..1000 (255; a gradient that repeats or reflects gets the same whole number of them in each run, at least one, so a run starts on an object's edge; one that needs more than 256 runs across the box stays a gradient)} one undo step; a dimension whose art an option changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked → {ids}", has_selection, expand ), @@ -56,7 +56,7 @@ pub fn specs() -> Vec<CommandSpec> { "Expand Options", [], None, - "{} what each Expand option would change in the selection → {object, fill, stroke, gradient, appearance, symbolArt?: {fill, stroke, gradient}} (true: something to expand; gradient: a gradient fill that Fill expands, which Expand Gradient To applies to; appearance: appearance attributes Expand Appearance expands first, for which Object › Expand… is dimmed in the menus; symbolArt, when the selection holds symbol instances that Object expands: true when only their art holds it, which Fill and Stroke reach only with Object on)", + "{} what each Expand option would change in the selection → {object, fill, stroke, gradient, appearance, symbolArt?: {fill, stroke, gradient}} (true: something to expand; gradient: a gradient fill that Fill expands (in type, on the outline Object makes of a character), which Expand Gradient To applies to; appearance: appearance attributes Expand Appearance expands first, for which Object › Expand… is dimmed in the menus; symbolArt, when the selection holds symbol instances that Object expands: true when only their art holds it, which Fill and Stroke reach only with Object on)", has_selection, |s, _| { let roots = selected_roots(s)?; @@ -194,10 +194,12 @@ impl Expandable { NodeKind::Text(t) => t.runs.iter().any(|r| r.style.has_stroke()), _ => shape && !c.appearance.stroke_paint().is_none(), }; - e.gradient |= match &c.kind { - NodeKind::Text(t) => t.runs.iter().any(|r| matches!(r.style.fill, Paint::Gradient(_))), - _ => shape && c.appearance.items.iter().any(|i| gradient_fill(i).is_some()), - }; + // Once one is found, the next path is not measured. + e.gradient = e.gradient + || match &c.kind { + NodeKind::Text(t) => text_gradient_expands(d, t), + _ => shape && gradient_expands(d, c), + }; e.fill |= e.gradient; e.fill |= match &c.kind { NodeKind::Text(t) => t.runs.iter().any(|r| matches!(&r.style.fill, Paint::Pattern { pattern, .. } if d.pattern(pattern).is_some())), @@ -222,6 +224,71 @@ fn gradient_fill(i: &AppearanceItem) -> Option<(&FillLayer, &GradientPaint)> { } } +/// Whether path `l` has a gradient fill that Fill expands ([`expand_fills`]): one that repeats or +/// reflects stays a gradient when its box needs more runs than are written ([`padded_on`]). For a +/// path that live-effect plug-ins paint, whether a piece of the art they paint has one +/// ([`expand_pieces`]). +fn gradient_expands(d: &Document, l: &Node) -> bool { + if !l.appearance.items.iter().any(|i| gradient_fill(i).is_some()) { + return false; + } + if !vectorcraft_render::effects::has_painted_effects(l) { + return piece_gradient_expands(d, l); + } + let Some(art) = vectorcraft_render::effects::reshape(Some(d), l, None) else { return false }; + let mut any = false; + art.walk(&mut |c| { + any = any + || (matches!(c.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) + && !c.is_ruler_guide() + && c.appearance.items.iter().any(|i| gradient_fill(i).is_some()) + && piece_gradient_expands(d, c)); + }); + any +} + +/// Whether type `t` has a gradient fill that Fill expands once Object has outlined it: one of the +/// paths `type.createOutlines` makes of its glyphs, ruby glyphs and underline and strikethrough +/// bars, each painted as its run, has one ([`gradient_expands`] on that path's own box). Inline +/// graphics and color glyphs become other art. Leaves the document as it is and stops at the +/// first such path. +fn text_gradient_expands(d: &Document, t: &TextObject) -> bool { + if !t.runs.iter().any(|r| matches!(r.style.fill, Paint::Gradient(_))) { + return false; + } + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + let expands = |run: usize, outline: &BezPath| { + let style = t.runs.get(run).map(|r| &r.style); + if !matches!(style.map_or_else(|| t.first_style().fill, |s| s.fill.clone()), Paint::Gradient(_)) { + return false; + } + let path = PathData::from_bezpath(outline).transformed(t.xf); + if path.is_empty() { + return false; + } + let appearance = style.map_or_else(|| t.first_style().appearance(), |s| s.appearance()); + gradient_expands(d, &Node::path(NodeId(u64::MAX), path, appearance)) + }; + let inline = |gi: usize| lay.inlines.iter().find(|i| i.glyph == gi).is_some_and(|i| t.runs.get(i.run).is_some_and(|r| r.inline.is_some())); + lay.glyphs.iter().enumerate().any(|(gi, g)| !inline(gi) && g.image.is_none() && g.colour.is_none() && expands(g.run, &g.outline)) + || lay.ruby.iter().any(|g| expands(g.run, &g.outline)) + || vectorcraft_text::decorations(&lay, vectorcraft_text::FontDb::global(), t).iter().any(|(run, bar)| expands(*run, bar)) +} + +/// [`gradient_expands`] for a path that no live-effect plug-in paints ([`expand_piece_fills`]). +fn piece_gradient_expands(d: &Document, l: &Node) -> bool { + if !l.appearance.items.iter().filter_map(gradient_fill).any(|(_, g)| g.gradient.is_spread()) { + return l.appearance.items.iter().any(|i| gradient_fill(i).is_some()); + } + let reshaped = reshaped(d, l); + let l = reshaped.as_ref().unwrap_or(l); + let Some((path, _)) = node_path(l) else { return false }; + let Some(bounds) = path.bounds() else { return false }; + l.appearance.items.iter().filter(|i| gradient_fill(i).is_some()).any(|item| { + fill_shape(d, l, item, &path, bounds).is_some_and(|(_, _, b, moved)| gradient_fill(&moved).is_some_and(|(_, g)| padded_on(g, b).is_some())) + }) +} + /// The definition and placement of a visible pattern fill whose pattern `d` defines. fn pattern_fill<'a, 'd>(d: &'d Document, i: &'a AppearanceItem) -> Option<(&'a FillLayer, &'d PatternDef, Affine)> { match i { @@ -476,11 +543,15 @@ fn gradient_art(d: &mut Document, l: &Node, path: &PathData, bounds: Rect, f: &F let m = GradientMesh::for_path_with(path, FREEFORM_MESH, FREEFORM_MESH, &*gradient_sampler(g, bounds, d.color_mode.model()))?; vec![Node::new(d.alloc_id(), NodeKind::Mesh(m))] } else { + // A gradient that repeats or reflects expands as its stops repeated over the box (and + // stays a gradient when the box needs more runs than are written). + let (g, runs) = padded_on(g, bounds)?; + let g = &*g; let frame = Frame::new(g, bounds); match to { GradientTo::Mesh => vec![Node::new(d.alloc_id(), NodeKind::Mesh(frame.mesh(&g.gradient)))], GradientTo::Objects(n) => frame - .pieces(&g.gradient, n as usize) + .pieces(&g.gradient, n as usize, runs) .into_iter() .map(|(shape, (color, opacity))| { let fill = FillLayer { opacity, overprint: f.overprint, ..FillLayer::new(Paint::solid(color)) }; @@ -543,12 +614,16 @@ fn expand_piece_leaves( } /// Path `l` as the canvas paints its fills and strokes: its visible geometry effects applied to its -/// path (a plain path then), and every geometry effect of its own removed. `None` when it has no +/// path (a plain path then), and every geometry effect of its own removed, with each raster effect +/// following the Transform effects after it +/// ([`without_geometry`](vectorcraft_render::effects::without_geometry)) and those of its fills and +/// strokes following its Transform effects +/// ([`follow_items`](vectorcraft_render::effects::follow_items)). `None` when it has no /// visible geometry effect. The swatches and patterns that live-effect plug-ins painting their /// pieces name are looked up in `doc`. This merges the pieces of such a plug-in into one path, so a /// path that one paints goes through [`expand_pieces`] instead. pub(crate) fn reshaped(doc: &Document, l: &Node) -> Option<Node> { - use vectorcraft_render::effects::{GeomContext, apply_geometry_carrying, has_geometry, is_geometry}; + use vectorcraft_render::effects::{GeomContext, apply_geometry_carrying, has_geometry, without_geometry}; if !has_geometry(&l.appearance.effects) { return None; } @@ -559,7 +634,11 @@ pub(crate) fn reshaped(doc: &Document, l: &Node) -> Option<Node> { if carry.moves(&m.appearance) { carry.apply(&mut m.appearance); } - m.appearance.effects.retain(|e| !is_geometry(&e.id)); + // So do the raster effects of it and of its fills and strokes, by the Transform effects that + // moved it. + carry.hide_skipped(&mut m.appearance.effects); + vectorcraft_render::effects::follow_items(&mut m); + m.appearance.effects = without_geometry(&m.appearance.effects); Some(m) } @@ -585,7 +664,8 @@ pub(crate) fn fill_shape( if carry.moves(&one) { carry.apply(&mut one); } - let moved = one.items.pop().unwrap_or_else(|| item.clone()); + let mut moved = one.items.pop().unwrap_or_else(|| item.clone()); + carry.hide_skipped(moved.effects_mut()); Some((with_path(l, outline.clone()), outline, b, moved)) } @@ -601,9 +681,10 @@ fn with_path(l: &Node, path: PathData) -> Node { } /// The effects of fill `f` that stay on its expanded art: all but its geometry effects, which -/// shape the outline it paints ([`fill_shape`]). +/// shape the outline it paints ([`fill_shape`]), with each raster effect following the Transform +/// effects after it ([`without_geometry`](vectorcraft_render::effects::without_geometry)). fn fill_effects(f: &FillLayer) -> Vec<vectorcraft_doc::Effect> { - f.effects.iter().filter(|e| !vectorcraft_render::effects::is_geometry(&e.id)).cloned().collect() + vectorcraft_render::effects::without_geometry(&f.effects) } /// Replace every pattern fill of the selected paths by the tiles it paints (see [`expand_patterns`]). @@ -834,8 +915,8 @@ fn blended(n: &Node) -> bool { n.opacity < 1.0 || n.blend != BlendMode::Normal } -/// Whether `n` (art of `d`) is or holds an image with see-through pixels (key in `keys`), a -/// colorize paint that `colorize` counts, opacity or a blending mode of its own or of a group in +/// Whether `n` (art of `d`) is or holds an image with see-through pixels (key in `keys`, a +/// color-masked image's masked pixels counted as its own), a colorize paint that `colorize` counts, opacity or a blending mode of its own or of a group in /// `n`, or anywhere when `on`, also in the tile art of the pattern fills of the paths in `n`, down /// to `levels` patterns. Hidden art doesn't count. fn transparent_image(d: &Document, n: &Node, keys: &BTreeSet<String>, colorize: &dyn Fn(&Document, &Node) -> bool, on: bool, levels: u32) -> bool { @@ -844,7 +925,9 @@ fn transparent_image(d: &Document, n: &Node, keys: &BTreeSet<String>, colorize: } let on = on || blended(n); match &n.kind { - NodeKind::Image(im) => on || keys.contains(&im.key) || (n.extras().colorize.is_some() && colorize(d, n)), + NodeKind::Image(im) => { + on || keys.contains(&im.key) || keys.contains(&d.shown_image(n, im).key) || (n.extras().colorize.is_some() && colorize(d, n)) + } NodeKind::Path { .. } | NodeKind::Compound { .. } => { n.appearance.items.iter().any(|i| pattern_fill_holds_transparent_image(d, i, keys, colorize, on, levels)) } @@ -1234,8 +1317,70 @@ pub(crate) fn gradient_sampler(g: &GradientPaint, bounds: Rect, doc_model: Model (super::paint::stored_color(store_in, c), a) }); } + let (geom, spread) = (g.resolve(bounds), g.gradient.spreader()); + Box::new(move |p| g.gradient.sample_keep_model(spread(geom.param_at(g.gradient.kind, p)) as f32)) +} + +/// For stops repeated by [`padded_on`]: where along the vector (0 to 1) their first run starts and +/// how many runs lie evenly from there to 1. +type Runs = Option<(f64, usize)>; + +/// `g` placed on box `bounds` as a gradient that pads past its ends: a linear, radial or diamond +/// gradient that repeats or reflects with its stops repeated as many times as the box needs +/// ([`vectorcraft_color::Gradient::padded_over`]), a conic one with its stops repeated around the +/// turn ([`vectorcraft_color::Gradient::unrolled`]); others as they are. With it, for the repeated +/// stops, where along the vector (0 to 1) their first run starts and how many runs lie evenly from +/// there to 1. `None` when the box needs more runs than are written +/// ([`vectorcraft_color::Padded::capped`]): the gradient stays. +fn padded_on(g: &GradientPaint, bounds: Rect) -> Option<(std::borrow::Cow<'_, GradientPaint>, Runs)> { + use std::borrow::Cow; + if !g.gradient.is_spread() { + return Some((Cow::Borrowed(g), None)); + } let geom = g.resolve(bounds); - Box::new(move |p| g.gradient.sample_keep_model(geom.param_at(g.gradient.kind, p) as f32)) + match g.gradient.padded_over(&geom, bounds) { + Some(p) if p.capped => None, + Some(p) => { + let runs = Some((p.first, p.runs)); + Some((Cow::Owned(GradientPaint { gradient: p.gradient, geom: Some(p.geom), angle: p.geom.angle_deg(), ..g.clone() }), runs)) + } + None => { + let runs = Some((0.0, g.gradient.repeat_count() as usize)); + Some((Cow::Owned(GradientPaint { gradient: g.gradient.unrolled().into_owned(), geom: Some(geom), ..g.clone() }), runs)) + } + } +} + +/// The edges (gradient parameters, from `lo` to `hi`) of about `n` bands [`Frame::pieces`] cuts: +/// evenly spaced, or for stops repeated in `runs` ([`padded_on`]: where the first run starts and +/// how many runs lie evenly from there to 1) the same whole number of bands in each run between +/// `lo` and `hi` (at least one, about `n` in all), so every run starts on an edge and no band +/// holds two runs' colors. +fn band_edges(lo: f64, hi: f64, n: usize, runs: Option<(f64, usize)>) -> Vec<f64> { + let n = n.max(1); + let even = || { + let step = (hi - lo) / n as f64; + (0..=n).map(|k| lo + k as f64 * step).collect() + }; + let Some((first, count)) = runs.filter(|&(first, count)| count > 0 && (0.0..1.0).contains(&first)) else { return even() }; + let run = (1.0 - first) / count as f64; + let (from, to) = (lo.max(first), hi.min(1.0)); + let shown = (to - from) / run; + if !(shown > 0.0 && shown.is_finite()) { + return even(); + } + let step = run / (n as f64 / shown).round().max(1.0); + // Both whole numbers of steps from `first`, at most `n` plus the runs shown, plus one. + let (k0, k1) = (((from - first) / step).ceil(), ((to - first) / step).floor()); + let mut edges = vec![lo]; + for k in (k0 as usize)..(k1 as usize).saturating_add(1) { + let t = first + k as f64 * step; + if t > edges.last().copied().unwrap_or(lo) + 1e-12 && t < hi - 1e-12 { + edges.push(t); + } + } + edges.push(hi); + edges } /// Where the colour changes along a gradient between parameters `t0` and `t1`: both ends, every @@ -1246,8 +1391,9 @@ pub(crate) fn gradient_sampler(g: &GradientPaint, bounds: Rect, doc_model: Model fn breaks(g: &Gradient, t0: f64, t1: f64, max_gap: f64) -> Vec<(f64, (Color, f32))> { let at = |t: f64| (t, g.sample_keep_model(t as f32)); let mut v = vec![at(t0)]; - // A Perceptual gradient curves between its stops: the mesh takes a column at each of the stops - // its expansion adds, so the linear mix between columns follows that curve. + // A Perceptual gradient, or one mixed around the hue wheel, curves between its stops: the mesh + // takes a column at each of the stops its expansion adds, so the linear mix between columns + // follows that curve. if !g.method.is_classic() { v.extend(g.expanded().map(|(o, ..)| f64::from(o)).filter(|o| *o > t0 && *o < t1).map(at)); } @@ -1283,9 +1429,12 @@ fn breaks(g: &Gradient, t0: f64, t1: f64, max_gap: f64) -> Vec<(f64, (Color, f32 /// cover the box (linear: along the vector `t0..t1` and across it `s0..s1` in points; radial: /// `0..t1`, each level's ellipse centred on the way from the focal point to the start). /// A conic gradient also has its placement, the box and the radius in its frame that reaches -/// past the box's corners ([`Frame::pieces`] and [`Frame::mesh`] go around its center). +/// past the box's corners ([`Frame::pieces`] and [`Frame::mesh`] go around its center). A +/// diamond gradient has its frame ([`vectorcraft_color::GradientGeom::diamond_frame`]; `None` +/// when it has no extent), the box and the level of the square that reaches its corners. struct Frame { conic: Option<(vectorcraft_color::GradientGeom, Rect, f64)>, + diamond: Option<(Option<Affine>, Rect, f64)>, radial: bool, start: Point, focal: Point, @@ -1323,7 +1472,11 @@ impl Frame { let reach = if reach.is_finite() { reach * 1.01 / (std::f64::consts::PI * CONIC_MESH_GAP).cos() } else { 1.0 }; (geom, bounds, reach) }); - Self { conic, radial, start: geom.start, focal: geom.focal_point(), along, across, t0, t1, s0, s1 } + let diamond = (g.gradient.kind == GradientKind::Diamond).then(|| { + let reach = corners.iter().map(|c| geom.param_at(GradientKind::Diamond, *c)).fold(0.0f64, f64::max); + (geom.diamond_frame(), bounds, if reach.is_finite() { reach.max(1e-6) * 1.01 } else { 1.0 }) + }); + Self { conic, diamond, radial, start: geom.start, focal: geom.focal_point(), along, across, t0, t1, s0, s1 } } /// Linear: the point at parameter `t` along and `s` across. Radial: the point at parameter `t` @@ -1351,6 +1504,34 @@ impl Frame { }; return GradientMesh::from_grid(&us, &[0.0, 1.0], &at, &|_, c, _| br[c].1); } + if let Some((frame, b, reach)) = &self.diamond { + let Some(frame) = frame else { + // No extent: the whole box is the last stop. + let last = g.sample_keep_model(1.0); + let at = |u: f64, v: f64| Point::new(b.x0 + u * b.width(), b.y0 + v * b.height()); + return GradientMesh::from_grid(&[0.0, 1.0], &[0.0, 1.0], &at, &|_, _, _| last); + }; + // Rings of squares where the color changes, with columns at the corners: each patch + // lies between two rings along one side, where the level runs straight across it. + let br = breaks(g, 0.0, *reach, f64::INFINITY); + let ts: Vec<f64> = br.iter().map(|(t, _)| t / reach).collect(); + let at = |u: f64, v: f64| *frame * (diamond_perimeter(u).to_vec2() * (v * reach)).to_point(); + const CORNERS: [f64; 5] = [0.0, 0.25, 0.5, 0.75, 1.0]; + let mut mesh = GradientMesh::from_grid(&CORNERS, &ts, &at, &|r, _, _| br[r].1); + // Every column is at a corner, where `from_grid`'s tangent is the mean of the two + // sides: each handle along a ring points a third of the way along its own side, so + // the sides stay straight. + let side = |v: f64, from: usize, to: Option<&f64>| to.map_or(vectorcraft_geom::Vec2::ZERO, |&u| (at(u, v) - at(CORNERS[from], v)) / 3.0); + for (r, &v) in ts.iter().enumerate() { + for c in 0..CORNERS.len() { + if let Some(point) = mesh.points.get_mut(r * CORNERS.len() + c) { + point.handles[0] = side(v, c, CORNERS.get(c + 1)); + point.handles[1] = side(v, c, c.checked_sub(1).and_then(|i| CORNERS.get(i))); + } + } + } + return mesh; + } // Rings as close as the columns around them, so the mesh draws smoothly. let gap = if self.radial { (self.t1 - self.t0) / RADIAL_MESH_COLS as f64 } else { f64::INFINITY }; let br = breaks(g, self.t0, self.t1, gap); @@ -1367,46 +1548,88 @@ impl Frame { /// `n` solid shapes covering the box in paint order, each coloured as the gradient in the /// middle of its band: for a linear gradient, rectangles from each band's start to the far /// end, for a radial one, nested ellipses (largest first), for a conic one, wedges around the - /// center from each band's start to the seam. Each paints over the ones below except its - /// band, so no seam shows between bands. With translucent stops each shape is just its band, - /// so nothing doubles up. - fn pieces(&self, g: &Gradient, n: usize) -> Vec<(PathData, (Color, f32))> { + /// center from each band's start to the seam, for a diamond one, nested squares (largest + /// first). Each paints over the ones below except its band, so no seam shows between bands. + /// With translucent stops each shape is just its band, so nothing doubles up. Stops repeated + /// in `runs` ([`padded_on`]) get the same whole number of bands in each run ([`band_edges`]). + fn pieces(&self, g: &Gradient, n: usize, runs: Option<(f64, usize)>) -> Vec<(PathData, (Color, f32))> { let opaque = g.stops.iter().all(|s| s.opacity >= 1.0); + let color = |e: &[f64], k: usize| { + let (a, b) = (e.get(k).copied().unwrap_or(0.0), e.get(k + 1).copied().unwrap_or(1.0)); + g.sample_keep_model(((a + b) / 2.0) as f32) + }; if let Some((geom, b, _)) = &self.conic { + // Evenly spaced around the turn, as the wedges are. + let n = band_edges(0.0, 1.0, n, runs).len().saturating_sub(1); return geom .conic_wedges(*b, n, opaque) .into_iter() .map(|(pts, t)| (PathData::single(SubPath::polyline(&pts, true)), g.sample_keep_model(t as f32))) .collect(); } - let step = (self.t1 - self.t0) / n as f64; - let color = |k: usize| g.sample_keep_model((self.t0 + (k as f64 + 0.5) * step) as f32); + if let Some((frame, b, reach)) = &self.diamond { + let Some(frame) = frame else { + return vec![(shapes::rectangle(*b), g.sample_keep_model(1.0))]; + }; + // Nested squares about the center, largest first, as a radial gradient's ellipses. + let edges = band_edges(0.0, *reach, n, runs); + let square = |t: f64| -> SubPath { + let pts: Vec<Point> = [0.0, 0.25, 0.5, 0.75].iter().map(|&u| *frame * (diamond_perimeter(u).to_vec2() * t).to_point()).collect(); + SubPath::polyline(&pts, true) + }; + return (0..edges.len().saturating_sub(1)) + .rev() + .map(|k| { + let mut shape = PathData::single(square(edges.get(k + 1).copied().unwrap_or(*reach))); + if !opaque && k > 0 { + let mut hole = square(edges.get(k).copied().unwrap_or(0.0)); + hole.reverse(); + shape.subpaths.push(hole); + } + (shape, color(&edges, k)) + }) + .collect(); + } + let edges = band_edges(self.t0, self.t1, n, runs); + let bands = edges.len().saturating_sub(1); + let edge = |k: usize| edges.get(k).copied().unwrap_or(self.t1); if self.radial { let ellipse = |t: f64| { let c = self.focal + (self.start - self.focal) * t; let m = Affine::new([self.along.x * t, self.along.y * t, self.across.x * t, self.across.y * t, c.x, c.y]); shapes::ellipse(Rect::new(-1.0, -1.0, 1.0, 1.0)).transformed(m) }; - return (0..n) + return (0..bands) .rev() .map(|k| { - let mut shape = ellipse((k + 1) as f64 * step); + let mut shape = ellipse(edge(k + 1)); if !opaque && k > 0 { - let mut hole = ellipse(k as f64 * step).subpaths.remove(0); + let mut hole = ellipse(edge(k)).subpaths.remove(0); hole.reverse(); shape.subpaths.push(hole); } - (shape, color(k)) + (shape, color(&edges, k)) }) .collect(); } - (0..n) + (0..bands) .map(|k| { - let a = self.t0 + k as f64 * step; - let b = if opaque { self.t1 } else { a + step }; + let a = edge(k); + let b = if opaque { self.t1 } else { edge(k + 1) }; let pts = [self.at(a, self.s0), self.at(b, self.s0), self.at(b, self.s1), self.at(a, self.s1)]; - (PathData::single(SubPath::polyline(&pts, true)), color(k)) + (PathData::single(SubPath::polyline(&pts, true)), color(&edges, k)) }) .collect() } } + +/// The point a fraction `u` (0..1) of the way around the square with corners (1, 0), (0, 1), +/// (-1, 0) and (0, -1), from the first: a diamond gradient's last stop in its frame. +fn diamond_perimeter(u: f64) -> Point { + const CORNERS: [(f64, f64); 5] = [(1.0, 0.0), (0.0, 1.0), (-1.0, 0.0), (0.0, -1.0), (1.0, 0.0)]; + let s = if u.is_finite() { u.clamp(0.0, 1.0) * 4.0 } else { 0.0 }; + let i = (s.floor() as usize).min(3); + let f = s - i as f64; + let ((x0, y0), (x1, y1)) = (CORNERS.get(i).copied().unwrap_or((1.0, 0.0)), CORNERS.get(i + 1).copied().unwrap_or((1.0, 0.0))); + Point::new(x0 + (x1 - x0) * f, y0 + (y1 - y0) * f) +} diff --git a/crates/engine/src/cmd/fileinfo.rs b/crates/engine/src/cmd/fileinfo.rs index 36ccd7cdb0..9a59d0f2f8 100644 --- a/crates/engine/src/cmd/fileinfo.rs +++ b/crates/engine/src/cmd/fileinfo.rs @@ -1,7 +1,8 @@ //! File → File Info (`file.info`): the document title and its descriptive metadata (author, //! description, keywords, rating, copyright), with the read-only created and modified dates. The -//! SVG (with `metadata`), PDF and PNG writers carry it, and a PDF or `.ai` opens with the File Info -//! it gives ([`read_pdf`]). +//! title is the one the file the document was opened from gave itself ([`DocMetadata::title`]), +//! else the document's name. The SVG (with `metadata`), PDF and PNG writers carry it, and a PDF or +//! `.ai` opens with the File Info it gives ([`read_pdf`]). use serde_json::{Map, Value, json}; use vectorcraft_doc::metadata::{MAX_RATING, iso8601}; @@ -22,7 +23,7 @@ const READ_ONLY: [&str; 6] = ["created", "modified", "colorMode", "units", "artb pub(crate) fn info_json(d: &Document) -> Value { let m = &d.metadata; json!({ - "title": d.title, + "title": d.info_title(), "author": m.author, "authorTitle": m.author_title, "description": m.description, @@ -48,14 +49,22 @@ pub(crate) fn file_info(s: &mut Session, p: &Value) -> Result<Value> { _ => return Err(bad(C, "params must be an object")), }; let d = &s.doc()?.doc; - let (mut title, mut m) = (d.title.clone(), d.metadata.clone()); + let (mut title, mut m) = (d.info_title().to_string(), d.metadata.clone()); for (k, v) in o { apply(&mut title, &mut m, k, v)?; } let d = &s.doc()?.doc; - if title != d.title || m != d.metadata { + // A title File Info changes becomes the document's own, as it always has (the tab and Save As + // offer it where the document has no file), and replaces the one its file gave. + let retitled = title != d.info_title(); + if retitled { + m.title = None; + } + if retitled || m != d.metadata { s.edit("File Info", |d, _| { - d.title = title; + if retitled { + d.title = title; + } d.metadata = m; Ok(()) })?; @@ -64,8 +73,8 @@ pub(crate) fn file_info(s: &mut Session, p: &Value) -> Result<Value> { } /// The File Info a PDF or PDF-compatible `.ai` gives ([`vectorcraft_pdf::file_info`]) into `m`: each -/// field that `file.info` would take (a value it refuses is left out), and the created and -/// modified dates. +/// field that `file.info` would take (a value it refuses is left out), its title ([`imported_title`]) +/// as the File Info title, and the created and modified dates. pub(crate) fn read_pdf(m: &mut DocMetadata, f: vectorcraft_pdf::FileInfo) { let status = f.copyrighted.map(|c| if c { CopyrightStatus::Copyrighted } else { CopyrightStatus::PublicDomain }); let fields = [ @@ -83,6 +92,7 @@ pub(crate) fn read_pdf(m: &mut DocMetadata, f: vectorcraft_pdf::FileInfo) { let _ = apply(&mut title, m, k, &v); } } + m.title = f.title.as_deref().and_then(imported_title); m.created = f.created.or(m.created); m.modified = f.modified.or(m.modified); } @@ -141,6 +151,18 @@ fn text(k: &str, v: &Value, multiline: bool) -> Result<String> { Ok(s.to_string()) } +/// The File Info title `raw`, read from a file, makes: runs of white space (line breaks too) +/// become single spaces, other control characters are dropped, at most [`MAX_TEXT`] characters +/// are kept, as `file.info` takes a title. `None` when nothing is left, or when it is the +/// Untitled-N name New gives (what a document that never had a title writes to its files). +pub(crate) fn imported_title(raw: &str) -> Option<String> { + let words: Vec<String> = + raw.split_whitespace().map(|w| w.chars().filter(|c| !c.is_control()).collect::<String>()).filter(|w| !w.is_empty()).collect(); + let title: String = words.join(" ").chars().take(MAX_TEXT).collect(); + let title = title.trim_end(); + super::fileio::is_own_title(title).then(|| title.to_string()) +} + /// Keywords from a list or a comma- or semicolon-separated string: trimmed, each once (ignoring /// case), empty ones dropped. fn keywords(v: &Value) -> Result<Vec<String>> { diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 04a443ed4c..9154ce7ee5 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -2,7 +2,7 @@ //! save, export and serialize by path or bytes (base64), the format table, `command.batch` and //! `action.batch` (the Actions panel menu's Batch…). //! -//! - `load`: `document.open` (native, legacy, SVG/SVGZ, PDF/.ai/.ait, DXF, raster images). +//! - `load`: `document.open` (native, legacy, SVG/SVGZ, PDF/.ai/.ait, DXF, HP-GL, raster images). //! - `action_batch`: play an action on every file in a folder or every data set. //! - `encode`: one encoder per writable format, with typed options parsed from the params. //! - `svg`: the SVG Options (styling, fonts, images, object ids, artboards…). @@ -13,10 +13,11 @@ //! per-format options (`file.formatOptions`); [`save_with`] is the one save path of every frontend. //! - `pdf`: PDF settings and presets for every PDF export, `document.exportPdf`. //! - `pdfimport`: the PDF pages, box and password `document.open` and Place read, `document.pdfInfo`. -//! - `dxf`: DXF export options, `document.exportDxf`, and the formats that can't be written (DWG, PICT). +//! - `dxf`: DXF export options, `document.exportDxf`, and the formats that can't be written (DWG, PageMaker). //! - `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. +//! - `metafile`: EMF and WMF export, open and place; PICT open and place. +//! - `hpgl`: HP-GL export options and plots. //! - `importer`: files that importer plug-ins open (`document.open {importer}`, and extensions no //! built-in format reads). //! - `mesh3d`: 3D assets as OBJ, glTF, USDA and USDZ mesh files (`assets.export3D`). @@ -40,6 +41,7 @@ mod load; mod mesh3d; pub(crate) use load::{MAX_RASTER_ALLOC, size_note}; mod heifread; +mod hpgl; mod jp2read; mod metafile; mod naming; @@ -50,6 +52,7 @@ mod pdfimport; pub mod pngtext; pub mod ppi; pub mod progress; +mod psdlayers; pub mod psdread; mod pxrread; mod save; @@ -63,12 +66,11 @@ 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 use encode::{ARTBOARD_PARAMS, ArtboardPick, Encoded, Note, NoteKind, encode, encode_all, encode_with_notes, encode_with_warnings, note_texts}; pub(crate) use encode::{anti_alias, background, with_single_artboard}; pub(crate) use export::with_artboard_fills; -pub(crate) use export::{export_crop, isolated}; -pub use export::{export_doc, export_source}; -pub(crate) use load::check_not_lossy_overwrite; +pub(crate) use export::{EXPORT_PARAMS, export_crop, isolated}; +pub use export::{export_doc, export_source, unused_option_notes}; use load::err; pub(crate) use load::import_svg; pub(crate) use load::is_placeholder; @@ -79,6 +81,7 @@ pub use load::{ Loaded, RasterImage, ReadFile, detect, file_name, load, load_with, open_bytes, open_bytes_with, open_read, open_template, raster_image, read_for_open, texture_image, }; +pub(crate) use load::{check_files_not_lossy_overwrite, check_not_lossy_overwrite, lossy_source}; 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}; @@ -89,9 +92,9 @@ pub use pdfimport::{LoadOptions, page_document}; pub(crate) use save::job_for; pub(crate) use save::save as save_document; pub use save::{ - SAVE_FORMATS, SaveJob, SaveMode, SavePlan, StreamWrite, TEMPLATE_FORMATS, dialog_folder, export_folder, reads_option as save_reads_option, - remembered_save_options, save_filters, save_format, save_job, save_plan, save_with, stamp_save_dates, template_filters, templates_dialog_folder, - templates_folder, + SAVE_FORMATS, SaveJob, SaveMode, SavePlan, StreamWrite, TEMPLATE_FORMATS, dialog_folder, documents_dialog_folder, export_folder, + leave_out_unreadable_save_paths, reads_option as save_reads_option, remembered_save_options, save_filters, save_format, save_job, save_plan, + save_with, stamp_save_dates, template_filters, templates_dialog_folder, templates_folder, }; pub(crate) use screens::{ PARAM_KEYS as SCREEN_PARAM_KEYS, ROW_KEYS as SCREEN_ROW_KEYS, UNWRITTEN_FORMATS as SCREEN_UNWRITTEN_FORMATS, @@ -120,10 +123,16 @@ mod formats; #[cfg(not(target_arch = "wasm32"))] pub(crate) use access::list_dir; -pub use access::write_file_with; +pub use access::{write_file_with, write_save_file, write_save_file_with}; + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests_readonly; #[cfg(not(target_arch = "wasm32"))] pub(crate) use access::{Placed, copy_new, file_metadata}; -pub(crate) use access::{absolute_path, create_dir, document_path, file_created, file_stamp, read_file, read_file_head, write_file, write_new_file}; +pub(crate) use access::{ + absolute_path, create_dir, document_path, file_created, file_stamp, naming_in_error, read_file, read_file_head, shown_link, shown_path, + write_file, write_new_file, +}; #[cfg(all(test, windows))] pub(crate) use access::{document_path_on, document_path_with}; #[cfg(test)] @@ -138,6 +147,7 @@ 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}; +pub(crate) use formats::is_own_title; use formats::{ARTBOARD, ARTBOARDS, RANGE, USE_ARTBOARDS, import_name, writable}; pub use formats::{ DOC_EXTS, DOCX_EXTS, FORMATS, Format, FormatOption, OPEN_EXTS, PLACE_EXTS, RTF_EXTS, TEXT_EXTS, UNASSOCIATED_EXTS, builtin_open_filters, @@ -204,7 +214,11 @@ mod tests_eps; #[cfg(test)] mod tests_dxfimport; #[cfg(test)] +mod tests_hpgl; +#[cfg(test)] mod tests_metafile; +#[cfg(test)] +mod tests_pict; #[cfg(test)] mod tests_pdfoutput; @@ -218,6 +232,8 @@ mod tests_pdfx; #[cfg(test)] mod tests_psd; #[cfg(test)] +mod tests_psdlayers; +#[cfg(test)] mod tests_psdread; #[cfg(test)] diff --git a/crates/engine/src/cmd/fileio/access.rs b/crates/engine/src/cmd/fileio/access.rs index 4dce2023bb..6488972d31 100644 --- a/crates/engine/src/cmd/fileio/access.rs +++ b/crates/engine/src/cmd/fileio/access.rs @@ -42,6 +42,85 @@ pub(crate) fn touched<T>(f: impl FnOnce() -> T) -> (T, Vec<String>) { (out, seen) } +/// May a reply to the request being served name `path`, a file or folder the client did not give? +/// Always without roots in force; with them, only inside the read roots ([`crate::file_access::check_read`]). +pub(crate) fn shown(path: &str) -> bool { + crate::file_access::check_read(path).is_ok() +} + +/// `path` as a reply to the request being served names it: whole when [`shown`], else its file name, +/// after the last `/` or `\` whichever platform wrote it (empty for a path that ends in no name, such +/// as `..` or a folder ending in a separator). +pub(crate) fn shown_path(path: &str) -> std::borrow::Cow<'_, str> { + shown_link(path, None) +} + +/// A link's `stored` path as a reply to the request being served names it: whole when the file it +/// names (`resolved`, else `stored` itself) is [`shown`], else its file name as [`shown_path`] gives it. +pub(crate) fn shown_link<'a>(stored: &'a str, resolved: Option<&str>) -> std::borrow::Cow<'a, str> { + if shown(resolved.unwrap_or(stored)) { + return std::borrow::Cow::Borrowed(stored); + } + let name = stored.rsplit(vectorcraft_doc::links::path_separators(stored)).next().unwrap_or_default(); + std::borrow::Cow::Borrowed(if matches!(name, "." | "..") { "" } else { name }) +} + +/// What an error names a file or folder outside the read roots by when [`shown_path`] gives no +/// name for it, or gives one that is not valid text. +pub(crate) const UNNAMED: &str = "a file or folder outside the read roots"; + +/// An error about `path`, a file or folder the client did not give, as the request being served +/// may see it: where the message names `path` ([`naming_in_message`]), it names it as +/// [`shown_path`] does, or as [`UNNAMED`] when that is empty or holds a replacement character. The +/// roots the message names and the reason stay whole. Unchanged when `path` is [`shown`]. +pub(crate) fn naming_in_error(e: EngineError, path: &str) -> EngineError { + if path.is_empty() || shown(path) { + return e; + } + naming_as(e, path, &error_name(path)) +} + +/// What an error names `path` by when it is outside the read roots: [`shown_path`], or +/// [`UNNAMED`] when that is empty or holds a replacement character. +pub(crate) fn error_name(path: &str) -> String { + let name = shown_path(path); + if name.is_empty() || name.contains('\u{FFFD}') { UNNAMED.to_string() } else { name.into_owned() } +} + +/// [`naming_in_error`] with `path` named `name`, whether or not it is [`shown`] (a name worked out +/// earlier, for the request that prepared the work). +pub(crate) fn naming_as(e: EngineError, path: &str, name: &str) -> EngineError { + match e { + EngineError::Other(msg) => EngineError::Other(naming_in_message(&msg, path, name)), + EngineError::BadParams { cmd, msg } => EngineError::BadParams { cmd, msg: naming_in_message(&msg, path, name) }, + EngineError::ReadOnlyLocation(msg) => EngineError::ReadOnlyLocation(naming_in_message(&msg, path, name)), + e => e, + } +} + +/// `msg` with `path` given as `name` where it begins a path the message is about: at the start of +/// `msg` (`<path>: <reason>`), after a `: ` (`... outside the write root <root>: <path>`) or after +/// `cannot resolve `, followed by the end, a separator, a `:` or a space. A root the message names +/// stays whole, even one inside `path`. +pub(crate) fn naming_in_message(msg: &str, path: &str, name: &str) -> String { + const BEFORE: [&str; 2] = [": ", "cannot resolve "]; + let mut out = String::with_capacity(msg.len()); + let mut rest = msg; + loop { + if let Some(after) = rest.strip_prefix(path) + && after.chars().next().is_none_or(|c| matches!(c, '/' | '\\' | ':' | ' ')) + { + out.push_str(name); + rest = after; + } + let Some((i, len)) = BEFORE.iter().filter_map(|b| rest.find(b).map(|i| (i, b.len()))).min() else { break }; + out.push_str(&rest[..i + len]); + rest = &rest[i + len..]; + } + out.push_str(rest); + out +} + /// `path` checked for writing against the automation roots in force. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn may_write(path: &str) -> Result<()> { @@ -89,6 +168,31 @@ pub fn write_file_with(path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) vectorcraft_format::write_atomic_with(std::path::Path::new(path), |f| fill(f)).map_err(|e| EngineError::Other(format!("{path}: {e}"))) } +/// The save commands' writer: preserves a filesystem location refusal as a typed error. Other +/// writers keep their existing errors; an automation-root refusal is never reclassified. +pub fn write_save_file(path: &str, bytes: &[u8]) -> Result<()> { + write_save_file_with(path, &mut |w| w.write_all(bytes)) +} + +/// [`write_save_file`] for a streamed save. +#[cfg(not(target_arch = "wasm32"))] +pub fn write_save_file_with(path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>) -> Result<()> { + vectorcraft_doc::cancel::check()?; + may_write(path)?; + vectorcraft_format::write_atomic_with(std::path::Path::new(path), |f| fill(f)).map_err(|e| save_write_error(path, e)) +} + +#[cfg(not(target_arch = "wasm32"))] +pub(super) fn save_write_error(path: &str, error: std::io::Error) -> EngineError { + let reason = format!("{path}: {error}"); + if vectorcraft_format::read_only_location(&error) { EngineError::ReadOnlyLocation(reason) } else { EngineError::Other(reason) } +} + +#[cfg(target_arch = "wasm32")] +pub fn write_save_file_with(path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>) -> Result<()> { + write_file_with(path, fill) +} + #[cfg(not(target_arch = "wasm32"))] pub(crate) fn create_dir(path: &str) -> Result<()> { may_write(path)?; @@ -418,3 +522,52 @@ pub(crate) fn create_dir(path: &str) -> Result<()> { pub(crate) fn write_new_file(path: &str, _: &[u8]) -> Result<()> { Err(no_fs(path)) } + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests { + use super::*; + use crate::file_access::{AutomationRoots, confine}; + + /// An error about a path the client did not give, under roots that don't let it be read: the + /// path is named by its file name (after a `/` or a `\`), or as [`UNNAMED`] when it ends in no + /// name or its name is not valid text, and every root and the reason stay whole. A path inside the + /// read roots, and any path without roots in force, stay whole. + #[test] + fn an_error_names_a_path_outside_the_read_roots_by_its_name() { + let base = std::env::temp_dir().join(format!("vc-access-naming-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let (a, b, out) = (base.join("a"), base.join("b"), base.join("kept-out")); + for f in [&a, &b, &out] { + std::fs::create_dir_all(f).unwrap(); + } + let text = |p: &std::path::Path| p.to_string_lossy().into_owned(); + let roots = AutomationRoots::new(&[a.as_path(), b.as_path()], &[a.as_path(), b.as_path()]).unwrap(); + let file = text(&out.join("doc.svg")); + let raw = confine(roots.as_ref(), || crate::file_access::check_write(&file)).unwrap_err(); + let shown_root = |p: &std::path::Path| crate::cmd::findfiles::plain(std::fs::canonicalize(p).unwrap()).display().to_string(); + let (ra, rb) = (shown_root(&a), shown_root(&b)); + let named = |e: EngineError, path: &str| confine(roots.as_ref(), || naming_in_error(e, path)).to_string(); + + assert_eq!(named(EngineError::Other(raw.clone()), &file), format!("automation path rejected: outside the write roots {ra}, {rb}: doc.svg")); + let io = named(EngineError::Other(format!("{file}: disk full")), &file); + assert_eq!(io, "doc.svg: disk full"); + let bad = named(EngineError::BadParams { cmd: "x".into(), msg: format!("{file}: not a file") }, &file); + assert_eq!(bad, "invalid parameters for `x`: doc.svg: not a file"); + // A save refused by the file system keeps its type and its code. + let read_only = confine(roots.as_ref(), || naming_in_error(EngineError::ReadOnlyLocation(format!("{file}: Permission denied")), &file)); + assert!(matches!(&read_only, EngineError::ReadOnlyLocation(_))); + assert_eq!(read_only.to_string(), format!("{}: doc.svg: Permission denied", crate::READ_ONLY_LOCATION)); + // A Windows path written with `\`, a path that ends in no name and a name that isn't text. + let win = r"C:\Users\me\secret\doc.svg"; + assert_eq!(named(EngineError::Other(format!("{win}: denied")), win), "doc.svg: denied"); + let folder = format!("{}/", text(&out)); + assert_eq!(named(EngineError::Other(format!("{folder}: denied")), &folder), format!("{UNNAMED}: denied")); + let lossy = text(&out.join("bad\u{FFFD}.svg")); + assert_eq!(named(EngineError::Other(format!("{lossy}: denied")), &lossy), format!("{UNNAMED}: denied")); + // Readable, or nothing confined: whole. + let inside = text(&a.join("x.svg")); + assert_eq!(named(EngineError::Other(format!("{inside}: denied")), &inside), format!("{inside}: denied")); + assert_eq!(naming_in_error(EngineError::Other(raw.clone()), &file).to_string(), raw); + let _ = std::fs::remove_dir_all(base); + } +} diff --git a/crates/engine/src/cmd/fileio/action_batch.rs b/crates/engine/src/cmd/fileio/action_batch.rs index 74d9185ea3..232d5ba1f4 100644 --- a/crates/engine/src/cmd/fileio/action_batch.rs +++ b/crates/engine/src/cmd/fileio/action_batch.rs @@ -11,7 +11,7 @@ use serde_json::json; use super::super::{Result, Session, bad}; #[cfg(not(target_arch = "wasm32"))] -use super::super::{bool_or, find_command, str_param}; +use super::super::{check_switches, find_command, switch_or, text_param}; #[cfg(target_arch = "wasm32")] pub(super) fn action_batch(_: &mut Session, _: &Value) -> Result<Value> { @@ -68,12 +68,24 @@ pub(super) fn action_batch(s: &mut Session, p: &Value) -> Result<Value> { )); } } - let source = str_param(p, "source").unwrap_or("folder"); - let destination = str_param(p, "destination").unwrap_or("none"); + // Every option is checked before the destination folder is made. + let source = text_param(p, "source", C)?.unwrap_or("folder"); + if !matches!(source, "folder" | "datasets") { + return Err(bad(C, "`source` must be `folder` or `datasets`")); + } + let destination = text_param(p, "destination", C)?.unwrap_or("none"); if !matches!(destination, "none" | "saveAndClose" | "folder") { return Err(bad(C, "`destination` must be `none`, `saveAndClose` or `folder`")); } - let dest_folder = str_param(p, "destinationFolder").map(absolute_path); + let dest_folder = text_param(p, "destinationFolder", C)?.map(absolute_path); + text_param(p, "folder", C)?; + let label = text_param(p, "label", C)?.unwrap_or("Batch").to_string(); + let dataset_file_naming = text_param(p, "datasetFileNaming", C)?.unwrap_or("fileDataSetName"); + let override_open = switch_or(p, "overrideOpen", true, C)?; + let stop_on_error = switch_or(p, "stopOnError", true, C)?; + let override_save = switch_or(p, "overrideSave", true, C)?; + let override_export = switch_or(p, "overrideExport", true, C)?; + check_switches(p, &["includeSubdirs"], C)?; if destination == "folder" { let Some(ref folder) = dest_folder else { return Err(bad(C, "`destinationFolder` is required when destination is `folder`")); @@ -81,17 +93,15 @@ pub(super) fn action_batch(s: &mut Session, p: &Value) -> Result<Value> { may_write(folder)?; std::fs::create_dir_all(folder).map_err(|e| bad(C, format!("{folder}: {e}")))?; } - let label = str_param(p, "label").unwrap_or("Batch").to_string(); - let override_open = bool_or(p, "overrideOpen", true); let run = Run { label: &label, steps: cmds, - stop_on_error: bool_or(p, "stopOnError", true), - override_save: bool_or(p, "overrideSave", true), - override_export: bool_or(p, "overrideExport", true), + stop_on_error, + override_save, + override_export, destination, dest_folder: dest_folder.as_deref(), - dataset_file_naming: p.get("datasetFileNaming").map_or("fileDataSetName", |v| v.as_str().unwrap_or("")), + dataset_file_naming, }; match source { "folder" => batch_folder(s, C, p, override_open, &run), @@ -186,9 +196,9 @@ fn retargeting_save(c: &Value, redirected: bool) -> bool { fn batch_folder(s: &mut Session, cmd: &str, p: &Value, override_open: bool, run: &Run<'_>) -> Result<Value> { use super::{absolute_path, may_read}; - let folder = str_param(p, "folder").map(absolute_path).ok_or_else(|| bad(cmd, "missing `folder`"))?; + let folder = text_param(p, "folder", cmd)?.map(absolute_path).ok_or_else(|| bad(cmd, "missing `folder`"))?; may_read(&folder)?; - let include_subdirs = bool_or(p, "includeSubdirs", false); + let include_subdirs = switch_or(p, "includeSubdirs", false, cmd)?; let files = collect_files(&folder, include_subdirs, 0)?; if files.len() > MAX_BATCH_FILES { return Err(bad(cmd, format!("more than {MAX_BATCH_FILES} files"))); @@ -526,6 +536,7 @@ fn dataset_output_extensions(run: &Run<'_>, doc: &vectorcraft_doc::Document, def | "dxf" | "emf" | "wmf" + | "hpgl" | "ai" ) }; @@ -716,6 +727,11 @@ fn collect_files(folder: &str, include_subdirs: bool, depth: usize) -> Result<Ve } } files.sort(); + // Names that are not valid text come back lossily, so different names can give one path: each + // folder is listed once. + files.dedup(); + subdirs.sort(); + subdirs.dedup(); for sub in subdirs { let mut nested = collect_files(&sub, true, depth + 1)?; files.append(&mut nested); @@ -749,6 +765,22 @@ mod tests { d } + #[cfg(unix)] + #[test] + fn folders_whose_names_alias_after_lossy_conversion_are_listed_once() { + use std::os::unix::ffi::OsStrExt; + let root = tmp("alias"); + // `a\u{FFFD}` is a real folder; two others with bytes that aren't text give the same name. + let real = root.join("a\u{FFFD}"); + std::fs::create_dir_all(&real).unwrap(); + write_svg(&real, "x.svg", "red"); + for bad in [b"a\xFF", b"a\xFE"] { + let _ = std::fs::create_dir_all(root.join(std::ffi::OsStr::from_bytes(bad))); + } + let files = collect_files(&root.to_string_lossy(), true, 0).unwrap(); + assert_eq!(files.len(), 1, "{files:?}"); + } + fn write_svg(dir: &std::path::Path, name: &str, fill: &str) -> std::path::PathBuf { let p = dir.join(name); std::fs::write( @@ -789,6 +821,46 @@ mod tests { assert!(dest.join("b.svg").is_file(), "b.svg written"); } + #[test] + fn batch_refuses_options_of_the_wrong_type_before_it_writes() { + let src = tmp("types-src"); + let dest = tmp("types-dest"); + write_svg(&src, "a.svg", "#f00"); + let mut s = Session::new(); + let cases = [ + ("stopOnError", json!("false"), "`stopOnError` must be true or false"), + ("overrideOpen", json!(0), "`overrideOpen` must be true or false"), + ("overrideSave", json!("true"), "`overrideSave` must be true or false"), + ("overrideExport", json!([]), "`overrideExport` must be true or false"), + ("includeSubdirs", json!(1), "`includeSubdirs` must be true or false"), + ("source", json!(1), "`source` must be a string"), + ("source", json!("files"), "`source` must be `folder` or `datasets`"), + ("destination", json!(true), "`destination` must be a string"), + ("folder", json!(5), "`folder` must be a string"), + ("label", json!(5), "`label` must be a string"), + ("datasetFileNaming", json!(3), "`datasetFileNaming` must be a string"), + ]; + for (key, value, message) in cases { + let out = dest.join(key); + let mut p = json!({ + "folder": src.to_string_lossy(), + "destination": "folder", + "destinationFolder": out.to_string_lossy(), + "commands": [{"command": "object.unlockAll", "params": {}}], + }); + p[key] = value; + let e = s.execute("action.batch", &p).unwrap_err().to_string(); + assert!(e.contains(message), "{key}: {e}"); + assert!(!out.exists(), "{key}: the destination folder was created"); + } + let e = s + .execute("action.batch", &json!({"folder": src.to_string_lossy(), "destination": "folder", "destinationFolder": 7, "commands": [{"command": "object.unlockAll"}]})) + .unwrap_err() + .to_string(); + assert!(e.contains("`destinationFolder` must be a string"), "{e}"); + assert!(s.active().is_none(), "no file was opened"); + } + #[cfg(unix)] #[test] fn batch_folder_keeps_backslash_in_source_file_name() { @@ -1357,6 +1429,42 @@ mod tests { assert_eq!(written.len(), 2, "{written:?}"); } + /// A Data Sets batch whose Save step has no path saves the document's own file. When that file is + /// outside the client's read and write roots, each row's error keeps the write root and names the + /// file by its file name, with Stop on Error on and off. A source folder the client gives stays + /// whole in the error. + #[test] + fn dataset_batch_step_error_hides_document_path() { + use crate::file_access::{AutomationRoots, confine}; + + let base = tmp("roots-error"); + let (inside, outside) = (base.join("in"), base.join("kept-out")); + for f in [&inside, &outside] { + std::fs::create_dir_all(f).unwrap(); + } + let mut s = with_data_sets(&["Alpha", "Beta"]); + let own = outside.join("doc.vectorcraft").to_string_lossy().into_owned(); + s.execute("document.save", &json!({"path": own})).unwrap(); + let roots = AutomationRoots::new(&[inside.as_path()], &[inside.as_path()]).unwrap(); + let root = crate::cmd::findfiles::plain(std::fs::canonicalize(&inside).unwrap()).display().to_string(); + let hidden = outside.to_string_lossy().into_owned(); + for (stop, rows) in [(true, 1), (false, 2)] { + let p = json!({"source": "datasets", "stopOnError": stop, "commands": [{"command": "document.save", "params": {}}]}); + let r = confine(roots.as_ref(), || s.execute("action.batch", &p)).unwrap(); + assert_eq!((r["failed"].as_u64(), r["processed"].as_array().map(Vec::len)), (Some(rows), Some(rows as usize)), "{r}"); + for row in r["processed"].as_array().unwrap() { + let e = row["error"].as_str().unwrap_or_default(); + let want = format!("batch step 0 (`document.save`) failed: automation path rejected: outside the write root {root}: doc.vectorcraft"); + assert_eq!(e, want, "{r}"); + } + assert!(!r.to_string().contains(&hidden), "{r}"); + } + let p = json!({"source": "folder", "folder": hidden, "commands": [{"command": "object.unlockAll", "params": {}}]}); + let e = confine(roots.as_ref(), || s.execute("action.batch", &p)).unwrap_err().to_string(); + assert!(e.contains(&hidden), "{e}"); + let _ = std::fs::remove_dir_all(base); + } + /// The names of the files in `dir`, sorted. fn file_names(dir: &std::path::Path) -> Vec<String> { let mut names: Vec<String> = diff --git a/crates/engine/src/cmd/fileio/batch.rs b/crates/engine/src/cmd/fileio/batch.rs index 18bc78b5d9..5863dd4ff7 100644 --- a/crates/engine/src/cmd/fileio/batch.rs +++ b/crates/engine/src/cmd/fileio/batch.rs @@ -41,6 +41,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> { roll_back(s, start, &stash); s.notify_text_tool("batch.rollBack"); s.active = active; + s.sync_front_profiles(); (s.paint, s.fill_active, s.draw_mode, s.draw_inside, s.clipboard, s.untitled_counter, s.explicit_undo_group) = saved; s.pending_paint = None; return Err(e); @@ -78,8 +79,13 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> { /// `artboard`, as the Artboards panel shows it in the document the step runs in: past that /// document's last artboard, the last one; a Paste in Place, in Front or in Back step that names /// `artboards` keeps them, and one that names neither, while the Artboard tool is chosen with -/// several artboards selected, pastes on those. A step that resizes the active artboard -/// ([`crate::FIT_ACTIVE_ARTBOARD`]) and names no `index` gets that artboard as its `index`. +/// several artboards selected, pastes on those. A Fit to Artwork Bounds step that names neither +/// `index` nor `indices`, while the Artboard tool is chosen with two or more artboards selected when +/// the step runs, gets those as its `indices`. Otherwise a step that resizes the active artboard +/// ([`crate::FIT_ACTIVE_ARTBOARD`]) and names no `index` (nor `indices`, for Fit to Artwork Bounds) +/// gets that artboard as its `index`. A Fit to Artwork Bounds step that still names neither gets +/// `index` 0, the command's default. A Fit to Artwork Bounds step's journal entry records the +/// `indices` or `index` it got. /// `grouped` gets each step's undo groups, as [`Session::batch_steps`] keeps them. fn run_steps( s: &mut Session, @@ -100,7 +106,8 @@ fn run_steps( if s.active().is_some() { s.begin_interaction(label)?; } - let mut params = c.get("params").cloned().unwrap_or(json!({})); + // `"params": null` reads as no params, so the artboards below can still be added. + let mut params = c.get("params").filter(|v| !v.is_null()).cloned().unwrap_or(json!({})); let key = if crate::ON_ACTIVE_ARTBOARD.contains(&id.as_str()) { Some("artboard") } else { @@ -110,15 +117,34 @@ fn run_steps( // Artboard tool is chosen with several artboards selected, pastes on those. let names_artboards = id.starts_with("edit.pasteIn") && (params.get("artboards").is_some() || (params.get("artboard").is_none() && !crate::cmd::edit::artboard_tool_picks(s).is_empty())); + // A Fit to Artwork Bounds step that names neither `index` nor `indices`, while the Artboard + // tool is chosen with two or more artboards selected, fits those. + let fit_unnamed = id == "artboard.fitToArt" && params.get("index").is_none() && params.get("indices").is_none(); + let fit_picks = if fit_unnamed { crate::cmd::edit::artboard_tool_picks(s) } else { Vec::new() }; + if !fit_picks.is_empty() + && let Some(o) = params.as_object_mut() + { + o.insert("indices".into(), json!(fit_picks)); + } if let Some(a) = artboard && let Some(key) = key && params.get(key).is_none() + && !(id == "artboard.fitToArt" && params.get("indices").is_some()) && !names_artboards && let Some(last) = s.active().and_then(|d| d.doc.artboards.len().checked_sub(1)) && let Some(o) = params.as_object_mut() { o.insert(key.into(), json!(usize::try_from(a).map_or(last, |a| a.min(last)))); } + // With neither, the step fits the command's default, the first artboard, named here so the + // journal records it. + if fit_unnamed + && params.get("index").is_none() + && params.get("indices").is_none() + && let Some(o) = params.as_object_mut() + { + o.insert("index".into(), json!(0)); + } // The documents with an undo group open, held so that the step's first edit in one copies it. let start = s.active().map(|d| d.uid); let held: Vec<(u64, Arc<Document>)> = s.docs.iter().filter(|st| st.undo_group.is_some()).map(|st| (st.uid, st.doc.clone())).collect(); @@ -129,8 +155,10 @@ fn run_steps( } grouped.push(step_groups(s, start, &held)); // The step's journal entry records what it took from the preferences or the clock (a - // save's date, a new document's), as a command of its own would. - if noted != params + // save's date, a new document's), as a command of its own would, and the artboards a Fit to + // Artwork Bounds step took from the Artboard tool, the batch or the command's default, so a + // replay does not fit the artboards the Artboard tool has selected then. + if (noted != params || fit_unnamed) && let Some(c) = c.as_object_mut() { c.insert("params".into(), noted); diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index 81e8168d06..5abe3e879c 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -9,7 +9,7 @@ pub fn specs() -> Vec<CommandSpec> { "Open Document", [], None, - "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page) | false (one layer per page, without the art that is off; Save then asks for a name), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), importer?: \"plugin.<id>\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's <image> files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks)", + "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), importer?: \"plugin.<id>\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), PICT .pct/.pic/.pict (QuickDraw versions 1 and 2, with or without the file's 512-byte header: one artboard, the picture's frame; shapes, lines and regions as paths, text as point type, bitmaps, pixel maps and QuickTime JPEG images as images; what isn't read is listed in warnings), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's <image> files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks). An SVG's variable data (SVG Options › Include Variable Data, a variableSets element) gives the document its text variables and data sets, each text variable bound to the type object its docRef names, unless the SVG restores the native document; variable data variable.loadLibrary would refuse is left out with a warning", always, load::open ), @@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> { "Serialize Document", [], None, - "{format?: vectorcraft (default)|template|svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd (ait, a .ait template, is written by file.saveAsTemplate), …the format's options (see document.formats; SVG ones also as svg: {…}), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own)} → {text, warnings} for svg (plus dataBase64, the file, when its encoding isn't UTF-8), else {dataBase64, warnings}; an SVG of several artboards also gives files: [{name, text}], linked images linked: [{name, dataBase64}]. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored", + "{format?: vectorcraft (default)|template|svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd (ait, a .ait template, is written by file.saveAsTemplate), …the format's options (see document.formats; SVG ones also as svg: {…}), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own)} → {text, warnings} for svg (plus dataBase64, the file, when its encoding isn't UTF-8), else {dataBase64, warnings}; an SVG of several artboards also gives files: [{name, text}], linked images linked: [{name, dataBase64}]. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it", has_doc, export::serialize ), @@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> { "Export Document", [], None, - "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored. Never changes the document's path", + "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the visible art), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Never changes the document's path", has_doc, export::export ), @@ -45,7 +45,7 @@ pub fn specs() -> Vec<CommandSpec> { "Export Selection…", ["File"], None, - "{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|vectorcraft|template (default: from the extension, else png), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), …the format's options} the selected objects (template layers left out), each in the layers and groups that hold it, whose clipping paths, opacity masks, effects, opacity and blend modes apply as on the canvas (an object of a blend, envelope, repeat or intertwine on its own; txt: the selected type alone), cropped to the bounds the renderer measures for that art (a clip group by its clip) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored", + "{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|hpgl|vectorcraft|template (default: from the extension, else png), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), …the format's options} the selected objects (template layers left out), each in the layers and groups that hold it, whose clipping paths, opacity masks, effects, opacity and blend modes apply as on the canvas (an object of a blend, envelope, repeat or intertwine on its own; txt: the selected type alone), cropped to the bounds the renderer measures for that art (a clip group by its clip) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it", has_selection, export::export_selection ), @@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> { "Export for Screens", ["File", "Export"], None, - "{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]}; no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused", + "{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]} (into the folder of exportPreset, outside the automation read roots: no ZIP path, and files relative to that folder); no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused", has_doc, screens::export_for_screens ), @@ -63,7 +63,7 @@ pub fn specs() -> Vec<CommandSpec> { "Export Presets", [], None, - "{} → {presets: [{name, builtIn, settings}]} the built-in batch export presets (Logo Package, Print-Ready PDF), then the saved ones; any name works as document.exportForScreens' exportPreset", + "{} → {presets: [{name, builtIn, settings}]} the built-in batch export presets (Logo Package, Print-Ready PDF), then the saved ones (a folder outside the automation read roots is left out of settings); any name works as document.exportForScreens' exportPreset", always, screens::presets_list ), @@ -99,7 +99,7 @@ pub fn specs() -> Vec<CommandSpec> { "Export Export Presets", [], None, - "{names?: [preset names, built-in ones too] (default: every saved preset), path?} write the presets as a .vcexportpresets file (JSON); more than 1000 presets or a file larger than 4194304 bytes is an error → {path, count}; without path → {data: the file's text, count}", + "{names?: [preset names, built-in ones too] (default: every saved preset), path?} write the presets as a .vcexportpresets file (JSON; a folder outside the automation read roots is left out); more than 1000 presets or a file larger than 4194304 bytes is an error → {path, count}; without path → {data: the file's text, count}", always, screens::presets_export ), @@ -108,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> { "Batch", [], None, - "{label?, commands: [{command, params}], artboard?: index (the active artboard; the app passes it: each edit.pasteInPlace, edit.pasteInFront, edit.pasteInBack, object.align, object.distribute, object.distributeSpacing, select.allOnArtboard or symbol.edit step that names none gets it, and each artboard.fitToArt or artboard.fitToSelection step that names no index gets it as index, or the last artboard of a document with fewer)} run several commands as ONE undo step (one in each document they edit: steps may open, switch, close or revert documents); stops at the first error and rolls everything back, documents included", + "{label?, commands: [{command, params}], artboard?: index (the active artboard; the app passes it: each edit.pasteInPlace, edit.pasteInFront, edit.pasteInBack, object.align, object.distribute, object.distributeSpacing, select.allOnArtboard or symbol.edit step that names none gets it, and each artboard.fitToArt or artboard.fitToSelection step that names no index gets it as index, or the last artboard of a document with fewer; an artboard.fitToArt step that names neither index nor indices, while the Artboard tool is chosen with two or more artboards selected when the step runs, gets those as indices instead; the journal records the indices or index an artboard.fitToArt step got)} run several commands as ONE undo step (one in each document they edit: steps may open, switch, close or revert documents); stops at the first error and rolls everything back, documents included", has_doc, batch::batch ), @@ -117,7 +117,7 @@ pub fn specs() -> Vec<CommandSpec> { "Batch…", [], None, - "{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close; for source datasets, save the open document over its own file after each data set, and refuse a document that was never saved, was converted from an older version or was restored by Data Recovery, unless a recorded Save or Save As step writes a file first; a Save or Save As step that overrideSave points into destinationFolder makes each data set's file the document's own) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportSelection the same way, and give document.exportForScreens / assets.export the folder destinationFolder/{stem}, one for each source file or data set, in which the export names its files as it does outside Batch), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs; {stem} is the file's name without its extension and without trailing periods and spaces, with `-2`, `-3`… added to a name an earlier file used or whose file or folder has the name of one an earlier file wrote or of another source file or a folder of source files in destinationFolder), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-` and trailing periods and spaces are dropped; a name already used in the batch or whose output file or folder already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest. → {processed: [{path|dataset, result|error}…], count, failed, stopped, warning?} (warning: for source datasets, when Save and Close without such a step, or a Save, Save a Copy, Save as Template or export step (document.export, exportSelection, exportForScreens, exportPdf, exportEps, exportDxf, exportForWeb, exportForOffice) that writes a file and is not pointed into destinationFolder, saves every data set over the same file)", + "{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close; for source datasets, save the open document over its own file after each data set, and refuse a document that was never saved, was converted from an older version or was restored by Data Recovery, unless a recorded Save or Save As step writes a file first; a Save or Save As step that overrideSave points into destinationFolder makes each data set's file the document's own) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportSelection the same way, and give document.exportForScreens / assets.export the folder destinationFolder/{stem}, one for each source file or data set, in which the export names its files as it does outside Batch), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs; {stem} is the file's name without its extension and without trailing periods and spaces, with `-2`, `-3`… added to a name an earlier file used or whose file or folder has the name of one an earlier file wrote or of another source file or a folder of source files in destinationFolder), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-` and trailing periods and spaces are dropped; a name already used in the batch or whose output file or folder already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest. A switch (includeSubdirs, overrideOpen, overrideSave, overrideExport, stopOnError) that is not true or false, or a source, folder, destination, destinationFolder, datasetFileNaming or label that is not a string, is an error before any folder is made or file opened; null reads as left out. → {processed: [{path|dataset, result|error}…], count, failed, stopped, warning?} (warning: for source datasets, when Save and Close without such a step, or a Save, Save a Copy, Save as Template or export step (document.export, exportSelection, exportForScreens, exportPdf, exportEps, exportDxf, exportForWeb, exportForOffice) that writes a file and is not pointed into destinationFolder, saves every data set over the same file)", always, action_batch::action_batch ), @@ -126,7 +126,7 @@ pub fn specs() -> Vec<CommandSpec> { "File Formats", [], None, - "{} → {formats: [{id, label, extensions, mime, read, write, raster, options: {name: {type, default, description}}, plugin?: the id of the exporter plug-in (write only) or importer plug-in (read only) that adds the format (its id is plugin.<plug-in id>; see plugin.list)}], readable: [id…], writable: [id…], openExtensions: [ext…] (the importers' extensions that no built-in format reads included), unsupported: [{id, label, extensions, hint}] (formats asked for that can be neither opened nor written, such as DWG and PICT, with what to use instead)}", + "{} → {formats: [{id, label, extensions, mime, read, write, raster, options: {name: {type, default, description}}, plugin?: the id of the exporter plug-in (write only) or importer plug-in (read only) that adds the format (its id is plugin.<plug-in id>; see plugin.list)}], readable: [id…], writable: [id…], openExtensions: [ext…] (the importers' extensions that no built-in format reads included), unsupported: [{id, label, extensions, hint}] (formats asked for that can be neither opened nor written, such as DWG and PageMaker, with what to use instead)}", always, formats ), @@ -153,7 +153,7 @@ pub fn specs() -> Vec<CommandSpec> { "Export for Screens Settings", [], None, - "{} → {settings}: the document.exportForScreens params the document last exported with ({} when never; saved with the document, the dialog reopens on them)", + "{} → {settings}: the document.exportForScreens params the document last exported with ({} when never; saved with the document, the dialog reopens on them; a folder outside the automation read roots is left out)", has_doc, screens::export_settings ), diff --git a/crates/engine/src/cmd/fileio/dxf.rs b/crates/engine/src/cmd/fileio/dxf.rs index b63447e228..8486cd2226 100644 --- a/crates/engine/src/cmd/fileio/dxf.rs +++ b/crates/engine/src/cmd/fileio/dxf.rs @@ -1,6 +1,6 @@ //! DXF export for every DXF path (`document.export {format: dxf}`, `document.exportDxf`, Export As //! → DXF Options): the options parsed from the params, one drawing per artboard with Use -//! Artboards, and the formats that can't be written (DWG, PICT) with what to use instead. +//! Artboards, and the formats that can't be written (DWG, PageMaker) with what to use instead. use std::sync::Arc; @@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> { "Export DXF", [], None, - "{path?, dxfPreset?: custom (default)|cnc (CNC / CAM: version 2000, the oldest version that has both lightweight polylines and lineweights; unit mm, scale 1; colors 256, all 2000 holds; preserve editability and alterPaths false, so strokes stay center lines; outlineText true, so type is paths; rasterFormat png; the options given override it), version?: R12|R13|R14|2000|2004|2007|2010|2013|2018 (default), unit?: mm (default; any unit name: pt, in, cm…), scale?: 1 (drawing units per unit), scaleLineweights?: false, colors?: 8|16|256|true (default; true colour needs 2004+, else 256), rasterFormat?: png (default)|jpeg (placed images, written next to the file), preserve?: appearance (default: type as outlines; strokes a CAD line can't draw as filled outlines; brush art)|editability (type as text; every stroke a line with its lineweight and dashes), alterPaths?: false (strokes a CAD line can't draw as their filled outlines, with editability too; also strokes wider than 2.11 mm, and every stroke in R13 and R14), outlineText?: false, selectedOnly?: false (the selected objects, in their layers), artboard?: 0 (the origin is its bottom-left corner), useArtboards?: true (one drawing per chosen artboard, artboards?/range?, holding the art over it: {stem}-{artboard}.dxf) | false (the origin at the art's bounds)} → {path, bytes, warnings, files?, linked?: [image files]}; no path → {dataBase64, …, linked?: [{name, dataBase64}]}. Layers become DXF layers (hidden: off; locked; non-printing: not plotted); paths become polylines and splines, fills their outlines (which laser and cutter software reads) and solid hatches. Same as document.export {format: dxf}. A key DXF doesn't take is refused", + "{path?, dxfPreset?: custom (default)|cnc (CNC / CAM: version 2000, the oldest version that has both lightweight polylines and lineweights; unit mm, scale 1; colors 256, all 2000 holds; preserve editability and alterPaths false, so strokes stay center lines; outlineText true, so type is paths; includeImages and includeHatches false, so fills are their outlines and no image files are written; rasterFormat png; the options given override it), version?: R12|R13|R14|2000|2004|2007|2010|2013|2018 (default), unit?: mm (default; any unit name: pt, in, cm…), scale?: 1 (drawing units per unit), scaleLineweights?: false, colors?: 8|16|256|true (default; true colour needs 2004+, else 256), rasterFormat?: png (default)|jpeg (placed images, written next to the file), includeImages?: true (false: placed images and their files are left out), includeHatches?: true (false: fills are their outlines, without solid hatches), preserve?: appearance (default: type as outlines; strokes a CAD line can't draw as filled outlines; brush art)|editability (type as text; every stroke a line with its lineweight and dashes), alterPaths?: false (strokes a CAD line can't draw as their filled outlines, with editability too; also strokes wider than 2.11 mm, and every stroke in R13 and R14), outlineText?: false, selectedOnly?: false (the selected objects, in their layers), artboard?: 0 (the origin is its bottom-left corner), useArtboards?: true (one drawing per chosen artboard, artboards?/range?, holding the art over it: {stem}-{artboard}.dxf) | false (the origin at the art's bounds)} → {path, bytes, warnings, files?, linked?: [image files]}; no path → {dataBase64, …, linked?: [{name, dataBase64}]}. Layers become DXF layers (hidden: off; locked; non-printing: not plotted); paths become polylines and splines, fills their outlines (which laser and cutter software reads) and solid hatches. Same as document.export {format: dxf}. A key DXF doesn't take is refused", has_doc, export_dxf )] @@ -37,7 +37,7 @@ pub(crate) const OPTIONS: &[FormatOption] = &[ name: "dxfPreset", ty: "string", default: "\"custom\"", - description: "custom, or cnc (CNC / CAM: version 2000, mm, 256 colors, editability, type as outlines, PNG images); the options given override it", + description: "custom, or cnc (CNC / CAM: version 2000, mm, 256 colors, editability, type as outlines, no images, no fill hatches); the options given override it", }, FormatOption { name: "version", ty: "string", default: "\"2018\"", description: "R12, R13, R14, 2000, 2004, 2007, 2010, 2013 or 2018" }, FormatOption { @@ -60,6 +60,18 @@ pub(crate) const OPTIONS: &[FormatOption] = &[ default: "\"png\"", description: "png or jpeg: the files placed images are written to, next to the drawing", }, + FormatOption { + name: "includeImages", + ty: "boolean", + default: "true", + description: "placed images are written, linked to their files; false leaves them and their files out", + }, + FormatOption { + name: "includeHatches", + ty: "boolean", + default: "true", + description: "filled areas get a solid hatch after their outlines; false writes the outlines alone", + }, FormatOption { name: "preserve", ty: "string", @@ -94,12 +106,6 @@ pub const UNSUPPORTED: &[Unsupported] = &[ extensions: &["dwg"], hint: "DWG is not available (no openly licensed writer exists): export DXF instead, which CAD apps open", }, - Unsupported { - id: "pict", - label: "PICT", - extensions: &["pict", "pct", "pic"], - hint: "PICT is a retired format and is not supported: convert the file to PDF or PNG first", - }, Unsupported { id: "pmd", label: "PageMaker", @@ -133,6 +139,8 @@ struct Params { scale_lineweights: Option<bool>, colors: Option<Value>, raster_format: Option<String>, + include_images: Option<bool>, + include_hatches: Option<bool>, preserve: Option<String>, alter_paths: Option<bool>, outline_text: Option<bool>, @@ -176,6 +184,8 @@ fn parse(p: &Value) -> Result<(DxfOptions, ArtboardPick)> { scale_lineweights: q.scale_lineweights.unwrap_or(d.scale_lineweights), colors: choice("colors", q.colors.as_ref().map(text), ColorDepth::from_id, d.colors, "8, 16, 256 or true")?, raster: choice("rasterFormat", q.raster_format, RasterFormat::from_id, d.raster, "png or jpeg")?, + include_images: q.include_images.unwrap_or(d.include_images), + include_hatches: q.include_hatches.unwrap_or(d.include_hatches), preserve: choice("preserve", q.preserve, Preserve::from_id, d.preserve, "appearance or editability")?, alter_paths: q.alter_paths.unwrap_or(d.alter_paths), outline_text: q.outline_text.unwrap_or(d.outline_text), @@ -225,6 +235,7 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option<bool>) -> enc.warnings.push(w); } } + enc.add_setting_notes(out.setting_notes); for img in out.images { if !enc.linked.iter().any(|l| l.name == img.name) { enc.linked.push(vectorcraft_svg::LinkedImage { name: img.name, bytes: Arc::new(img.bytes) }); diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs index 84188c313a..0fbffcea82 100644 --- a/crates/engine/src/cmd/fileio/encode.rs +++ b/crates/engine/src/cmd/fileio/encode.rs @@ -74,18 +74,104 @@ pub struct Encoded { pub linked: Vec<vectorcraft_svg::LinkedImage>, /// Image maps, each written beside its image under the image's name (raster `imageMap`). pub maps: Vec<imagemap::Map>, - /// The encoder's warnings (features approximated or left out, options not applied yet). + /// The encoder's warnings: what the file leaves out of the document or writes differently + /// ([`NoteKind::Loss`]). pub warnings: Vec<String>, + /// The encoder's notes on the options: options not applied yet or applied another way, and + /// what an option turns off ([`NoteKind::Setting`]). A reply gives them after the warnings + /// ([`Self::notes`]). + pub setting_notes: Vec<String>, /// What joins the file's stem and the artboard name when there is a file per artboard /// (default `-`; EPS uses `_`, as the reference app names them). pub joiner: Option<&'static str>, } +/// What a note an export gives with its file is about. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum NoteKind { + /// Something of the document (its art, type, layers or artboards) that the file leaves out or + /// that reaches it changed: the format, its version or a limit can't hold it, or the export + /// couldn't write it. + Loss, + /// An option the export didn't apply or applied another way while the art reaches the file as + /// it looks, or something left out because an option turns it off. + Setting, +} + +/// A note an export gives with its file. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Note { + /// What the note is about. + pub kind: NoteKind, + /// The note, in English. + pub text: String, +} + +impl Note { + /// A note about what the file loses ([`NoteKind::Loss`]). + pub fn loss(text: impl Into<String>) -> Self { + Self { kind: NoteKind::Loss, text: text.into() } + } + + /// A note on the options ([`NoteKind::Setting`]). + pub fn setting(text: impl Into<String>) -> Self { + Self { kind: NoteKind::Setting, text: text.into() } + } +} + +/// The texts of `notes` in the order a reply gives them: the losses first, then the notes on the +/// options, each kind in the order given (the status bar names the first). +pub fn note_texts(notes: &[Note]) -> Vec<String> { + let of = |kind| notes.iter().filter(move |n| n.kind == kind).map(|n| n.text.clone()); + of(NoteKind::Loss).chain(of(NoteKind::Setting)).collect() +} + +/// Add `note` to `notes` unless a note with its text is there already. +pub(super) fn add_note(notes: &mut Vec<Note>, note: Note) { + if !notes.iter().any(|n| n.text == note.text) { + notes.push(note); + } +} + impl Encoded { pub(super) fn one(bytes: Vec<u8>) -> Self { Self { files: vec![(None, bytes)], ..Self::default() } } + /// The file `bytes` with `notes`, each in the list of its kind, in the order given. + pub(super) fn one_with_notes(bytes: Vec<u8>, notes: Vec<Note>) -> Self { + let mut enc = Self::one(bytes); + for n in notes { + match n.kind { + NoteKind::Loss => enc.warnings.push(n.text), + NoteKind::Setting => enc.setting_notes.push(n.text), + } + } + enc + } + + /// Add each of `texts` to [`Self::setting_notes`] unless a note with its text is there already. + pub(super) fn add_setting_notes(&mut self, texts: impl IntoIterator<Item = String>) { + for t in texts { + if !self.warnings.contains(&t) && !self.setting_notes.contains(&t) { + self.setting_notes.push(t); + } + } + } + + /// Every note with its kind: the warnings, then the notes on the options that aren't also + /// warnings. + pub fn kinded_notes(&self) -> Vec<Note> { + let settings = self.setting_notes.iter().filter(|t| !self.warnings.contains(t)).map(Note::setting); + self.warnings.iter().map(Note::loss).chain(settings).collect() + } + + /// The notes' texts in the order a reply gives them ([`note_texts`]): the warnings, then the + /// notes on the options, each once. + pub fn notes(&self) -> Vec<String> { + note_texts(&self.kinded_notes()) + } + /// Every file to write for the destination `path` (a path or a file name): the file itself /// when there is one, else `{stem}-{artboard name}.{ext}` beside it (see `joiner`; a file of no artboard /// among several, as Save's master file, is the file itself), then the linked images beside it @@ -128,13 +214,14 @@ impl Encoded { out } - /// The one file and the warnings, when the export wrote nothing else. - fn single(self, f: &Format) -> Result<(Vec<u8>, Vec<String>)> { + /// The one file and the notes, when the export wrote nothing else. + fn single(self, f: &Format) -> Result<(Vec<u8>, Vec<Note>)> { if !self.linked.is_empty() || !self.maps.is_empty() { return Err(bad(C, format!("{} with linked images or an image map writes several files: use document.export", f.label))); } + let notes = self.kinded_notes(); match <[_; 1]>::try_from(self.files) { - Ok([(_, bytes)]) => Ok((bytes, self.warnings)), + Ok([(_, bytes)]) => Ok((bytes, notes)), Err(_) => Err(bad(C, format!("{} writes one file per artboard here: use document.export, or name one artboard", f.label))), } } @@ -321,15 +408,31 @@ pub(crate) fn anti_alias(id: &str) -> std::result::Result<AntiAlias, String> { /// The `useArtboards` param of a PDF, AI, DXF or raster export (SVG has its own): `true` writes every /// chosen artboard (default all), `false` the bounds of the visible art instead, absent one -/// artboard (raster, DXF) or the chosen pages (PDF, AI). -fn use_artboards(p: &Value) -> Result<Option<bool>> { +/// artboard (raster, DXF) or the chosen pages (PDF, AI). Errors name the command `cmd`. +pub(super) fn use_artboards(cmd: &str, p: &Value) -> Result<Option<bool>> { match p.get("useArtboards") { None | Some(Value::Null) => Ok(None), Some(Value::Bool(b)) => Ok(Some(*b)), - Some(v) => Err(bad(C, format!("useArtboards must be true or false, not {v}"))), + Some(v) => Err(bad(cmd, format!("useArtboards must be true or false, not {v}"))), } } +/// With `useArtboards: false` in `p`: `doc` without its opacity-mask or symbol editing layer and +/// with one artboard, the bounds of its visible art, and `p` without the artboard choice. `None` +/// when `useArtboards` is absent, null or true. A document with no visible art is refused. +pub(super) fn art_page(cmd: &str, doc: &Document, p: &Value) -> Result<Option<(Document, Value)>> { + if use_artboards(cmd, p)? != Some(false) { + return Ok(None); + } + let doc = &*doc.without_edit_modes(); + let bounds = vectorcraft_render::encode::art_bounds(doc).ok_or_else(|| bad(cmd, "nothing to export: the document has no visible art"))?; + let mut q = super::export::without_artboards(p); + if let Some(o) = q.as_object_mut() { + o.remove("useArtboards"); + } + Ok(Some((single_artboard(doc, bounds, "Art"), q))) +} + /// The `rect` param of a raster export: `[x, y, width, height]` in points, y down. `None` when /// absent; an error when it is not four finite numbers with a positive size, when the format isn't /// a raster one, or when it comes with an artboard choice (`rect` is the area, so those would @@ -419,8 +522,14 @@ pub fn encode(doc: &Document, format: &str, p: &Value) -> Result<Vec<u8>> { /// Like [`encode`], also returning the encoder's warnings (PDF and SVG: options not applied yet, /// features approximated or left out; every format that draws type: fonts written in the fallback -/// font; PDF, EPS, SVG, EMF, WMF and the raster formats: type that doesn't fit its frame). +/// font; PDF, EPS, SVG, EMF, WMF and the raster formats: type that doesn't fit its frame), what +/// the file loses first ([`note_texts`]). pub fn encode_with_warnings(doc: &Document, format: &str, p: &Value) -> Result<(Vec<u8>, Vec<String>)> { + encode_with_notes(doc, format, p).map(|(bytes, notes)| (bytes, note_texts(¬es))) +} + +/// Like [`encode_with_warnings`], with each note's kind ([`Encoded::kinded_notes`]). +pub fn encode_with_notes(doc: &Document, format: &str, p: &Value) -> Result<(Vec<u8>, Vec<Note>)> { let f = super::writable(C, Some(format), None)?; let enc = encode_all(doc, f.id, p)?; // The error for a version 7 .ai of several artboards names the legacy .ai. @@ -464,7 +573,7 @@ fn encode_all_of(doc: &Document, format: &str, p: &Value) -> Result<Encoded> { } // Formats that draw type: missing fonts come out in the fallback font (PDF and SVG say so // themselves: SVG only when it outlines or embeds fonts). - if (f.raster || matches!(f.id, "eps" | "emf" | "wmf")) + if (f.raster || matches!(f.id, "eps" | "emf" | "wmf" | "hpgl")) && let Some(w) = crate::cmd::fonts::substitution_warning(doc) { enc.warnings.push(w); @@ -476,7 +585,7 @@ fn encode_all_of(doc: &Document, format: &str, p: &Value) -> Result<Encoded> { /// ([`vectorcraft_plugins::export`]). The plug-in is given the native file's JSON /// ([`vectorcraft_format::json_part`]) and `p`'s `params`, for the file `p`'s `path` names (else /// one named after the document) with that path's extension when the plug-in lists it, else its -/// first. Its warnings come back with the file. +/// first. Its warnings come back with the file, as losses (the plug-in gives them no kind). fn plugin_file(doc: &Document, plugin: &vectorcraft_plugins::Plugin, f: &Format, p: &Value) -> Result<Encoded> { use vectorcraft_plugins::{Error, export}; let doc = &*doc.without_edit_modes(); @@ -503,7 +612,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> { let doc = &*doc.without_edit_modes(); let n = doc.artboards.len(); // SVG reads its own `useArtboards` (an SVG option). - let use_artboards = if f.raster || matches!(f.id, "pdf" | "ai" | "dxf" | "emf" | "wmf") { use_artboards(p)? } else { None }; + let use_artboards = if f.raster || matches!(f.id, "pdf" | "ai" | "dxf" | "emf" | "wmf" | "hpgl") { use_artboards(C, p)? } else { None }; // `rect`: that area of the page, as if it were the only artboard (the document is not changed). if let Some(rect) = page_rect(f, p)? { let mut q = super::export::without_artboards(p); @@ -513,13 +622,24 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> { } return encode_files(&single_artboard(doc, rect, "Rect"), f, &q); } - if use_artboards == Some(false) { - let bounds = vectorcraft_render::encode::art_bounds(doc).ok_or_else(|| bad(C, "nothing to export: the document has no visible art"))?; - let mut q = super::export::without_artboards(p); - if let Some(o) = q.as_object_mut() { - o.remove("useArtboards"); - } - return encode_files(&single_artboard(doc, bounds, "Art"), f, &q); + // A PDF of the art's bounds carries no editing data (it would replace the artboards). + if use_artboards == Some(false) + && f.id == "pdf" + && let Some((bytes, notes)) = super::pdf::encode_art_page(C, doc, p)? + { + return Ok(Encoded::one_with_notes(bytes, notes)); + } + // So does a `.ai` file of the art's bounds (a legacy version 7 `.ai` file has none to leave out). + if use_artboards == Some(false) + && f.id == "ai" + && let Some(enc) = super::save::encode_ai_art_page(C, f, doc, p)? + { + return Ok(enc); + } + if use_artboards == Some(false) + && let Some((art, q)) = art_page(C, doc, p)? + { + return encode_files(&art, f, &q); } let bytes = match f.id { "vectorcraft" => super::native::encode(C, f, doc, p)?, @@ -536,10 +656,11 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> { "eps" => return super::eps::encode(doc, p), "emf" => return super::metafile::encode(doc, p, use_artboards, vectorcraft_metafile::Kind::Emf), "wmf" => return super::metafile::encode(doc, p, use_artboards, vectorcraft_metafile::Kind::Wmf), + "hpgl" => return super::hpgl::encode(doc, p, use_artboards), "ai" => return super::save::encode_ai(C, f, doc, p), "pdf" => { - let (bytes, warnings) = super::pdf::encode(C, doc, p)?; - return Ok(Encoded { warnings, ..Encoded::one(bytes) }); + let (bytes, notes) = super::pdf::encode(C, doc, p)?; + return Ok(Encoded::one_with_notes(bytes, notes)); } "png" | "jpg" | "webp" | "gif" | "png8" | "tiff" | "bmp" | "tga" | "psd" => { let o: RasterOptions = options(f, p)?; @@ -591,7 +712,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> { let bytes = renderer.export_region(doc, region, format, &settings).map_err(EngineError::Other)?; // File Info as PNG text chunks. let bytes = if matches!(format, RasterFormat::Png | RasterFormat::Png8) { - vectorcraft_render::encode::png::with_text(bytes, &doc.metadata.png_text(&doc.title)) + vectorcraft_render::encode::png::with_text(bytes, &doc.metadata.png_text(doc.info_title())) } else { bytes }; @@ -606,7 +727,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> { let regions: Vec<Rect> = enc.files.iter().filter_map(|(b, _)| b.and_then(|b| doc.artboards.get(b))).map(|a| a.rect).collect(); enc.warnings.extend(crate::cmd::fonts::export_overflow_warning(doc, &doc.layers, Some(®ions))); if format == RasterFormat::WebP && o.lossless == Some(false) { - enc.warnings.push("lossy WebP isn't available yet: the file is lossless (exact, but larger)".into()); + enc.setting_notes.push("lossy WebP isn't available yet: the file is lossless (exact, but larger)".into()); } return Ok(enc); } diff --git a/crates/engine/src/cmd/fileio/eps.rs b/crates/engine/src/cmd/fileio/eps.rs index ac33326994..3acd23e854 100644 --- a/crates/engine/src/cmd/fileio/eps.rs +++ b/crates/engine/src/cmd/fileio/eps.rs @@ -1,8 +1,8 @@ //! EPS export for every EPS path (`document.export {format: eps}`, `document.exportEps`, Export As //! → EPS Options): the options parsed from the params, transparency flattened with a flattener //! preset, one file of the art's bounds or one per artboard (with a central file of the whole -//! document when there are several and art shows), the preview and thumbnail rendered, -//! and the native document embedded for reopening. +//! document when there are several and art shows), the preview rendered and the thumbnail made +//! from it, and the native document embedded for reopening. use std::borrow::Cow; @@ -11,6 +11,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::Document; use vectorcraft_eps::{EpsOptions, Level, Overprint, Preview, Raster}; use vectorcraft_geom::{Point, Rect}; +use vectorcraft_render::Rendered; use super::super::flatten::{FlattenOptions, expand_transparent_tile_images, flatten_expanded}; use super::super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, str_param}; @@ -47,7 +48,7 @@ pub(crate) const OPTIONS: &[FormatOption] = &[ name: "useArtboards", ty: "boolean", default: "null", - description: "true: one file per chosen artboard (default all), <file>_<artboard>.eps, and with two or more a central <file>.eps of the whole document (none when no art shows); absent: the same when artboard, artboards or range names artboards, else one file of the visible art; false: one file of the visible art, even when artboards are named", + description: "true: one file per chosen artboard (default all), <file>_<artboard>.eps, and with two or more a central <file>.eps of the whole document (when no art shows, Export writes none and Save writes it on the first artboard); absent: the same when artboard, artboards or range names artboards, else one file of the visible art; false: one file of the visible art, even when artboards are named (Save: the first artboard when no art shows)", }, FormatOption { name: "level", ty: "integer", default: "3", description: "PostScript language level, 2 or 3" }, FormatOption { @@ -202,10 +203,15 @@ fn expanded(cmd: &str, p: &Value, saved: &[super::super::FlattenerPreset]) -> Re } } +/// One file to write: its artboard, region and origin. +type Page = (Option<usize>, Rect, Point); + /// The files to write: `(artboard, region, origin)` each — every chosen artboard with its corner /// as the origin, or the visible art's bounds with the first artboard's corner. With two or more /// chosen artboards, a central file of the visible art comes first (none when no art shows). -fn pages(doc: &Document, set: &Settings) -> Result<Vec<(Option<usize>, Rect, Point)>> { +/// `saving`: Save always writes the file it names, so with no visible art that file's region is +/// the first artboard, and the second value is true. +fn pages(doc: &Document, set: &Settings, saving: bool) -> Result<(Vec<Page>, bool)> { let n = doc.artboards.len(); let named = set.boards.resolve(n).map_err(|e| bad(C, e))?; let boards = match (set.use_artboards, named) { @@ -216,29 +222,61 @@ fn pages(doc: &Document, set: &Settings) -> Result<Vec<(Option<usize>, Rect, Poi }; let corner = |r: Rect| Point::new(r.x0, r.y1); let art = |art: Rect| (None, art, doc.artboards.first().map_or(corner(art), |a| corner(a.rect))); + // The visible art's bounds; for Save with no visible art, the first artboard (true). + let visible = || match vectorcraft_render::encode::art_bounds(doc) { + Some(bounds) => Some((bounds, false)), + None if saving => doc.artboards.first().map(|a| (a.rect, true)), + None => None, + }; match boards { Some(boards) => { - let central = (boards.len() > 1).then(|| vectorcraft_render::encode::art_bounds(doc).map(art)).flatten(); + let central = (boards.len() > 1).then(visible).flatten(); let each = boards .into_iter() .map(|b| doc.artboards.get(b).map(|a| (Some(b), a.rect, corner(a.rect))).ok_or_else(|| bad(C, format!("no artboard {}", b + 1)))); - central.map(Ok).into_iter().chain(each).collect() + let pages = central.map(|(bounds, _)| Ok(art(bounds))).into_iter().chain(each).collect::<Result<_>>()?; + Ok((pages, central.is_some_and(|(_, blank)| blank))) } None => { - let bounds = vectorcraft_render::encode::art_bounds(doc).ok_or_else(|| bad(C, "nothing to export: the document has no visible art"))?; - Ok(vec![art(bounds)]) + let missing = if saving { "the document has no artboard" } else { "nothing to export: the document has no visible art" }; + let (bounds, blank) = visible().ok_or_else(|| bad(C, missing))?; + Ok((vec![art(bounds)], blank)) } } } -/// `rect` of `doc` drawn at a pixel a point (fewer when larger than `max` a side), straight RGBA, -/// transparent or on white. -fn render(r: &mut vectorcraft_render::Renderer, doc: &Document, rect: Rect, max: f64, transparent: bool) -> Result<Raster> { +/// Pixels a point for `rect`: one, or fewer when it is larger than `max` a side. +fn fit(rect: Rect, max: f64) -> f64 { let long = rect.width().max(rect.height()); - let scale = if long > max { max / long } else { 1.0 }; + if long > max { max / long } else { 1.0 } +} + +/// `rect` of `doc` drawn at [`fit`]'s scale for `max`, transparent or on white. +fn render(r: &mut vectorcraft_render::Renderer, doc: &Document, rect: Rect, max: f64, transparent: bool) -> Result<Rendered> { + let scale = fit(rect, max); vectorcraft_render::raster_size(rect, scale).map_err(|e| bad(C, e))?; - let img = r.render_region(doc, rect, scale, !transparent); - Ok(Raster { width: img.width, height: img.height, rgba: img.to_straight() }) + Ok(r.render_region(doc, rect, scale, !transparent)) +} + +/// `img` as the writer takes it: straight RGBA. +fn straight(img: &Rendered) -> Raster { + Raster { width: img.width, height: img.height, rgba: img.to_straight() } +} + +/// The thumbnail of `rect` made from `preview`, the same rect rendered larger: at the size a +/// thumbnail render of `rect` has, each pixel the average of the preview's pixels under it, on white. +fn thumbnail_of(preview: &Rendered, rect: Rect) -> Result<Raster> { + let (width, height) = vectorcraft_render::raster_size(rect, fit(rect, THUMBNAIL)).map_err(|e| bad(C, e))?; + let mut rgba = preview.area_resized(width, height).map_err(|e| bad(C, e))?.pixels; + // Premultiplied over white: each channel gains the white the pixel's alpha leaves showing. + for px in rgba.as_chunks_mut::<4>().0 { + let clear = 255 - px[3]; + for c in &mut px[..3] { + *c = c.saturating_add(clear); + } + px[3] = 255; + } + Ok(Raster { width, height, rgba }) } /// What the file carries to reopen: `doc` (with only artboard `board` when the file is one of @@ -268,16 +306,17 @@ pub(super) fn encode(doc: &Document, p: &Value) -> Result<Encoded> { encode_document(doc, p, false) } -/// Save keeps a single page's original frame and all native editing data, unlike Export's -/// optional art-bound crop or separate file per artboard. Existing EPS loss warnings still apply. +/// Save writes the pages Export does (the visible art's bounds, or with Use Artboards the chosen +/// artboards), with a smaller preview. A single file, the one the document becomes, carries all +/// the native editing data; with no visible art its page is the first artboard. pub(super) fn encode_save(doc: &Document, p: &Value) -> Result<Encoded> { encode_document(doc, p, true) } fn encode_document(doc: &Document, p: &Value, saving: bool) -> Result<Encoded> { let set = parse(p)?; - if saving && (set.use_artboards == Some(false) || bool_or(p, "selectedOnly", false)) { - return Err(bad(C, "EPS Save retains the artboard and all artwork: use document.export for cropped or selected-only EPS")); + if saving && bool_or(p, "selectedOnly", false) { + return Err(bad(C, "EPS Save writes all artwork: use document.export for selected-only EPS")); } let original = doc; let (full, warnings) = crate::cmd::place::document::full_documents(doc); @@ -290,18 +329,16 @@ fn encode_document(doc: &Document, p: &Value, saving: bool) -> Result<Encoded> { } else { Cow::Borrowed(original) }; - let pages = if saving { - let board = set.boards.one(doc.artboards.len()).map_err(|e| bad(C, e))?; - let rect = doc.artboards.get(board).ok_or_else(|| bad(C, "the document has no artboard"))?.rect; - vec![(Some(board), rect, Point::new(rect.x0, rect.y1))] - } else { - pages(doc, &set)? - }; + let (pages, blank) = pages(doc, &set, saving)?; if pages.is_empty() { return Err(bad(C, "the document has no artboard")); } - // The artboards' background colors, behind the art (the editing data keeps them as colors). - let filled = super::export::with_artboard_fills(doc, p, pages.iter().filter_map(|(b, ..)| *b)).map_err(|e| bad(C, e))?; + // The file Save writes alone becomes the document's own, so it carries every artboard. + let whole = saving && pages.len() == 1; + // The artboards' background colors, behind the art (the editing data keeps them as colors); + // a page on the first artboard because no art shows has that artboard's color. + let fills = pages.iter().filter_map(|(b, ..)| *b).chain(blank.then_some(0)); + let filled = super::export::with_artboard_fills(doc, p, fills).map_err(|e| bad(C, e))?; let doc = &*filled; let regions: Vec<Rect> = pages.iter().map(|(_, region, _)| *region).collect(); let expanded = expand_transparent_tile_images(doc, &set.flatten)?; @@ -318,17 +355,24 @@ fn encode_document(doc: &Document, p: &Value, saving: bool) -> Result<Encoded> { let mut renderer = vectorcraft_render::Renderer::new(); for (board, region, origin) in pages { let rect = vectorcraft_eps::preview_rect(region, origin); - let preview = match set.eps.preview { + let shown = match set.eps.preview { Preview::None => None, kind => Some(render(&mut renderer, doc, rect, preview_limit, set.eps.transparent_preview && kind == Preview::TiffColor)?), }; - let thumbnail = set.thumbnails.then(|| render(&mut renderer, doc, rect, THUMBNAIL, false)).transpose()?; + // The thumbnail is made from the preview; only a file without one renders it. + let thumbnail = match (set.thumbnails, &shown) { + (false, _) => None, + (true, Some(img)) => Some(thumbnail_of(img, rect)?), + (true, None) => Some(straight(&render(&mut renderer, doc, rect, THUMBNAIL, false)?)), + }; + let preview = shown.as_ref().map(straight); + drop(shown); let o = EpsOptions { region, origin, - title: doc.title.clone(), + title: doc.info_title().to_owned(), created, - native: Some(native(&editing, if saving { None } else { board }, set.include_linked)), + native: Some(native(&editing, if whole { None } else { board }, set.include_linked)), ..set.eps.clone() }; let out = vectorcraft_eps::export(drawn, &o, preview.as_ref(), thumbnail.as_ref()).map_err(|e| bad(C, e))?; @@ -338,6 +382,7 @@ fn encode_document(doc: &Document, p: &Value, saving: bool) -> Result<Encoded> { enc.warnings.push(w); } } + enc.add_setting_notes(out.setting_notes); } enc.warnings.extend(crate::cmd::fonts::export_overflow_warning(doc, &doc.layers, Some(®ions))); Ok(enc) diff --git a/crates/engine/src/cmd/fileio/export.rs b/crates/engine/src/cmd/fileio/export.rs index 62e5b78e6b..1ae96c6f81 100644 --- a/crates/engine/src/cmd/fileio/export.rs +++ b/crates/engine/src/cmd/fileio/export.rs @@ -15,8 +15,45 @@ use super::{ ARTBOARD_PARAMS, Format, default_name, encode_all, encode_with_warnings, merge, with_black_output, writable, write_encoded, write_or_return, }; +/// The keys the export commands take for every format, beside the path, the format and the +/// options `document.formats` lists for each: `richBlack` is Appearance of Black's setting for a +/// raster export, and `params` an exporter plug-in's own. +pub(crate) const EXPORT_PARAMS: [&str; 4] = ["includeArtboardFill", "selectedOnly", "richBlack", "params"]; + +/// A note for each option in `p` that some format takes but the file an export of `cmd` writes in +/// `f` doesn't read (`{format: pdf, quality: 80}`), in the wording of a save's note. An exporter +/// plug-in's format gets none. The notes cover the formats' options only: a key of the command's +/// own ([`EXPORT_PARAMS`]) and an artboard choice that a selection export leaves out get none. +pub fn unused_option_notes(cmd: &str, f: &Format, p: &Value) -> Vec<String> { + let Some(given) = p.as_object() else { return Vec::new() }; + if vectorcraft_plugins::export::by_format(f.id).is_some() { + return Vec::new(); + } + let listed = |k: &str| super::FORMATS.iter().filter(|f| f.write).flat_map(|f| f.options).any(|o| o.name == k); + let written = super::save::written_as(cmd, f, p); + let legacy = f.id == "ai" && super::legacy_ai::wanted(cmd, f, p).unwrap_or(false); + let reads = |k: &str| match (f.id, k) { + // A legacy `.ai` file is not a PDF: it reads its own options only. + ("ai", _) if legacy => super::legacy_ai::reads(k), + // The other `.ai` files don't read the legacy file's options, and `preserveEditing` is + // on for them whatever is given. + ("ai", "preserveEditing") => false, + ("ai", _) if super::legacy_ai::LEGACY_ONLY.contains(&k) => false, + // An export writes one file: only a save writes each artboard to a file of its own, and + // a native file's `range` names those files. + ("vectorcraft" | "template" | "ai", "separateArtboards") | ("vectorcraft" | "template", "range") => false, + _ => super::save::reads_option(f, k), + }; + given + .iter() + .filter(|(k, v)| !v.is_null() && !EXPORT_PARAMS.contains(&k.as_str()) && listed(k) && !reads(k)) + .map(|(k, _)| super::save::unused_option_note(k, &written)) + .collect() +} + pub(super) fn serialize(s: &mut Session, p: &Value) -> Result<Value> { let f = writable("document.serialize", Some(text_param(p, "format", "document.serialize")?.unwrap_or("vectorcraft")), None)?; + let unused = unused_option_notes("document.serialize", f, p); let expanded = expand_presets(s, "document.serialize", p)?; let p = with_black_output(s, &expanded); let (doc, display_doc_title) = source(s, f, &p, "document.serialize")?; @@ -27,7 +64,8 @@ pub(super) fn serialize(s: &mut Session, p: &Value) -> Result<Value> { { o.insert("_displayDocTitle".into(), json!(display_doc_title)); } - let enc = encode_all(doc, f.id, &q)?; + let mut enc = encode_all(doc, f.id, &q)?; + enc.add_setting_notes(unused); let files = enc.named(doc, &default_name(doc, f.extensions[0])); let (main, linked) = files.split_at(enc.files.len()); // Text formats come back as text; an SVG in UTF-16 or ISO 8859-1 also as its bytes. @@ -42,7 +80,7 @@ pub(super) fn serialize(s: &mut Session, p: &Value) -> Result<Value> { } _ => json!({ "dataBase64": vectorcraft_format::base64_encode(bytes) }), }; - let mut out = merge(data(main.first().map_or(&[][..], |m| &m.1)), json!({ "warnings": enc.warnings })); + let mut out = merge(data(main.first().map_or(&[][..], |m| &m.1)), json!({ "warnings": enc.notes() })); if main.len() > 1 { out["files"] = main.iter().map(|(name, bytes)| merge(json!({ "name": name }), data(bytes))).collect(); } @@ -58,6 +96,7 @@ pub(super) fn export(s: &mut Session, p: &Value) -> Result<Value> { super::check_not_lossy_overwrite(s.doc()?, path, p, "document.export")?; } let f = writable("document.export", text_param(p, "format", "document.export")?, path)?; + let unused = unused_option_notes("document.export", f, p); let expanded = expand_presets(s, "document.export", p)?; let p = with_black_output(s, &expanded); let (doc, display_doc_title) = source(s, f, &p, "document.export")?; @@ -68,8 +107,9 @@ pub(super) fn export(s: &mut Session, p: &Value) -> Result<Value> { { o.insert("_displayDocTitle".into(), json!(display_doc_title)); } - let enc = encode_all(doc, f.id, &q)?; - write_encoded(path, &default_name(doc, f.extensions[0]), doc, &enc, json!({ "format": f.id, "warnings": enc.warnings })) + let mut enc = encode_all(doc, f.id, &q)?; + enc.add_setting_notes(unused); + write_encoded(path, &default_name(doc, f.extensions[0]), doc, &enc, json!({ "format": f.id, "warnings": enc.notes() })) } /// The document an export of `st` in format `f` writes ([`export_source`]): a `.ai` or `.ait` @@ -315,12 +355,18 @@ pub(super) fn export_selection(s: &mut Session, p: &Value) -> Result<Value> { super::check_not_lossy_overwrite(s.doc()?, path, p, C)?; } let f = writable(C, text_param(p, "format", C)?, path)?; + let unused = unused_option_notes(C, f, p); let expanded = expand_presets(s, C, p)?; let p = with_black_output(s, &expanded); let (d, bounds) = selection(s, C, f.id == "txt")?; // The encoder's warnings (options accepted but not applied, features approximated or left // out), as document.export reports them. - let (bytes, warnings) = encode_with_warnings(&d, f.id, &without_artboards(&p))?; + let (bytes, mut warnings) = encode_with_warnings(&d, f.id, &without_artboards(&p))?; + for note in unused { + if !warnings.contains(¬e) { + warnings.push(note); + } + } write_or_return(path, &bytes, json!({ "format": f.id, "warnings": warnings, "bounds": [bounds.x0, bounds.y0, bounds.width(), bounds.height()] })) } diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index 23aeb83bb0..75b202c8ab 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -1,6 +1,7 @@ use super::super::unique_name; use super::{ - Result, Session, TEMPLATE_FORMATS, UNSUPPORTED, Unsupported, Value, bad, dxf, eps, json, metafile, native, pdf, screens, svg, text, unsupported, + Result, Session, TEMPLATE_FORMATS, UNSUPPORTED, Unsupported, Value, bad, dxf, eps, hpgl, json, metafile, native, pdf, screens, svg, text, + unsupported, }; /// One option a format's encoder reads from the export params. @@ -479,6 +480,17 @@ pub const FORMATS: &[Format] = &[ }, Format { id: "emf", label: "EMF", extensions: &["emf"], mime: "image/emf", read: true, write: true, raster: false, options: metafile::OPTIONS }, Format { id: "wmf", label: "WMF", extensions: &["wmf"], mime: "image/wmf", read: true, write: true, raster: false, options: metafile::OPTIONS }, + // HP-GL/2 plot files, read by `vectorcraft_cad::hpgl` into paths and written as pen moves. + Format { + id: "hpgl", + label: "HP-GL", + extensions: &["plt", "hpgl", "hgl", "hpg"], + mime: "application/vnd.hp-hpgl", + read: true, + write: true, + raster: false, + options: hpgl::OPTIONS, + }, Format { id: "tga", label: "Targa", @@ -493,7 +505,8 @@ pub const FORMATS: &[Format] = &[ // Affinity Photo's `.afphoto` opens by its content but isn't listed: Finder shouldn't offer a // vector app for a raster editor's documents. reader("affinity", "Affinity", &["af", "afdesign", "afpub"], "application/x-affinity", false), - // Photoshop's large document format: read like a PSD (its merged image), never written. + // The large document form of PSD: read like a PSD (its layers, or its merged image), never + // written. reader("psb", "PSB", &["psb"], "image/x-psb", true), // PostScript programs, read as EPS files are; Print to PostScript writes them, exports don't. reader("ps", "PostScript", &["ps"], "application/postscript", false), @@ -507,6 +520,8 @@ pub const FORMATS: &[Format] = &[ reader("heif", "HEIC/HEIF", &["heic", "heif"], "image/heic", true), // jxl-oxide reads a JPEG XL file's first frame, which is stored as PNG. Exports don't write it. reader("jxl", "JPEG XL", &["jxl"], "image/jxl", true), + // QuickDraw pictures, read by `vectorcraft_metafile::import_pict` into paths, type and images. + reader("pict", "PICT", &["pct", "pic", "pict"], "image/x-pict", false), ]; /// Every extension `document.open` reads (the "All readable files" filter of open dialogs). @@ -551,6 +566,13 @@ pub const OPEN_EXTS: &[&str] = &[ "dxf", "emf", "wmf", + "pct", + "pic", + "pict", + "plt", + "hpgl", + "hgl", + "hpg", "eps", "epsf", "ps", @@ -564,9 +586,10 @@ pub const OPEN_EXTS: &[&str] = &[ /// `.epsf`, `.ps`, Targa, PCX, Pixar, JPEG 2000, HEIC/HEIF or JPEG XL type, nor one for the `.pns`, `.dib` and `.rle` names of /// PNG and BMP files (File › Open and Place still read them all). On Linux the desktop entry's EPS /// type (shared-mime-info's) also covers `.epsf`, so file managers offer VectorCraft for it. +/// The packaging declares no type for HP-GL plot files or PICT pictures either. pub const UNASSOCIATED_EXTS: &[&str] = &[ "psd", "pdd", "psb", "epsf", "ps", "pns", "dib", "rle", "tga", "vda", "icb", "vst", "pcx", "pxr", "jpf", "jpx", "jp2", "j2k", "j2c", "jpc", - "heic", "heif", "jxl", + "heic", "heif", "jxl", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict", ]; /// The extension that picks each writable format when exporting (the format's first; PNG-8 shares @@ -640,6 +663,13 @@ pub const PLACE_EXTS: &[&str] = &[ "dxf", "emf", "wmf", + "pct", + "pic", + "pict", + "plt", + "hpgl", + "hgl", + "hpg", "eps", "epsf", "ps", @@ -760,9 +790,9 @@ pub fn open_extensions() -> &'static [&'static str] { /// File › Open's filters: "All readable files" first, then one per readable format, then one per /// importer plug-in (under its name, with the extensions [`open_extensions`] takes from it), then -/// swatch libraries (which open in the library panel), Libraries panel libraries, flattener, PDF, -/// print and export presets (imported), scripts (checked without running them) and plug-ins -/// (installed). +/// swatch and graphic style libraries (which open in their library panels), Libraries panel +/// libraries, flattener, PDF, print, perspective grid and export presets and composite fonts +/// (imported), shortcut sets, scripts (checked without running them) and plug-ins (installed). pub fn open_filters() -> impl Iterator<Item = (&'static str, &'static [&'static str])> { let (all, importers) = importer_open_part(); std::iter::once(("All readable files", all)).chain(format_filters()).chain(importers).chain(other_open_filters()) @@ -775,14 +805,17 @@ pub fn builtin_open_filters() -> impl Iterator<Item = (&'static str, &'static [& std::iter::once(("All readable files", OPEN_EXTS)).chain(format_filters()).chain(other_open_filters()) } -/// The open-dialog filters after the document formats: swatch libraries, Libraries panel -/// libraries, presets, composite fonts, shortcut sets, scripts and plug-ins. +/// The open-dialog filters after the document formats: swatch and graphic style libraries, +/// Libraries panel libraries, presets (perspective grid presets among them), composite fonts, +/// shortcut sets, scripts and plug-ins. fn other_open_filters() -> impl Iterator<Item = (&'static str, &'static [&'static str])> { std::iter::once(("Swatch libraries", crate::cmd::swatchlib::LIBRARY_EXTS)) + .chain(std::iter::once(("Graphic Style Libraries", std::slice::from_ref(&vectorcraft_doc::style_libs::STYLES_EXT)))) .chain(std::iter::once(("Libraries", crate::cmd::library::LIBRARY_EXTS))) .chain(std::iter::once(("Flattener presets", crate::cmd::flatten::PRESET_EXTS))) .chain(std::iter::once(("PDF presets", crate::cmd::pdfcmds::PRESET_EXTS))) .chain(std::iter::once(("Print presets", crate::cmd::printpresets::PRESET_EXTS))) + .chain(std::iter::once(("Perspective grid presets", crate::cmd::perspgrid::PRESET_EXTS))) .chain(std::iter::once(("Export presets", screens::PRESET_FILE_EXTS))) .chain(std::iter::once(("Composite fonts", crate::cmd::compositefonts::EXTS))) .chain(std::iter::once(("Shortcut sets", crate::cmd::shortcutset::EXTS))) @@ -793,13 +826,13 @@ fn other_open_filters() -> impl Iterator<Item = (&'static str, &'static [&'stati /// Open-dialog filters for Swatch Libraries and Graphic Style Libraries Other Library… and Locate /// Library…. The library formats come first so Linux file portals (which grey out files that don't /// match the default filter) still list `.ase` and the other library extensions; then the same -/// filters as [`builtin_open_filters`] so a document can be picked for its swatches or graphic -/// styles. +/// filters as [`builtin_open_filters`], without a second copy of the library filter, so a document +/// can be picked for its swatches or graphic styles. pub fn library_open_filters( library_label: &'static str, library_exts: &'static [&'static str], ) -> impl Iterator<Item = (&'static str, &'static [&'static str])> { - std::iter::once((library_label, library_exts)).chain(builtin_open_filters()) + std::iter::once((library_label, library_exts)).chain(builtin_open_filters().filter(move |f| *f != (library_label, library_exts))) } /// File → Place dialog filters: "All placeable files", then one per placeable format, then text, @@ -908,13 +941,20 @@ pub(crate) fn import_name(base: &str, taken: impl Fn(&str) -> bool) -> String { /// (the title PDF, PNG and SVG metadata carry). A title of its own stays, and native files keep /// the stored title. pub fn has_own_title(doc: &vectorcraft_doc::Document) -> bool { - !doc.title.trim().is_empty() && !doc.title.strip_prefix("Untitled-").is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit())) + is_own_title(doc.info_title()) +} + +/// Is `title` one a person or a file gave, not blank and not the Untitled-N name New gives? +pub(crate) fn is_own_title(title: &str) -> bool { + !title.trim().is_empty() && !title.strip_prefix("Untitled-").is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit())) } pub fn titled_for_export(doc: &vectorcraft_doc::Document, path: Option<&str>, format: &str) -> Option<vectorcraft_doc::Document> { let path = path.filter(|_| !has_own_title(doc) && !matches!(format, "vectorcraft" | "template" | "ai"))?; let mut d = doc.clone(); d.title = file_stem(path); + // A File Info title that is no title of its own (blank, or an Untitled-N name) would hide it. + d.metadata.title = None; Some(d) } diff --git a/crates/engine/src/cmd/fileio/hpgl.rs b/crates/engine/src/cmd/fileio/hpgl.rs new file mode 100644 index 0000000000..1baac844e6 --- /dev/null +++ b/crates/engine/src/cmd/fileio/hpgl.rs @@ -0,0 +1,127 @@ +//! HP-GL for every path that writes plot files (`vectorcraft_cad::hpgl`): `document.export {format: +//! hpgl}` and Export As (one plot of an artboard, or one per artboard with Use Artboards), with the +//! options parsed from the params. + +use serde_json::Value; +use vectorcraft_cad::hpgl::write::{DEFAULT_TOLERANCE, MAX_PENS, TOLERANCE_RANGE}; +use vectorcraft_cad::hpgl::{HpglOptions, Origin, Version}; +use vectorcraft_doc::Document; + +use super::super::{Result, bad, number_or, switch_or, text_param}; +use super::{ArtboardPick, Encoded, FormatOption}; + +const C: &str = "document.export"; + +/// The options `document.formats` lists for HP-GL. +pub(super) const OPTIONS: &[FormatOption] = &[ + super::ARTBOARD, + super::ARTBOARDS, + super::RANGE, + super::USE_ARTBOARDS, + FormatOption { + name: "hpglVersion", + ty: "string", + default: "\"hpgl\"", + description: "hpgl (IN, SP, PU and PD only; a coordinate outside -32,768 to 32,767 gets a warning) or hpgl2 (also the pens' colors, NP and PC, and each pen's paths as one encoded polyline, PE)", + }, + FormatOption { + name: "curveTolerance", + ty: "number", + default: "0.1", + description: "how far the straight moves a curve becomes may lie from it, in points (0.01 to 10)", + }, + FormatOption { + name: "pens", + ty: "array", + default: "null", + description: "the pen table, pen 1's color first: up to 255 \"#rrggbb\" colors, each path drawn with the pen of the nearest color; null: a pen for each color in the order the art first draws in it, numbered alike in every file of one export", + }, + FormatOption { + name: "origin", + ty: "string", + default: "\"bottomLeft\"", + description: "bottomLeft or center: where (0, 0) lies on the artboard (or the art's bounds)", + }, + FormatOption { + name: "sortPaths", + ty: "boolean", + default: "false", + description: "draw each pen's next path from the end nearest where the pen stopped, instead of in paint order", + }, + FormatOption { + name: "insideFirst", + ty: "boolean", + default: "false", + description: "draw a path only after the pen's paths that lie inside it (a letter's counter before the letter, a hole before the part), the paths otherwise in paint order; with sortPaths, the nearest of the paths free to draw comes next", + }, +]; + +/// The HP-GL options in `p` (the region is set per plot). +fn parse(p: &Value) -> Result<HpglOptions> { + let mut o = HpglOptions::default(); + if let Some(s) = text_param(p, "hpglVersion", C)? { + let key = "hpglVersion"; + o.version = Version::from_id(s).ok_or_else(|| bad(C, format!("`{key}` must be one of {}", Version::ALL.map(Version::id).join(", "))))?; + } + let x = number_or(p, "curveTolerance", DEFAULT_TOLERANCE, C)?; + if !TOLERANCE_RANGE.contains(&x) { + let (key, min, max) = ("curveTolerance", TOLERANCE_RANGE.start(), TOLERANCE_RANGE.end()); + return Err(bad(C, format!("`{key}` must be between {min} and {max} (got {x})"))); + } + o.tolerance = x; + match p.get("pens") { + None | Some(Value::Null) => {} + Some(v) => { + let colors: Option<Vec<[u8; 3]>> = v.as_array().filter(|a| (1..=MAX_PENS).contains(&a.len())).and_then(|a| a.iter().map(hex).collect()); + o.pens = colors.ok_or_else(|| bad(C, "`pens` must be an array of 1 to 255 #rrggbb colors"))?; + } + } + if let Some(s) = text_param(p, "origin", C)? { + let key = "origin"; + o.origin = Origin::from_id(s).ok_or_else(|| bad(C, format!("`{key}` must be one of {}", Origin::ALL.map(Origin::id).join(", "))))?; + } + o.sort = switch_or(p, "sortPaths", false, C)?; + o.inside_first = switch_or(p, "insideFirst", false, C)?; + Ok(o) +} + +/// A `#rrggbb` color. +fn hex(v: &Value) -> Option<[u8; 3]> { + let s = v.as_str()?.strip_prefix('#').filter(|s| s.len() == 6 && s.bytes().all(|b| b.is_ascii_hexdigit()))?; + let byte = |i: usize| s.get(i..i + 2).and_then(|h| u8::from_str_radix(h, 16).ok()); + Some([byte(0)?, byte(2)?, byte(4)?]) +} + +/// Encode `doc` as HP-GL: a plot of the chosen artboard (default the first), or with +/// `use_artboards` one plot per chosen artboard (default all), with one pen numbering for them all. +pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option<bool>) -> Result<Encoded> { + let opts = parse(p)?; + let f = super::format("hpgl").ok_or_else(|| bad(C, "no HP-GL format"))?; + let pick: ArtboardPick = super::encode::options(f, p)?; + let n = doc.artboards.len(); + let boards = match use_artboards { + Some(true) => pick.resolve(n).map_err(|e| bad(C, e))?.unwrap_or_else(|| (0..n).collect()), + _ => vec![pick.one(n).map_err(|e| bad(C, e))?], + }; + let regions = boards + .iter() + .map(|&b| doc.artboards.get(b).map(|a| a.rect).ok_or_else(|| bad(C, format!("no artboard {}", b + 1)))) + .collect::<Result<Vec<_>>>()?; + let plots = vectorcraft_cad::hpgl::export_regions(doc, &opts, ®ions).map_err(|e| bad(C, e))?; + let mut enc = Encoded::default(); + for (b, out) in boards.into_iter().zip(plots) { + enc.files.push((Some(b), out.bytes)); + for w in out.warnings { + if !enc.warnings.contains(&w) { + enc.warnings.push(w); + } + } + enc.add_setting_notes(out.setting_notes); + } + if enc.files.is_empty() { + return Err(bad(C, "the document has no artboard")); + } + let regions: Vec<vectorcraft_geom::Rect> = enc.files.iter().filter_map(|(b, _)| b.and_then(|b| doc.artboards.get(b))).map(|a| a.rect).collect(); + enc.warnings.extend(crate::cmd::fonts::export_overflow_warning(doc, &doc.layers, Some(®ions))); + Ok(enc) +} diff --git a/crates/engine/src/cmd/fileio/legacy_ai.rs b/crates/engine/src/cmd/fileio/legacy_ai.rs index a197363b23..23168f1e25 100644 --- a/crates/engine/src/cmd/fileio/legacy_ai.rs +++ b/crates/engine/src/cmd/fileio/legacy_ai.rs @@ -65,6 +65,18 @@ pub(super) fn named(f: &Format) -> Format { Format { label: "legacy .ai (version 7)", ..*f } } +/// The `.ai` options that only a legacy file reads: a PDF-compatible `.ai` file and a `.ai` file +/// without PDF content don't. +pub(super) const LEGACY_ONLY: [&str; 3] = ["transparentImages", "hiddenObjects", "outlineText"]; + +/// Does an export of a legacy file read option `key`? It reads the version, the file's own +/// options ([`LEGACY_ONLY`]), the artboards to write, and `useArtboards`, which the export reads +/// before [`encode`] runs. It reads none of the other `.ai` options and none of the PDF options +/// that a PDF-compatible `.ai` file takes. +pub(super) fn reads(key: &str) -> bool { + matches!(key, "aiVersion" | "useArtboards") || LEGACY_ONLY.contains(&key) || super::ARTBOARD_PARAMS.contains(&key) +} + /// What a legacy `.ai` does with the images it can't hold (`transparentImages`). #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum SeeThrough { @@ -136,20 +148,23 @@ pub(super) fn encode(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result } let images = see_through_images(&d, mode); if !images.is_empty() { - note(&mut enc.warnings, if mode == SeeThrough::Flatten { FLATTENED } else { OMITTED }); if mode == SeeThrough::Flatten { + note(&mut enc.warnings, FLATTENED); flatten_images(&mut d, &images)?; } else { + // A note on the options: `transparentImages: omit` leaves them out. + enc.add_setting_notes([OMITTED.to_string()]); for (_, id) in images { let _ = d.remove(id); // Inside an image left out before: gone already. } } } - let o = vectorcraft_eps::LegacyAiOptions { title: doc.title.clone(), created, hidden, outline_text }; + let o = vectorcraft_eps::LegacyAiOptions { title: doc.info_title().to_owned(), created, hidden, outline_text }; let out = vectorcraft_eps::export_legacy_ai(&d, &o).map_err(|e| bad(cmd, e))?; for w in placed.iter().chain(&out.warnings) { note(&mut enc.warnings, w); } + enc.add_setting_notes(out.setting_notes); enc.files.push((Some(b), out.bytes)); } // Expanding raster effects and flattening images draw the art, and an image the renderer @@ -182,7 +197,8 @@ fn expand_image_patterns(d: &mut Document) -> Result<()> { } /// The images of `d` a legacy `.ai` can't hold, in paint order with their places in it (as -/// [`Document::walk`] counts). These have see-through pixels or a colorize paint (except the +/// [`Document::walk`] counts). These have see-through pixels (a color-masked image's masked pixels +/// counted as its own) or a colorize paint (except the /// colorized images the writer writes as image masks, clear pixels included, /// [`vectorcraft_eps::writes_image_mask`]), or /// have opacity or a blending mode of their own or, with `flatten`, of a group they are in. @@ -194,7 +210,8 @@ fn see_through_images(d: &Document, mode: SeeThrough) -> Vec<(usize, NodeId)> { let mut at = 0; d.walk(|n| { if let NodeKind::Image(im) = &n.kind - && (((keys.contains(&im.key) || n.extras().colorize.is_some()) && !vectorcraft_eps::writes_image_mask(d, n)) + && (((keys.contains(&im.key) || keys.contains(&d.shown_image(n, im).key) || n.extras().colorize.is_some()) + && !vectorcraft_eps::writes_image_mask(d, n)) || n.opacity < 1.0 || n.blend != BlendMode::Normal || (mode == SeeThrough::Flatten && transparent(d, n.id))) diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index 58fff3cad1..bb9dc3711a 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -7,6 +7,7 @@ use vectorcraft_doc::{Document, ImageBlob, ImageObject, Node, NodeKind}; use vectorcraft_geom::Affine; use vectorcraft_render::effects::pixel::LoadedTexture; +use super::super::fileinfo::imported_title; use super::super::{Result, Session, bad, bool_or, clipboard, parse_range, str_param}; use super::pdfimport::LoadOptions; use super::{Format, SAVE_FORMATS, absolute_path, file_stamp, format, jxlread, psdread, read_file, readable_format_for_name}; @@ -72,6 +73,8 @@ pub struct RasterImage { pub height: u32, /// The resolution the file declares (see [`super::ppi::resolution`]). pub ppi: Option<(f64, f64)>, + /// A DCS file's clipping path, in the image's pixel space ([`crate::cmd::place::dcs`]). + pub clip: Option<vectorcraft_geom::PathData>, } pub(super) fn err(e: impl std::fmt::Display) -> EngineError { @@ -131,9 +134,26 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> { if let Some(f) = image::guess_format(bytes).ok().and_then(image_format) { return Some(f); } + // A version 2 PICT is known by its version opcodes after the picture's frame, at byte 522 of a + // file or byte 10 of a bare picture (version 1 by its file's name), so a format whose + // signature starts the file is checked first. + if vectorcraft_metafile::is_pict(bytes) { + return format("pict"); + } if clipboard::looks_like_svg(&String::from_utf8_lossy(&bytes[..bytes.len().min(4096)])) { return format("svg"); } + // HP-GL has no signature: a file that starts with plotter instructions, named as one or with an + // extension no other format (text, the formats VectorCraft names as unsupported, and the files + // File › Open takes in other ways included) reads. + let ext = super::extension(name); + let other = by_name.is_some_and(|f| f.id != "hpgl") + || super::TEXT_EXTS.contains(&ext.as_str()) + || super::unsupported(&ext).is_some() + || super::opens_as_other(&ext); + if !other && vectorcraft_cad::hpgl::is_hpgl(bytes) { + return format("hpgl"); + } by_name } @@ -368,6 +388,10 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded> let (mut doc, mut warnings, restored) = match format.id { // EPS, .ps and PostScript .ai: the document our EPS files carry, else the PostScript read. _ if matches!(format.id, "eps" | "ps") || vectorcraft_pdf::is_postscript(bytes) => { + // A DCS file's plates print from its file: it is only placed linked. + if crate::cmd::place::dcs::is_dcs(bytes) { + return Err(err(format!("can't open `{}`: {}", file_name(name), crate::cmd::place::dcs::LINK_ONLY))); + } let editing = vectorcraft_eps::has_native(bytes).then_some((true, || vectorcraft_eps::native(bytes))); restore_or_import(editing, || { let r = vectorcraft_eps::import_names(bytes, opts.editing_data, opts.trust_editing_data, opts.legacy_names) @@ -386,7 +410,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded> let editing = vectorcraft_svg::editing(&text).map(|e| (e.intact, move || vectorcraft_format::base64_decode(&e.data))); // Relative links are found in the SVG's folder (when `name` is a path). let folder = std::path::Path::new(name).parent().map(|f| f.to_string_lossy()).filter(|f| !f.is_empty()).map(|f| absolute_path(&f)); - restore_or_import(editing, || import_svg(&text, folder.as_deref()))? + restore_or_import(editing, || open_svg(&text, folder.as_deref()))? } "pdf" | "ai" | "ait" => { // The file is read and checked once, for the document it carries, its pages, the @@ -487,11 +511,29 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded> let (doc, warnings) = super::metafile::import(bytes)?; (doc, warnings, false) } + "pict" => { + let (doc, warnings) = super::metafile::import_pict(bytes)?; + (doc, warnings, false) + } + "hpgl" => { + let i = vectorcraft_cad::hpgl::import(bytes).map_err(err)?; + (i.document, i.warnings, false) + } "affinity" => { let i = super::affinity::import(&title, bytes)?; preview_only = i.preview_only; (i.doc, i.warnings, false) } + // A PSD or PSB file's layers become layers (`layers`, default on); without layers, or with + // `layers: false`, its merged image opens. Layers that can't be read leave the merged image. + "psd" | "psb" if opts.layers => { + let cms = vectorcraft_color::cms::active(); + match super::psdlayers::import(bytes, opts.hidden_layers, MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false)) { + Ok(Some((doc, warnings))) => (doc, warnings, false), + Ok(None) => (raster_doc(&title, bytes)?, vec![], false), + Err(e) => (raster_doc(&title, bytes)?, vec![format!("the layers can't be read ({e}): the file opened as its merged image")], false), + } + } _ if format.raster => (raster_doc(&title, bytes)?, vec![], false), _ => return Err(err(format!("{} files can't be opened yet", format.label))), }; @@ -525,6 +567,15 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded> if let Some(mode) = opts.color_mode.filter(|m| *m != doc.color_mode) { super::super::colormgmt::set_color_mode(&mut doc, mode, true, None, opts.grays); } + // The title the file gives itself (an SVG's `<title>`, a PDF's, `.ai`'s or `.ait`'s XMP `dc:title` + // or Info `Title`, which the readers put in File Info) is separate from the document's name. + // Restored File Info is preserved exactly; newly imported SVG candidates and a restored + // document's legacy name fallback are cleaned as imported text. The name stays the file's (#3626). + if !restored && matches!(format.id, "svg" | "svgz") { + doc.metadata.title = doc.metadata.title.as_deref().and_then(imported_title); + } + let held = restored.then_some(doc.title.as_str()).filter(|t| *t != title); + doc.metadata.title = doc.metadata.title.or_else(|| held.and_then(imported_title)); // Imports are named after the file; a native document keeps its own title (the tab shows the // file name once it has a path). if !matches!(format.id, "vectorcraft" | "template") || doc.title.is_empty() { @@ -538,6 +589,33 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded> /// own): rasters stay linked, SVG files become art, missing ones placeholders (see /// [`vectorcraft_svg::ImportOptions`]). pub(crate) fn import_svg(text: &str, folder: Option<&str>) -> Result<(Document, Vec<String>)> { + import_svg_finding(text, folder, &std::collections::HashSet::new()).map(|(doc, warnings, _)| (doc, warnings)) +} + +/// [`import_svg`] for a document opened from an SVG: with the variable data the file carries (SVG +/// Options › Include Variable Data), read as [`crate::cmd::variablecmds::svg_library`] says. Variable +/// data that can't be read is left out with a warning; the art opens either way. +fn open_svg(text: &str, folder: Option<&str>) -> Result<(Document, Vec<String>)> { + let lib = match crate::cmd::variablecmds::svg_library(text) { + None => return import_svg(text, folder), + Some(Err(e)) => { + let (doc, mut warnings) = import_svg(text, folder)?; + warnings.push(format!("the file's variable data wasn't read: {e}")); + return Ok((doc, warnings)); + } + Some(Ok(lib)) => lib, + }; + let (mut doc, mut warnings, found) = import_svg_finding(text, folder, &lib.elements())?; + warnings.extend(crate::cmd::variablecmds::give_svg_library(&mut doc, lib, &found)); + Ok((doc, warnings)) +} + +/// [`import_svg`], also returning the object made of each element whose id `ids` lists. +fn import_svg_finding( + text: &str, + folder: Option<&str>, + ids: &std::collections::HashSet<String>, +) -> Result<(Document, Vec<String>, vectorcraft_svg::Found)> { // The importer reads on a thread of its own (for its stack): what may be read is what may be // read here. let scope = crate::file_access::ScopeHandle::capture(); @@ -553,7 +631,7 @@ pub(crate) fn import_svg(text: &str, folder: Option<&str>) -> Result<(Document, Some((bytes, link)) }) }; - vectorcraft_svg::import_with(text, &vectorcraft_svg::ImportOptions { folder, read: Some(&read) }).map_err(err) + vectorcraft_svg::import_finding(text, &vectorcraft_svg::ImportOptions { folder, read: Some(&read) }, ids).map_err(err) } /// Open a file's bytes as the new active document (what `document.open` does) → @@ -653,6 +731,7 @@ fn open_loaded(s: &mut Session, loaded: Loaded, links: Resolved, path: Option<St if template { doc.template = false; doc.title = s.next_untitled(); + doc.metadata.title = None; } // A .ai (or .ait) another app wrote carries no open Layers rows we read: all of them start // closed, its top-level layers as its groups (#1475). Ours carry their own. @@ -686,7 +765,7 @@ fn open_loaded(s: &mut Session, loaded: Loaded, links: Resolved, path: Option<St st.import_losses = losses; st.links_from = read_from; let opened = &s.documents()[index]; - let (title, file_info_title) = (opened.title(), opened.doc.title.clone()); + let (title, file_info_title) = (opened.title(), opened.doc.info_title().to_string()); Ok(super::merge( json!({ "index": index, "title": title, "fileInfoTitle": file_info_title, "format": format.id, "warnings": warnings, "restored": restored }), links.to_json(), @@ -789,6 +868,12 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option<String> { /// A TIFF with more strips or tiles than the decoder can count /// ([`vectorcraft_doc::cmyk::oversized_tiff`]) is refused as too large to draw. JPEG XL images are /// read with [`jxlread`] and stored as PNG, with the ICC profile their colors are left in. +/// A PNG, JPEG, GIF, WebP or TIFF whose orientation ([`vectorcraft_doc::cmyk::exif_orientation`]) turns or flips it is +/// stored as it is shown, with its resolution's axes swapped when it turns a quarter; a CMYK JPEG +/// or TIFF keeps its inks, at the 8 or 16 bits the file has, and its CMYK ICC profile as a CMYK +/// TIFF ([`vectorcraft_doc::cmyk::turned_cmyk`]). An image the decoder reads and that is stored as +/// PNG keeps its gray or RGB samples at 8 or 16 bits, and the gray or RGB ICC profile they are in; +/// other samples become 8-bit RGBA. pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> { let ppi = super::ppi::resolution(bytes); if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(bytes) { @@ -827,7 +912,16 @@ pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> { let f = image_format(kind).ok_or_else(|| err(format!("{kind:?} images can't be opened (see document.formats)")))?; // A photo whose EXIF orientation turns or flips it (a camera held upright) is stored as it is // seen, so it places the way it was taken (#4284); the others keep their own bytes. - let turned = matches!(f.id, "png" | "jpg" | "gif" | "webp" | "tiff") && exif_orientation(bytes).is_some(); + let orientation = matches!(f.id, "png" | "jpg" | "gif" | "webp" | "tiff").then(|| vectorcraft_doc::cmyk::exif_orientation(bytes)).flatten(); + let turned = orientation.is_some(); + // The resolution describes the stored pixels; a quarter turn swaps its axes. + let quarter = orientation.is_some_and(|o| o.to_exif() >= 5); + let shown_ppi = ppi.map(|(x, y)| if quarter { (y, x) } else { (x, y) }); + if let Some(orientation) = orientation.filter(|_| matches!(f.id, "jpg" | "tiff")) + && let Some((tiff, size)) = vectorcraft_doc::cmyk::turned_cmyk(bytes, orientation, shown_ppi) + { + return stored(tiff, "image/tiff", size, shown_ppi); + } let kept = match f.id { _ if turned => None, "png" | "jpg" | "gif" | "webp" => Some(bytes.to_vec()), @@ -842,10 +936,12 @@ pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> { let cms = vectorcraft_color::cms::active(); vectorcraft_doc::cmyk::extra_samples_tiff_rgba(bytes, |c| cms.cmyk_to_srgb(c, false)) }; + // The ICC profile of the samples the image decoder reads; the other readers give sRGB pixels. + let mut icc = None; let mut img = match (f.id == "tiff").then(extra_samples).flatten() { - Some(img) => img, + Some(img) => image::DynamicImage::ImageRgba8(img), None => match (f.id == "tiff").then(|| vectorcraft_doc::cmyk::group3_tiff_rgba(bytes)).flatten() { - Some(read) => read.map_err(err)?, + Some(read) => image::DynamicImage::ImageRgba8(read.map_err(err)?), None => { use image::ImageDecoder as _; let mut decoder = reader.into_decoder().map_err(err)?; @@ -854,32 +950,46 @@ pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> { if decoder.total_bytes() > MAX_RASTER_ALLOC || u64::from(w) * u64::from(h) * 4 > MAX_RASTER_ALLOC { return Err(err(format!("an image of {w} × {h} pixels is too large to draw"))); } - let orientation = decoder.orientation().unwrap_or(image::metadata::Orientation::NoTransforms); - let mut img = image::DynamicImage::from_decoder(decoder).map_err(err)?; - img.apply_orientation(orientation); - img.to_rgba8() + // A profile the decoder can't read leaves the image without one. The image decoder + // reads a TIFF's tags within the size of its pixels, so a small TIFF's profile is + // read by the TIFF decoder itself. + icc = match f.id { + "tiff" => vectorcraft_doc::cmyk::tiff_icc_profile(bytes), + _ => decoder.icc_profile().ok().flatten(), + }; + image::DynamicImage::from_decoder(decoder).map_err(err)? } }, }; + img.apply_orientation(orientation.unwrap_or(image::metadata::Orientation::NoTransforms)); if f.id == "tga" { + let mut img = img.into_rgba8(); super::tgaread::fix_alpha(bytes, &mut img); + return as_png(img, None, shown_ppi); } - as_png(img, None, ppi) + use image::DynamicImage as D; + let img = match img { + D::ImageLuma8(_) | D::ImageLumaA8(_) | D::ImageRgb8(_) | D::ImageRgba8(_) => img, + D::ImageLuma16(_) | D::ImageLumaA16(_) | D::ImageRgb16(_) | D::ImageRgba16(_) => img, + other => D::ImageRgba8(other.into_rgba8()), + }; + let icc = icc.filter(|icc| png_takes_icc(&img, icc)); + as_png(img, icc, shown_ppi) } -/// The EXIF orientation of encoded image `bytes` when it turns or flips the pixels; `None` when -/// it leaves them as stored, or the image has none. -pub(crate) fn exif_orientation(bytes: &[u8]) -> Option<image::metadata::Orientation> { - use image::ImageDecoder as _; - let mut decoder = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?.into_decoder().ok()?; - decoder.orientation().ok().filter(|o| *o != image::metadata::Orientation::NoTransforms) +/// Can a PNG of `img`'s samples carry ICC profile `icc`? Its color space must be the samples': +/// `GRAY` for gray samples, `RGB ` for RGB ones. +fn png_takes_icc(img: &image::DynamicImage, icc: &[u8]) -> bool { + let want = if img.color().has_color() { *b"RGB " } else { *b"GRAY" }; + vectorcraft_doc::cmyk::icc_color_space(icc) == Some(want) } /// `img` stored as a PNG that keeps the file's resolution and carries `icc`, the ICC profile its -/// colors are in. -pub(super) fn as_png(img: image::RgbaImage, icc: Option<Vec<u8>>, ppi: Option<(f64, f64)>) -> Result<RasterImage> { +/// colors are in. `img` has samples a PNG holds: 8 or 16 bits of gray or RGB, with or without alpha. +pub(super) fn as_png(img: impl Into<image::DynamicImage>, icc: Option<Vec<u8>>, ppi: Option<(f64, f64)>) -> Result<RasterImage> { use image::ImageEncoder as _; - let size = img.dimensions(); + let img: image::DynamicImage = img.into(); + let size = (img.width(), img.height()); let mut png = Vec::new(); let mut encoder = image::codecs::png::PngEncoder::new(&mut png); if let Some(icc) = icc { @@ -936,13 +1046,13 @@ fn stored(bytes: Vec<u8>, mime: &'static str, (width, height): (u32, u32), ppi: return Err(err("the image is empty")); } let blob = ImageBlob::new(mime, bytes); - Ok(RasterImage { key: blob.content_key(), blob, width, height, ppi }) + Ok(RasterImage { key: blob.content_key(), blob, width, height, ppi, clip: None }) } /// An image as a document of its physical size at the resolution it declares (as Place sizes it; /// 72 ppi, 1 px = 1 pt, when it declares none), the image named after the file. pub(super) fn raster_doc(name: &str, bytes: &[u8]) -> Result<Document> { - let RasterImage { key, blob, width, height, ppi } = raster_image(bytes)?; + let RasterImage { key, blob, width, height, ppi, .. } = raster_image(bytes)?; let (sx, sy) = crate::cmd::place::pt_per_px(ppi); let mut d = Document::new(width as f64 * sx, height as f64 * sy); let layer = d.layers[0].id; @@ -968,13 +1078,38 @@ fn is_loss(note: &str) -> bool { /// Another name keeps the original file, with all it has. pub(crate) fn check_not_lossy_overwrite(st: &crate::DocState, target: &str, p: &Value, cmd: &str) -> Result<()> { let Some(losses) = overwrite_losses(st, target, p) else { return Ok(()) }; + Err(lossy_overwrite(target, losses, cmd)) +} + +/// The refusal to write `target`, the file the document was read from, when reading it left out `losses`. +fn lossy_overwrite(target: &str, losses: &[String], cmd: &str) -> EngineError { let what = losses_summary(losses); - Err(bad( + bad( cmd, format!( "{target} is the file this document was read from, and reading it left things out ({what}): writing over it would lose them for good. Write another file instead, or pass acknowledgeLoss: true to replace it anyway" ), - )) + ) +} + +/// The file the document was read from and what reading it left out, when a write to that file +/// needs `acknowledgeLoss` and `p` does not have it ([`overwrite_losses`]). +pub(crate) fn lossy_source(st: &crate::DocState, p: &Value) -> Option<(String, Vec<String>)> { + let source = st.imported_from.as_deref().filter(|_| !st.import_losses.is_empty())?; + (!bool_or(p, "acknowledgeLoss", false)).then(|| (source.to_string(), st.import_losses.clone())) +} + +/// None of the files `targets` (every file a save writes, before any is written) is the +/// `source` file that reading left `losses` out of ([`lossy_source`]). +pub(crate) fn check_files_not_lossy_overwrite<'a>( + source: &(String, Vec<String>), + targets: impl IntoIterator<Item = &'a str>, + cmd: &str, +) -> Result<()> { + match targets.into_iter().find(|t| same_file(&source.0, t)) { + Some(target) => Err(lossy_overwrite(target, &source.1, cmd)), + None => Ok(()), + } } /// What writing the file `target` for document `st` would lose for good: the notes of what reading diff --git a/crates/engine/src/cmd/fileio/metafile.rs b/crates/engine/src/cmd/fileio/metafile.rs index 6bc658a4a0..d987d82757 100644 --- a/crates/engine/src/cmd/fileio/metafile.rs +++ b/crates/engine/src/cmd/fileio/metafile.rs @@ -2,6 +2,7 @@ //! `document.export {format: emf|wmf}` and Export As (one picture of an artboard, or one per //! artboard with Use Artboards; raster effects as images, rendered at the document's raster //! effects resolution), `document.open` and File → Place (one artboard, the picture's frame). +//! QuickDraw pictures (PICT) open and place the same way; they are never written. use serde_json::Value; use vectorcraft_doc::Document; @@ -52,3 +53,9 @@ pub(super) fn import(bytes: &[u8]) -> Result<(Document, Vec<String>)> { let i = vectorcraft_metafile::import(bytes).map_err(super::err)?; Ok((i.document, i.warnings)) } + +/// A QuickDraw picture's document and the import's warnings. +pub(super) fn import_pict(bytes: &[u8]) -> Result<(Document, Vec<String>)> { + let p = vectorcraft_metafile::import_pict(bytes).map_err(super::err)?; + Ok((p.document, p.warnings)) +} diff --git a/crates/engine/src/cmd/fileio/pdf.rs b/crates/engine/src/cmd/fileio/pdf.rs index 365edbedbf..ec7d43472d 100644 --- a/crates/engine/src/cmd/fileio/pdf.rs +++ b/crates/engine/src/cmd/fileio/pdf.rs @@ -12,7 +12,7 @@ use vectorcraft_pdf::{Overprint, PdfError, PdfOptions, PdfPreset, PdfSettings, S use super::super::flatten::{FlattenOptions, flatten_document, see_through_images}; use super::super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, str_param}; -use super::{ArtboardPick, FormatOption, write_or_return}; +use super::{ArtboardPick, FormatOption, Note, note_texts, write_or_return}; use crate::EngineError; const C: &str = "document.exportPdf"; @@ -42,7 +42,7 @@ pub(crate) const OPTIONS: &[FormatOption] = &[ name: "compatibility", ty: "string", default: "\"1.7\"", - description: "PDF version: 1.3 (transparency flattened) | 1.4 | 1.5 | 1.6 | 1.7 | 2.0", + description: "PDF version: 1.3 (transparency flattened) | 1.4 | 1.5 | 1.6 | 1.7 | 2.0 (a pdfA2b file at 1.4 with a page longer than 14,400 pt is written as 1.6, with a UserUnit as at 1.6, and a warning; see document.exportPdf)", }, FormatOption { name: "preserveEditing", @@ -98,8 +98,8 @@ pub(crate) const OPTIONS: &[FormatOption] = &[ FormatOption { name: "longPagesInPoints", ty: "boolean", - default: "false", - description: "a page with a side longer than 14,400 pt (200 in) is written at its size in points, without a UserUnit, at every PDF version", + default: "true", + description: "a page with a side longer than 14,400 pt (200 in) is written at its size in points, without a UserUnit, at every PDF version, in files without a standard (PDF/A files keep the UserUnit); false writes it with a UserUnit from PDF 1.6 on", }, FormatOption { name: "createLayers", @@ -128,7 +128,7 @@ pub fn specs() -> Vec<CommandSpec> { "Export PDF", [], None, - "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption; PDF/X files, 1.3 and 1.4 write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: false (true: such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5; apps that keep to the limit cut it to 200 in), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused", + "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art, as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused", has_doc, export_pdf ), @@ -137,7 +137,7 @@ pub fn specs() -> Vec<CommandSpec> { "PDF Settings", [], None, - "{preset?, includeDocument?: false, …options of document.exportPdf} → {settings (the preset with the options applied), presets: [name…], changed: [{option: \"compression.compressText\", value}] (what differs from the preset), warnings}; includeDocument also exports the active document in memory and adds its warnings (knockout groups approximated, effects left out…). A key PDF doesn't take, and an unknown key inside one of the option objects, are refused", + "{preset?, includeDocument?: false, …options of document.exportPdf} → {settings (the preset with the options applied), presets: [name…], changed: [{option: \"compression.compressText\", value}] (what differs from the preset), warnings}; includeDocument also exports the active document in memory (one page of the art's bounds with useArtboards: false) and adds its warnings (knockout groups approximated, effects left out…). A key PDF doesn't take, and an unknown key inside one of the option objects, are refused", always, pdf_settings ), @@ -280,25 +280,47 @@ fn options_at(cmd: &str, doc: &Document, p: &Value, now: Option<i64>) -> Result< pub const EDITING_NEEDS_EVERY_ARTBOARD: &str = "Preserve editing was left out: it needs a PDF of every artboard, in order (reopened, this one would show the others too)"; +/// Why a PDF of the art's bounds (`useArtboards: false`) carries no editing data. +pub const EDITING_NEEDS_THE_ARTBOARDS: &str = + "Preserve editing was left out: it needs a PDF of the artboards (reopened, this one would replace them with one artboard around the art)"; + +/// With `useArtboards: false` in `p`: the PDF of one page, the bounds of `doc`'s visible art +/// ([`super::encode::art_page`]) → (bytes, notes). It carries no editing data: with Preserve +/// Editing on, the notes end with [`EDITING_NEEDS_THE_ARTBOARDS`]. `None` when `p` asks for the +/// artboards. +pub(super) fn encode_art_page(cmd: &str, doc: &Document, p: &Value) -> Result<Option<(Vec<u8>, Vec<Note>)>> { + let Some((art, mut q)) = super::encode::art_page(cmd, doc, p)? else { return Ok(None) }; + let left_out = settings(cmd, &q)?.preserve_editing; + if left_out && let Some(o) = q.as_object_mut() { + o.insert("preserveEditing".into(), json!(false)); + } + let (bytes, mut notes) = encode(cmd, &art, &q)?; + if left_out { + notes.push(Note::setting(EDITING_NEEDS_THE_ARTBOARDS)); + } + Ok(Some((bytes, notes))) +} + /// The warning for a PDF/X file that leaves out the document's bleed /// ([`vectorcraft_pdf::PdfSettings::leaves_out_bleed`]). pub const BLEED_LEFT_OUT: &str = "the document sets a bleed that this PDF/X file leaves out: turn on Use document bleed settings"; -/// Encode `doc` as PDF with the options in `p` → (bytes, warnings). Raster effects are rendered +/// Encode `doc` as PDF with the options in `p` → (bytes, notes). Raster effects are rendered /// to images at the document's raster effects resolution. Preserve Editing embeds `doc` itself /// when the PDF has every artboard (a PDF of some reopens as just those). -pub fn encode(cmd: &str, doc: &Document, p: &Value) -> Result<(Vec<u8>, Vec<String>)> { +pub fn encode(cmd: &str, doc: &Document, p: &Value) -> Result<(Vec<u8>, Vec<Note>)> { encode_at(cmd, doc, p, None) } /// [`encode`] modified at `modified` (Unix seconds) when given, instead of the time of writing. -pub(super) fn encode_at(cmd: &str, doc: &Document, p: &Value, modified: Option<i64>) -> Result<(Vec<u8>, Vec<String>)> { +pub(super) fn encode_at(cmd: &str, doc: &Document, p: &Value, modified: Option<i64>) -> Result<(Vec<u8>, Vec<Note>)> { // Keep the editable object tree independent of preview fallbacks used by the drawn pages. - let (full, mut warnings) = crate::cmd::place::document::full_documents(doc); - let (bytes, drawn_warnings) = encode_carrying_at(cmd, &full, p, modified, || Ok(vectorcraft_format::save(doc, false)), || Ok(None))?; - warnings.extend(drawn_warnings); - warnings.extend(overflow_warning(cmd, &full, p)?); - Ok((bytes, warnings)) + let (full, placed) = crate::cmd::place::document::full_documents(doc); + let mut notes: Vec<Note> = placed.into_iter().map(Note::loss).collect(); + let (bytes, drawn) = encode_carrying_at(cmd, &full, p, modified, || Ok(vectorcraft_format::save(doc, false)), || Ok(None))?; + notes.extend(drawn); + notes.extend(overflow_warning(cmd, &full, p)?.map(Note::loss)); + Ok((bytes, notes)) } /// The warning about the type that the pages of a PDF of `doc` with the options in `p` draw and @@ -321,7 +343,7 @@ pub(super) fn encode_carrying( p: &Value, native: impl FnOnce() -> Result<Vec<u8>>, private: impl FnOnce() -> Result<Option<(vectorcraft_pdf::PrivateData, Vec<String>)>>, -) -> Result<(Vec<u8>, Vec<String>)> { +) -> Result<(Vec<u8>, Vec<Note>)> { encode_carrying_at(cmd, doc, p, None, native, private) } @@ -334,7 +356,7 @@ fn encode_carrying_at( modified: Option<i64>, native: impl FnOnce() -> Result<Vec<u8>>, private: impl FnOnce() -> Result<Option<(vectorcraft_pdf::PrivateData, Vec<String>)>>, -) -> Result<(Vec<u8>, Vec<String>)> { +) -> Result<(Vec<u8>, Vec<Note>)> { let mut opts = options_at(cmd, doc, p, modified.or_else(vectorcraft_doc::metadata::output_time))?; // The pages' background colors, behind the art (the editing data keeps them as colors). let pages = opts.artboards.clone().unwrap_or_else(|| (0..doc.artboards.len()).collect()); @@ -345,21 +367,22 @@ fn encode_carrying_at( if opts.settings.thumbnails { opts.thumbnails = thumbnails(doc, &opts).map_err(|e| pdf_error(cmd, e))?; } - let mut warnings = vec![]; - // The status bar shows the first warning, so this one goes ahead of the flattening note. + let mut notes = vec![]; + // A loss, ahead of the flattening note: the PDF/X pages leave out the bleed that Document + // Setup gives. if opts.settings.leaves_out_bleed(doc) { - warnings.push(BLEED_LEFT_OUT.to_string()); + notes.push(Note::loss(BLEED_LEFT_OUT)); } if opts.settings.preserve_editing { if opts.artboards.as_ref().is_none_or(|v| v.iter().copied().eq(0..doc.artboards.len())) { opts.native = Some(native()?); if let Some((data, lost)) = private()? { opts.private_data = Some(data); - warnings.extend(lost); + notes.extend(lost.into_iter().map(Note::loss)); } } else { opts.settings.preserve_editing = false; - warnings.push(EDITING_NEEDS_EVERY_ARTBOARD.to_string()); + notes.push(Note::setting(EDITING_NEEDS_EVERY_ARTBOARD)); } } let set = &opts.settings; @@ -370,12 +393,13 @@ fn encode_carrying_at( vectorcraft_doc::cancel::check()?; if flattened { let kind = if set.standard.flattens() { set.standard.label() } else { set.compatibility.label() }; - warnings.push(format!("transparency is flattened into opaque art and images ({kind} files have none): see the flattener preset")); + notes.push(Note::loss(format!("transparency is flattened into opaque art and images ({kind} files have none): see the flattener preset"))); } let r = super::super::rasterfx::export_pdf_with_report(flat.as_ref().unwrap_or(doc), &opts).map_err(|e| pdf_error(cmd, e))?; - warnings.extend(r.warnings); - warnings.extend(crate::cmd::fonts::substitution_warning(doc)); - Ok((r.bytes, warnings)) + notes.extend(r.warnings.into_iter().map(Note::loss)); + notes.extend(r.setting_notes.into_iter().map(Note::setting)); + notes.extend(crate::cmd::fonts::substitution_warning(doc).map(Note::loss)); + Ok((r.bytes, notes)) } /// The flattener preset of PDF 1.3 files whose `flattenerPreset` is empty. @@ -479,8 +503,13 @@ fn export_pdf(s: &mut Session, p: &Value) -> Result<Value> { } else { q = json!({ "_displayDocTitle": display_doc_title }); } - let (bytes, warnings) = encode(C, titled.as_ref().unwrap_or(&st.doc), &q)?; - write_or_return(str_param(p, "path"), &bytes, json!({ "warnings": warnings })) + // The opacity-mask or symbol editing layer is left out. + let doc = titled.as_ref().unwrap_or(&st.doc).without_edit_modes(); + let (bytes, notes) = match encode_art_page(C, &doc, &q)? { + Some(encoded) => encoded, + None => encode(C, &doc, &q)?, + }; + write_or_return(str_param(p, "path"), &bytes, json!({ "warnings": note_texts(¬es) })) } /// `(path, value)` for every leaf of `v` that differs from `default` (`compression.color.ppi`). @@ -510,9 +539,18 @@ fn pdf_settings(s: &mut Session, p: &Value) -> Result<Value> { const Q: &str = "document.pdfSettings"; let saved = &s.prefs.pdf_presets; let set = settings_with(Q, p, saved)?; + super::encode::use_artboards(Q, p)?; let diff = changes(&set, &preset_settings(Q, p, saved)?); let warnings = match s.active() { - Some(st) if bool_or(p, "includeDocument", false) => encode(Q, &st.doc, &*expand_preset(s, Q, p)?)?.1, + Some(st) if bool_or(p, "includeDocument", false) => { + let q = expand_preset(s, Q, p)?; + let doc = st.doc.without_edit_modes(); + let (_, notes) = match encode_art_page(Q, &doc, &q)? { + Some(encoded) => encoded, + None => encode(Q, &doc, &q)?, + }; + note_texts(¬es) + } _ => set.warnings(), }; let v = serde_json::to_value(&set).map_err(|e| EngineError::Other(e.to_string()))?; diff --git a/crates/engine/src/cmd/fileio/pdfimport.rs b/crates/engine/src/cmd/fileio/pdfimport.rs index 2a67cf4a45..2a0dede17f 100644 --- a/crates/engine/src/cmd/fileio/pdfimport.rs +++ b/crates/engine/src/cmd/fileio/pdfimport.rs @@ -28,8 +28,10 @@ pub struct LoadOptions { /// What a PDF's text becomes. pub text_as: TextAs, /// A PDF's optional content groups become layers (else one layer per page, without the art - /// that is off). + /// that is off), and a PSD or PSB file's layers become layers (else its merged image opens). pub layers: bool, + /// A PSD or PSB file's hidden layers come in, hidden (`hiddenLayers`; else they are left out). + pub hidden_layers: bool, /// How a DXF drawing comes in (the `dxf` param, see [`super::dxfimport`]). pub dxf: vectorcraft_cad::ImportOptions, /// An Illustrator EPS or `.ai` that carries the editing copy of its art opens from it (its @@ -57,6 +59,7 @@ impl Default for LoadOptions { grays: Grays::default(), text_as: TextAs::default(), layers: true, + hidden_layers: false, dxf: Default::default(), editing_data: true, trust_editing_data: false, @@ -69,7 +72,8 @@ impl Default for LoadOptions { impl LoadOptions { /// From command params: `pages` (`"2-3, 5"`, a page number or `"all"`), `page` (one page, when /// `pages` isn't given), `cropTo` (or `crop`), `password`, `colorMode` (`rgb` | `cmyk`) with `grays`, - /// `textAs` (`text` | `outlines`), `layers` (true | false), `editingData` (true | false | `always`), + /// `textAs` (`text` | `outlines`), `layers` (true | false), `hiddenLayers` (true | false), + /// `editingData` (true | false | `always`), /// `legacyNameEncoding` (one of [`vectorcraft_eps::NameEncoding::LABELS`]) and `dxf` (the DXF /// import options). pub fn from_params(cmd: &str, p: &Value) -> Result<Self> { @@ -95,6 +99,10 @@ impl LoadOptions { None => true, Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "layers must be true or false"))?, }; + let hidden_layers = match p.get("hiddenLayers").filter(|v| !v.is_null()) { + None => false, + Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "hiddenLayers must be true or false"))?, + }; let (editing_data, trust_editing_data) = match p.get("editingData").filter(|v| !v.is_null()) { None => (true, false), Some(Value::String(s)) if s.eq_ignore_ascii_case("always") => (true, true), @@ -108,7 +116,21 @@ impl LoadOptions { .ok_or_else(|| bad(cmd, format!("legacyNameEncoding must be one of {}", vectorcraft_eps::NameEncoding::LABELS.join(", "))))?, }; let dxf = super::dxfimport::options(cmd, p.get("dxf"))?; - Ok(Self { pages, crop, password, color_mode, grays, text_as, layers, dxf, editing_data, trust_editing_data, legacy_names, native: true }) + Ok(Self { + pages, + crop, + password, + color_mode, + grays, + text_as, + layers, + hidden_layers, + dxf, + editing_data, + trust_editing_data, + legacy_names, + native: true, + }) } /// Does the document read only part of the file, or read it differently (a page range, another diff --git a/crates/engine/src/cmd/fileio/psdlayers.rs b/crates/engine/src/cmd/fileio/psdlayers.rs new file mode 100644 index 0000000000..c3c45029a0 --- /dev/null +++ b/crates/engine/src/cmd/fileio/psdlayers.rs @@ -0,0 +1,1529 @@ +//! File › Open of a PSD or PSB file with its layers as objects. The import option that converts +//! layers to objects +//! (<https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html>) +//! keeps as much of the layer structure as it can, merges the layers of a clipping mask into one +//! layer, and discards hidden layers that need merging; the rest of what this module does is +//! VectorCraft's own. Read from the layer records of the public PSD file format specification +//! (<https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/>). +//! +//! Each layer becomes a layer of the document, with the layer's name, visibility, opacity and blend +//! mode, holding its pixels as an image at their place on the canvas. A layer group becomes a layer +//! whose sublayers are the group's layers (a pass-through group lets them blend with what is below +//! it; any other group is isolated). A layer mask becomes the layer's opacity mask: a gray image +//! whose outside is hidden or shown as the mask's default color says, kept and switched off when +//! the mask is disabled. A layer's opacity is multiplied by its fill opacity, except in a layer +//! that others are clipped to, whose fill opacity fades only its own pixels. A solid color fill +//! layer that stores no pixels and has no vector mask comes in as an image of its color over the +//! canvas (an RGB, CMYK, Grayscale, Lab or HSB color); type, shape and other fill layers come in as +//! the pixels the file stores for them. +//! +//! Layers clipped to the layer below them are merged into it as one image (named after them all, +//! joined with " + "), shown where the layer below has pixels. Layers clipped to an adjustment +//! layer, or to a fill layer drawn over the whole canvas, show over the whole canvas. A layer in a +//! blend mode VectorCraft doesn't have (Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear +//! Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color, Lighter Color) is merged with the +//! layers below it in its group. A Dissolve layer's partly transparent pixels are merged as opaque +//! or transparent, opaque at the share of its pixels their transparency gives, in a fixed pattern +//! that differs from layer to layer. When a merge's canvases would need more memory than allowed, +//! the layer comes in alone: in the Normal mode, or unclipped. +//! Hidden layers are left out unless `hidden` asks for them. A hidden layer that would need a merge +//! (one in a mode VectorCraft lacks, one that layers are clipped to, one clipped to another, or +//! one below a merged layer) is always left out, with the layers clipped to it. Adjustment layers, +//! fill layers that store no pixels and whose fill isn't read or whose shape is a vector mask, +//! layer effects that are switched on, knockouts and vector masks aren't applied; the warnings +//! count them and the hidden layers left out. +//! +//! The file is untrusted: every count, length and size is checked before anything is allocated, +//! groups nest at most [`MAX_DEPTH`] deep (layers deeper than a document may nest merge into the +//! group around them, with a warning), each layer's pixels, like the canvases one step of a +//! merge holds together, must fit the memory allowed, and all the pixels decoded and the canvases +//! the merges make must fit [`TOTAL_DECODED`] times that. + +use std::cell::Cell; +use std::sync::Arc; + +use image::RgbaImage; +use vectorcraft_color::BlendMode; +use vectorcraft_color::blend::{blend_rgb, composite}; +use vectorcraft_color::cms::{Lab, lab::lab_to_srgb}; +use vectorcraft_doc::{Document, ImageObject, LAYER_COLORS, LayerColor, Node, NodeKind, OpacityMask}; +use vectorcraft_geom::Affine; + +use super::load::{RasterImage, as_png}; +use super::psdread::{Header, Reader, byte, header, layer_channel, layer_info, long_key, row_bytes, sample, to_rgb}; +use crate::cmd::place::text::mac_roman; + +/// Most layer groups inside one another. +pub(super) const MAX_DEPTH: usize = 64; +/// The pixels all layers and masks decode to, merges' second readings included, and the canvases +/// the merges make may take this many times the memory allowed for one image. +const TOTAL_DECODED: u64 = 8; +/// Most channels one layer has (colors, transparency and masks), as many as a document may. +const MAX_CHANNELS: usize = 56; +/// The fewest bytes a layer record takes. +const MIN_RECORD: usize = 34; +const DAMAGED: &str = "the PSD file's layer records are damaged"; + +/// The keys of the tagged blocks that make a layer an adjustment layer. +const ADJUSTMENTS: [&[u8; 4]; 18] = [ + b"levl", b"curv", b"brit", b"blnc", b"hue ", b"hue2", b"selc", b"mixr", b"grdm", b"phfl", b"expA", b"vibA", b"thrs", b"nvrt", b"post", b"clrL", + b"blwh", b"CgEd", +]; + +/// A layer's blend mode. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Blend { + Mode(BlendMode), + /// A group's Pass Through. + Pass, + /// A mode VectorCraft doesn't have: the layer is merged with the layers below it. + Other(Other), +} + +#[derive(Clone, Copy, Debug, PartialEq)] +enum Other { + Dissolve, + LinearBurn, + LinearDodge, + VividLight, + LinearLight, + PinLight, + HardMix, + Subtract, + Divide, + DarkerColor, + LighterColor, +} + +impl Other { + fn label(self) -> &'static str { + match self { + Other::Dissolve => "Dissolve", + Other::LinearBurn => "Linear Burn", + Other::LinearDodge => "Linear Dodge", + Other::VividLight => "Vivid Light", + Other::LinearLight => "Linear Light", + Other::PinLight => "Pin Light", + Other::HardMix => "Hard Mix", + Other::Subtract => "Subtract", + Other::Divide => "Divide", + Other::DarkerColor => "Darker Color", + Other::LighterColor => "Lighter Color", + } + } +} + +/// The blend mode a record's key names (an unknown key: Normal). +fn blend(key: &[u8; 4]) -> Blend { + use BlendMode as M; + let mode = match key { + b"pass" => return Blend::Pass, + b"diss" => return Blend::Other(Other::Dissolve), + b"lbrn" => return Blend::Other(Other::LinearBurn), + b"lddg" => return Blend::Other(Other::LinearDodge), + b"vLit" => return Blend::Other(Other::VividLight), + b"lLit" => return Blend::Other(Other::LinearLight), + b"pLit" => return Blend::Other(Other::PinLight), + b"hMix" => return Blend::Other(Other::HardMix), + b"fsub" => return Blend::Other(Other::Subtract), + b"fdiv" => return Blend::Other(Other::Divide), + b"dkCl" => return Blend::Other(Other::DarkerColor), + b"lgCl" => return Blend::Other(Other::LighterColor), + b"dark" => M::Darken, + b"mul " => M::Multiply, + b"idiv" => M::ColorBurn, + b"lite" => M::Lighten, + b"scrn" => M::Screen, + b"div " => M::ColorDodge, + b"over" => M::Overlay, + b"sLit" => M::SoftLight, + b"hLit" => M::HardLight, + b"diff" => M::Difference, + b"smud" => M::Exclusion, + b"hue " => M::Hue, + b"sat " => M::Saturation, + b"colr" => M::Color, + b"lum " => M::Luminosity, + _ => M::Normal, + }; + Blend::Mode(mode) +} + +/// A rectangle of the canvas, in pixels: top, left, bottom, right. +#[derive(Clone, Copy, Debug, Default)] +struct Bounds { + top: i32, + left: i32, + bottom: i32, + right: i32, +} + +impl Bounds { + fn read(r: &mut Reader<'_>) -> Result<Self, String> { + let mut v = || r.u32().map(|v| v as i32); + Ok(Self { top: v()?, left: v()?, bottom: v()?, right: v()? }) + } + /// Width and height (0 when empty or inverted). + fn size(self) -> (usize, usize) { + let side = |a: i32, b: i32| usize::try_from(i64::from(b) - i64::from(a)).unwrap_or(0); + (side(self.left, self.right), side(self.top, self.bottom)) + } +} + +/// What a layer holds besides plain pixels. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Content { + Pixels, + /// A type layer: its pixels come in. + Type, + /// An adjustment layer: not applied. + Adjustment, + /// A solid color fill layer: its stored pixels, or its color over the whole canvas when it + /// stores none (nothing when the color can't be read, or when its shape is a vector mask). + Solid(Option<Paint>), + /// A gradient or pattern fill layer: its stored pixels, if any. + Fill, +} + +/// A solid color fill layer's color. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Paint { + /// sRGB, 0..1. + Rgb([f32; 3]), + /// Ink amounts, 0..1. + Cmyk([f32; 4]), +} + +/// A layer mask's place and its color outside it. +#[derive(Clone, Copy, Debug)] +struct MaskInfo { + bounds: Bounds, + default: u8, + disabled: bool, + /// The mask's values, and its default color, are read inverted. + inverted: bool, +} + +/// One layer record: a layer, or a group's opening or closing divider. +struct Record<'a> { + name: String, + bounds: Bounds, + /// Channel id (−1 transparency, −2 the layer mask, 0.. the colors) and its data, compression + /// method first. + channels: Vec<(i16, &'a [u8])>, + blend: Blend, + /// The layer's opacity, 0..1. + opacity: f32, + /// Its fill opacity, 0..1. + fill: f32, + clipped: bool, + hidden: bool, + mask: Option<MaskInfo>, + /// The section divider type: 0 a layer, 1 or 2 a group (open or closed in the panel), 3 the + /// end of a group (the record below its layers). + divider: u32, + content: Content, + effects: bool, + vector_mask: bool, + knockout: bool, +} + +/// The layer records of `info` (the layer count, the records, then their channels' data). +fn records(info: &[u8], psb: bool) -> Result<Vec<Record<'_>>, String> { + let mut r = Reader::new(info); + let count = usize::from((r.u16()? as i16).unsigned_abs()); + if count.saturating_mul(MIN_RECORD) > info.len() { + return Err(DAMAGED.into()); + } + let mut heads = Vec::with_capacity(count); + for _ in 0..count { + heads.push(record(&mut r, psb)?); + } + let mut out = Vec::with_capacity(count); + for (mut rec, lengths) in heads { + rec.channels = lengths.into_iter().map(|(id, n)| r.take(n).map(|d| (id, d))).collect::<Result<_, _>>()?; + out.push(rec); + } + Ok(out) +} + +/// One record, with the lengths of its channels' data (which follows every record). +fn record<'a>(r: &mut Reader<'a>, psb: bool) -> Result<(Record<'a>, Vec<(i16, usize)>), String> { + let bounds = Bounds::read(r)?; + let n = usize::from(r.u16()?); + if n > MAX_CHANNELS { + return Err(DAMAGED.into()); + } + let mut lengths = Vec::with_capacity(n); + for _ in 0..n { + let id = r.u16()? as i16; + lengths.push((id, r.length(psb)?)); + } + if &r.array::<4>()? != b"8BIM" { + return Err(DAMAGED.into()); + } + let blend = blend(&r.array()?); + let opacity = f32::from(r.u8()?) / 255.0; + let clipped = r.u8()? != 0; + // Bit 1: hidden. + let hidden = r.u8()? & 2 != 0; + r.u8()?; + let extra = r.section(false)?; + let mut rec = Record { + name: String::new(), + bounds, + channels: vec![], + blend, + opacity, + fill: 1.0, + clipped, + hidden, + mask: None, + divider: 0, + content: Content::Pixels, + effects: false, + vector_mask: false, + knockout: false, + }; + rec.read_extra(extra, psb)?; + Ok((rec, lengths)) +} + +impl Record<'_> { + /// The layer mask, blending ranges, name and tagged blocks after the record's fixed part. A + /// damaged mask, blending ranges or name is an error; a damaged tagged block keeps what was + /// read before it. + fn read_extra(&mut self, extra: &[u8], psb: bool) -> Result<(), String> { + let damaged = |_| DAMAGED.to_string(); + let mut e = Reader::new(extra); + let mask = e.section(false).map_err(damaged)?; + self.mask = match mask_info(mask) { + Some(info) => Some(info), + None if mask.is_empty() => None, + None => return Err(DAMAGED.into()), + }; + // The blending ranges. + e.section(false).map_err(damaged)?; + // A Pascal string padded to a multiple of 4 bytes, length byte included, in the system's + // encoding (its Unicode name follows in `luni`), read as Mac Roman as psd-tools (MIT) reads + // it: <https://github.com/psd-tools/psd-tools>, `psd/layer_and_mask.py`. + let n = usize::from(e.u8().map_err(damaged)?); + let name = e.take(n).map_err(damaged)?; + self.name = name.iter().map(|&b| mac_roman(b)).collect(); + e.take((4 - (n + 1) % 4) % 4).map_err(damaged)?; + // Effects in a descriptor (`lfx2`, `lmfx`) say whether they are switched on; the older + // `lrFX` block is counted whenever it is there. + let (mut effects, mut old_effects) = (None, false); + while e.rest().len() >= 12 { + let (Ok(signature), Ok(key)) = (e.array::<4>(), e.array::<4>()) else { break }; + if !matches!(&signature, b"8BIM" | b"8B64") { + break; + } + let Ok(data) = e.section(psb && long_key(&key)) else { break }; + match &key { + b"luni" => { + if let Some(name) = unicode(data) { + self.name = name; + } + } + b"lsct" | b"lsdk" => { + if let Some(t) = data.get(..4) { + self.divider = u32::from_be_bytes([t[0], t[1], t[2], t[3]]); + } + if data.get(4..8) == Some(b"8BIM") + && let Some(Ok(key)) = data.get(8..12).map(<[u8; 4]>::try_from) + { + self.blend = blend(&key); + } + } + b"iOpa" => self.fill = data.first().map_or(1.0, |&v| f32::from(v) / 255.0), + b"TySh" | b"tySh" => self.content = Content::Type, + b"SoCo" => self.content = Content::Solid(solid_color(data)), + b"GdFl" | b"PtFl" => self.content = Content::Fill, + b"lfx2" | b"lmfx" => effects = Some(effects == Some(true) || effects_on(data)), + b"lrFX" => old_effects = true, + b"vmsk" | b"vsms" => self.vector_mask = true, + // Shallow or deep knockout. + b"knko" => self.knockout = data.first().is_some_and(|&k| k != 0), + k if ADJUSTMENTS.contains(&k) => self.content = Content::Adjustment, + _ => {} + } + // Some writers pad blocks further: skip to the next signature. + for _ in 0..3 { + if e.rest().is_empty() || e.rest().starts_with(b"8BIM") || e.rest().starts_with(b"8B64") { + break; + } + let _ = e.take(1); + } + } + self.effects = effects.unwrap_or(old_effects); + Ok(()) + } + + /// Does the record store no pixels (bounds of no area, or no color channel)? + fn stores_nothing(&self) -> bool { + let (w, h) = self.bounds.size(); + w == 0 || h == 0 || !self.channels.iter().any(|(id, _)| *id >= 0) + } + + /// Is the layer a fill drawn from its color over the whole canvas (a solid color fill that + /// stores no pixels and has no vector mask)? + fn color_over_canvas(&self) -> bool { + matches!(self.content, Content::Solid(Some(_))) && self.stores_nothing() && !self.vector_mask + } + + /// Does the layer cover the whole canvas without drawing (an adjustment layer, or a fill that + /// stores no pixels, has no vector mask and isn't drawn from its color)? Layers clipped to it + /// show over the whole canvas. + fn covers_without_drawing(&self) -> bool { + match self.content { + Content::Adjustment => true, + Content::Solid(None) | Content::Fill => self.stores_nothing() && !self.vector_mask, + _ => false, + } + } + + /// Is the layer a fill that stores no pixels and whose shape is a vector mask, so that it + /// isn't drawn? + fn undrawn_shape(&self) -> bool { + matches!(self.content, Content::Solid(_) | Content::Fill) && self.stores_nothing() && self.vector_mask + } +} + +/// Does an effects descriptor (`lfx2`, `lmfx`) have its master switch on and an effect switched on? +/// Read as psd-tools (MIT) reads them, a missing switch being off: `masterFXSwitch` and each +/// effect's `enab` (<https://github.com/psd-tools/psd-tools>, `api/effects.py`). +fn effects_on(data: &[u8]) -> bool { + // A key, then its type `bool`, then one byte. + let values = |key: &'static [u8]| data.windows(key.len() + 1).filter(move |w| w.starts_with(key)).filter_map(|w| w.last().map(|&v| v != 0)); + values(b"masterFXSwitchbool").any(|on| on) && values(b"enabbool").any(|on| on) +} + +/// The layer mask data's place, default color, disabled flag (bit 1) and invert flag (bit 2). +fn mask_info(data: &[u8]) -> Option<MaskInfo> { + let mut r = Reader::new(data); + let bounds = Bounds::read(&mut r).ok()?; + let default = r.u8().ok()?; + let flags = r.u8().ok()?; + Some(MaskInfo { bounds, default, disabled: flags & 2 != 0, inverted: flags & 4 != 0 }) +} + +/// A `luni` block's name: a count of UTF-16 units, then the units. +fn unicode(data: &[u8]) -> Option<String> { + let mut r = Reader::new(data); + let n = usize::try_from(r.u32().ok()?).ok()?; + let units: Vec<u16> = r.take(n.checked_mul(2)?).ok()?.as_chunks::<2>().0.iter().map(|u| u16::from_be_bytes(*u)).collect(); + Some(String::from_utf16_lossy(&units).trim_end_matches('\0').to_string()) +} + +/// The color of a solid color fill layer's descriptor, from the values after its color keys: red, +/// green and blue (0..255, or 0..1 in the `redFloat` keys), cyan, magenta, yellow and black (0..100 +/// percent ink), gray (0..100 percent black), Lab (L 0..100, a and b) or hue (degrees), saturation +/// and brightness (0..100). `None` for a color in another model. +fn solid_color(data: &[u8]) -> Option<Paint> { + // A key, then `doub` and a double, or `UntF`, a unit and a double. + let value = |key: &[u8]| -> Option<f64> { + let at = data.windows(key.len()).position(|w| w == key)? + key.len(); + let at = match data.get(at..at + 4)? { + b"doub" => at + 4, + b"UntF" => at + 8, + _ => return None, + }; + let v = f64::from_be_bytes(data.get(at..at + 8)?.try_into().ok()?); + v.is_finite().then_some(v) + }; + let unit = |v: f64| v.clamp(0.0, 1.0) as f32; + let rgb = |keys: [&[u8]; 3], scale: f64| -> Option<[f32; 3]> { + Some([unit(value(keys[0])? / scale), unit(value(keys[1])? / scale), unit(value(keys[2])? / scale)]) + }; + if let Some(c) = rgb([b"Rd ", b"Grn ", b"Bl "], 255.0).or_else(|| rgb([b"redFloat", b"greenFloat", b"blueFloat"], 1.0)) { + return Some(Paint::Rgb(c)); + } + if let (Some(c), Some(m), Some(y), Some(k)) = (value(b"Cyn "), value(b"Mgnt"), value(b"Ylw "), value(b"Blck")) { + return Some(Paint::Cmyk([c, m, y, k].map(|v| unit(v / 100.0)))); + } + if let Some(g) = value(b"Gry ") { + return Some(Paint::Rgb([unit(1.0 - g / 100.0); 3])); + } + if let (Some(l), Some(a), Some(b)) = (value(b"Lmnc"), value(b"A "), value(b"B ")) { + let [r, g, b] = lab_to_srgb(Lab { l: l as f32, a: a as f32, b: b as f32 }); + return Some(Paint::Rgb([r, g, b].map(|v| v.clamp(0.0, 1.0)))); + } + let (h, s, b) = (value(b"H ")?, value(b"Strt")?, value(b"Brgh")?); + Some(Paint::Rgb(hsb(h, unit(s / 100.0), unit(b / 100.0)))) +} + +/// Hue `h` (degrees), saturation `s` and brightness `b` (0..1) as RGB. +fn hsb(h: f64, s: f32, b: f32) -> [f32; 3] { + let h = (h.rem_euclid(360.0) / 60.0) as f32; + let f = |n: f32| { + let k = (n + h) % 6.0; + b - b * s * k.min(4.0 - k).clamp(0.0, 1.0) + }; + [f(5.0), f(3.0), f(1.0)] +} + +/// The layer tree: records in the order the file stores them, bottom first. +enum Item { + Layer(usize), + /// A group's record and its layers. + Group(usize, Vec<Item>), +} + +fn tree(records: &[Record<'_>]) -> Result<Vec<Item>, String> { + let mut stack: Vec<Vec<Item>> = vec![vec![]]; + for (i, rec) in records.iter().enumerate() { + match rec.divider { + 3 => { + if stack.len() > MAX_DEPTH { + return Err("the PSD file's layer groups are nested too deeply".into()); + } + stack.push(vec![]); + } + 1 | 2 => { + // A group without its end divider holds nothing. + let children = if stack.len() > 1 { stack.pop().unwrap_or_default() } else { vec![] }; + if let Some(top) = stack.last_mut() { + top.push(Item::Group(i, children)); + } + } + _ => { + if let Some(top) = stack.last_mut() { + top.push(Item::Layer(i)); + } + } + } + } + // Groups the file never closes: their layers join the group around them. + while stack.len() > 1 { + let inner = stack.pop().unwrap_or_default(); + if let Some(top) = stack.last_mut() { + top.extend(inner); + } + } + Ok(stack.pop().unwrap_or_default()) +} + +/// Straight RGBA, 0..1, at `left`, `top` on the canvas. +#[derive(Clone, Default)] +struct Canvas { + left: i64, + top: i64, + width: usize, + height: usize, + px: Vec<[f32; 4]>, +} + +impl Canvas { + fn from_image(left: i64, top: i64, img: &RgbaImage) -> Self { + let px = img.pixels().map(|p| p.0.map(|v| f32::from(v) / 255.0)).collect(); + Self { left, top, width: img.width() as usize, height: img.height() as usize, px } + } + fn get(&self, x: i64, y: i64) -> Option<[f32; 4]> { + let (x, y) = (usize::try_from(x - self.left).ok()?, usize::try_from(y - self.top).ok()?); + if x >= self.width || y >= self.height { + return None; + } + self.px.get(y * self.width + x).copied() + } + /// The canvas as an image, cropped to its painted pixels; `None` when nothing is painted. + fn to_image(&self) -> Option<(i64, i64, RgbaImage)> { + let painted = |x: usize, y: usize| self.px.get(y * self.width + x).is_some_and(|p| p[3] > 0.0); + let rows: Vec<usize> = (0..self.height).filter(|&y| (0..self.width).any(|x| painted(x, y))).collect(); + let (&y0, &y1) = (rows.first()?, rows.last()?); + let cols: Vec<usize> = (0..self.width).filter(|&x| (y0..=y1).any(|y| painted(x, y))).collect(); + let (&x0, &x1) = (cols.first()?, cols.last()?); + let img = RgbaImage::from_fn((x1 - x0 + 1) as u32, (y1 - y0 + 1) as u32, |x, y| { + let p = self.px.get((y0 + y as usize) * self.width + x0 + x as usize).copied().unwrap_or_default(); + image::Rgba(p.map(byte)) + }); + Some((self.left + x0 as i64, self.top + y0 as i64, img)) + } +} + +/// The blend function of a mode VectorCraft doesn't have, on straight RGB. +fn blend_other(mode: Other, b: [f32; 3], s: [f32; 3]) -> [f32; 3] { + let each = |f: fn(f32, f32) -> f32| [0, 1, 2].map(|i| f(b[i].clamp(0.0, 1.0), s[i].clamp(0.0, 1.0)).clamp(0.0, 1.0)); + // Darker and Lighter Color compare the total of the channel values. + let total = |c: [f32; 3]| c[0] + c[1] + c[2]; + let burn = |b: f32, s: f32| blend_rgb(BlendMode::ColorBurn, [b; 3], [s; 3])[0]; + let dodge = |b: f32, s: f32| blend_rgb(BlendMode::ColorDodge, [b; 3], [s; 3])[0]; + match mode { + // Dissolve's pixels are opaque or transparent (`coverage`); the opaque ones replace. + Other::Dissolve => s, + Other::LinearBurn => each(|b, s| b + s - 1.0), + Other::LinearDodge => each(|b, s| b + s), + Other::VividLight => [0, 1, 2].map(|i| { + let (b, s) = (b[i].clamp(0.0, 1.0), s[i].clamp(0.0, 1.0)); + if s <= 0.5 { burn(b, 2.0 * s) } else { dodge(b, 2.0 * s - 1.0) } + }), + Other::LinearLight => each(|b, s| b + 2.0 * s - 1.0), + Other::PinLight => each(|b, s| if s <= 0.5 { b.min(2.0 * s) } else { b.max(2.0 * s - 1.0) }), + Other::HardMix => each(|b, s| if b + s >= 1.0 { 1.0 } else { 0.0 }), + Other::Subtract => each(|b, s| b - s), + Other::Divide => each(|b, s| if s <= 0.0 { if b <= 0.0 { 0.0 } else { 1.0 } } else { b / s }), + Other::DarkerColor => { + if total(s) < total(b) { + s + } else { + b + } + } + Other::LighterColor => { + if total(s) > total(b) { + s + } else { + b + } + } + } +} + +/// Source-over compositing of straight `s` onto straight `b` in `mode`, as +/// [`vectorcraft_color::blend::composite`] does for the modes it has. +fn over(mode: Blend, b: [f32; 4], s: [f32; 4]) -> [f32; 4] { + let other = match mode { + Blend::Mode(m) => return composite(m, b, s), + Blend::Pass => return composite(BlendMode::Normal, b, s), + Blend::Other(o) => o, + }; + let (ab, a) = (b[3].clamp(0.0, 1.0), s[3].clamp(0.0, 1.0)); + let ao = a + ab * (1.0 - a); + if ao <= 0.0 { + return [0.0; 4]; + } + let mixed = blend_other(other, [b[0], b[1], b[2]], [s[0], s[1], s[2]]); + let c = |i: usize| ((1.0 - ab) * s[i] + ab * mixed[i]) * a + (1.0 - a) * ab * b[i]; + [c(0) / ao, c(1) / ao, c(2) / ao, ao] +} + +/// What one entry of a layer list becomes: a layer of the document. +struct Unit<'i> { + name: String, + visible: bool, + opacity: f32, + blend: Blend, + /// The record whose layer mask the layer takes. + mask_of: Option<usize>, + /// The record the layer comes from (each record has its own Dissolve pattern). + record: usize, + body: Body<'i>, + /// While layers are clipped to it: how its merged canvas is shaped. + clip: Option<Clip>, +} + +impl Unit<'_> { + /// Is it what a merge of layers in modes VectorCraft lacks made: one image, visible, at full + /// opacity in the Normal mode, without a mask? + fn is_merge(&self) -> bool { + matches!(self.body, Body::Merged(_)) + && self.clip.is_none() + && self.mask_of.is_none() + && self.visible + && self.opacity >= 1.0 + && self.blend == Blend::Mode(BlendMode::Normal) + } +} + +/// The shape of a layer merged with the layers clipped to it. +enum Clip { + /// The layer's own transparency at each pixel of its canvas; the canvas holds its pixels at its + /// fill opacity, the clipped layers composited over them. + Shape(Vec<f32>), + /// The whole canvas of the file (a layer that covers it without drawing): the canvas holds the + /// clipped layers alone. + Whole, +} + +enum Body<'i> { + /// A layer record's pixels. + Layer(usize), + /// A group's layers. + Group(&'i [Item]), + /// Layers merged into one image. + Merged(Canvas), +} + +/// A unit's body drawn alone. +enum Drawn { + /// It draws nothing. + Nothing, + Canvas(Canvas), + /// Its canvas would need more memory than allowed. + TooLarge, +} + +/// What the warnings say. +#[derive(Default)] +struct Notes { + types: usize, + adjustments: usize, + fills: usize, + effects: usize, + vector_masks: usize, + knockouts: usize, + /// Hidden layers left out, and layers clipped to them. + hidden: usize, + merged: Vec<&'static str>, + unmerged: usize, + /// Clipped layers left unclipped: the merge needs more memory than allowed. + unclipped: usize, + /// Layers clipped to a fill that isn't drawn. + clipped_out: usize, +} + +/// The counts a merge that can't be made gives back. +#[derive(Clone, Copy)] +struct Counts { + skipped: usize, + merged: usize, + unmerged: usize, + unclipped: usize, + clipped_out: usize, +} + +/// `n` things: "1 layer was", "2 layers were". +fn count(n: usize, one: &str, many: &str) -> String { + if n == 1 { format!("1 {one} was") } else { format!("{n} {many} were") } +} + +impl Notes { + fn warnings(self) -> Vec<String> { + let mut out = vec![]; + if self.types > 0 { + let n = if self.types == 1 { "1 type layer".to_string() } else { format!("{} type layers", self.types) }; + out.push(format!("{n} came in as pixels: the text isn't editable")); + } + if self.adjustments > 0 { + out.push(format!("{} not applied", count(self.adjustments, "adjustment layer", "adjustment layers"))); + } + if self.fills > 0 { + out.push(format!( + "{} not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels)", + count(self.fills, "fill layer", "fill layers") + )); + } + let layers = |n: usize| if n == 1 { "1 layer".to_string() } else { format!("{n} layers") }; + if self.effects > 0 { + out.push(format!("the layer effects of {} weren't drawn", layers(self.effects))); + } + if self.vector_masks > 0 { + out.push(format!("the vector masks of {} weren't applied", layers(self.vector_masks))); + } + if self.knockouts > 0 { + out.push(format!("the knockout of {} wasn't applied", layers(self.knockouts))); + } + if self.hidden > 0 { + out.push(format!("{} left out (hidden layers and the layers clipped to them)", count(self.hidden, "layer", "layers"))); + } + if self.clipped_out == 1 { + out.push("1 layer clipped to a fill layer that wasn't drawn was left out".into()); + } else if self.clipped_out > 1 { + out.push(format!("{} layers clipped to fill layers that weren't drawn were left out", self.clipped_out)); + } + if !self.merged.is_empty() { + out.push(format!("layers in blend modes VectorCraft doesn't have ({}) were merged with the layers below them", self.merged.join(", "))); + } + if self.unmerged > 0 { + out.push(format!( + "{} in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed", + layers(self.unmerged) + )); + } + if self.unclipped > 0 { + out.push(format!("{} clipped to the layer below came in unclipped: the merge needs more memory than allowed", layers(self.unclipped))); + } + out + } + + fn counts(&self, skipped: usize) -> Counts { + Counts { skipped, merged: self.merged.len(), unmerged: self.unmerged, unclipped: self.unclipped, clipped_out: self.clipped_out } + } +} + +struct Builder<'a, F> { + h: &'a Header<'a>, + records: &'a [Record<'a>], + /// Hidden layers come in, hidden. + hidden: bool, + max_alloc: u64, + /// Bytes held by the copies of what is below the pass-through groups being merged. + held: u64, + cmyk: F, + doc: Document, + /// Canvas pixels to points. + to_doc: Affine, + ppi: Option<(f64, f64)>, + layers: usize, + notes: Notes, + /// The records [`Notes`] counted. + noted: Vec<bool>, + /// The records counted as hidden layers left out. + skipped: Vec<bool>, + /// Those records, in the order they were counted. + skip_log: Vec<usize>, + /// Bytes of layer and mask pixels decoded, and of canvases the merges made, so far. + spent: Cell<u64>, +} + +impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { + fn record(&self, i: usize) -> Result<&Record<'_>, String> { + self.records.get(i).ok_or_else(|| DAMAGED.to_string()) + } + + /// Refuse to allocate `bytes` past the memory allowed. + fn fits(&self, bytes: u64) -> Result<(), String> { + if bytes > self.max_alloc { Err("a layer of the PSD file is too large to read".into()) } else { Ok(()) } + } + + /// Count `bytes` of decoded pixels, or of a canvas a merge makes, against the whole import's + /// allowance, [`TOTAL_DECODED`] times the memory allowed for one image. + fn spend(&self, bytes: u64) -> Result<(), String> { + let total = self.spent.get().saturating_add(bytes); + self.spent.set(total); + if total > self.max_alloc.saturating_mul(TOTAL_DECODED) { + return Err("the PSD file's layers take more memory to read than allowed".into()); + } + Ok(()) + } + + /// Record `i`'s pixels as straight RGBA, at their place on the canvas; `None` when it has none. + fn image(&self, i: usize) -> Result<Option<(i64, i64, RgbaImage)>, String> { + let rec = self.record(i)?; + let h = self.h; + let max_side = if h.psb { 300_000 } else { 30_000 }; + let (w, rows) = match rec.content { + Content::Adjustment => return Ok(None), + // A fill layer that stores no pixels (a shape layer stores its shape's; one that + // doesn't, with only its vector mask, isn't drawn). + Content::Solid(Some(paint)) if rec.color_over_canvas() => { + let (w, rows) = (h.width as usize, h.height as usize); + self.fits(4 * w as u64 * rows as u64)?; + self.spend(4 * w as u64 * rows as u64)?; + let rgb = match paint { + Paint::Rgb(rgb) => rgb, + Paint::Cmyk(ink) => (self.cmyk)(ink), + }; + let px = image::Rgba([byte(rgb[0]), byte(rgb[1]), byte(rgb[2]), 255]); + return Ok(Some((0, 0, RgbaImage::from_pixel(h.width, h.height, px)))); + } + Content::Pixels | Content::Type | Content::Solid(_) | Content::Fill => rec.bounds.size(), + }; + if rec.stores_nothing() { + return Ok(None); + } + if w > max_side || rows > max_side { + return Err(DAMAGED.into()); + } + let colors = h.mode.colors(); + let row = row_bytes(w, h.depth); + self.fits(((colors as u64 + 1) * row as u64).saturating_add(4 * w as u64).saturating_mul(rows as u64))?; + self.spend(4 * w as u64 * rows as u64)?; + let plane = |id: i16| -> Result<Option<Vec<u8>>, String> { + match rec.channels.iter().find(|(c, _)| *c == id) { + Some((_, data)) => layer_channel(data, rows, row, h.psb, h.depth).map(Some), + None => Ok(None), + } + }; + let planes = (0..colors as i16).map(plane).collect::<Result<Vec<_>, _>>()?; + let alpha = plane(-1)?; + let linear = h.depth == 32; + let img = RgbaImage::from_fn(w as u32, rows as u32, |x, y| { + let (x, y) = (x as usize, y as usize); + let at = |p: &Option<Vec<u8>>, linear: bool, missing: f32| { + p.as_ref().and_then(|p| p.get(y * row..(y + 1) * row)).map_or(missing, |r| sample(r, x, h.depth, linear)) + }; + let rgb = to_rgb(h, |c| planes.get(c).map_or(0.0, |p| at(p, linear, 0.0)), &self.cmyk); + image::Rgba([byte(rgb[0]), byte(rgb[1]), byte(rgb[2]), byte(at(&alpha, false, 1.0))]) + }); + Ok(Some((i64::from(rec.bounds.left), i64::from(rec.bounds.top), img))) + } + + /// Record `i`'s layer mask as gray values at their place, with the value outside them; `None` + /// when it has none, or it is disabled and not `even_disabled`. + fn mask(&self, i: usize, even_disabled: bool) -> Result<Option<(i64, i64, image::GrayImage, u8)>, String> { + let rec = self.record(i)?; + let Some(m) = rec.mask.filter(|m| even_disabled || !m.disabled) else { return Ok(None) }; + let Some((_, data)) = rec.channels.iter().find(|(c, _)| *c == -2) else { return Ok(None) }; + let (w, rows) = m.bounds.size(); + let max_side = if self.h.psb { 300_000 } else { 30_000 }; + if w > max_side || rows > max_side { + return Err(DAMAGED.into()); + } + let row = row_bytes(w, self.h.depth); + self.fits((row as u64 + w as u64).saturating_mul(rows as u64))?; + self.spend(w as u64 * rows as u64)?; + let plane = layer_channel(data, rows, row, self.h.psb, self.h.depth)?; + let read = |v: u8| if m.inverted { 255 - v } else { v }; + let img = image::GrayImage::from_fn(w as u32, rows as u32, |x, y| { + let r = plane.get(y as usize * row..(y as usize + 1) * row).unwrap_or_default(); + image::Luma([read(byte(sample(r, x as usize, self.h.depth, false)))]) + }); + Ok(Some((i64::from(m.bounds.left), i64::from(m.bounds.top), img, read(m.default)))) + } + + /// Multiply `c`'s transparency by record `i`'s layer mask. + fn apply_mask(&self, c: &mut Canvas, i: usize) -> Result<(), String> { + let Some((left, top, m, default)) = self.mask(i, false)? else { return Ok(()) }; + let (w, h) = (i64::from(m.width()), i64::from(m.height())); + for (k, p) in c.px.iter_mut().enumerate() { + let (x, y) = (c.left + (k % c.width.max(1)) as i64, c.top + (k / c.width.max(1)) as i64); + let inside = (left..left + w).contains(&x) && (top..top + h).contains(&y); + let v = if inside { m.get_pixel((x - left) as u32, (y - top) as u32).0[0] } else { default }; + p[3] *= f32::from(v) / 255.0; + } + Ok(()) + } + + /// What `items` (a layer list, bottom first) become, before the modes VectorCraft lacks are + /// merged: layers clipped to the one below are merged into it, and hidden ones are left out + /// unless `keep_hidden`. Hidden layers a clip would merge are always left out. + fn units<'i>(&mut self, items: &'i [Item], keep_hidden: bool) -> Result<Vec<Unit<'i>>, String> { + let mut out: Vec<Unit<'i>> = vec![]; + // The layer the next clipped layers clip to: its index in `out`, or `None` when it was left + // out (its clipped layers go with it). + let mut base: Option<Option<usize>> = None; + // The next clipped layers come in unclipped: a merge with their base didn't fit. + let mut unclipped = false; + for item in items { + let (i, body) = match item { + Item::Layer(i) => (*i, Body::Layer(*i)), + Item::Group(i, children) => (*i, Body::Group(children)), + }; + let rec = self.record(i)?; + let (name, hidden, clipped, blend) = (rec.name.clone(), rec.hidden, rec.clipped, rec.blend); + let opacity = rec.opacity * rec.fill; + if clipped && let Some(b) = base { + match b { + // Clipped to a layer left out, or hidden itself: left out. + None => self.skip(i), + Some(_) if hidden => self.skip(i), + // A hidden base (with `keep_hidden`) would need the merge: it is left out with + // the layers clipped to it. + Some(b) if out.get(b).is_some_and(|u| !u.visible) => { + if b < out.len() { + let u = out.remove(b); + self.skip(u.record); + } + self.skip(i); + base = Some(None); + } + Some(b) => { + // Counted even when it draws nothing (an adjustment layer). + self.note(i)?; + if !unclipped && self.clip(&mut out, b, &body, i, &name, blend, opacity)? { + continue; + } + // The merge doesn't fit: this layer and the next ones clipped to the same + // base come in as layers of their own. + unclipped = true; + self.notes.unclipped += 1; + out.push(Unit { name, visible: true, opacity, blend, mask_of: Some(i), record: i, body, clip: None }); + } + } + continue; + } + unclipped = false; + if hidden && !keep_hidden { + self.skip(i); + base = Some(None); + continue; + } + self.note(i)?; + out.push(Unit { name, visible: !hidden, opacity, blend, mask_of: Some(i), record: i, body, clip: None }); + base = Some(Some(out.len() - 1)); + } + for u in &mut out { + self.finish_clip(u); + } + Ok(out) + } + + /// Merge the layer of record `i` (`body`, named `name`, drawn alone with its layer mask, at + /// `opacity` in `blend`) into unit `b` of `out`, which it is clipped to. The base's own layer + /// mask stays its opacity mask, which hides the clipped layers with it. `false`, with `out` as + /// it was, when the canvases would need more memory than allowed. + #[allow(clippy::too_many_arguments)] + fn clip(&mut self, out: &mut [Unit<'_>], b: usize, body: &Body<'_>, i: usize, name: &str, blend: Blend, opacity: f32) -> Result<bool, String> { + let Some(u) = out.get(b) else { return Ok(true) }; + let (whole, undrawn, fill, base_opacity) = { + let r = self.record(u.record)?; + let layer = matches!(u.body, Body::Layer(_)); + (layer && r.covers_without_drawing(), layer && r.undrawn_shape(), r.fill, r.opacity) + }; + // A fill whose shape is a vector mask isn't drawn, and nothing clipped to it is either. + if undrawn && u.clip.is_none() { + self.notes.clipped_out += 1; + return Ok(true); + } + let layer = match self.draw_body(body, Some(i))? { + Drawn::Nothing => return Ok(true), + Drawn::TooLarge => return Ok(false), + Drawn::Canvas(c) => c, + }; + let room = self.room(); + let layer_bytes = 16 * layer.px.len() as u64; + let Some(u) = out.get_mut(b) else { return Ok(true) }; + if u.clip.is_none() { + let (canvas, clip) = if whole { + (Canvas::default(), Clip::Whole) + } else { + match self.draw_body(&u.body, None)? { + Drawn::TooLarge => return Ok(false), + // A base that draws nothing shows nothing of its clipped layers either. + Drawn::Nothing => (Canvas::default(), Clip::Shape(vec![])), + Drawn::Canvas(mut c) => { + // Its transparency, 4 bytes a pixel, is kept beside the canvas. + if (20 * c.px.len() as u64).saturating_add(layer_bytes) > room { + return Ok(false); + } + self.spend(4 * c.px.len() as u64)?; + let shape = c.px.iter().map(|p| p[3]).collect(); + for p in &mut c.px { + p[3] = fill; + } + (c, Clip::Shape(shape)) + } + } + }; + u.body = Body::Merged(canvas); + u.clip = Some(clip); + u.opacity = base_opacity; + } + let Body::Merged(c) = &mut u.body else { return Ok(true) }; + match &u.clip { + Some(Clip::Shape(_)) => { + if (20 * c.px.len() as u64).saturating_add(layer_bytes) > room { + return Ok(false); + } + clip_onto(c, &layer, blend, opacity, i); + } + _ => { + let mut acc = (!c.px.is_empty()).then(|| std::mem::take(c)); + let laid = blend_onto(&mut acc, &layer, blend, opacity, i, room, &|n| self.spend(n)); + *c = acc.unwrap_or_default(); + if !laid? { + return Ok(false); + } + } + } + u.name.push_str(" + "); + u.name.push_str(name); + Ok(true) + } + + /// Unit `u`'s merged canvas, once every layer clipped to it is in: transparent outside its + /// shape. + fn finish_clip(&self, u: &mut Unit<'_>) { + let Some(clip) = u.clip.take() else { return }; + let Body::Merged(c) = &mut u.body else { return }; + match clip { + Clip::Shape(shape) => c.px.iter_mut().zip(shape).for_each(|(p, a)| p[3] *= a), + Clip::Whole => { + let (w, h, width) = (i64::from(self.h.width), i64::from(self.h.height), c.width.max(1)); + for (k, p) in c.px.iter_mut().enumerate() { + let (x, y) = (c.left + (k % width) as i64, c.top + (k / width) as i64); + if !(0..w).contains(&x) || !(0..h).contains(&y) { + p[3] = 0.0; + } + } + } + } + } + + /// Count what record `i` holds that doesn't come in. + fn note(&mut self, i: usize) -> Result<(), String> { + // Once, though a merge may draw it again. + match self.noted.get_mut(i) { + Some(true) => return Ok(()), + Some(n) => *n = true, + None => {} + } + let (content, empty, effects, vector_mask, knockout) = { + let rec = self.record(i)?; + (rec.content, rec.stores_nothing(), rec.effects, rec.vector_mask, rec.knockout) + }; + match content { + Content::Type => self.notes.types += 1, + Content::Adjustment => self.notes.adjustments += 1, + // A fill drawn from neither its pixels nor its color. + Content::Fill | Content::Solid(None) if empty => self.notes.fills += 1, + Content::Solid(Some(_)) if empty && vector_mask => self.notes.fills += 1, + _ => {} + } + self.notes.effects += usize::from(effects); + self.notes.vector_masks += usize::from(vector_mask); + self.notes.knockouts += usize::from(knockout); + Ok(()) + } + + /// Count record `i` as a hidden layer left out (once). + fn skip(&mut self, i: usize) { + if let Some(s) = self.skipped.get_mut(i) + && !*s + { + *s = true; + self.notes.hidden += 1; + self.skip_log.push(i); + } + } + + /// `items`' units with the layers in blend modes VectorCraft lacks merged with those below. + fn merged<'i>(&mut self, items: &'i [Item], keep_hidden: bool) -> Result<Vec<Unit<'i>>, String> { + let mut out: Vec<Unit<'i>> = vec![]; + for mut u in self.units(items, keep_hidden)? { + let Blend::Other(other) = u.blend else { + out.push(u); + continue; + }; + // A hidden layer that would need the merge is left out. + if !u.visible { + self.skip(u.record); + continue; + } + // A merge that can't be made counts nothing its groups would have counted. + let saved = self.notes.counts(self.skip_log.len()); + let made = match out.as_mut_slice() { + // Onto the previous merge alone: composited onto its canvas, in place. + [prev] if prev.is_merge() => { + let mut acc = match &mut prev.body { + Body::Merged(c) => Some(std::mem::take(c)), + _ => None, + }; + let made = self.composite(&mut acc, &u); + if let Body::Merged(c) = &mut prev.body { + *c = acc.unwrap_or_default(); + } + if made? { + prev.name.push_str(" + "); + prev.name.push_str(&u.name); + true + } else { + false + } + } + _ => match self.merge(&out, &u)? { + Some(canvas) => { + let mut name = String::new(); + for (k, b) in out.iter_mut().filter(|b| b.visible).enumerate() { + if k == 0 { + name = std::mem::take(&mut b.name); + } else { + name.push_str(" + "); + name.push_str(&b.name); + } + } + if out.iter().any(|b| b.visible) { + name.push_str(" + "); + } + name.push_str(&u.name); + // Hidden layers below are left out with the rest. + for b in out.iter().filter(|b| !b.visible).map(|b| b.record).collect::<Vec<_>>() { + self.skip(b); + } + out.clear(); + out.push(Unit { + name, + visible: true, + opacity: 1.0, + blend: Blend::Mode(BlendMode::Normal), + mask_of: None, + record: u.record, + body: Body::Merged(canvas), + clip: None, + }); + true + } + None => false, + }, + }; + if made { + if !self.notes.merged.contains(&other.label()) { + self.notes.merged.push(other.label()); + } + } else { + self.restore(saved); + self.notes.unmerged += 1; + u.blend = Blend::Mode(BlendMode::Normal); + out.push(u); + } + } + Ok(out) + } + + /// The counts as they were before a merge that couldn't be made. + fn restore(&mut self, c: Counts) { + for i in self.skip_log.split_off(c.skipped) { + if let Some(s) = self.skipped.get_mut(i) { + *s = false; + self.notes.hidden = self.notes.hidden.saturating_sub(1); + } + } + self.notes.merged.truncate(c.merged); + self.notes.unmerged = c.unmerged; + self.notes.unclipped = c.unclipped; + self.notes.clipped_out = c.clipped_out; + } + + /// The visible units `below` with `top` composited over them; `None` when the canvas would need + /// more memory than allowed. + fn merge(&mut self, below: &[Unit<'_>], top: &Unit<'_>) -> Result<Option<Canvas>, String> { + let mut acc: Option<Canvas> = None; + for u in below.iter().filter(|u| u.visible).chain([top]) { + if !self.composite(&mut acc, u)? { + return Ok(None); + } + } + Ok(Some(acc.unwrap_or_default())) + } + + /// The bytes a merge step may still take: the memory allowed, less the copies of what is below + /// the pass-through groups being merged. + fn room(&self) -> u64 { + self.max_alloc.saturating_sub(self.held) + } + + /// Unit `u` composited onto `acc`. A pass-through group lays its layers onto `acc` one by one, + /// so that they blend with what is below it; at less than full opacity or with a layer mask, the + /// result is then faded back toward `acc` as it was by the opacity and the mask. Anything else + /// is drawn alone first. `false` when the canvas would need more memory than allowed. + fn composite(&mut self, acc: &mut Option<Canvas>, u: &Unit<'_>) -> Result<bool, String> { + if let (Body::Group(items), Blend::Pass) = (&u.body, u.blend) { + let mask = match u.mask_of { + Some(i) if self.has_mask(Some(i))? => self.mask(i, false)?, + _ => None, + }; + if u.opacity >= 1.0 && mask.is_none() { + return self.lay(acc, items); + } + let bytes = acc.as_ref().map_or(0, |c| 16 * c.px.len() as u64); + if bytes > self.room() { + return Ok(false); + } + self.spend(bytes)?; + let below = acc.clone(); + self.held = self.held.saturating_add(bytes); + let laid = self.lay(acc, items); + self.held = self.held.saturating_sub(bytes); + if !laid? { + return Ok(false); + } + if let Some(after) = acc.as_mut() { + fade(after, below.as_ref(), u.opacity, mask.as_ref()); + } + return Ok(true); + } + let c = match self.draw_body(&u.body, u.mask_of)? { + Drawn::Nothing => return Ok(true), + Drawn::Canvas(c) => c, + Drawn::TooLarge => return Ok(false), + }; + blend_onto(acc, &c, u.blend, u.opacity, u.record, self.room(), &|n| self.spend(n)) + } + + /// `items`' layers composited onto `acc` one by one; `false` when a canvas would need more + /// memory than allowed. + fn lay(&mut self, acc: &mut Option<Canvas>, items: &[Item]) -> Result<bool, String> { + for c in self.merged(items, false)? { + if !self.composite(acc, &c)? { + return Ok(false); + } + } + Ok(true) + } + + /// Does record `mask_of` have a layer mask that is switched on? + fn has_mask(&self, mask_of: Option<usize>) -> Result<bool, String> { + let Some(i) = mask_of else { return Ok(false) }; + let rec = self.record(i)?; + Ok(rec.mask.is_some_and(|m| !m.disabled) && rec.channels.iter().any(|(c, _)| *c == -2)) + } + + /// A unit's body drawn alone, with the layer mask of record `mask_of`, before its own opacity + /// and blend mode. Its canvas counts against the import's allowance. + fn draw_body(&mut self, body: &Body<'_>, mask_of: Option<usize>) -> Result<Drawn, String> { + let mut c = match body { + Body::Merged(c) => { + let bytes = 16 * c.px.len() as u64; + if bytes > self.room() { + return Ok(Drawn::TooLarge); + } + self.spend(bytes)?; + c.clone() + } + Body::Layer(i) => match self.image(*i)? { + Some((left, top, img)) => { + let bytes = 16 * u64::from(img.width()) * u64::from(img.height()); + if bytes > self.room() { + return Ok(Drawn::TooLarge); + } + self.spend(bytes)?; + Canvas::from_image(left, top, &img) + } + None => return Ok(Drawn::Nothing), + }, + Body::Group(items) => { + let mut acc: Option<Canvas> = None; + if !self.lay(&mut acc, items)? { + return Ok(Drawn::TooLarge); + } + let Some(acc) = acc else { return Ok(Drawn::Nothing) }; + acc + } + }; + if let Some(i) = mask_of { + self.apply_mask(&mut c, i)?; + } + Ok(Drawn::Canvas(c)) + } + + /// A new layer of the document named `name`, colored as the next new layer would be. + fn layer(&mut self, name: &str) -> Node { + let n = Node::layer(self.doc.alloc_id(), name, LayerColor::Preset((self.layers % LAYER_COLORS.len()) as u8)); + self.layers += 1; + n + } + + /// `img` at `left`, `top` on the canvas as an image of the document named `name`. + fn image_node(&mut self, name: &str, left: i64, top: i64, img: RgbaImage) -> Result<Node, String> { + let RasterImage { key, blob, width, height, .. } = as_png(img, None, self.ppi).map_err(|e| e.to_string())?; + let xf = self.to_doc * Affine::translate((left as f64, top as f64)); + let mut n = Node::new( + self.doc.alloc_id(), + NodeKind::Image(Box::new(ImageObject { key: key.clone(), width, height, xf, link: None, placement: Default::default(), pixels: None })), + ); + n.name = Some(name.to_string()); + self.doc.images.insert(key, blob); + Ok(n) + } + + /// Layers of the document for `items`, bottom first. + fn list(&mut self, items: &[Item]) -> Result<Vec<Arc<Node>>, String> { + let mut out = vec![]; + for u in self.merged(items, self.hidden)? { + if let Some(n) = self.node(u)? { + out.push(Arc::new(n)); + } + } + Ok(out) + } + + /// The layer of the document unit `u` becomes; `None` for a layer that draws nothing (an + /// adjustment layer, or one without pixels). + fn node(&mut self, u: Unit<'_>) -> Result<Option<Node>, String> { + let children = match &u.body { + Body::Layer(i) => match self.image(*i)? { + Some((left, top, img)) => vec![Arc::new(self.image_node(&u.name, left, top, img)?)], + None => return Ok(None), + }, + Body::Merged(c) => match c.to_image() { + Some((left, top, img)) => vec![Arc::new(self.image_node(&u.name, left, top, img)?)], + None => return Ok(None), + }, + Body::Group(items) => self.list(items)?, + }; + let mut layer = self.layer(&u.name); + layer.visible = u.visible; + layer.opacity = u.opacity.clamp(0.0, 1.0); + (layer.blend, layer.isolate) = match u.blend { + Blend::Mode(m) => (m, matches!(u.body, Body::Group(_))), + Blend::Pass | Blend::Other(_) => (BlendMode::Normal, false), + }; + if let Some(c) = layer.children_mut() { + *c = children; + } + if let Some(i) = u.mask_of { + layer.extras_mut().mask = self.opacity_mask(i)?.map(Box::new); + } + Ok(Some(layer)) + } + + /// Record `i`'s layer mask as an opacity mask: a gray image, outside which the layer is hidden + /// or shown as the mask's default color says (a mask of no pixels hides all of it, or none). + fn opacity_mask(&mut self, i: usize) -> Result<Option<OpacityMask>, String> { + let disabled = self.record(i)?.mask.is_some_and(|m| m.disabled); + let Some((left, top, gray, default)) = self.mask(i, true)? else { return Ok(None) }; + let (art, clip) = if gray.width() == 0 || gray.height() == 0 { + if default == 255 { + return Ok(None); + } + let black = RgbaImage::from_pixel(1, 1, image::Rgba([0, 0, 0, 255])); + (self.image_node("Layer Mask", left, top, black)?, true) + } else { + self.fits(5 * u64::from(gray.width()) * u64::from(gray.height()))?; + let rgba = RgbaImage::from_fn(gray.width(), gray.height(), |x, y| { + let v = gray.get_pixel(x, y).0[0]; + image::Rgba([v, v, v, 255]) + }); + (self.image_node("Layer Mask", left, top, rgba)?, default == 0) + }; + let mut mask = OpacityMask::new(art, clip); + mask.disabled = disabled; + Ok(Some(mask)) + } +} + +/// The coverage of a pixel at `x`, `y` of the canvas with `alpha`, 0..1, in `blend`: in Dissolve +/// fully opaque or fully transparent, opaque at a share of the pixels equal to `alpha`, chosen by a +/// fixed hash of the pixel's place and of `record`, so that each layer has its own pattern; `alpha` +/// in every other mode. +fn coverage(blend: Blend, alpha: f32, x: i64, y: i64, record: usize) -> f32 { + if !matches!(blend, Blend::Other(Other::Dissolve)) { + return alpha; + } + let mut h = (x as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) + ^ (y as u64).wrapping_mul(0xC2B2_AE3D_27D4_EB4F) + ^ (record as u64).wrapping_mul(0x1656_67B1_9E37_79F9); + h ^= h >> 31; + h = h.wrapping_mul(0xBF58_476D_1CE4_E5B9); + h ^= h >> 29; + // The top 24 bits, 0..1. + let r = (h >> 40) as f32 / (1u64 << 24) as f32; + if r < alpha { 1.0 } else { 0.0 } +} + +/// `layer` (of record `record`) composited onto `base`, the canvas of the layer it is clipped to, +/// in `blend` at `opacity`, where the two overlap. +fn clip_onto(base: &mut Canvas, layer: &Canvas, blend: Blend, opacity: f32, record: usize) { + let (x0, x1) = (base.left.max(layer.left), (base.left + base.width as i64).min(layer.left + layer.width as i64)); + let (y0, y1) = (base.top.max(layer.top), (base.top + base.height as i64).min(layer.top + layer.height as i64)); + for y in y0..y1 { + for x in x0..x1 { + let Some(mut s) = layer.get(x, y) else { continue }; + let k = (y - base.top) as usize * base.width + (x - base.left) as usize; + let Some(b) = base.px.get_mut(k) else { continue }; + s[3] = coverage(blend, s[3] * opacity, x, y, record); + *b = over(blend, *b, s); + } + } +} + +/// `after` faded back toward `before` (transparent where it has no pixels) by `opacity` times the +/// value of `mask` (its place, its gray values and the value outside it) at each pixel, in +/// premultiplied color. +fn fade(after: &mut Canvas, before: Option<&Canvas>, opacity: f32, mask: Option<&(i64, i64, image::GrayImage, u8)>) { + let width = after.width.max(1); + for (k, p) in after.px.iter_mut().enumerate() { + let (x, y) = (after.left + (k % width) as i64, after.top + (k / width) as i64); + let m = mask.map_or(255, |(left, top, m, default)| { + let inside = (*left..*left + i64::from(m.width())).contains(&x) && (*top..*top + i64::from(m.height())).contains(&y); + if inside { m.get_pixel((x - left) as u32, (y - top) as u32).0[0] } else { *default } + }); + let t = opacity * f32::from(m) / 255.0; + let b = before.and_then(|c| c.get(x, y)).unwrap_or([0.0; 4]); + let alpha = (1.0 - t) * b[3] + t * p[3]; + if alpha <= 0.0 { + *p = [0.0; 4]; + continue; + } + let mix = |i: usize| ((1.0 - t) * b[3] * b[i] + t * p[3] * p[i]) / alpha; + *p = [mix(0), mix(1), mix(2), alpha]; + } +} + +/// `src` (of record `record`) at `opacity` composited onto `acc` (nothing when `None`) in `blend`, +/// on a canvas covering both (`acc` itself when it covers `src`; a larger one is counted with +/// `spend`). `false`, with `acc` as it was, when the canvases held, `acc` and `src` and a larger +/// canvas when one is needed, would take more than `max_alloc` bytes. +fn blend_onto( + acc: &mut Option<Canvas>, + src: &Canvas, + blend: Blend, + opacity: f32, + record: usize, + max_alloc: u64, + spend: &dyn Fn(u64) -> Result<(), String>, +) -> Result<bool, String> { + let (mut left, mut top, mut right, mut bottom) = (src.left, src.top, src.left + src.width as i64, src.top + src.height as i64); + if let Some(a) = acc.as_ref() { + left = left.min(a.left); + top = top.min(a.top); + right = right.max(a.left + a.width as i64); + bottom = bottom.max(a.top + a.height as i64); + } + let (Ok(width), Ok(height)) = (usize::try_from(right - left), usize::try_from(bottom - top)) else { return Ok(false) }; + let held = (src.px.len() as u64).saturating_add(acc.as_ref().map_or(0, |a| a.px.len() as u64)); + let covers = acc.as_ref().is_some_and(|a| (a.left, a.top, a.width, a.height) == (left, top, width, height)); + if covers { + if held.saturating_mul(16) > max_alloc { + return Ok(false); + } + } else { + let bytes = (width as u64).saturating_mul(height as u64).saturating_mul(16); + if bytes.saturating_add(held.saturating_mul(16)) > max_alloc { + return Ok(false); + } + spend(bytes)?; + let mut out = Canvas { left, top, width, height, px: vec![[0.0; 4]; width * height] }; + if let Some(a) = acc.take() { + for (y, row) in a.px.chunks(a.width.max(1)).enumerate() { + let at = (a.top - top) as usize + y; + let start = at * width + (a.left - left) as usize; + if let Some(dst) = out.px.get_mut(start..start + row.len()) { + dst.copy_from_slice(row); + } + } + } + *acc = Some(out); + } + let Some(out) = acc.as_mut() else { return Ok(false) }; + // Only the source's rows and columns change. + let (sw, x0, y0) = (src.width.max(1), (src.left - left) as usize, (src.top - top) as usize); + for (k, s) in src.px.iter().enumerate() { + let Some(p) = out.px.get_mut((y0 + k / sw) * width + x0 + k % sw) else { continue }; + let a = coverage(blend, s[3] * opacity, src.left + (k % sw) as i64, src.top + (k / sw) as i64, record); + *p = over(blend, *p, [s[0], s[1], s[2], a]); + } + Ok(true) +} + +/// PSD or PSB file `bytes` with its layers as layers of the document (see the module +/// documentation), with warnings for what doesn't come in. `None` when the file has no layers (its +/// merged image is all of it). CMYK converts through `cmyk` (ink amounts 0..1 → sRGB). +pub(super) fn import( + bytes: &[u8], + hidden: bool, + max_alloc: u64, + cmyk: impl Fn([f32; 4]) -> [f32; 3], +) -> Result<Option<(Document, Vec<String>)>, String> { + let mut r = Reader::new(bytes); + let h = header(&mut r)?; + // Layer info that holds only the count (which says whether the merged image has transparency) + // has no layers either. + let Some(info) = layer_info(h.layers, h.psb).filter(|info| info.len() > 2) else { return Ok(None) }; + let records = records(info, h.psb)?; + if records.is_empty() { + return Ok(None); + } + let items = tree(&records)?; + let ppi = super::ppi::resolution(bytes).filter(|(x, y)| x.is_finite() && y.is_finite() && *x > 0.0 && *y > 0.0); + let (sx, sy) = crate::cmd::place::pt_per_px(ppi); + let doc = Document::new(f64::from(h.width) * sx, f64::from(h.height) * sy); + let mut b = Builder { + h: &h, + records: &records, + hidden, + max_alloc, + held: 0, + cmyk, + doc, + to_doc: Affine::scale_non_uniform(sx, sy), + ppi, + layers: 0, + notes: Notes::default(), + noted: vec![false; records.len()], + skipped: vec![false; records.len()], + skip_log: vec![], + spent: Cell::new(0), + }; + let layers = b.list(&items)?; + let Builder { mut doc, notes, .. } = b; + if !layers.is_empty() { + doc.layers = layers; + } + // Groups nest up to `MAX_DEPTH`, deeper than a document may: what is too deep merges into + // the group around it, with a warning. + let mut warnings = notes.warnings(); + doc.limit_depth_noting(&mut warnings); + Ok(Some((doc, warnings))) +} diff --git a/crates/engine/src/cmd/fileio/psdread.rs b/crates/engine/src/cmd/fileio/psdread.rs index 84ac8203aa..93e7b61f17 100644 --- a/crates/engine/src/cmd/fileio/psdread.rs +++ b/crates/engine/src/cmd/fileio/psdread.rs @@ -1,7 +1,8 @@ //! Reading Photoshop documents (PSD, and PSB, the large document format) for File › Open and //! File › Place (#918): the merged image, the flattened picture every PSD carries after its layers, //! as a linked PSD shows. Written from Adobe's public "Photoshop File Formats Specification" -//! (<https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/>). Layers aren't read. +//! (<https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/>). File › Open reads the +//! layers with [`super::psdlayers`], which shares this reader. //! //! Every mode Photoshop saves a merged image in is read: Bitmap, Grayscale, Duotone (as its //! grayscale data), Indexed, RGB, CMYK and Lab, at 1, 8, 16 and 32 bits per channel, stored raw, @@ -16,7 +17,7 @@ use vectorcraft_color::cms::{Lab, lab::lab_to_srgb}; /// Photoshop's colour modes (the header's numbers), as far as the merged image is concerned. #[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Mode { +pub(super) enum Mode { Bitmap, Gray, Indexed, @@ -27,7 +28,7 @@ enum Mode { impl Mode { /// The channels holding colour (an alpha channel may follow them). - fn colors(self) -> usize { + pub(super) fn colors(self) -> usize { match self { Mode::Bitmap | Mode::Gray | Mode::Indexed => 1, Mode::Rgb | Mode::Lab => 3, @@ -46,68 +47,68 @@ pub fn is_psb(bytes: &[u8]) -> bool { is_psd(bytes) && bytes.get(4..6) == Some(&[0, 2]) } -const TRUNCATED: &str = "the PSD file is cut short"; +pub(super) const TRUNCATED: &str = "the PSD file is cut short"; const DAMAGED: &str = "the PSD file's header is damaged"; /// Big-endian reads through `b`, each checked against its end. -struct Reader<'a> { +pub(super) struct Reader<'a> { b: &'a [u8], at: usize, } impl<'a> Reader<'a> { - fn new(b: &'a [u8]) -> Self { + pub(super) fn new(b: &'a [u8]) -> Self { Self { b, at: 0 } } - fn take(&mut self, n: usize) -> Result<&'a [u8], String> { + pub(super) fn take(&mut self, n: usize) -> Result<&'a [u8], String> { let s = self.at.checked_add(n).and_then(|end| self.b.get(self.at..end)).ok_or(TRUNCATED)?; self.at += n; Ok(s) } - fn array<const N: usize>(&mut self) -> Result<[u8; N], String> { + pub(super) fn array<const N: usize>(&mut self) -> Result<[u8; N], String> { self.take(N)?.try_into().map_err(|_| TRUNCATED.to_string()) } - fn u8(&mut self) -> Result<u8, String> { + pub(super) fn u8(&mut self) -> Result<u8, String> { self.array::<1>().map(|[v]| v) } - fn u16(&mut self) -> Result<u16, String> { + pub(super) fn u16(&mut self) -> Result<u16, String> { self.array().map(u16::from_be_bytes) } - fn u32(&mut self) -> Result<u32, String> { + pub(super) fn u32(&mut self) -> Result<u32, String> { self.array().map(u32::from_be_bytes) } /// A section length: 4 bytes in a PSD, 8 in a PSB. - fn length(&mut self, psb: bool) -> Result<usize, String> { + pub(super) fn length(&mut self, psb: bool) -> Result<usize, String> { let n = if psb { self.array().map(u64::from_be_bytes)? } else { u64::from(self.u32()?) }; usize::try_from(n).map_err(|_| TRUNCATED.to_string()) } /// A section: its length, then that many bytes. - fn section(&mut self, psb: bool) -> Result<&'a [u8], String> { + pub(super) fn section(&mut self, psb: bool) -> Result<&'a [u8], String> { let n = self.length(psb)?; self.take(n) } - fn rest(&self) -> &'a [u8] { + pub(super) fn rest(&self) -> &'a [u8] { self.b.get(self.at..).unwrap_or_default() } } /// The fixed-size header and the sections before the image data. -struct Header<'a> { - psb: bool, +pub(super) struct Header<'a> { + pub(super) psb: bool, channels: usize, - width: u32, - height: u32, - depth: u16, - mode: Mode, + pub(super) width: u32, + pub(super) height: u32, + pub(super) depth: u16, + pub(super) mode: Mode, /// Colour mode data: an indexed image's palette (256 reds, then greens, then blues). palette: &'a [u8], /// The image resources. resources: &'a [u8], /// The layer and mask information. - layers: &'a [u8], + pub(super) layers: &'a [u8], } -fn header<'a>(r: &mut Reader<'a>) -> Result<Header<'a>, String> { +pub(super) fn header<'a>(r: &mut Reader<'a>) -> Result<Header<'a>, String> { if !is_psd(r.b) { return Err("not a PSD file".into()); } @@ -183,41 +184,45 @@ pub fn resolution(bytes: &[u8]) -> Option<(f64, f64)> { /// count is negative: in the layer info, or for 16- and 32-bit documents (whose layer info is /// empty) in their `Lr16` / `Lr32` block. fn merged_alpha(layers: &[u8], psb: bool) -> bool { - let count_negative = |info: &[u8]| info.get(..2).is_some_and(|c| i16::from_be_bytes([c[0], c[1]]) < 0); + layer_info(layers, psb).is_some_and(|info| info.get(..2).is_some_and(|c| i16::from_be_bytes([c[0], c[1]]) < 0)) +} + +/// Do tagged blocks with this key give an 8-byte length in a PSB? +pub(super) fn long_key(key: &[u8; 4]) -> bool { + matches!(key, b"Lr16" | b"Lr32" | b"Layr" | b"LMsk" | b"Mt16" | b"Mt32" | b"Mtrn" | b"Alph" | b"FMsk" | b"lnk2" | b"FEid" | b"FXid" | b"PxSD") +} + +/// The layer info: the layer count, the layer records and their channels. It is the first part of +/// the layer and mask information, or for 16- and 32-bit documents (whose first part is empty) the +/// `Lr16` / `Lr32` block after it. `None` when the file has neither. +pub(super) fn layer_info(layers: &[u8], psb: bool) -> Option<&[u8]> { let mut r = Reader::new(layers); - let Ok(info) = r.section(psb) else { return false }; + let info = r.section(psb).ok()?; if !info.is_empty() { - return count_negative(info); + return Some(info); } // The global layer mask info, then tagged blocks: signature, key, length (8 bytes for the // layer blocks of a PSB), data padded to 4 bytes. - if r.section(false).is_err() { - return false; - } + r.section(false).ok()?; while r.rest().len() >= 12 { - let (Ok(_), Ok(key)) = (r.take(4), r.array::<4>()) else { return false }; - let layer_block = matches!(&key, b"Lr16" | b"Lr32" | b"Layr"); - let long = layer_block || matches!(&key, b"LMsk" | b"Mt16" | b"Mt32" | b"Mtrn" | b"Alph" | b"FMsk" | b"lnk2" | b"FEid" | b"FXid" | b"PxSD"); - let Ok(data) = r.section(psb && long) else { - return false; - }; - if layer_block { - return count_negative(data); - } - if r.take((4 - data.len() % 4) % 4).is_err() { - return false; + r.take(4).ok()?; + let key = r.array::<4>().ok()?; + let data = r.section(psb && long_key(&key)).ok()?; + if matches!(&key, b"Lr16" | b"Lr32" | b"Layr") { + return Some(data); } + r.take((4 - data.len() % 4) % 4).ok()?; } - false + None } /// The most bytes one channel row may take (a PSB at 32 bits). -fn row_bytes(width: usize, depth: u16) -> usize { +pub(super) fn row_bytes(width: usize, depth: u16) -> usize { if depth == 1 { width.div_ceil(8) } else { width * usize::from(depth / 8) } } /// Undo PackBits: `src` into `dst` (a row; a short or overlong run leaves the rest as it is). -fn unpack_bits(mut src: &[u8], dst: &mut [u8]) { +pub(super) fn unpack_bits(mut src: &[u8], dst: &mut [u8]) { let mut at = 0; while let Some((&n, rest)) = src.split_first() { src = rest; @@ -269,32 +274,77 @@ fn channel_data(data: &[u8], h: &Header<'_>, channels: usize, row: usize) -> Res } Ok(out) } - 2 | 3 => { - let mut out = Vec::new(); - flate2::read::ZlibDecoder::new(r.rest()) - .take(wanted as u64) - .read_to_end(&mut out) - .map_err(|e| format!("the PSD file's image data can't be read: {e}"))?; - if out.len() < wanted { - return Err(TRUNCATED.into()); - } - if method == 3 { - // Each row stores the difference from the sample before it. - match h.depth { - 8 => out.chunks_exact_mut(row).for_each(|r| (1..r.len()).for_each(|i| r[i] = r[i].wrapping_add(r[i - 1]))), - 16 => out.chunks_exact_mut(row).for_each(|r| { - let mut prev = 0u16; - for s in r.as_chunks_mut::<2>().0 { - prev = prev.wrapping_add(u16::from_be_bytes(*s)); - *s = prev.to_be_bytes(); - } - }), - _ => return Err("zipped 32-bit PSD image data with prediction can't be read".into()), + 2 | 3 => inflate(r.rest(), wanted, method == 3, h.depth, row), + m => Err(format!("the PSD file's image data uses an unknown compression ({m})")), + } +} + +/// `wanted` bytes of zipped image data, rows of `row` bytes; with `predicted`, each row stores the +/// difference from the sample before it. In 32-bit data a row stores the first bytes of its samples, +/// then their second bytes, and so on, and the differences run byte by byte along the whole row (as +/// psd-tools, MIT, reads it: <https://github.com/psd-tools/psd-tools>, `compression/__init__.py`). +fn inflate(src: &[u8], wanted: usize, predicted: bool, depth: u16, row: usize) -> Result<Vec<u8>, String> { + let mut out = Vec::new(); + flate2::read::ZlibDecoder::new(src) + .take(wanted as u64) + .read_to_end(&mut out) + .map_err(|e| format!("the PSD file's image data can't be read: {e}"))?; + if out.len() < wanted { + return Err(TRUNCATED.into()); + } + if predicted && row > 0 { + match depth { + 8 => out.chunks_exact_mut(row).for_each(|r| (1..r.len()).for_each(|i| r[i] = r[i].wrapping_add(r[i - 1]))), + 16 => out.chunks_exact_mut(row).for_each(|r| { + let mut prev = 0u16; + for s in r.as_chunks_mut::<2>().0 { + prev = prev.wrapping_add(u16::from_be_bytes(*s)); + *s = prev.to_be_bytes(); } + }), + 32 => { + let w = row / 4; + let mut planes = vec![0u8; row]; + for r in out.chunks_exact_mut(row) { + let mut prev = 0u8; + for (dst, &b) in planes.iter_mut().zip(r.iter()) { + prev = prev.wrapping_add(b); + *dst = prev; + } + for (x, s) in r.as_chunks_mut::<4>().0.iter_mut().enumerate() { + for (k, v) in s.iter_mut().enumerate() { + *v = planes.get(k * w + x).copied().unwrap_or(0); + } + } + } + } + // 1-bit. + _ => return Err("zipped 1-bit PSD image data with prediction can't be read".into()), + } + } + Ok(out) +} + +/// One channel of a layer: its compression method, then `rows` rows of `row` bytes (PackBits rows +/// after their byte counts, 4 bytes each in a PSB). +pub(super) fn layer_channel(data: &[u8], rows: usize, row: usize, psb: bool, depth: u16) -> Result<Vec<u8>, String> { + let mut r = Reader::new(data); + let method = r.u16()?; + let wanted = rows.checked_mul(row).ok_or(TRUNCATED)?; + match method { + 0 => r.take(wanted).map(<[u8]>::to_vec), + 1 => { + let size = if psb { 4 } else { 2 }; + let counts = r.take(rows.checked_mul(size).ok_or(TRUNCATED)?)?; + let mut out = vec![0; wanted]; + for (dst, n) in out.chunks_exact_mut(row.max(1)).zip(counts.chunks_exact(size)) { + let n = n.iter().fold(0usize, |n, &b| n << 8 | usize::from(b)); + unpack_bits(r.take(n)?, dst); } Ok(out) } - m => Err(format!("the PSD file's image data uses an unknown compression ({m})")), + 2 | 3 => inflate(r.rest(), wanted, method == 3, depth, row), + m => Err(format!("the PSD file's layer data uses an unknown compression ({m})")), } } @@ -304,7 +354,7 @@ fn srgb_encode(v: f32) -> f32 { } /// Sample `x` of a channel row, 0..1. -fn sample(row: &[u8], x: usize, depth: u16, linear: bool) -> f32 { +pub(super) fn sample(row: &[u8], x: usize, depth: u16, linear: bool) -> f32 { match depth { 1 => { // Bitmap: a set bit is black. @@ -321,10 +371,25 @@ fn sample(row: &[u8], x: usize, depth: u16, linear: bool) -> f32 { } } -fn byte(v: f32) -> u8 { +pub(super) fn byte(v: f32) -> u8 { (v.clamp(0.0, 1.0) * 255.0).round() as u8 } +/// The sRGB color of a pixel whose color channels `v` gives (0..1, as stored), in `h`'s mode. +pub(super) fn to_rgb(h: &Header<'_>, v: impl Fn(usize) -> f32, cmyk: &impl Fn([f32; 4]) -> [f32; 3]) -> [f32; 3] { + match h.mode { + Mode::Bitmap | Mode::Gray => [v(0); 3], + Mode::Indexed => { + let i = usize::from(byte(v(0))); + [0, 256, 512].map(|at| h.palette.get(at + i).map_or(0.0, |&c| f32::from(c) / 255.0)) + } + Mode::Rgb => [v(0), v(1), v(2)], + // Inks are stored as 1 − amount. + Mode::Cmyk => cmyk([0, 1, 2, 3].map(|c| 1.0 - v(c))), + Mode::Lab => lab_to_srgb(Lab { l: v(0) * 100.0, a: v(1) * 255.0 - 128.0, b: v(2) * 255.0 - 128.0 }), + } +} + /// A Photoshop document's merged image as straight RGBA. CMYK converts through `cmyk` (ink /// amounts 0..1 → sRGB). Fails, without allocating, when the image would need more than /// `max_alloc` bytes. @@ -348,17 +413,7 @@ pub fn decode(bytes: &[u8], max_alloc: u64, cmyk: impl Fn([f32; 4]) -> [f32; 3]) let planes: Vec<&[u8]> = (0..channels).map(|c| data.get((c * rows + y) * row..(c * rows + y + 1) * row).unwrap_or_default()).collect(); for (x, px) in line.enumerate() { let v = |c: usize| planes.get(c).map_or(0.0, |p| sample(p, x, h.depth, linear && c < colors)); - let rgb = match h.mode { - Mode::Bitmap | Mode::Gray => [v(0); 3], - Mode::Indexed => { - let i = usize::from(byte(v(0))); - [0, 256, 512].map(|at| h.palette.get(at + i).map_or(0.0, |&c| f32::from(c) / 255.0)) - } - Mode::Rgb => [v(0), v(1), v(2)], - // Inks are stored as 1 − amount. - Mode::Cmyk => cmyk([0, 1, 2, 3].map(|c| 1.0 - v(c))), - Mode::Lab => lab_to_srgb(Lab { l: v(0) * 100.0, a: v(1) * 255.0 - 128.0, b: v(2) * 255.0 - 128.0 }), - }; + let rgb = to_rgb(&h, v, &cmyk); let a = if alpha { v(colors) } else { 1.0 }; // The merged image is stored on white: take the white back out. let straight = |c: f32| if a <= 0.0 { 0.0 } else { (c - (1.0 - a)) / a }; diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index 9f4e5b0572..0a306ee1a9 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -99,6 +99,10 @@ pub struct SavePlan { /// `preview`, `precision`) given beside the path, and each key of `options`, that the format /// doesn't read, naming the file the save writes. pub notes: Vec<String>, + /// The file the document was read from and what reading it left out, when the save needs + /// `acknowledgeLoss` to write over it and was not given it: every file the save writes is + /// checked against it before the first is written. + pub lossy_source: Option<(String, Vec<String>)>, } impl SavePlan { @@ -157,6 +161,11 @@ fn documents_folder() -> Option<std::path::PathBuf> { Some(home.join("Documents")) } +/// A Save As after a refused Save starts in Documents, else home, never the refused folder. +pub fn documents_dialog_folder() -> Option<String> { + documents_folder().filter(|p| p.is_dir()).map(|p| p.to_string_lossy().into_owned()).or_else(home_folder) +} + /// `XDG_DOCUMENTS_DIR` in a `user-dirs.dirs` file's `text`, `$HOME` being `home`. None when it isn't /// set, is relative, or is the home folder itself (the spec's way of turning it off). fn xdg_documents(text: &str, home: &std::path::Path) -> Option<std::path::PathBuf> { @@ -298,7 +307,9 @@ pub fn save_plan(s: &Session, mode: SaveMode, p: &Value) -> Result<SavePlan> { }; let modified = date_param(p, "modified", cmd)?; if let Some(path) = &path { - super::check_not_lossy_overwrite(st, path, p, cmd)?; + // Without a path, it is the document's own file: the error names it as the request may see it. + let given = str_param(p, "path").is_some_and(|g| !g.is_empty()); + super::check_not_lossy_overwrite(st, path, p, cmd).map_err(|e| if given { e } else { super::access::naming_in_error(e, path) })?; } let written = written_as(cmd, format, &Value::Object(options.clone())); let top = NATIVE_OPTIONS.iter().filter(|k| p.get(**k).is_some_and(|v| !v.is_null())).map(|k| k.to_string()); @@ -306,9 +317,10 @@ pub fn save_plan(s: &Session, mode: SaveMode, p: &Value) -> Result<SavePlan> { let notes = top .filter(|k| !reads_option(format, k)) .chain(nested.filter(|k| !reads_option(format, k)).map(|k| format!("options.{k}"))) - .map(|k| format!("`{k}` was not used: {} files don't read it", written.label)) + .map(|k| unused_option_note(&k, &written)) .collect(); - Ok(SavePlan { mode, path, format, options, name, folder, modified, notes }) + let lossy_source = super::lossy_source(st, p); + Ok(SavePlan { mode, path, format, options, name, folder, modified, notes, lossy_source }) } /// The native save options, which a save also takes beside the path. @@ -455,6 +467,12 @@ pub fn reads_option(f: &Format, key: &str) -> bool { f.options.iter().any(|o| o.name == key) || (is_pdf(f) && (super::pdf::OPTIONS.iter().any(|o| o.name == key) || super::pdf::is_setting(key))) } +/// The note a save or an export gives for option `key`, as the request names it, which the file it +/// writes (`written`, see [`written_as`]) doesn't read. +pub(super) fn unused_option_note(key: &str, written: &Format) -> String { + format!("`{key}` was not used: {} files don't read it", written.label) +} + /// Formats that carry the whole native document: they lose nothing, and record links relative to /// where they are written. A `.ai` or `.ait` file is a PDF carrying it; EPS carries it in comments. fn is_native(f: &Format) -> bool { @@ -624,7 +642,7 @@ fn without_pdf(f: &Format) -> Format { /// `f` named, in its errors and notes, as the file a save with options `p` writes: a version 7 /// `.ai` as the legacy `.ai`, and a `.ai` or `.ait` with `pdfCompatible: false` as one saved /// without PDF content. -fn written_as(cmd: &str, f: &Format, p: &Value) -> Format { +pub(super) fn written_as(cmd: &str, f: &Format, p: &Value) -> Format { if f.id == "ai" && super::legacy_ai::wanted(cmd, f, p).unwrap_or(false) { super::legacy_ai::named(f) } else if matches!(f.id, "ai" | "ait") && !bool_or(p, "pdfCompatible", true) { @@ -673,6 +691,31 @@ struct AiEditingData { editing_data: Option<bool>, } +/// Why a `.ai` file of the art's bounds (`useArtboards: false`) carries no editing data. +pub const AI_EDITING_NEEDS_THE_ARTBOARDS: &str = + "Preserve editing was left out: an .ai file of the art's bounds would replace the document's artboards when reopened"; + +/// The error for a `.ai` file of the art's bounds without PDF content. +pub const ART_PAGE_NEEDS_PDF: &str = "pdfCompatible: false needs the artboards to keep the editable artwork when useArtboards is false"; + +/// With `useArtboards: false` in `p`: the PDF-compatible `.ai` file of one page, the bounds of +/// `doc`'s visible art ([`super::encode::art_page`]). It carries neither the native document nor +/// the editing copy for other apps, and its notes end with [`AI_EDITING_NEEDS_THE_ARTBOARDS`]. +/// `pdfCompatible: false` is refused. `None` when `p` asks for the artboards or for a legacy +/// version 7 `.ai` file. +pub(super) fn encode_ai_art_page(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result<Option<Encoded>> { + if super::encode::use_artboards(cmd, p)? != Some(false) || super::legacy_ai::wanted(cmd, f, p)? { + return Ok(None); + } + if !bool_or(p, "pdfCompatible", true) { + return Err(bad(cmd, ART_PAGE_NEEDS_PDF)); + } + let Some((art, q)) = super::encode::art_page(cmd, doc, p)? else { return Ok(None) }; + let mut enc = encode_ai_pages(cmd, f, &art, &q, false)?; + enc.setting_notes.push(AI_EDITING_NEEDS_THE_ARTBOARDS.to_string()); + Ok(Some(enc)) +} + /// The shared Save and Export encoder for `.ai` files (and `.ait` templates, the same file): /// PDF-compatible by default, without PDF content (`pdfCompatible: false`), or legacy version 7 /// `.ai` files (`aiVersion: "7"`). @@ -680,13 +723,23 @@ pub(super) fn encode_ai(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Res if super::legacy_ai::wanted(cmd, f, p)? { return super::legacy_ai::encode(cmd, f, doc, p); } + encode_ai_pages(cmd, f, doc, p, true) +} + +/// [`encode_ai`] of a `.ai` file with or without PDF content, carrying the native document and +/// the editing copy for other apps when `editing` is true, and neither otherwise. +fn encode_ai_pages(cmd: &str, f: &Format, doc: &Document, p: &Value, editing: bool) -> Result<Encoded> { let mut params = if p.is_object() { p.clone() } else { json!({}) }; if let Some(o) = params.as_object_mut() { - o.insert("preserveEditing".into(), json!(true)); + o.insert("preserveEditing".into(), json!(editing)); // Keep upstream AI PDF layers, including hidden layers, unless a standard decides. if o.get("standard").is_none_or(Value::is_null) { o.entry("createLayers").or_insert(json!(true)); } + // A page longer than 14,400 pt keeps its `UserUnit` (PDF export writes it in points). + if o.get("longPagesInPoints").is_none_or(Value::is_null) { + o.insert("longPagesInPoints".into(), json!(false)); + } if let Some(c) = o.get("compress").and_then(Value::as_bool) { let compression = o.entry("compression").or_insert_with(|| json!({})); if let Some(m) = compression.as_object_mut() { @@ -731,7 +784,7 @@ pub(super) fn encode_ai(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Res // With the artboards' background colors, as the pages draw them. let art = super::export::with_artboard_fills(art, ¶ms, 0..art.artboards.len()).map_err(|e| bad(cmd, e))?; let o = vectorcraft_eps::AiEditingOptions { - title: doc.title.clone(), + title: doc.info_title().to_owned(), created: doc.metadata.created.or_else(vectorcraft_doc::metadata::output_time), }; let (data, lost) = vectorcraft_eps::ai_private_data(&art, &o).map_err(|e| bad(cmd, e))?; @@ -740,12 +793,14 @@ pub(super) fn encode_ai(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Res carries_editing.set(true); Ok(Some((data, resolved_warnings))) }; - let (bytes, mut warnings) = super::pdf::encode_carrying(cmd, &pages, ¶ms, native, private)?; - warnings.extend(placed_warnings); + let (bytes, notes) = super::pdf::encode_carrying(cmd, &pages, ¶ms, native, private)?; + let mut enc = Encoded::one_with_notes(bytes, notes); + enc.warnings.extend(placed_warnings); + // A note on the options: `pdfCompatible: false` writes blank pages. if !pdf_compatible { - warnings.push(if carries_editing.get() { NOT_PDF_COMPATIBLE_EDITING } else { NOT_PDF_COMPATIBLE }.to_string()); + enc.setting_notes.push(if carries_editing.get() { NOT_PDF_COMPATIBLE_EDITING } else { NOT_PDF_COMPATIBLE }.to_string()); } - Ok(Encoded { warnings, ..Encoded::one(bytes) }) + Ok(enc) } /// Snapshot the active document for `plan` (stamping File Info's dates on the snapshot when the @@ -833,8 +888,8 @@ impl SaveJob { } /// Encode the file → it (and, with `separateArtboards`, a file per artboard after it), with - /// the warnings (what the format loses first, then the encoder's own notes: PDF options not - /// applied yet…, then the plan's notes on its params). + /// the notes (what the format loses first, then the encoder's own notes: PDF options not + /// applied yet…, then the plan's notes on its params, which are notes on the options). pub fn encode(&self) -> Result<Encoded> { let mut enc = self.encode_one(&self.doc)?; for &b in &self.boards { @@ -842,7 +897,7 @@ impl SaveJob { enc.files.extend(one.files.into_iter().map(|(_, bytes)| (Some(b), bytes))); } enc.warnings.splice(0..0, self.format_losses()); - enc.warnings.extend(self.plan.notes.iter().cloned()); + enc.setting_notes.extend(self.plan.notes.iter().cloned()); Ok(enc) } @@ -870,8 +925,10 @@ impl SaveJob { _ => encode_all(doc, f.id, &self.params), } .map_err(|e| named_for_save(cmd, e))?; - // A legacy .ai file per artboard. - let per_artboard = f.id == "ai" && super::legacy_ai::wanted(cmd, f, &self.params)?; + // A legacy .ai file per artboard, or the files the EPS encoder writes: one, or with Use + // Artboards and two or more artboards the central file at the path and a file per + // artboard beside it. + let per_artboard = f.id == "eps" || (f.id == "ai" && super::legacy_ai::wanted(cmd, f, &self.params)?); if enc.files.len() != 1 && !per_artboard { return Err(bad(cmd, "Save writes one artboard: name one, or export several with document.export")); } @@ -883,11 +940,16 @@ impl SaveJob { /// folder?, warnings, files?: [{name, dataBase64}] (every file, when there are several), /// linked?: [{name, dataBase64}]}`; with one → `{path, format, bytes, warnings, files?: /// [path…], linked?: [path…]}`. - pub fn write(&self, mut write: impl FnMut(&str, &[u8]) -> Result<()>) -> Result<Value> { + pub fn write(&self, write: impl FnMut(&str, &[u8]) -> Result<()>) -> Result<Value> { + self.write_unless(|_| None, write) + } + + /// [`SaveJob::write`], once `stop` has seen the paths of every file it writes to a path, in + /// order: when `stop` returns a value, nothing is written and that value is returned. + pub fn write_unless(&self, stop: impl FnOnce(&[&str]) -> Option<Value>, mut write: impl FnMut(&str, &[u8]) -> Result<()>) -> Result<Value> { let (plan, doc) = (&self.plan, &*self.doc); - let mut enc = self.encode()?; - let warnings = std::mem::take(&mut enc.warnings); - let extra = json!({ "format": plan.format.id, "warnings": warnings }); + let enc = self.encode()?; + let extra = json!({ "format": plan.format.id, "warnings": enc.notes() }); let Some(path) = &plan.path else { let mut out = write_encoded(None, &plan.name, doc, &enc, extra)?; out["name"] = json!(plan.name); @@ -897,6 +959,12 @@ impl SaveJob { return Ok(out); }; let files = enc.named(doc, path); + if let Some(source) = &plan.lossy_source { + super::check_files_not_lossy_overwrite(source, files.iter().map(|(p, _)| p.as_str()), plan.mode.command())?; + } + if let Some(stopped) = stop(&files.iter().map(|(p, _)| p.as_str()).collect::<Vec<_>>()) { + return Ok(stopped); + } for (p, bytes) in &files { write(p, bytes)?; } @@ -1005,6 +1073,8 @@ impl SaveJob { } // The other open documents that place this one show the new version. let written = self.plan.path.clone().filter(|_| matches!(self.plan.format.id, "vectorcraft" | "template")); + // A save of the arrowheads file lists its heads in the arrowhead menus. + let native = self.plan.format.id == "vectorcraft"; if let Some(st) = s.document_mut(uid) { self.finish(st); } @@ -1012,6 +1082,9 @@ impl SaveJob { crate::cmd::recovery::forget(s, uid); } if let Some(path) = written { + if native { + s.arrowheads_saved(&path); + } crate::cmd::links::refresh_placed(s, uid, &path); } } @@ -1032,11 +1105,52 @@ pub(crate) fn save(s: &mut Session, mode: SaveMode, p: &Value) -> Result<Value> let plan = save_plan(s, mode, p)?; let job = save_job(s, plan)?; let uid = s.doc()?.uid; - let out = job.write_streamed(&mut super::write_file_with)?; + let given = str_param(p, "path").is_some_and(|g| !g.is_empty()); + // Without a path, the files written are the document's own file and those beside it. + let mut write = |path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>| { + super::write_save_file_with(path, fill).map_err(|e| if given { e } else { super::access::naming_in_error(e, path) }) + }; + let mut out = job.write_streamed(&mut write)?; job.complete(s, uid); + leave_out_unreadable_save_paths(&mut out, str_param(p, "path")); Ok(out) } +/// The reply `out` of a save with the `path` param `given`, as the request being served may see it +/// ([`super::access::shown`]). A save without a path writes the document's own file: its `path` is +/// left out, and the `files` and `linked` written beside it are named by their file names, when they +/// are outside the read roots. The suggested `folder` of a reply without a path is left out when it +/// is outside them. Without roots in force `out` is unchanged. +pub fn leave_out_unreadable_save_paths(out: &mut Value, given: Option<&str>) { + use super::access::{shown, shown_path}; + + if crate::file_access::current().is_none() { + return; + } + let Some(o) = out.as_object_mut() else { return }; + if o.get("folder").and_then(Value::as_str).is_some_and(|f| !shown(f)) { + o.remove("folder"); + } + // Every path the reply names then is the one the client gave, or beside it. + if given.is_some_and(|g| !g.is_empty()) { + return; + } + if o.get("path").and_then(Value::as_str).is_some_and(|p| !shown(p)) { + o.remove("path"); + } + for key in ["files", "linked"] { + if let Some(Value::Array(rows)) = o.get_mut(key) { + for row in rows { + if let Value::String(p) = row + && !shown(p) + { + *row = json!(shown_path(p)); + } + } + } + } +} + fn can_revert(s: &Session) -> std::result::Result<(), String> { let st = s.active().ok_or("no document open")?; match (&st.path, st.is_dirty()) { @@ -1051,7 +1165,8 @@ fn can_revert(s: &Session) -> std::result::Result<(), String> { fn revert(s: &mut Session, _: &Value) -> Result<Value> { let index = s.active_index().ok_or(crate::EngineError::NoDocument)?; let path = s.doc()?.path.clone().ok_or_else(|| bad("file.revert", "the document has never been saved"))?; - let Loaded { mut doc, native_pdf_compatible, .. } = load(&path, &read_file(&path)?)?.with_grid_prefs(&s.prefs).with_unit_prefs(&s.prefs); + let bytes = read_file(&path).map_err(|e| super::access::naming_in_error(e, &path))?; + let Loaded { mut doc, native_pdf_compatible, .. } = load(&path, &bytes)?.with_grid_prefs(&s.prefs).with_unit_prefs(&s.prefs); doc.template = false; // Back to the saved file: its recovery copy has nothing left to recover. let uid = s.doc()?.uid; @@ -1092,6 +1207,25 @@ fn format_options(s: &mut Session, p: &Value) -> Result<Value> { } } } + // An EPS save that named artboards without Use Artboards, or with it on, had it on (the + // encoder reads them so): it shows on, with those artboards as the range. + if f.id == "eps" + && let Some(m) = &saved + && m.get("useArtboards").and_then(Value::as_bool) != Some(false) + { + let range = m.get("range").and_then(Value::as_str).filter(|r| !r.trim().is_empty()); + let boards = m + .get("artboards") + .and_then(|a| serde_json::from_value::<Vec<usize>>(a.clone()).ok()) + .or_else(|| m.get("artboard").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()).map(|i| vec![i])) + .filter(|b| !b.is_empty()); + if range.is_some() || boards.is_some() { + v["options"]["useArtboards"]["value"] = json!(true); + if let (None, Some(boards)) = (range, boards) { + v["options"]["range"]["value"] = json!(range_text(&boards)); + } + } + } v["saveFormats"] = SAVE_FORMATS.iter().filter_map(|id| format(id)).map(|f| json!({"id": f.id, "label": f.label, "extensions": f.extensions})).collect(); Ok(v) @@ -1104,7 +1238,7 @@ pub(super) fn specs() -> Vec<CommandSpec> { "Save Document", [], None, - "{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings say when the format doesn't read compress, version, preview or precision given flat, or a key given in options), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file: a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS saves the chosen artboard (first by default), retaining its page margins and the whole editable document; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused", + "{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings say when the format doesn't read compress, version, preview or precision given flat, or a key given in options), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to <name>_<artboard>.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel", has_doc, |s, p| save(s, SaveMode::Save, p) ), @@ -1158,7 +1292,7 @@ pub(super) fn specs() -> Vec<CommandSpec> { "Format Options", [], None, - "{format?: a writable format id or ait (default: the document's own)} → {id, label, extensions, mime, read, write, raster, options: {name: {type, default, description, value}}, saveFormats: [{id, label, extensions}]}; value = the document's option as last saved in that format, else (native, for a document not yet saved as one) as the last native save used it, else the default", + "{format?: a writable format id or ait (default: the document's own)} → {id, label, extensions, mime, read, write, raster, options: {name: {type, default, description, value}}, saveFormats: [{id, label, extensions}]}; value = the document's option as last saved in that format, else (native, for a document not yet saved as one) as the last native save used it, else the default (EPS: useArtboards is true when the last save named artboards without it, and range then names them)", always, format_options ), diff --git a/crates/engine/src/cmd/fileio/screens.rs b/crates/engine/src/cmd/fileio/screens.rs index 56c0d808a5..91f43cfd36 100644 --- a/crates/engine/src/cmd/fileio/screens.rs +++ b/crates/engine/src/cmd/fileio/screens.rs @@ -17,12 +17,12 @@ use vectorcraft_doc::Document; use vectorcraft_geom::Rect; use super::super::{EngineError, NodeId, Result, Session, bad, bool_or, str_param}; -use super::encode::single_artboard; +use super::encode::{add_note, single_artboard}; use super::export::{export_crop, isolated, selected_artwork, without_artboards}; use super::naming::{self, NameParts}; use super::{ - ARTBOARD_PARAMS, ArtboardPick, Format, artboard_file_names_keeping_dots, create_dir, distinct_names_by, encode_with_warnings, merge, - unique_file_names_keeping_dots, with_black_output, writable, write_file, + ARTBOARD_PARAMS, ArtboardPick, Format, Note, artboard_file_names_keeping_dots, create_dir, distinct_names_by, encode_with_notes, merge, + note_texts, unique_file_names_keeping_dots, with_black_output, writable, write_file, }; const C: &str = "document.exportForScreens"; @@ -196,7 +196,7 @@ pub(super) fn name_without_device(name: &str) -> String { pub(crate) const ROW_KEYS: [&str; 7] = ["format", "scale", "ppi", "width", "height", "suffix", "folder"]; /// The writable formats a format row can't name. -pub(crate) const UNWRITTEN_FORMATS: [&str; 5] = ["template", "txt", "dxf", "emf", "wmf"]; +pub(crate) const UNWRITTEN_FORMATS: [&str; 6] = ["template", "txt", "dxf", "emf", "wmf", "hpgl"]; /// One format row: what to write, at which size, with which suffix, into which sub-folder. struct Row { @@ -644,12 +644,61 @@ impl Output { /// File → Export for Screens: [`export`] (over the settings of `exportPreset`, when given), with /// the params remembered in the document (`document.exportSettings`). pub(super) fn export_for_screens(s: &mut Session, p: &Value) -> Result<Value> { + // A folder the client gave, as against the one its `exportPreset` keeps. + let given = p.get("folder").is_some(); let p = with_preset(s, p)?; - let r = export(s, &p)?; + let hidden = if given { None } else { str_param(&p, "folder").filter(|f| !f.is_empty() && !super::access::shown(f)) }; + let mut r = export(s, &p).map_err(|e| match hidden { + Some(folder) => super::access::naming_in_error(e, folder), + None => e, + })?; remember(s, &p); + // A prepared export is written later, maybe on another thread: it names the folder as this + // request may see it. + if let (Some(folder), Some(Some(export))) = (hidden, s.screens_hand_off.as_mut()) { + export.hidden = Some((folder.to_string(), super::access::error_name(folder))); + } + if !given && let Some(folder) = str_param(&p, "folder").filter(|f| !f.is_empty()) { + leave_out_unreadable_folder(&mut r, folder); + } Ok(r) } +/// The reply `r` of an export into `folder`, a folder the client did not give, as the request being +/// served may see it: when `folder` is outside the read roots ([`super::access::shown`]), the ZIP's +/// `path` is left out and `files` names each file written relative to `folder` (`2x/Logo@2x.png`), +/// as the reply of an export to a ZIP names them. +fn leave_out_unreadable_folder(r: &mut Value, folder: &str) { + if !super::access::shown(folder) { + leave_out_folder(r, folder); + } +} + +/// The reply `r` of an export into `folder` with the ZIP's `path` left out and `files` named +/// relative to `folder` ([`leave_out_unreadable_folder`]). +fn leave_out_folder(r: &mut Value, folder: &str) { + let Some(o) = r.as_object_mut() else { return }; + o.remove("path"); + let inside = format!("{folder}/"); + if let Some(Value::Array(files)) = o.get_mut("files") { + for file in files { + // A ZIP's files are named relative to it already. + if let Some(name) = file.as_str().and_then(|path| path.strip_prefix(&inside)) { + *file = json!(name); + } + } + } +} + +/// Export settings kept in the document or a preset, as the request being served may see them: a +/// `folder` outside the read roots ([`super::access::shown`]) is left out. +fn leave_out_unreadable_settings_folder(mut settings: Map<String, Value>) -> Map<String, Value> { + if settings.get("folder").and_then(Value::as_str).is_some_and(|f| !f.is_empty() && !super::access::shown(f)) { + settings.remove("folder"); + } + settings +} + // ---------- export presets ---------- /// A saved batch export: what to write and how to name and sort it, to use again @@ -727,7 +776,13 @@ pub fn preset_list(saved: &[ScreenExportPreset]) -> Value { } pub(super) fn presets_list(s: &mut Session, _: &Value) -> Result<Value> { - Ok(json!({ "presets": preset_list(&s.prefs.screen_export_presets) })) + let saved: Vec<ScreenExportPreset> = s + .prefs + .screen_export_presets + .iter() + .map(|p| ScreenExportPreset { name: p.name.clone(), settings: leave_out_unreadable_settings_folder(p.settings.clone()) }) + .collect(); + Ok(json!({ "presets": preset_list(&saved) })) } /// The [`PRESET_KEYS`] of `given`, refused as an error of command `cmd` when an export would @@ -831,6 +886,8 @@ pub(super) fn presets_export(s: &mut Session, p: &Value) -> Result<Value> { return Err(too_many()); } let count = presets.len(); + let presets: Vec<ScreenExportPreset> = + presets.into_iter().map(|p| ScreenExportPreset { settings: leave_out_unreadable_settings_folder(p.settings), ..p }).collect(); let text = serde_json::to_string_pretty(&PresetFile { format: PRESET_FILE_FORMAT.into(), presets }).map_err(|e| bad(EXPORT, e.to_string()))?; if text.len() > MAX_PRESET_FILE_BYTES { return Err(bad(EXPORT, format!("export presets file is larger than {MAX_PRESET_FILE_BYTES} bytes"))); @@ -964,7 +1021,8 @@ pub(crate) fn with_export_preset(s: &Session, cmd: &str, settings: &mut Map<Stri /// holds its artboard alone), or with `fullDocument` one file per row (a PDF of every artboard, /// else the bounds of all art). Items that share a name get `-2`, `-3`… instead of overwriting, and /// so do different files that would share a name, with or without the `name` pattern. The reply's -/// `warnings` lists every warning the encoders give for the files, each once. +/// `warnings` lists every warning the encoders give for the files, each once, what the files lose +/// first ([`super::note_texts`]). pub(crate) fn export(s: &mut Session, p: &Value) -> Result<Value> { check_passwords(p)?; let o = ScreenParams::of(p)?; @@ -992,7 +1050,7 @@ pub(crate) fn export(s: &mut Session, p: &Value) -> Result<Value> { // Include Artboard Fill off: the encoders leave the background colors out. let fill = if o.include_artboard_fill == Some(false) { json!({ "includeArtboardFill": false }) } else { json!({}) }; let rows = rows.into_iter().map(|r| Row { options: merge(with_black_output(s, &r.options), fill.clone()), ..r }).collect(); - let export = ScreenExport { cmd: C, o, rows, naming, items }; + let export = ScreenExport { cmd: C, o, rows, naming, items, hidden: None }; match &mut s.screens_hand_off { Some(slot) => { *slot = Some(export); @@ -1013,9 +1071,27 @@ pub struct ScreenExport { rows: Vec<Row>, naming: Naming, items: Vec<Item>, + /// The export folder and the name the request that prepared the export may see it by, when the + /// folder came from the `exportPreset` and is outside that request's read roots: the reply and + /// the errors of [`ScreenExport::write`] name it as [`export_for_screens`] does. + hidden: Option<(String, String)>, } impl Session { + /// The folder `document.exportForScreens` (`id`) with `params` writes into, the client's + /// `folder` or else the one its `exportPreset` keeps, with the name the request being served may + /// see it by when the reply leaves it out: a preset's folder outside the read roots, named by + /// its own name ([`super::access::shown_path`]). `assets.export` takes no preset, so for it the + /// folder is the client's. → `None` without a folder (the files come back in the reply) or for + /// an unknown preset, which the export itself refuses. + pub fn screen_export_folder(&self, id: &str, params: &Value) -> Option<(String, Option<String>)> { + let given = params.get("folder").is_some(); + let p = if given || id == ASSETS { params.clone() } else { with_preset(self, params).ok()? }; + let folder = str_param(&p, "folder").filter(|f| !f.is_empty())?.to_string(); + let hidden = (!given && !super::access::shown(&folder)).then(|| super::access::shown_path(&folder).into_owned()); + Some((folder, hidden)) + } + /// Run `assets.export` when `id` names it, else `document.exportForScreens`, with `params` as /// a command (checked and journaled as any other; Export for Screens remembers its settings) /// that encodes and writes nothing → the export it prepared, which [`ScreenExport::write`] @@ -1041,10 +1117,19 @@ impl ScreenExport { /// return → the reply of `document.exportForScreens`. It reports one progress step per file /// ([`vectorcraft_doc::cancel::progress`]), and a cancel stops it before it encodes or writes /// another file. - pub fn write(self, writer: &mut dyn FnMut(&str, &[u8]) -> Result<()>) -> Result<Value> { + pub fn write(mut self, writer: &mut dyn FnMut(&str, &[u8]) -> Result<()>) -> Result<Value> { let cmd = self.cmd; + let hidden = self.hidden.take(); // A refusal names `assets.export` when that command prepared the export, as its reply does. - encode_and_write(self, writer).map_err(|e| if cmd == C { e } else { crate::cmd::assets::of_cmd(cmd, e) }) + let r = encode_and_write(self, writer).map_err(|e| if cmd == C { e } else { crate::cmd::assets::of_cmd(cmd, e) }); + match hidden { + Some((folder, name)) => { + let mut r = r.map_err(|e| super::access::naming_as(e, &folder, &name))?; + leave_out_folder(&mut r, &folder); + Ok(r) + } + None => r, + } } } @@ -1056,18 +1141,16 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) -> create_dir(dir)?; } let mut out = Output::default(); - // The encoders' warnings for every file, each once. - let mut warnings: Vec<String> = Vec::new(); + // The encoders' notes for every file, each once. + let mut notes: Vec<Note> = Vec::new(); // Include Bleed: a grown artboard already holds the bleed. Assets, layers and a selection are // written on a page of their own bounds, which it doesn't grow. let bleed_on_page = o.include_bleed && o.assets.is_none() && o.layers.is_none() && o.selection.is_none(); let mut write = |doc: &Document, format: &str, options: &Value| -> Result<Vec<u8>> { // The steps are the files: an encoder's own steps (artboards, pages) are not reported. - let (bytes, notes) = vectorcraft_doc::cancel::quiet(|| encode_with_warnings(doc, format, options))?; - for w in notes { - if !(bleed_on_page && w == super::pdf::BLEED_LEFT_OUT) && !warnings.contains(&w) { - warnings.push(w); - } + let (bytes, given) = vectorcraft_doc::cancel::quiet(|| encode_with_notes(doc, format, options))?; + for n in given.into_iter().filter(|n| !(bleed_on_page && n.text == super::pdf::BLEED_LEFT_OUT)) { + add_note(&mut notes, n); } Ok(bytes) }; @@ -1142,6 +1225,8 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) -> if o.zip || folder.is_none() { vectorcraft_doc::cancel::check()?; } + // What the files lose first, across every file. + let warnings = note_texts(¬es); let names: Vec<&str> = out.kept.iter().map(|(n, _)| n.as_str()).collect(); if o.zip { let zip = super::zip::deflate(&out.kept, super::zip::FIXED_TIME, vectorcraft_doc::cancel::is_cancelled); @@ -1388,13 +1473,33 @@ pub(crate) fn store_settings(s: &mut Session, mut settings: Map<String, Value>) /// `document.exportSettings`: the Export for Screens settings the document last exported with. pub(super) fn export_settings(s: &mut Session, _: &Value) -> Result<Value> { - Ok(json!({ "settings": s.doc()?.doc.export_settings })) + Ok(json!({ "settings": leave_out_unreadable_settings_folder(s.doc()?.doc.export_settings.clone()) })) } #[cfg(test)] mod tests { + use super::super::access::naming_in_message; use super::{Output, ScreenSize, safe_file_name}; + /// A hidden export folder is named by its name where a message is about it, and a root that + /// starts with the same text, or a longer path, stays whole. + #[test] + fn a_hidden_folder_is_named_by_its_name_in_a_message() { + let f = "/work/out"; + let cases = [ + ( + "automation path rejected: outside the write root /work/out/in: /work/out", + "automation path rejected: outside the write root /work/out/in: out", + ), + ("automation path rejected: cannot resolve /work/out: denied", "automation path rejected: cannot resolve out: denied"), + ("/work/out/2x/a.png: disk full", "out/2x/a.png: disk full"), + ("automation path rejected: outside the write root /a: /work/outer", "automation path rejected: outside the write root /a: /work/outer"), + ]; + for (msg, want) in cases { + assert_eq!(naming_in_message(msg, f, "out"), want, "{msg}"); + } + } + /// Files given one name are numbered in turn, each numbering going on from the last one (so /// thousands of them don't each try every number used before), and a file asking again for /// the name it got is told it has it. diff --git a/crates/engine/src/cmd/fileio/svg.rs b/crates/engine/src/cmd/fileio/svg.rs index 3123fdcfb1..969b12467e 100644 --- a/crates/engine/src/cmd/fileio/svg.rs +++ b/crates/engine/src/cmd/fileio/svg.rs @@ -90,6 +90,12 @@ pub const OPTIONS: &[FormatOption] = &[ default: "false", description: "embed the fonts type uses as @font-face, subset to the characters used (whole when the font's licence forbids subsetting, left out with a warning when it forbids embedding)", }, + FormatOption { + name: "variableData", + ty: "boolean", + default: "false", + description: "Include Variable Data: write the text variables, the data sets and the type object each text variable is bound to as a variable library (variableSets) that document.open and variable.loadLibrary read back; variables of other kinds, and what is past the limits variable.loadLibrary reads (256 text variables, 1,000 data sets, 8 MiB), are left out with a warning", + }, FormatOption { name: "svg", ty: "object", @@ -198,6 +204,7 @@ pub(super) fn encode(doc: &Document, p: &Value, compressed: bool) -> Result<Enco enc.warnings.push(w); } } + enc.add_setting_notes(out.setting_notes); enc.files.push((artboard, if compressed { vectorcraft_svg::compress_bytes(&bytes) } else { bytes })); } // Live type names its fonts; outlines and embedded fonts are the fallback font's. diff --git a/crates/engine/src/cmd/fileio/tests.rs b/crates/engine/src/cmd/fileio/tests.rs index 6236d281e2..71c1bd06e5 100644 --- a/crates/engine/src/cmd/fileio/tests.rs +++ b/crates/engine/src/cmd/fileio/tests.rs @@ -48,6 +48,19 @@ fn image_of(s: &Session) -> vectorcraft_doc::ImageObject { } } +/// A path outside a confined request's read roots shows as its file name, after the last `/` or `\` +/// on every platform; one that ends in no name shows as nothing. Without roots it shows whole. +#[test] +fn a_hidden_path_shows_as_its_file_name_on_every_platform() { + let windows = "C:\\Users\\someone\\art\\red.png"; + crate::file_access::confine(Some(&crate::file_access::AutomationRoots::none()), || { + for (path, name) in [("/home/someone/art/red.png", "red.png"), (windows, "red.png"), ("/home/someone/..", ""), ("C:\\Users\\someone\\", "")] { + assert_eq!(shown_path(path), name, "{path}"); + } + }); + assert_eq!(shown_path(windows), windows); +} + #[test] fn opens_every_readable_format() { let mut s = session(200.0, 100.0, 1); @@ -377,9 +390,20 @@ fn open_exts_cover_every_readable_format() { assert_eq!(filters[0], ("All readable files", OPEN_EXTS)); assert_eq!( filters.len(), - 11 + FORMATS.iter().filter(|f| f.read).count(), - "and swatch libraries, libraries, flattener, PDF, print and export presets, composite fonts, shortcut sets, scripts, plug-ins" + 13 + FORMATS.iter().filter(|f| f.read).count(), + "and swatch and graphic style libraries, libraries, flattener, PDF, print, perspective grid and export presets, composite \ + fonts, shortcut sets, scripts, plug-ins" ); + let at = |label: &str| filters.iter().position(|f| f.0 == label).unwrap_or_else(|| panic!("File › Open has no {label} filter")); + let styles: &[&str] = &[vectorcraft_doc::style_libs::STYLES_EXT]; + assert_eq!(filters[at("Graphic Style Libraries")].1, styles, "File › Open opens graphic style libraries"); + assert_eq!(at("Graphic Style Libraries"), at("Swatch libraries") + 1, "next to the swatch libraries"); + assert_eq!(filters[at("Perspective grid presets")].1, crate::cmd::perspgrid::PRESET_EXTS, "File › Open imports perspective grid presets"); + assert_eq!(at("Perspective grid presets"), at("Print presets") + 1, "among the presets"); + assert_eq!(at("Export presets"), at("Perspective grid presets") + 1, "among the presets"); + for e in [vectorcraft_doc::style_libs::STYLES_EXT].iter().chain(crate::cmd::perspgrid::PRESET_EXTS) { + assert!(!filters[0].1.contains(e), "All readable files lists documents only, not .{e}"); + } assert!(filters.contains(&("Export presets", SCREEN_EXPORT_PRESET_EXTS)), "File › Open imports export presets"); assert!(filters.contains(&("Scripts", crate::cmd::scripts::EXTS)), "File › Open checks scripts"); assert_eq!(filters.last(), Some(&("Plug-ins", crate::cmd::plugin::EXTS)), "File › Open installs plug-ins"); @@ -391,6 +415,11 @@ fn library_open_filters_list_library_formats_first() { assert_eq!(filters[0], ("Swatch libraries", crate::cmd::swatchlib::LIBRARY_EXTS)); assert!(filters[0].1.contains(&"ase")); assert_eq!(filters[1], ("All readable files", OPEN_EXTS)); + let styles: &'static [&'static str] = std::slice::from_ref(&vectorcraft_doc::style_libs::STYLES_EXT); + for (label, exts) in [("Swatch libraries", crate::cmd::swatchlib::LIBRARY_EXTS), ("Graphic Style Libraries", styles)] { + let filters: Vec<_> = library_open_filters(label, exts).collect(); + assert_eq!(filters.iter().filter(|f| f.0 == label).count(), 1, "{label} is listed once"); + } } /// The extensions usage texts list for export: one per writable format, each picking that format @@ -418,6 +447,7 @@ fn export_extensions_name_every_writable_format() { "eps", "emf", "wmf", + "plt", "tga", "psd" ] @@ -453,6 +483,7 @@ fn formats_query_lists_readers_writers_and_options() { "eps", "emf", "wmf", + "hpgl", "tga", "psd" ] @@ -892,6 +923,464 @@ fn a_photo_places_the_way_its_exif_orientation_says() { assert!(red(px.get_pixel(4, 3)) && !red(px.get_pixel(4, 12)), "the left half is on top"); } +/// Where the first stored pixel shows once EXIF (or TIFF) `orientation` turns the image, as +/// (right, bottom): orientations 1 and 5 keep it at the top left, 2 and 6 put it at the top right, +/// 3 and 7 at the bottom right, 4 and 8 at the bottom left. Values outside 1 to 8 leave it. +fn first_pixel_at(orientation: u16) -> (bool, bool) { + match orientation { + 2 | 6 => (true, false), + 3 | 7 => (true, true), + 4 | 8 => (false, true), + _ => (false, false), + } +} + +/// A little-endian EXIF block (a TIFF header and directory, as a PNG `eXIf` chunk or a WebP +/// `EXIF` chunk holds it) with an Orientation of `orientation` and an XResolution and YResolution +/// of `x` and `y` pixels per inch. +fn exif_block(orientation: u16, (x, y): (u32, u32)) -> Vec<u8> { + let entry = |tag: u16, kind: u16, value: u32| [&tag.to_le_bytes()[..], &kind.to_le_bytes(), &1u32.to_le_bytes(), &value.to_le_bytes()].concat(); + // Orientation, XResolution, YResolution, ResolutionUnit inches; the two rationals follow. + [ + b"II".as_slice(), + &[0x2a, 0, 8, 0, 0, 0], + &4u16.to_le_bytes(), + &entry(0x0112, 3, u32::from(orientation)), + &entry(0x011a, 5, 62), + &entry(0x011b, 5, 70), + &entry(0x0128, 3, 2), + &[0, 0, 0, 0], + &[x.to_le_bytes(), 1u32.to_le_bytes(), y.to_le_bytes(), 1u32.to_le_bytes()].concat(), + ] + .concat() +} + +/// A photo turned a quarter by its EXIF orientation keeps its physical size: the resolution's +/// axes swap with the pixels', in what Place reports and in the stored image. Every orientation +/// puts the first stored pixel in its corner once, and the stored image, read again, is not turned +/// a second time. Values outside 1 to 8 leave the photo as stored. +#[test] +fn a_quarter_turn_swaps_the_resolution_axes() { + // 48 × 32: the top-left 16 × 16 (one whole JPEG MCU) red, the rest white. + let rgb = image::RgbImage::from_fn(48, 32, |x, y| if x < 16 && y < 16 { image::Rgb([220, 0, 0]) } else { image::Rgb([255, 255, 255]) }); + let mut jpg = Vec::new(); + image::DynamicImage::ImageRgb8(rgb).write_to(&mut Cursor::new(&mut jpg), image::ImageFormat::Jpeg).unwrap(); + for orientation in [0u16, 1, 2, 3, 4, 5, 6, 7, 8, 9] { + let exif = [b"Exif\0\0".as_slice(), &exif_block(orientation, (300, 150))].concat(); + // Without a JFIF density the resolution comes from the EXIF block. + let mut turned = jpg[..2].to_vec(); + turned.extend([0xff, 0xe1]); + turned.extend(u16::try_from(exif.len() + 2).unwrap().to_be_bytes()); + turned.extend(&exif); + turned.extend(&jpg[2..]); + let what = format!("orientation {orientation}"); + assert_eq!(super::ppi::resolution(&turned), Some((300.0, 150.0)), "{what}: as stored"); + let quarter = (5..=8).contains(&orientation); + let (size, ppi) = if quarter { ((32, 48), (150.0, 300.0)) } else { ((48, 32), (300.0, 150.0)) }; + let img = raster_image(&turned).unwrap(); + assert_eq!(((img.width, img.height), img.ppi), (size, Some(ppi)), "{what}"); + assert_eq!(super::ppi::resolution(&img.blob.bytes), Some(ppi), "{what}: the stored image"); + let px = image::load_from_memory(&img.blob.bytes).unwrap().to_rgb8(); + let red = |x: u32, y: u32| px.get_pixel(x, y)[1] < 80; + let (w, h) = size; + let corners = [(false, false), (true, false), (true, true), (false, true)]; + let reds: Vec<_> = + corners.into_iter().filter(|&(right, bottom)| red(if right { w - 4 } else { 4 }, if bottom { h - 4 } else { 4 })).collect(); + assert_eq!(reds, [first_pixel_at(orientation)], "{what}: the first stored pixel's corner"); + let again = raster_image(&img.blob.bytes).unwrap(); + assert_eq!(((again.width, again.height), again.ppi), (size, Some(ppi)), "{what}: read again, it isn't turned again"); + } +} + +/// `tiff` (little-endian) with an Orientation tag (274) of `value`, a SHORT or, when `long`, a +/// LONG, and, when `y_ppi` is given, a YResolution (283, which `tiff` must have) of that many +/// pixels per inch: its first directory copied to the end of the file with the tag added in order, +/// and the header pointing there, so that every other offset in the file still holds. +fn tiff_oriented(tiff: &[u8], value: u16, long: bool, y_ppi: Option<u32>) -> Vec<u8> { + let at = usize::try_from(u32::from_le_bytes(tiff[4..8].try_into().unwrap())).unwrap(); + let n = usize::from(u16::from_le_bytes([tiff[at], tiff[at + 1]])); + let mut entries: Vec<Vec<u8>> = tiff[at + 2..at + 2 + 12 * n].chunks(12).map(<[u8]>::to_vec).collect(); + let i = entries.iter().position(|e| u16::from_le_bytes([e[0], e[1]]) > 274).unwrap_or(n); + let (kind, v) = if long { (4u16, u32::from(value).to_le_bytes()) } else { (3, [value.to_le_bytes(), [0, 0]].concat().try_into().unwrap()) }; + entries.insert(i, [&274u16.to_le_bytes()[..], &kind.to_le_bytes(), &1u32.to_le_bytes(), &v].concat()); + let mut out = tiff.to_vec(); + if out.len() % 2 == 1 { + out.push(0); + } + if let Some(y) = y_ppi { + let rational = u32::try_from(out.len()).unwrap(); + out.extend([y.to_le_bytes(), 1u32.to_le_bytes()].concat()); + let e = entries.iter_mut().find(|e| u16::from_le_bytes([e[0], e[1]]) == 283).unwrap(); + e[8..12].copy_from_slice(&rational.to_le_bytes()); + } + let ifd = u32::try_from(out.len()).unwrap(); + out[4..8].copy_from_slice(&ifd.to_le_bytes()); + out.extend(u16::try_from(n + 1).unwrap().to_le_bytes()); + out.extend(entries.concat()); + out.extend([0; 4]); + out +} + +/// TIFFs the image decoder can't read, grayscale with an alpha channel and 1-bit ones compressed +/// with CCITT Group 3, turn and flip as their Orientation tag says, as the others do (#4284), +/// whether the tag is a SHORT or a LONG. A quarter turn swaps the resolution's axes. +#[test] +fn tiffs_read_without_the_image_decoder_follow_their_orientation() { + // 3 × 2 at 150 × 300 ppi, the first pixel black and the rest white, opaque. + let gray = hand_tiff(1, 8, &[2], false, &[vec![0, 255, 255, 255, 255, 255], vec![255; 6]]); + let rows: Vec<Vec<bool>> = (0..2).map(|y| (0..3).map(|x| x == 0 && y == 0).collect()).collect(); + let g = vectorcraft_testkit::tiff::Group3 { + rows: &rows, + compression: 2, + t4_options: 0, + photometric: 0, + fill_order: 1, + rows_per_strip: 2, + tile: None, + rtc: false, + }; + let fax = vectorcraft_testkit::tiff::group3(&g); + // The Group 3 file declares no resolution. + for (kind, file, y_ppi) in [("Group 3", fax, None), ("gray with alpha", gray, Some(300))] { + assert!(image::load_from_memory(&file).is_err(), "{kind}: the image decoder reads it now"); + for (orientation, long) in (1..=8).flat_map(|o| [(o, false), (o, true)]) { + let what = format!("{kind}, orientation {orientation}, LONG {long}"); + let img = raster_image(&tiff_oriented(&file, orientation, long, y_ppi)).unwrap_or_else(|e| panic!("{what}: {e}")); + let quarter = orientation >= 5; + let size = if quarter { (2, 3) } else { (3, 2) }; + let ppi = y_ppi.map(|y| if quarter { (f64::from(y), 150.0) } else { (150.0, f64::from(y)) }); + assert_eq!(((img.width, img.height), img.ppi), (size, ppi), "{what}"); + assert_eq!(super::ppi::resolution(&img.blob.bytes), ppi, "{what}: the stored image"); + let px = image::load_from_memory(&img.blob.bytes).unwrap().to_luma8(); + let (right, bottom) = first_pixel_at(orientation); + let (x, y) = (if right { size.0 - 1 } else { 0 }, if bottom { size.1 - 1 } else { 0 }); + let black: Vec<_> = px.enumerate_pixels().filter(|p| p.2[0] < 128).map(|p| (p.0, p.1)).collect(); + assert_eq!(black, [(x, y)], "{what}: the first stored pixel's corner"); + } + } +} + +/// A CMYK TIFF that its Orientation tag turns or flips keeps its inks, turned, whether it stores +/// them together or one plane per ink, at 8 or 16 bits; a quarter turn swaps the resolution's axes. +/// Read again, the stored image is not turned a second time. +#[test] +fn cmyk_tiffs_turned_by_their_orientation_keep_their_inks() { + // 3 × 2 at 150 × 300 ppi: the first pixel full cyan, the others 30% black. + let first: [u8; 4] = [255, 0, 0, 0]; + let other: [u8; 4] = [0, 0, 0, 77]; + let channel = |i: usize| -> Vec<u16> { (0..6).map(|p| u16::from(if p == 0 { first[i] } else { other[i] })).collect() }; + for (bits, planar) in [(8, false), (8, true), (16, false), (16, true)] { + let channels: Vec<Vec<u16>> = (0..4).map(|i| channel(i).iter().map(|v| if bits == 16 { v * 257 } else { *v }).collect()).collect(); + let file = hand_tiff(5, bits, &[], planar, &channels); + for orientation in 1..=8 { + let what = format!("{bits} bits, planar {planar}, orientation {orientation}"); + let img = raster_image(&tiff_oriented(&file, orientation, false, Some(300))).unwrap_or_else(|e| panic!("{what}: {e}")); + let quarter = orientation >= 5; + let size = if quarter { (2, 3) } else { (3, 2) }; + let ppi = if quarter { (300.0, 150.0) } else { (150.0, 300.0) }; + assert_eq!(((img.width, img.height), img.ppi, img.blob.mime.as_str()), (size, Some(ppi), "image/tiff"), "{what}"); + assert_eq!(super::ppi::resolution(&img.blob.bytes), Some(ppi), "{what}: the stored image"); + let inks = img.blob.cmyk().unwrap_or_else(|| panic!("{what}: the inks are lost")); + assert_eq!((inks.width, inks.height), size, "{what}: the inks' size"); + let (right, bottom) = first_pixel_at(orientation); + let at = (if right { size.0 - 1 } else { 0 }, if bottom { size.1 - 1 } else { 0 }); + for (i, px) in inks.data.chunks(4).enumerate() { + let (x, y) = (u32::try_from(i).unwrap() % size.0, u32::try_from(i).unwrap() / size.0); + assert_eq!(px, if (x, y) == at { first } else { other }, "{what}: the inks of pixel ({x}, {y})"); + } + let again = raster_image(&img.blob.bytes).unwrap(); + assert_eq!(((again.width, again.height), again.blob.cmyk()), (size, Some(inks)), "{what}: read again, it isn't turned again"); + } + } +} + +/// A CMYK JPEG that its EXIF orientation turns or flips keeps its inks, turned, stored as a CMYK +/// TIFF; a quarter turn swaps the resolution's axes. Orientation 1 keeps the JPEG as it is, and +/// the stored image, read again, is not turned a second time. +#[test] +fn cmyk_jpegs_turned_by_their_orientation_keep_their_inks() { + use vectorcraft_render::encode::jpeg::{self, ColorModel, JpegOptions}; + // 48 × 32: the top-left 16 × 16 (one whole JPEG MCU) full cyan, the rest 30% black. + let inks: Vec<u8> = + (0..32u32).flat_map(|y| (0..48u32).flat_map(move |x| if x < 16 && y < 16 { [255, 0, 0, 0] } else { [0, 0, 0, 77] })).collect(); + let o = JpegOptions { color_model: ColorModel::Cmyk, embed_icc: false, ..Default::default() }; + let jpg = jpeg::encode(&inks, 48, 32, 100, None, &o).unwrap(); + for orientation in 1..=8u16 { + let exif = [b"Exif\0\0".as_slice(), &exif_block(orientation, (300, 150))].concat(); + let mut file = jpg[..2].to_vec(); + file.extend([0xff, 0xe1]); + file.extend(u16::try_from(exif.len() + 2).unwrap().to_be_bytes()); + file.extend(&exif); + file.extend(&jpg[2..]); + let what = format!("orientation {orientation}"); + let quarter = orientation >= 5; + let (size, ppi) = if quarter { ((32, 48), (150.0, 300.0)) } else { ((48, 32), (300.0, 150.0)) }; + let mime = if orientation == 1 { "image/jpeg" } else { "image/tiff" }; + let img = raster_image(&file).unwrap_or_else(|e| panic!("{what}: {e}")); + assert_eq!(((img.width, img.height), img.ppi, img.blob.mime.as_str()), (size, Some(ppi), mime), "{what}"); + assert_eq!(super::ppi::resolution(&img.blob.bytes), Some(ppi), "{what}: the stored image"); + let inks = img.blob.cmyk().unwrap_or_else(|| panic!("{what}: the inks are lost")); + assert_eq!((inks.width, inks.height), size, "{what}: the inks' size"); + let (w, h) = size; + let at = |x: u32, y: u32| inks.data[usize::try_from((y * w + x) * 4).unwrap()..][..4].to_vec(); + let cyan = |p: &[u8]| p[0] > 200 && p[3] < 40; + let corners = [(false, false), (true, false), (true, true), (false, true)]; + let cyans: Vec<_> = + corners.into_iter().filter(|&(right, bottom)| cyan(&at(if right { w - 4 } else { 4 }, if bottom { h - 4 } else { 4 }))).collect(); + assert_eq!(cyans, [first_pixel_at(orientation)], "{what}: the first stored pixel's corner"); + let black = at(w / 2, h / 2); + assert!(black[0] < 40 && (60..=95).contains(&black[3]), "{what}: the other inks, {black:?}"); + let again = raster_image(&img.blob.bytes).unwrap(); + assert_eq!(((again.width, again.height), again.blob.cmyk()), (size, Some(inks)), "{what}: read again, it isn't turned again"); + } +} + +/// A PNG (its `eXIf` chunk and `pHYs` resolution), a WebP (its `EXIF` chunk) and an RGB TIFF read +/// by the image decoder, turned a quarter by their orientation, swap their resolution's axes; a +/// half turn keeps them. +#[test] +fn png_webp_and_rgb_tiff_turned_a_quarter_swap_their_resolution() { + use image::ImageEncoder as _; + let rgb = image::RgbImage::from_fn(3, 2, |x, y| image::Rgb(if x == 0 && y == 0 { [0, 0, 0] } else { [255, 255, 255] })); + for orientation in [3u16, 6, 8] { + let mut png = Vec::new(); + let mut enc = image::codecs::png::PngEncoder::new(&mut png); + enc.set_exif_metadata(exif_block(orientation, (150, 300))).unwrap(); + enc.write_image(rgb.as_raw(), 3, 2, image::ExtendedColorType::Rgb8).unwrap(); + let png = super::ppi::with_png_resolution(&png, (150.0, 300.0)); + let mut webp = Vec::new(); + let mut enc = image::codecs::webp::WebPEncoder::new_lossless(&mut webp); + enc.set_exif_metadata(exif_block(orientation, (150, 300))).unwrap(); + enc.write_image(rgb.as_raw(), 3, 2, image::ExtendedColorType::Rgb8).unwrap(); + let channel = |c: usize| -> Vec<u16> { rgb.pixels().map(|p| u16::from(p[c])).collect() }; + let tiff = tiff_oriented(&hand_tiff(2, 8, &[], false, &[channel(0), channel(1), channel(2)]), orientation, false, Some(300)); + for (kind, file) in [("PNG", png), ("WebP", webp), ("TIFF", tiff)] { + let what = format!("{kind}, orientation {orientation}"); + assert_eq!(super::ppi::resolution(&file), Some((150.0, 300.0)), "{what}: as stored"); + let quarter = orientation >= 5; + let (size, ppi) = if quarter { ((2, 3), (300.0, 150.0)) } else { ((3, 2), (150.0, 300.0)) }; + let img = raster_image(&file).unwrap_or_else(|e| panic!("{what}: {e}")); + assert_eq!(((img.width, img.height), img.ppi), (size, Some(ppi)), "{what}"); + assert_eq!(super::ppi::resolution(&img.blob.bytes), Some(ppi), "{what}: the stored image"); + let px = image::load_from_memory(&img.blob.bytes).unwrap().to_luma8(); + let (right, bottom) = first_pixel_at(orientation); + let at = (if right { size.0 - 1 } else { 0 }, if bottom { size.1 - 1 } else { 0 }); + let black: Vec<_> = px.enumerate_pixels().filter(|p| p.2[0] < 128).map(|p| (p.0, p.1)).collect(); + assert_eq!(black, [at], "{what}: the first stored pixel's corner"); + } + } +} + +/// A made-up ICC profile of `len` bytes (at least a header's 128) whose header names the color +/// space `space`; the bytes after the header differ from place to place. +fn icc_profile(space: &[u8; 4], len: usize) -> Vec<u8> { + let mut icc: Vec<u8> = (0..len).map(|i| (i % 251) as u8).collect(); + icc[..4].copy_from_slice(&u32::try_from(len).unwrap().to_be_bytes()); + icc[12..16].copy_from_slice(b"mntr"); + icc[16..20].copy_from_slice(space); + icc[36..40].copy_from_slice(b"acsp"); + icc +} + +/// `tiff` (little-endian) with an ICCProfile tag (34675, of type UNDEFINED) holding `icc`: its first +/// directory copied to the end of the file with the tag added in order, as [`tiff_oriented`] adds +/// its tag. +fn tiff_with_icc(tiff: &[u8], icc: &[u8]) -> Vec<u8> { + let at = usize::try_from(u32::from_le_bytes(tiff[4..8].try_into().unwrap())).unwrap(); + let n = usize::from(u16::from_le_bytes([tiff[at], tiff[at + 1]])); + let mut entries: Vec<Vec<u8>> = tiff[at + 2..at + 2 + 12 * n].chunks(12).map(<[u8]>::to_vec).collect(); + let mut out = tiff.to_vec(); + if out.len() % 2 == 1 { + out.push(0); + } + let data = u32::try_from(out.len()).unwrap(); + out.extend(icc); + if out.len() % 2 == 1 { + out.push(0); + } + let i = entries.iter().position(|e| u16::from_le_bytes([e[0], e[1]]) > 34675).unwrap_or(n); + let count = u32::try_from(icc.len()).unwrap(); + entries.insert(i, [&34675u16.to_le_bytes()[..], &7u16.to_le_bytes(), &count.to_le_bytes(), &data.to_le_bytes()].concat()); + let ifd = u32::try_from(out.len()).unwrap(); + out[4..8].copy_from_slice(&ifd.to_le_bytes()); + out.extend(u16::try_from(n + 1).unwrap().to_le_bytes()); + out.extend(entries.concat()); + out.extend([0; 4]); + out +} + +/// The ICC profile and pixels of a stored image, read by the image decoder for its format. +fn stored_pixels(what: &str, img: &RasterImage) -> (Option<Vec<u8>>, image::ExtendedColorType, image::DynamicImage) { + use image::ImageDecoder as _; + let bytes = Cursor::new(img.blob.bytes.as_slice()); + let mut d: Box<dyn image::ImageDecoder> = match img.blob.mime.as_str() { + "image/png" => Box::new(image::codecs::png::PngDecoder::new(bytes).unwrap()), + "image/tiff" => Box::new(image::codecs::tiff::TiffDecoder::new(bytes).unwrap()), + other => panic!("{what}: stored as {other}"), + }; + let icc = d.icc_profile().unwrap(); + let color = d.original_color_type(); + (icc, color, image::DynamicImage::from_decoder(d).unwrap()) +} + +/// An image turned by its orientation and stored as PNG keeps the gray or RGB ICC profile its file +/// carries, and its 16-bit samples at 16 bits, from a PNG, a JPEG, a WebP and a TIFF; a TIFF the +/// image decoder reads, stored as PNG without a turn, keeps them too. A profile of another color +/// space than the samples' is left out. +#[test] +fn images_stored_as_png_keep_their_icc_profile_and_16_bit_samples() { + use image::{DynamicImage, ImageEncoder as _}; + let (rgb_icc, gray_icc, cmyk_icc) = (icc_profile(b"RGB ", 600), icc_profile(b"GRAY", 300), icc_profile(b"CMYK", 400)); + // 3 × 2, every sample's low byte different. + let rgb16 = image::ImageBuffer::from_fn(3, 2, |x, y| { + let v = u16::try_from(x * 0x1111 + y * 0x2345).unwrap(); + image::Rgb([0x1000 + v, 0x8001 + v, 0xF0F3 - v]) + }); + let rgb16 = DynamicImage::ImageRgb16(rgb16); + let gray16 = DynamicImage::ImageLuma16(image::ImageBuffer::from_fn(3, 2, |x, y| image::Luma([u16::try_from(x * 0x3001 + y * 0x0107).unwrap()]))); + let rgb8 = DynamicImage::ImageRgb8(image::RgbImage::from_fn(3, 2, |x, y| image::Rgb([u8::try_from(x * 70 + y * 9).unwrap(), 200, 13]))); + let png = |img: &DynamicImage, icc: &[u8], orientation: u16| { + let mut out = Vec::new(); + let mut enc = image::codecs::png::PngEncoder::new(&mut out); + enc.set_icc_profile(icc.to_vec()).unwrap(); + enc.set_exif_metadata(exif_block(orientation, (150, 150))).unwrap(); + img.write_with_encoder(enc).unwrap(); + out + }; + let webp = { + let mut out = Vec::new(); + let mut enc = image::codecs::webp::WebPEncoder::new_lossless(&mut out); + enc.set_icc_profile(rgb_icc.clone()).unwrap(); + enc.set_exif_metadata(exif_block(6, (150, 150))).unwrap(); + rgb8.write_with_encoder(enc).unwrap(); + out + }; + let tiff = |orientation: Option<u16>| { + let mut out = Vec::new(); + let mut enc = image::codecs::tiff::TiffEncoder::new(Cursor::new(&mut out)); + enc.set_icc_profile(rgb_icc.clone()).unwrap(); + rgb16.write_with_encoder(enc).unwrap(); + match orientation { + Some(o) => tiff_oriented(&out, o, false, None), + None => out, + } + }; + // (what, file, the ICC profile to keep, the pixels as they show, 16 bits) + type Case<'a> = (&'a str, Vec<u8>, Option<&'a [u8]>, DynamicImage, bool); + let cases: Vec<Case> = vec![ + ("16-bit RGB PNG, orientation 6", png(&rgb16, &rgb_icc, 6), Some(&rgb_icc), rgb16.rotate90(), true), + ("16-bit gray PNG, orientation 8", png(&gray16, &gray_icc, 8), Some(&gray_icc), gray16.rotate270(), true), + ("8-bit RGB PNG, orientation 3", png(&rgb8, &rgb_icc, 3), Some(&rgb_icc), rgb8.rotate180(), false), + ("RGB PNG with a CMYK profile, orientation 6", png(&rgb8, &cmyk_icc, 6), None, rgb8.rotate90(), false), + ("WebP, orientation 6", webp, Some(&rgb_icc), rgb8.rotate90(), false), + ("16-bit RGB TIFF, not turned", tiff(None), Some(&rgb_icc), rgb16.clone(), true), + ("16-bit RGB TIFF, orientation 6", tiff(Some(6)), Some(&rgb_icc), rgb16.rotate90(), true), + ]; + for (what, file, icc, want, wide) in cases { + let img = raster_image(&file).unwrap_or_else(|e| panic!("{what}: {e}")); + assert_eq!((img.width, img.height, img.blob.mime.as_str()), (want.width(), want.height(), "image/png"), "{what}"); + let (kept, color, px) = stored_pixels(what, &img); + assert_eq!(kept.as_deref(), icc, "{what}: the ICC profile"); + assert_eq!(color.bits_per_pixel() / u16::from(color.channel_count()), if wide { 16 } else { 8 }, "{what}: the sample depth"); + if wide { + assert_eq!(px.to_rgb16(), want.to_rgb16(), "{what}: the samples"); + } else { + assert_eq!(px.to_rgb8(), want.to_rgb8(), "{what}: the samples"); + } + } + // A JPEG's samples change in encoding; its profile is kept. + let mut jpg = Vec::new(); + let mut enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpg, 95); + enc.set_icc_profile(rgb_icc.clone()).unwrap(); + rgb8.write_with_encoder(enc).unwrap(); + let exif = [b"Exif\0\0".as_slice(), &exif_block(6, (150, 150))].concat(); + let mut turned = jpg[..2].to_vec(); + turned.extend([0xff, 0xe1]); + turned.extend(u16::try_from(exif.len() + 2).unwrap().to_be_bytes()); + turned.extend(&exif); + turned.extend(&jpg[2..]); + let img = raster_image(&turned).unwrap(); + assert_eq!((img.width, img.height, img.blob.mime.as_str()), (2, 3, "image/png"), "JPEG"); + assert_eq!(stored_pixels("JPEG", &img).0, Some(rgb_icc.clone()), "JPEG: the ICC profile"); + // Not turned, a PNG keeps its own bytes. + let plain = png(&rgb16, &rgb_icc, 1); + assert_eq!(raster_image(&plain).unwrap().blob.bytes.as_slice(), plain.as_slice(), "a PNG as taken keeps its bytes"); +} + +/// A CMYK TIFF stored again, because it stores one plane per ink or because its orientation turns +/// it, keeps its ICC profile as tag 34675 and its 8 or 16 bits a sample, exactly; one that stores +/// its inks together and isn't turned keeps its own bytes. +#[test] +fn cmyk_tiffs_written_again_keep_their_icc_profile_and_depth() { + use image::DynamicImage; + let icc = icc_profile(b"CMYK", 900); + // 3 × 2, no black, every sample's low byte different. + let ink = |c: usize, p: usize| -> u16 { u16::try_from(0x0101 * (c * 5 + p + 1) + 0x10 * p + c).unwrap() }; + for bits in [8u16, 16] { + let sample = |c: usize, p: usize| match (c, bits) { + (3, _) => 0, + (_, 16) => ink(c, p), + _ => ink(c, p) & 0xFF, + }; + let channels: Vec<Vec<u16>> = (0..4).map(|c| (0..6).map(|p| sample(c, p)).collect()).collect(); + // The image decoder shows a CMYK pixel without black as 1 - C, 1 - M, 1 - Y, exactly. + let full = if bits == 16 { 0xFFFF } else { 0xFF }; + let shown: Vec<u16> = (0..6).flat_map(|p| (0..3).map(|c| full - channels[c][p]).collect::<Vec<_>>()).collect(); + let shown = if bits == 16 { + DynamicImage::ImageRgb16(image::ImageBuffer::from_raw(3, 2, shown).unwrap()) + } else { + DynamicImage::ImageRgb8(image::RgbImage::from_raw(3, 2, shown.iter().map(|v| u8::try_from(*v).unwrap()).collect()).unwrap()) + }; + for planar in [false, true] { + let file = tiff_with_icc(&hand_tiff(5, bits, &[], planar, &channels), &icc); + for (orientation, want) in [(None, shown.clone()), (Some(6), shown.rotate90()), (Some(3), shown.rotate180())] { + let what = format!("{bits} bits, planar {planar}, orientation {orientation:?}"); + let file = orientation.map_or_else(|| file.clone(), |o| tiff_oriented(&file, o, false, Some(150))); + let img = raster_image(&file).unwrap_or_else(|e| panic!("{what}: {e}")); + if orientation.is_none() && !planar { + assert_eq!(img.blob.bytes.as_slice(), file.as_slice(), "{what}: kept as it is"); + } + let (kept, color, px) = stored_pixels(&what, &img); + assert_eq!(kept.as_deref(), Some(icc.as_slice()), "{what}: the ICC profile"); + let depth = if bits == 16 { image::ExtendedColorType::Cmyk16 } else { image::ExtendedColorType::Cmyk8 }; + assert_eq!(color, depth, "{what}: the sample depth"); + assert_eq!(px, want, "{what}: the samples"); + } + } + } +} + +/// A CMYK JPEG turned by its orientation and stored as a CMYK TIFF keeps its whole ICC profile, +/// put together from the two APP2 segments a profile larger than one segment is split into. +#[test] +fn a_turned_cmyk_jpeg_keeps_its_icc_profile_from_every_segment() { + use vectorcraft_render::encode::jpeg::{self, ColorModel, JpegOptions}; + let icc = icc_profile(b"CMYK", 70_000); + let inks: Vec<u8> = (0..16u32 * 8).flat_map(|i| [u8::try_from(i).unwrap(), 0, 0, 40]).collect(); + let o = JpegOptions { color_model: ColorModel::Cmyk, embed_icc: false, ..Default::default() }; + let jpg = jpeg::encode(&inks, 16, 8, 100, None, &o).unwrap(); + let exif = [b"Exif\0\0".as_slice(), &exif_block(6, (300, 300))].concat(); + let mut file = jpg[..2].to_vec(); + file.extend([0xff, 0xe1]); + file.extend(u16::try_from(exif.len() + 2).unwrap().to_be_bytes()); + file.extend(&exif); + let chunks: Vec<&[u8]> = icc.chunks(65_519).collect(); + assert_eq!(chunks.len(), 2, "the profile takes two segments"); + for (i, chunk) in chunks.iter().enumerate() { + file.extend([0xff, 0xe2]); + file.extend(u16::try_from(chunk.len() + 16).unwrap().to_be_bytes()); + file.extend(b"ICC_PROFILE\0"); + file.extend([u8::try_from(i + 1).unwrap(), 2]); + file.extend(*chunk); + } + file.extend(&jpg[2..]); + let img = raster_image(&file).unwrap(); + assert_eq!((img.width, img.height, img.blob.mime.as_str()), (8, 16, "image/tiff")); + let (kept, color, _) = stored_pixels("CMYK JPEG", &img); + assert_eq!(color, image::ExtendedColorType::Cmyk8); + assert!(kept.as_deref() == Some(icc.as_slice()), "the whole ICC profile: {:?} bytes", kept.map(|k| k.len())); +} + /// With `importer` named, a file up to the importer's limit is read whole and a larger one is an /// error, whatever its content. #[test] diff --git a/crates/engine/src/cmd/fileio/tests_aiimport.rs b/crates/engine/src/cmd/fileio/tests_aiimport.rs index 0f866c6588..fafcc12215 100644 --- a/crates/engine/src/cmd/fileio/tests_aiimport.rs +++ b/crates/engine/src/cmd/fileio/tests_aiimport.rs @@ -424,25 +424,45 @@ fn a_graphic_style_library_in_a_ai_file_without_layers_loads_its_styles() { /BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n{xa}0 1 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n;\n" ) }; + // Styles of one paint (`/SimpleStyle`): a red 2 pt stroke and no fill, and a gradient fill, + // which isn't read, so it is left out rather than listed with no paint. + let one_paint = |name: &str, paint: &str| format!("/KnownStyle :\n({name}) /Name ,\n/SimpleStyle :\n{paint}/Paint ;\n/Def ;\n"); let styles = format!( - "%AI9_BeginArtStyles\n{}{}{}%AI9_EndArtStyles\n%AI9_BeginArtStyleList\n(Red)\n(Green)\n(Blue)\n%AI9_EndArtStyleList\n", + "%AI9_BeginArtStyles\n{}{}{}{}{}%AI9_EndArtStyles\n\ + %AI9_BeginArtStyleList\n(Red)\n(Green)\n(Blue)\n(Red outline)\n(Sky fill)\n%AI9_EndArtStyleList\n", style("Blue", "0 0 0 0 0 0 1 Xa\n"), style("Green", "0 0 0 0 0 1 0 Xa\n"), - style("Red", "0 0 0 0 1 0 0 Xa\n") + style("Red", "0 0 0 0 1 0 0 Xa\n"), + one_paint("Red outline", "0 R\n0 1 1 0 K\n0 J 0 j 2 w 10 M []0 d\n1 0 Xd\n"), + one_paint("Sky fill", "0 O\n0 Bb\n2 (Sky) 0 0 0 100 1 0 0 1 0 0 Bg\n0 BB\n0 1 Xd\n") ); let data = ai::editing_data(200.0, 100.0, &styles); let file = ai::ai(&compressed(data.as_bytes()), "1 0 0 rg 10 50 30 40 re f"); let mut s = Session::new(); let p = json!({"dataBase64": vectorcraft_format::base64_encode(&file), "name": "fills.ai"}); let r = s.execute("graphicStyle.loadLibrary", &p).unwrap(); - assert_eq!((&r["name"], &r["count"]), (&json!("fills"), &json!(3)), "{r}"); - let lib = s.execute("graphicStyle.library", &json!({"library": r["library"]})).unwrap(); + assert_eq!((&r["name"], &r["count"]), (&json!("fills"), &json!(4)), "{r}"); + let library = r["library"].clone(); + let lib = s.execute("graphicStyle.library", &json!({"library": library})).unwrap(); let names: Vec<&str> = lib["styles"].as_array().unwrap().iter().map(|g| g["name"].as_str().unwrap()).collect(); - assert_eq!(names, ["Red", "Green", "Blue"], "{lib}"); + assert_eq!(names, ["Red", "Green", "Blue", "Red outline"], "{lib}"); + // The outline style strokes a rectangle red, 2 pt wide, and leaves it unfilled. + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let id = NodeId(s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()); + let r = s.execute("graphicStyle.addFromLibrary", &json!({"library": library, "names": ["Red outline"], "apply": true, "ids": [id.0]})).unwrap(); + assert_eq!(r["added"], json!(["Red outline"]), "{r}"); + let doc = &s.doc().unwrap().doc; + let look = &doc.node(id).unwrap().appearance; + assert!(look.fill().is_none(), "{look:?}"); + let strokes: Vec<_> = look.items.iter().filter(|i| matches!(i, vectorcraft_doc::AppearanceItem::Stroke(_))).collect(); + assert_eq!(strokes.len(), 1, "{look:?}"); + let stroke = look.stroke().unwrap(); + assert_eq!((stroke.paint.color(), stroke.width), (Some(vectorcraft_color::Color::cmyk(0.0, 1.0, 1.0, 0.0)), 2.0), "{look:?}"); + assert_eq!(doc.graphic_style("Red outline").map(|g| &g.appearance), Some(&**look)); let r = open(&mut s, "fills.ai", &file, json!({})).unwrap(); let doc = &s.doc().unwrap().doc; let styles: Vec<(&str, u32)> = doc.graphic_styles.iter().map(|g| (g.name.as_str(), g.id)).collect(); - assert_eq!(styles, [("Red", 1), ("Green", 2), ("Blue", 3)], "{r}"); + assert_eq!(styles, [("Red", 1), ("Green", 2), ("Blue", 3), ("Red outline", 4)], "{r}"); } /// A `.ai` symbol library (symbols and their list, no layers) opens with its symbols, and Other diff --git a/crates/engine/src/cmd/fileio/tests_artboard_fill.rs b/crates/engine/src/cmd/fileio/tests_artboard_fill.rs index 9a7684686a..371cdc05ab 100644 --- a/crates/engine/src/cmd/fileio/tests_artboard_fill.rs +++ b/crates/engine/src/cmd/fileio/tests_artboard_fill.rs @@ -109,23 +109,25 @@ fn the_ai_editing_copy_for_other_apps_draws_the_color_as_the_pages_do() { } } +/// Does PostScript `t` paint the only red the document has, the first artboard's color? RGB, or +/// CMYK PostScript's (its values depend on the color conversion the platform offers, so only its +/// hue is checked). +fn red(t: &str) -> bool { + t.lines().any(|l| { + let mut w: Vec<&str> = l.split_whitespace().collect(); + let Some(op) = w.pop() else { return false }; + let v: Vec<f64> = w.iter().filter_map(|n| n.parse().ok()).collect(); + match (op, v.as_slice()) { + ("rg" | "setrgbcolor", [r, g, b]) => *r > 0.9 && *g < 0.1 && *b < 0.1, + ("k" | "setcmykcolor", [c, m, y, k]) => *c < 0.1 && *m > 0.8 && *y > 0.8 && *k < 0.1, + _ => false, + } + }) +} + #[test] fn eps_and_postscript_print_draw_the_color() { let mut s = session(); - // The only red the document has, the first artboard's color: RGB, or CMYK PostScript's (its - // values depend on the color conversion the platform offers, so only its hue is checked). - let red = |t: &str| { - t.lines().any(|l| { - let mut w: Vec<&str> = l.split_whitespace().collect(); - let Some(op) = w.pop() else { return false }; - let v: Vec<f64> = w.iter().filter_map(|n| n.parse().ok()).collect(); - match (op, v.as_slice()) { - ("rg" | "setrgbcolor", [r, g, b]) => *r > 0.9 && *g < 0.1 && *b < 0.1, - ("k" | "setcmykcolor", [c, m, y, k]) => *c < 0.1 && *m > 0.8 && *y > 0.8 && *k < 0.1, - _ => false, - } - }) - }; let eps = |s: &mut Session, more: Value| { String::from_utf8_lossy(&file(s, with(json!({"format": "eps", "useArtboards": true, "artboard": 0}), &more))).into_owned() }; @@ -138,6 +140,22 @@ fn eps_and_postscript_print_draw_the_color() { assert!(!red(&ps(&mut s, json!({"includeArtboardFill": false}))), "print without it"); } +/// EPS Save draws the color on an artboard's page: with Use Artboards, or on the first artboard +/// when no art shows. The box of the visible art, as Export's, has none. +#[test] +fn eps_save_draws_the_color_on_an_artboard_page() { + let mut s = session(); + let save = |s: &mut Session, more: Value| { + let options = with(json!({"previewFormat": "none", "thumbnails": false}), &more); + String::from_utf8_lossy(&b64(&s.execute("document.save", &json!({"format": "eps", "options": options})).unwrap())).into_owned() + }; + assert!(!red(&save(&mut s, json!({}))), "the art's box"); + assert!(red(&save(&mut s, json!({"useArtboards": true, "range": "1"}))), "the artboard's page"); + s.execute("select.all", &json!({})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + assert!(red(&save(&mut s, json!({}))), "the first artboard when no art shows"); +} + #[test] fn export_for_screens_includes_the_fill_unless_unchecked() { let mut s = session(); diff --git a/crates/engine/src/cmd/fileio/tests_dxf.rs b/crates/engine/src/cmd/fileio/tests_dxf.rs index 8497676836..1a3368b56f 100644 --- a/crates/engine/src/cmd/fileio/tests_dxf.rs +++ b/crates/engine/src/cmd/fileio/tests_dxf.rs @@ -1,5 +1,5 @@ //! DXF export through the commands: options, artboards, selection, images, and the formats that -//! can't be written (DWG, PICT). +//! can't be written (DWG, PageMaker). use serde_json::{Value, json}; @@ -84,6 +84,11 @@ fn the_cnc_preset_sets_the_options_that_are_not_given() { true ) ); + assert_eq!((o.include_images, o.include_hatches), (false, false), "CNC / CAM leaves out images and fill hatches"); + let given = dxf::options(&json!({"dxfPreset": "cnc", "includeImages": true, "includeHatches": true})).unwrap(); + assert_eq!((given.include_images, given.include_hatches), (true, true), "the options given override it"); + let custom = dxf::options(&json!({})).unwrap(); + assert_eq!((custom.include_images, custom.include_hatches), (true, true), "Custom keeps both"); assert_eq!(dxf::options(&json!({})).unwrap().version, vectorcraft_cad::DxfVersion::R2018, "custom by default"); let e = s.execute("document.exportDxf", &json!({"dxfPreset": "laser"})).unwrap_err().to_string(); assert!(e.contains("custom or cnc"), "{e}"); @@ -151,6 +156,59 @@ fn placed_images_come_back_as_linked_files() { let _ = std::fs::remove_dir_all(dir); } +/// `includeImages` and `includeHatches` leave out placed images (with their files) and fill +/// hatches, each on its own, through both commands, with and without a path; CNC / CAM leaves +/// out both, and the options given override it. +#[test] +fn placed_images_and_fill_hatches_can_be_left_out() { + let mut s = super::tests_svg::image_session(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 1, "height": 1})).unwrap(); + let counts = |r: &Value| { + let e = entities(&text(r)); + let n = |k: &str| e.iter().filter(|x| *x == k).count(); + (n("LWPOLYLINE"), n("HATCH"), n("IMAGE"), r.get("linked").and_then(Value::as_array).map_or(0, Vec::len)) + }; + let warned = |r: &Value, w: &str| r["warnings"].as_array().unwrap().iter().any(|x| x.as_str().is_some_and(|x| x.starts_with(w))); + let all = s.execute("document.export", &json!({"format": "dxf"})).unwrap(); + assert_eq!(counts(&all), (1, 1, 1, 1)); + let r = s.execute("document.export", &json!({"format": "dxf", "includeImages": false})).unwrap(); + assert_eq!(counts(&r), (1, 1, 0, 0)); + assert!(warned(&r, "placed images are left out") && !warned(&r, "fill hatches"), "{r}"); + let r = s.execute("document.exportDxf", &json!({"includeHatches": false})).unwrap(); + assert_eq!(counts(&r), (1, 0, 1, 1)); + assert!(warned(&r, "fill hatches are left out") && !warned(&r, "placed images"), "{r}"); + let r = s.execute("document.exportDxf", &json!({"dxfPreset": "cnc"})).unwrap(); + assert_eq!(counts(&r), (1, 0, 0, 0)); + let r = s.execute("document.export", &json!({"format": "dxf", "dxfPreset": "cnc", "includeImages": true})).unwrap(); + assert_eq!(counts(&r), (1, 0, 1, 1)); + // With a path, no image file is written next to the drawing. + let dir = std::env::temp_dir().join(format!("vc-dxf-out-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("cut.dxf").to_string_lossy().to_string(); + let r = s.execute("document.exportDxf", &json!({"path": path, "dxfPreset": "cnc"})).unwrap(); + assert!(r.get("linked").is_none(), "{r}"); + let files: Vec<String> = std::fs::read_dir(&dir).unwrap().filter_map(|e| e.ok()).map(|e| e.file_name().to_string_lossy().to_string()).collect(); + assert_eq!(files, ["cut.dxf"]); + let _ = std::fs::remove_dir_all(dir); +} + +/// The reply gives what the drawings lose before a note on the options, across the files: the +/// first artboard's drawing notes the fill hatches that `includeHatches: false` leaves out, and +/// the second's also has a see-through rectangle that DXF 2000 writes opaque. +#[test] +fn what_the_drawings_lose_comes_before_what_an_option_left_out() { + let mut s = two_boards(); + s.execute("object.setProps", &json!({"opacity": 50})).unwrap(); + let r = s.execute("document.export", &json!({"format": "dxf", "version": "2000", "includeHatches": false, "useArtboards": true})).unwrap(); + let warnings: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + let Some((option, losses)) = warnings.split_last() else { panic!("no notes") }; + assert!(option.starts_with("fill hatches are left out"), "{warnings:?}"); + assert!(losses.iter().any(|w| w.starts_with("transparency needs DXF 2004")), "{warnings:?}"); + assert!(!losses.iter().any(|w| w.starts_with("fill hatches")), "each note once: {warnings:?}"); +} + /// Two placed images whose pixel data can't be decoded are left out of the drawing and get no /// linked file, and `warnings` holds the note raster exports give, once, without naming either /// image's key. @@ -181,6 +239,8 @@ fn bad_dxf_options_are_refused() { json!({"rasterFormat": "gif"}), json!({"preserve": "both"}), json!({"alterPaths": "yes"}), + json!({"includeImages": "no"}), + json!({"includeHatches": 0}), ] { let e = s.execute("document.exportDxf", &p).unwrap_err().to_string(); assert!(e.contains("DXF"), "{p}: {e}"); @@ -203,6 +263,8 @@ fn formats_list_dxf_and_what_can_not_be_written() { "scaleLineweights", "colors", "rasterFormat", + "includeImages", + "includeHatches", "preserve", "alterPaths", "outlineText", @@ -213,23 +275,24 @@ fn formats_list_dxf_and_what_can_not_be_written() { } assert!(r["writable"].as_array().unwrap().contains(&json!("dxf"))); let unsupported: Vec<&str> = r["unsupported"].as_array().unwrap().iter().map(|u| u["id"].as_str().unwrap()).collect(); - assert_eq!(unsupported, ["dwg", "pict", "pmd"]); + assert_eq!(unsupported, ["dwg", "pmd"]); } #[test] -fn dwg_and_pict_say_what_to_use_instead() { +fn dwg_and_pagemaker_say_what_to_use_instead() { let mut s = two_boards(); for p in [json!({"format": "dwg"}), json!({"path": "/tmp/plan.DWG"})] { let e = s.execute("document.export", &p).unwrap_err().to_string(); assert!(e.contains("DWG is not available") && e.contains("DXF"), "{p}: {e}"); } + // PICT opens; it isn't written. let e = s.execute("document.export", &json!({"format": "pict"})).unwrap_err().to_string(); - assert!(e.contains("PICT is a retired format"), "{e}"); + assert!(e.contains("PICT files can be opened but not written"), "{e}"); let e = s .execute("document.open", &json!({"name": "old.pct", "dataBase64": vectorcraft_format::base64_encode(&[0u8; 600])})) .unwrap_err() .to_string(); - assert!(e.contains("old.pct") && e.contains("PICT"), "{e}"); + assert!(e.contains("not a PICT file"), "{e}"); let e = s .execute("document.open", &json!({"name": "site.dwg", "dataBase64": vectorcraft_format::base64_encode(b"AC1032\0\0")})) .unwrap_err() diff --git a/crates/engine/src/cmd/fileio/tests_eps.rs b/crates/engine/src/cmd/fileio/tests_eps.rs index 8e2c1d429a..db667e6ef2 100644 --- a/crates/engine/src/cmd/fileio/tests_eps.rs +++ b/crates/engine/src/cmd/fileio/tests_eps.rs @@ -218,6 +218,106 @@ fn placed_images_are_written_and_previews_are_black_and_white_on_request() { assert!(l3.contains("/FlateDecode filter >> image")); } +/// The PNG thumbnail of an EPS file, decoded. +fn thumbnail_png(bytes: &[u8]) -> image::RgbaImage { + let png = vectorcraft_eps::thumbnail(bytes).expect("a thumbnail"); + image::load_from_memory_with_format(&png, image::ImageFormat::Png).unwrap().to_rgba8() +} + +/// The TIFF preview of an EPS file, decoded. +fn preview_tiff(bytes: &[u8]) -> image::RgbaImage { + let tiff = vectorcraft_eps::sections(bytes).unwrap().1.expect("a preview"); + image::load_from_memory_with_format(tiff, image::ImageFormat::Tiff).unwrap().to_rgba8() +} + +/// The size of a thumbnail render of the rect an EPS file's preview shows (its bounding box). +fn thumbnail_size(bytes: &[u8]) -> (u32, u32) { + let b: Vec<f64> = dsc(&postscript(bytes), "BoundingBox").unwrap().split(' ').map(|v| v.parse().unwrap()).collect(); + let rect = vectorcraft_geom::Rect::new(b[0], b[1], b[2], b[3]); + let long = rect.width().max(rect.height()); + vectorcraft_render::raster_size(rect, if long > 128.0 { 128.0 / long } else { 1.0 }).unwrap() +} + +/// The thumbnail is the color preview made smaller, the area average of its pixels at the size a +/// 128 px render has, not a second render of the document; it shows the same picture as one. +#[test] +fn the_thumbnail_is_made_from_the_preview() { + let mut s = session(1000.0, 700.0, 1); + s.execute("paint.setFill", &json!({"color": "#2060c0"})).unwrap(); + s.execute("shape.ellipse", &json!({"x": 37.3, "y": 41.9, "width": 811.7, "height": 563.1})).unwrap(); + let r = s.execute("document.exportEps", &json!({"useArtboards": true, "previewFormat": "tiffColor", "transparentPreview": false})).unwrap(); + let bytes = b64(&r); + let preview = preview_tiff(&bytes); + assert_eq!(preview.dimensions(), (1000, 700)); + let thumb = thumbnail_png(&bytes); + assert_eq!(thumb.dimensions(), (128, 90)); + // An opaque preview's straight pixels are its premultiplied ones. + let shown = vectorcraft_render::Rendered { width: 1000, height: 700, pixels: preview.into_raw() }; + assert!(thumb.as_raw() == &shown.area_resized(128, 90).unwrap().pixels, "the thumbnail isn't the preview made smaller"); + let doc = &s.doc().unwrap().doc; + let fresh = vectorcraft_render::Renderer::new().render_region(doc, vectorcraft_geom::Rect::new(0.0, 0.0, 1000.0, 700.0), 0.128, true); + let mut diffs: Vec<u8> = thumb.as_raw().iter().zip(&fresh.pixels).map(|(a, b)| a.abs_diff(*b)).collect(); + diffs.sort_unstable(); + let mean = diffs.iter().map(|d| f64::from(*d)).sum::<f64>() / diffs.len() as f64; + let p95 = diffs[diffs.len() * 95 / 100]; + assert!(mean <= 8.0 && p95 <= 32, "mean {mean}, 95th percentile {p95}"); +} + +/// A thumbnail is opaque color on white whatever the preview: a transparent color preview's, and a +/// black-and-white preview's, which keeps the art's colors. +#[test] +fn thumbnails_of_transparent_and_black_and_white_previews_are_opaque_color() { + let mut s = session(400.0, 200.0, 1); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 200, "height": 200})).unwrap(); + let doc = &s.doc().unwrap().doc; + let fresh = vectorcraft_render::Renderer::new().render_region(doc, vectorcraft_geom::Rect::new(0.0, 0.0, 400.0, 200.0), 0.32, true); + let red: [u8; 4] = fresh.pixels[(32 * 128 + 10) * 4..][..4].try_into().unwrap(); + for preview in ["tiffColor", "tiffBw"] { + let r = s.execute("document.exportEps", &json!({"useArtboards": true, "previewFormat": preview})).unwrap(); + let thumb = thumbnail_png(&b64(&r)); + assert_eq!(thumb.dimensions(), (128, 64), "{preview}"); + assert_eq!(thumb.get_pixel(10, 32).0, red, "{preview}"); + assert_eq!(thumb.get_pixel(120, 32).0, [255, 255, 255, 255], "{preview}"); + assert!(thumb.pixels().all(|p| p[3] == 255), "{preview}"); + } +} + +/// A page that fits in a thumbnail gets its preview's own pixels, unresampled. +#[test] +fn a_small_page_s_thumbnail_is_its_preview() { + let mut s = session(100.0, 60.0, 1); + s.execute("shape.ellipse", &json!({"x": 10.5, "y": 7.25, "width": 70, "height": 41})).unwrap(); + let bytes = b64(&s.execute("document.exportEps", &json!({"useArtboards": true, "transparentPreview": false})).unwrap()); + let thumb = thumbnail_png(&bytes); + assert_eq!(thumb.dimensions(), (100, 60)); + assert!(thumb == preview_tiff(&bytes), "the thumbnail isn't the preview"); +} + +/// Every file has a thumbnail at the size a thumbnail render has, with any page shape, on Save +/// too and without a preview; with thumbnails off there is none. +#[test] +fn every_file_s_thumbnail_has_the_thumbnail_size() { + let mut s = session(333.3, 77.7, 2); + let second = s.doc().unwrap().doc.artboards[1].rect.x0; + s.execute("shape.rectangle", &json!({"x": 3.7, "y": 5.1, "width": 300, "height": 61.3})).unwrap(); + s.execute("shape.ellipse", &json!({"x": second + 1.0, "y": 2.0, "width": 20, "height": 70})).unwrap(); + for preview in ["tiffColor", "tiffBw", "none"] { + let r = s.execute("document.exportEps", &json!({"useArtboards": true, "previewFormat": preview})).unwrap(); + let files = r["files"].as_array().unwrap(); + assert_eq!(files.len(), 3); + for f in files { + let bytes = b64(f); + assert_eq!(thumbnail_png(&bytes).dimensions(), thumbnail_size(&bytes), "{preview} {}", f["name"]); + } + } + assert_eq!(thumbnail_size(&b64(&s.execute("document.exportEps", &json!({"range": "1"})).unwrap())), (128, 30)); + let saved = b64(&s.execute("document.save", &json!({"format": "eps", "previewFormat": "tiffColor"})).unwrap()); + assert_eq!(thumbnail_png(&saved).dimensions(), thumbnail_size(&saved)); + let r = s.execute("document.exportEps", &json!({"useArtboards": true, "thumbnails": false})).unwrap(); + assert!(r["files"].as_array().unwrap().iter().all(|f| vectorcraft_eps::thumbnail(&b64(f)).is_none())); +} + /// Two placed images whose pixel data can't be decoded are left out of the EPS, and `warnings` /// holds the note raster exports give, once, without naming either image's key. #[test] diff --git a/crates/engine/src/cmd/fileio/tests_exportas.rs b/crates/engine/src/cmd/fileio/tests_exportas.rs index 09bbcf28f3..cc1345060d 100644 --- a/crates/engine/src/cmd/fileio/tests_exportas.rs +++ b/crates/engine/src/cmd/fileio/tests_exportas.rs @@ -117,3 +117,166 @@ fn formats_list_use_artboards() { } assert!(opts("vectorcraft").get("useArtboards").is_none()); } + +/// An export's reply gives what the file loses before its notes on the options, whatever order +/// the encoder gave them: the WebP encoder notes that lossy WebP isn't applied before the export +/// notes the type it drew in the fallback font. With only notes on the options, they keep their +/// order. +#[test] +fn what_the_file_loses_comes_before_a_note_on_the_options() { + let lossy = "lossy WebP isn't available yet: the file is lossless (exact, but larger)"; + let warnings = |s: &mut Session, p: Value| -> Vec<String> { + let r = s.execute("document.export", &p).unwrap(); + r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).map(str::to_string).collect() + }; + let mut s = session(60.0, 40.0, 1); + assert_eq!(warnings(&mut s, json!({"format": "webp", "lossless": false})), [lossy]); + s.execute("text.create", &json!({"x": 5, "y": 20, "text": "Ab", "font": "Nonexistent Sans Probe"})).unwrap(); + let w = warnings(&mut s, json!({"format": "webp", "lossless": false})); + assert_eq!(w.len(), 2, "{w:?}"); + assert!(w[0].contains("fallback font") && w[0].contains("Nonexistent Sans Probe"), "{w:?}"); + assert_eq!(w[1], lossy); + // document.serialize gives them in the same order. + let r = s.execute("document.serialize", &json!({"format": "webp", "lossless": false})).unwrap(); + assert_eq!(r["warnings"], json!(w)); +} + +/// A session with one artboard and a selected rectangle on it. +fn with_art() -> Session { + let mut s = session(60.0, 40.0, 1); + s.execute("shape.rectangle", &json!({"x": 5, "y": 5, "width": 20, "height": 10})).unwrap(); + s +} + +/// The warnings of reply `r` that name an option the file doesn't read. +fn unused(r: &Value) -> Vec<String> { + r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).filter(|w| w.contains("was not used")).map(str::to_string).collect() +} + +/// An option that only another format reads is accepted, and the reply's warnings name it in the +/// words of a save's note; `document.export`, `document.serialize` and `document.exportSelection` +/// give the same note. +#[test] +fn an_option_only_another_format_reads_gets_a_note() { + let (mut s, notes) = (with_art(), unused); + for cmd in ["document.export", "document.serialize", "document.exportSelection"] { + let r = s.execute(cmd, &json!({"format": "pdf", "quality": 80, "outlineText": true})).unwrap(); + assert_eq!( + notes(&r), + ["`outlineText` was not used: PDF files don't read it", "`quality` was not used: PDF files don't read it"], + "{cmd}: {r}" + ); + } + // The format's own options, the keys every export takes and null values get none. + for p in [ + json!({"format": "jpg", "quality": 80, "scale": 2}), + json!({"format": "ai", "compress": true, "compatibility": "1.7"}), + json!({"format": "pdf", "quality": null, "selectedOnly": false, "includeArtboardFill": false, "useArtboards": true}), + json!({"format": "svg", "outlineText": true, "svg": {"decimals": 2}}), + ] { + let r = s.execute("document.export", &p).unwrap(); + assert!(notes(&r).is_empty(), "{p}: {r}"); + } + let r = s.execute("document.serialize", &json!({"format": "png", "compress": true, "marks": {"trim": true}, "svg": {"minify": true}})).unwrap(); + assert_eq!( + notes(&r), + [ + "`compress` was not used: PNG files don't read it", + "`marks` was not used: PNG files don't read it", + "`svg` was not used: PNG files don't read it" + ], + "{r}" + ); + // The note names the kind of file written, as a save's does. + let r = s.execute("document.export", &json!({"format": "ai", "pdfCompatible": false, "quality": 80})).unwrap(); + assert_eq!(notes(&r), ["`quality` was not used: non-PDF-compatible .ai files don't read it"], "{r}"); + let r = s.execute("document.export", &json!({"format": "pdf", "preserveEditing": false, "range": "1"})).unwrap(); + assert!(notes(&r).is_empty(), "{r}"); + let r = s.execute("document.export", &json!({"format": "vectorcraft", "artboard": 0})).unwrap(); + assert_eq!(notes(&r), ["`artboard` was not used: VectorCraft files don't read it"], "{r}"); +} + +/// A legacy `.ai` file reads its own options and the artboards to write, not the other `.ai` +/// options or the PDF options. +#[test] +fn a_legacy_ai_export_notes_the_options_of_the_other_ai_files() { + let (mut s, notes) = (with_art(), unused); + let r = s.execute("document.export", &json!({"format": "ai", "aiVersion": "7", "compress": true, "marks": {"trim": true}})).unwrap(); + assert_eq!( + notes(&r), + ["`compress` was not used: legacy .ai (version 7) files don't read it", "`marks` was not used: legacy .ai (version 7) files don't read it"], + "{r}" + ); + let r = + s.execute("document.export", &json!({"format": "ai", "aiVersion": "7", "outlineText": true, "hiddenObjects": "omit", "range": "1"})).unwrap(); + assert!(notes(&r).is_empty(), "{r}"); + let r = s.execute("document.export", &json!({"format": "ai", "aiVersion": "7", "useArtboards": false})).unwrap(); + assert!(notes(&r).is_empty(), "{r}"); +} + +/// The `.ai` files other than the legacy one don't read the legacy file's own options. +#[test] +fn a_pdf_compatible_ai_export_notes_the_legacy_options() { + let (mut s, notes) = (with_art(), unused); + let unread = json!({"format": "ai", "aiVersion": "pdf", "outlineText": true, "hiddenObjects": "omit", "transparentImages": "omit"}); + let r = s.execute("document.export", &unread).unwrap(); + assert_eq!( + notes(&r), + [ + "`hiddenObjects` was not used: PDF-compatible .ai files don't read it", + "`outlineText` was not used: PDF-compatible .ai files don't read it", + "`transparentImages` was not used: PDF-compatible .ai files don't read it" + ], + "{r}" + ); +} + +/// `preserveEditing` is always on for a `.ai` file, so an export that gives it gets a note. +#[test] +fn an_ai_export_notes_preserve_editing() { + let (mut s, notes) = (with_art(), unused); + let r = s.execute("document.export", &json!({"format": "ai", "preserveEditing": false, "range": "1"})).unwrap(); + assert_eq!(notes(&r), ["`preserveEditing` was not used: PDF-compatible .ai files don't read it"], "{r}"); +} + +/// An export writes one file: only a save writes each artboard to a file of its own, so an export +/// notes `separateArtboards`, and the `range` that names those files for a native file. +#[test] +fn an_export_notes_the_options_that_only_a_save_reads() { + let (mut s, notes) = (with_art(), unused); + let r = s.execute("document.export", &json!({"format": "ai", "separateArtboards": true, "range": "1"})).unwrap(); + assert_eq!(notes(&r), ["`separateArtboards` was not used: PDF-compatible .ai files don't read it"], "{r}"); + for (format, label) in [("vectorcraft", "VectorCraft"), ("template", "VectorCraft Template")] { + let r = s.execute("document.export", &json!({"format": format, "separateArtboards": true, "range": "1", "compress": true})).unwrap(); + assert_eq!( + notes(&r), + [format!("`range` was not used: {label} files don't read it"), format!("`separateArtboards` was not used: {label} files don't read it")], + "{r}" + ); + } +} + +/// The legacy `.ai` options that the notes go by are the ones the `.ai` option table describes as +/// the legacy file's ("with aiVersion 7"), so an option added to the table is not noted as unread +/// on a legacy export by mistake. +#[test] +fn the_legacy_ai_options_are_the_ones_the_option_table_names() { + let described: Vec<&str> = native::AI_OPTIONS.iter().filter(|o| o.description.starts_with("with aiVersion 7")).map(|o| o.name).collect(); + assert_eq!(described, legacy_ai::LEGACY_ONLY); + for key in described.iter().chain(&ARTBOARD_PARAMS).chain(&["aiVersion", "useArtboards"]) { + assert!(legacy_ai::reads(key), "{key}"); + assert!(native::AI_OPTIONS.iter().any(|o| o.name == *key), "{key} is not a .ai option"); + } + for key in ["compress", "pdfCompatible", "separateArtboards", "editingData", "marks"] { + assert!(!legacy_ai::reads(key), "{key}"); + } +} + +#[test] +fn note_texts_give_the_losses_first_each_kind_in_order() { + use super::encode::{Note, note_texts}; + let notes = [Note::setting("s1"), Note::loss("l1"), Note::setting("s2"), Note::loss("l2")]; + assert_eq!(note_texts(¬es), ["l1", "l2", "s1", "s2"]); + assert_eq!(note_texts(&[Note::setting("s1"), Note::setting("s2")]), ["s1", "s2"]); + assert!(note_texts(&[]).is_empty()); +} diff --git a/crates/engine/src/cmd/fileio/tests_hpgl.rs b/crates/engine/src/cmd/fileio/tests_hpgl.rs new file mode 100644 index 0000000000..f4767fd81d --- /dev/null +++ b/crates/engine/src/cmd/fileio/tests_hpgl.rs @@ -0,0 +1,231 @@ +//! HP-GL plotter files through the commands: `document.open` by extension or by content, File › +//! Place as one group of paths, the dialogs' filters and the format list, files that aren't +//! HP-GL refused with a message, and `document.export` of one artboard, each or the art, with its +//! options checked. + +use serde_json::{Value, json}; +use vectorcraft_doc::NodeKind; + +use super::*; + +fn b64(bytes: &[u8]) -> String { + vectorcraft_format::base64_encode(bytes) +} + +/// An inch-wide red square and a black diagonal, with the thinnest pen. +const PLOT: &[u8] = b"IN;SP2;PW0;PA0,0;PD1016,0,1016,1016,0,1016,0,0;PU;SP1;PD1016,1016;PU;"; + +#[test] +fn document_open_reads_a_plot_file() { + let mut s = Session::new(); + let r = s.execute("document.open", &json!({"name": "part.plt", "dataBase64": b64(PLOT)})).unwrap(); + assert_eq!((r["format"].as_str(), r["title"].as_str()), (Some("hpgl"), Some("part.plt")), "{r}"); + let st = s.doc().unwrap(); + let board = st.doc.artboards[0].rect; + assert!((board.width() - 72.25).abs() < 1e-9 && (board.height() - 72.25).abs() < 1e-9, "{board:?}"); + let mut paths = vec![]; + st.doc.walk(|n| { + if let NodeKind::Path { .. } = n.kind { + paths.push(n.clone()); + } + }); + assert_eq!(paths.len(), 2); + // Opened as artwork: Save asks for a name. + assert!(st.path.is_none()); + + // A plot file opens by its content in any of its names, and under a name no format reads. + for name in ["drawing.prn", "PART.HPGL", "part.hgl", "part.hpg"] { + let r = Session::new().execute("document.open", &json!({"name": name, "dataBase64": b64(PLOT)})).unwrap(); + assert_eq!(r["format"].as_str(), Some("hpgl"), "{name}: {r}"); + } +} + +#[test] +fn file_place_places_a_plot_file_as_one_group() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 200})).unwrap(); + let p = json!({"name": "part.plt", "dataBase64": b64(PLOT), "thumbnail": 16}); + let info = s.execute("file.place.info", &p).unwrap(); + assert_eq!(info["format"], "hpgl", "{info}"); + assert!((info["width"].as_f64().unwrap() - 72.25).abs() < 1e-9, "{info}"); + let r = s.execute("file.place", &p).unwrap(); + assert_eq!((&r["format"], r["ids"].as_array().map(Vec::len)), (&json!("hpgl"), Some(1)), "{r}"); + let doc = &s.doc().unwrap().doc; + let group = doc.node(vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap())).unwrap(); + let NodeKind::Group { children, clip, .. } = &group.kind else { panic!("a group, got {:?}", group.kind) }; + assert_eq!((children.len(), *clip), (2, false), "the art's bounds, not clipped"); +} + +#[test] +fn files_that_are_not_hpgl_are_refused() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + let before = s.doc().unwrap().doc.artboards[0].rect.size(); + let script = b"set terminal png\nplot sin(x)\n"; + let e = s.execute("document.open", &json!({"name": "graph.plt", "dataBase64": b64(script)})).expect_err("refused"); + assert!(e.to_string().contains("not an HP-GL file"), "{e}"); + assert_eq!(s.doc().unwrap().doc.artboards[0].rect.size(), before); + assert!(s.execute("file.place", &json!({"name": "graph.plt", "dataBase64": b64(script)})).is_err()); + // Text that isn't a plot opens by its name, not as HP-GL. + assert!(detect("notes.txt", b"IN THE BEGINNING").is_none_or(|f| f.id != "hpgl")); + // Only a plot file's own names, and names no other format reads, are read by their content: + // text, other formats' files and the formats named as unsupported (a DWG drawing starts with + // `AC` and digits) aren't, even when they start like a plot. + for name in ["notes.txt", "notes.svg", "picture.tga", "drawing.dxf", "site.dwg", "old.pct"] { + for bytes in [&b"IN"[..], b"in 5;", b"AC1032\0\0", PLOT] { + assert!(detect(name, bytes).is_none_or(|f| f.id != "hpgl"), "{name}: {:?}", String::from_utf8_lossy(bytes)); + } + } + let text = s.execute("file.place", &json!({"name": "notes.txt", "dataBase64": b64(b"IN 5; PA 10;")})).unwrap(); + assert_eq!(text["format"], "txt", "{text}"); +} + +/// A plot file named as one opens when its first instruction is one a plot file seldom starts with; +/// under another name it isn't taken for HP-GL. +#[test] +fn a_plot_file_by_its_name_may_start_with_any_instruction() { + let plot = b"SI0.2,0.3;SP1;PA0,0;PD1016,0;"; + let r = Session::new().execute("document.open", &json!({"name": "part.plt", "dataBase64": b64(plot)})).unwrap(); + assert_eq!(r["format"].as_str(), Some("hpgl"), "{r}"); + assert!(detect("drawing.prn", plot).is_none_or(|f| f.id != "hpgl")); +} + +#[test] +fn the_dialogs_and_the_format_list_name_hpgl() { + let exts = ["plt", "hpgl", "hgl", "hpg"]; + for e in exts { + assert!(OPEN_EXTS.contains(&e) && PLACE_EXTS.contains(&e) && UNASSOCIATED_EXTS.contains(&e), "{e}"); + assert_eq!(format_for_name(&format!("a.{e}")).map(|f| f.id), Some("hpgl"), "{e}"); + } + let filter = ("HP-GL", &exts[..]); + assert!(open_filters().any(|f| f == filter) && place_filters().any(|f| f == filter)); + let r = Session::new().execute("document.formats", &json!({})).unwrap(); + let f = r["formats"].as_array().unwrap().iter().find(|f| f["id"] == "hpgl").unwrap().clone(); + assert_eq!((f["read"].as_bool(), f["write"].as_bool(), f["raster"].as_bool()), (Some(true), Some(true), Some(false))); + for o in ["useArtboards", "hpglVersion", "curveTolerance", "pens", "origin", "sortPaths", "insideFirst"] { + assert!(f["options"].get(o).is_some(), "{o}: {f}"); + } + assert_eq!(writable_format(None, Some("x/part.plt")).unwrap().id, "hpgl"); + assert_eq!(writable_format(None, Some("x/part.hpgl")).unwrap().id, "hpgl"); +} + +fn bytes(v: &Value) -> Vec<u8> { + vectorcraft_format::base64_decode(v["dataBase64"].as_str().expect("dataBase64")).unwrap() +} + +/// Two 100 pt artboards side by side, a 30 pt square on each, the second one red. +fn two_boards() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 2})).unwrap(); + let second = s.doc().unwrap().doc.artboards[1].rect.x0; + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap(); + let red = s.execute("shape.rectangle", &json!({"x": second + 10.0, "y": 10, "width": 30, "height": 30})).unwrap()["id"].clone(); + s.execute("paint.setStroke", &json!({"ids": [red], "color": "#ff0000"})).unwrap(); + s +} + +#[test] +fn export_writes_a_plot_of_one_artboard_or_each() { + let mut s = two_boards(); + let r = s.execute("document.export", &json!({"format": "hpgl"})).unwrap(); + assert_eq!(r["format"], "hpgl"); + // The first artboard's square, 1016 units to the inch from its bottom-left corner. + assert_eq!(String::from_utf8(bytes(&r)).unwrap(), "IN;PU;SP1;PU141,1270;PD564,1270,564,847,141,847,141,1270;PU;SP0;"); + let second = String::from_utf8(bytes(&s.execute("document.export", &json!({"format": "hpgl", "artboard": 1})).unwrap())).unwrap(); + assert_eq!(second, "IN;PU;SP1;PU141,1270;PD564,1270,564,847,141,847,141,1270;PU;SP0;", "its own square, its own pen 1"); + assert_eq!(bytes(&s.execute("document.serialize", &json!({"format": "hpgl"})).unwrap()), bytes(&r)); + let r = s.execute("document.export", &json!({"format": "hpgl", "useArtboards": true})).unwrap(); + let files = r["files"].as_array().unwrap(); + assert_eq!(files.len(), 2); + assert!(files[1]["name"].as_str().unwrap().ends_with("-Artboard-2.plt"), "{files:?}"); + // One pen numbering for every file: the red square is pen 2 in the second. + assert_eq!(String::from_utf8(bytes(&files[1])).unwrap(), "IN;PU;SP2;PU141,1270;PD564,1270,564,847,141,847,141,1270;PU;SP0;"); + // The bounds of the art: both squares, the second pen red, read back as two paths. + let art = bytes(&s.execute("document.export", &json!({"format": "hpgl", "useArtboards": false, "hpglVersion": "hpgl2"})).unwrap()); + assert!(art.starts_with(b"IN;NP4;PC1,0,0,0;PC2,255,0,0;"), "{:?}", String::from_utf8_lossy(&art)); + let back = Session::new().execute("document.open", &json!({"name": "art.plt", "dataBase64": b64(&art)})).unwrap(); + assert_eq!(back["format"], "hpgl", "{back}"); + // One file holds one artboard. + assert!(s.execute("document.export", &json!({"format": "hpgl", "artboards": [0, 1]})).is_err()); +} + +/// A plot read back opens with the same squares: as wide as the art drew them, a point at most +/// apart from the 30 pt sides plus the 0.35 mm pen. +#[test] +fn a_plot_reads_back_as_its_art() { + let mut s = two_boards(); + let plot = bytes(&s.execute("document.export", &json!({"format": "hpgl", "useArtboards": false})).unwrap()); + let mut back = Session::new(); + back.execute("document.open", &json!({"name": "art.plt", "dataBase64": b64(&plot)})).unwrap(); + let doc = &back.doc().unwrap().doc; + let mut paths = 0; + doc.walk(|n| paths += usize::from(matches!(n.kind, NodeKind::Path { .. }))); + assert_eq!(paths, 2); + let board = doc.artboards[0].rect; + let second = s.doc().unwrap().doc.artboards[1].rect.x0; + let pen = 0.35 * 72.0 / 25.4; + assert!((board.width() - (second + 30.0 + pen)).abs() < 0.1, "{board:?}"); + assert!((board.height() - (30.0 + pen)).abs() < 0.1, "{board:?}"); +} + +#[test] +fn export_options_are_checked() { + let mut s = two_boards(); + let refused = |s: &mut Session, p: Value| s.execute("document.export", &p).expect_err("refused").to_string(); + let cases = [ + (json!({"format": "hpgl", "hpglVersion": "hpgl3"}), "`hpglVersion` must be one of hpgl, hpgl2"), + (json!({"format": "hpgl", "hpglVersion": 2}), "`hpglVersion` must be a string"), + (json!({"format": "hpgl", "curveTolerance": 0}), "`curveTolerance` must be between 0.01 and 10 (got 0)"), + (json!({"format": "hpgl", "curveTolerance": "fine"}), "`curveTolerance` must be a number"), + (json!({"format": "hpgl", "pens": []}), "`pens` must be an array of 1 to 255 #rrggbb colors"), + (json!({"format": "hpgl", "pens": ["#ff0000", "red"]}), "`pens` must be an array of 1 to 255 #rrggbb colors"), + (json!({"format": "hpgl", "pens": "#ff0000"}), "`pens` must be an array of 1 to 255 #rrggbb colors"), + (json!({"format": "hpgl", "origin": "top"}), "`origin` must be one of bottomLeft, center"), + (json!({"format": "hpgl", "sortPaths": "yes"}), "`sortPaths` must be true or false"), + (json!({"format": "hpgl", "insideFirst": 1}), "`insideFirst` must be true or false"), + ]; + for (p, want) in cases { + let e = refused(&mut s, p.clone()); + assert!(e.contains(want), "{p}: {e}"); + } + let many: Vec<String> = (0..256).map(|i| format!("#{:02x}0000", i % 256)).collect(); + assert!(refused(&mut s, json!({"format": "hpgl", "pens": many})).contains("`pens`")); + // Given options take effect: the center as the origin, a pen table (black is pen 2), and the + // square starting at its corner nearest the origin. + let p = json!({"format": "hpgl", "origin": "CENTER", "pens": ["#ff0000", "#000000"], "curveTolerance": 10, "sortPaths": true}); + let plot = String::from_utf8(bytes(&s.execute("document.export", &p).unwrap())).unwrap(); + assert_eq!(plot, "IN;PU;SP2;PU-141,141;PD-564,141,-564,564,-141,564,-141,141;PU;SP0;"); +} + +/// `insideFirst` draws the square inside the other one first, though it was made last. +#[test] +fn inside_first_draws_the_inner_square_first() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 80, "height": 80})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 30, "y": 30, "width": 20, "height": 20})).unwrap(); + let starts = |s: &mut Session, p: Value| { + let plot = String::from_utf8(bytes(&s.execute("document.export", &p).unwrap())).unwrap(); + (plot.find("PU141,1270;").unwrap(), plot.find("PU423,988;").unwrap()) + }; + let (outer, inner) = starts(&mut s, json!({"format": "hpgl"})); + assert!(outer < inner); + let (outer, inner) = starts(&mut s, json!({"format": "hpgl", "insideFirst": true})); + assert!(inner < outer); +} + +/// Export Selection plots the selected square alone (the red one, made last), from the +/// bottom-left corner of its bounds. +#[test] +fn export_selection_writes_a_plot_of_the_selection() { + let mut s = two_boards(); + let r = s.execute("document.exportSelection", &json!({"format": "hpgl"})).unwrap(); + assert_eq!(r["format"], "hpgl"); + let plot = String::from_utf8(bytes(&r)).unwrap(); + assert_eq!(plot.matches("PD").count(), 1, "{plot}"); + assert!(plot.starts_with("IN;PU;SP1;PU7,430;PD"), "{plot}"); +} diff --git a/crates/engine/src/cmd/fileio/tests_pdf.rs b/crates/engine/src/cmd/fileio/tests_pdf.rs index 6f47307290..91fe9701e7 100644 --- a/crates/engine/src/cmd/fileio/tests_pdf.rs +++ b/crates/engine/src/cmd/fileio/tests_pdf.rs @@ -56,6 +56,126 @@ fn export_pdf_writes_the_compatibility_header_and_the_range() { assert!(b64(&v).starts_with(b"%PDF-1.6")); } +/// `useArtboards: false` writes one page, the bounds of the visible art, as `document.export` +/// does, whatever artboards are chosen. Art longer than 200 in keeps its size with +/// `longPagesInPoints`. A document with no visible art and a value that isn't a boolean are +/// refused. +#[test] +fn use_artboards_false_writes_one_page_of_the_arts_bounds() { + let mut s = session(3); + let page = |bytes: &[u8]| { + let d = vectorcraft_pdf::import(bytes).unwrap(); + (d.artboards.len(), d.artboards[0].rect.size()) + }; + let through_export = page(&b64(&s.execute("document.export", &as_export(&json!({"useArtboards": false}))).unwrap())); + assert!(through_export.0 == 1 && through_export.1.width < 50.0 && through_export.1.height < 40.0, "{through_export:?}"); + for p in [ + json!({"useArtboards": false}), + json!({"useArtboards": false, "range": "2"}), + json!({"useArtboards": false, "artboards": [0, 1]}), + json!({"useArtboards": false, "artboard": 2}), + ] { + assert_eq!(page(&b64(&export(&mut s, p.clone()))), through_export, "{p}"); + } + assert_eq!(pages(&b64(&export(&mut s, json!({"useArtboards": true})))), 3); + assert_eq!(pages(&b64(&export(&mut s, json!({"useArtboards": null})))), 3); + + // A 10 m drawing on a small artboard: its page is 10 m long, in points. + s.execute("shape.rectangle", &json!({"x": 0, "y": 200, "width": 28_346.46, "height": 100})).unwrap(); + let v = export(&mut s, json!({"useArtboards": false, "longPagesInPoints": true})); + let pdf = b64(&v); + let (n, size) = page(&pdf); + assert!(n == 1 && size.width > 28_346.0 && size.width < 28_350.0, "{size:?}"); + assert!(!String::from_utf8_lossy(&pdf).contains("/UserUnit")); + assert!(warnings(&v).iter().any(|w| w.contains("written without a UserUnit, in points")), "{v}"); + // The Summary's export in memory writes the same page. + let mut long = |p: Value| warnings(&s.execute("document.pdfSettings", &p).unwrap()).iter().any(|w| w.contains("longer than PDF's page limit")); + assert!(long(json!({"includeDocument": true, "useArtboards": false}))); + assert!(!long(json!({"includeDocument": true})), "the artboards are small"); + let e = s.execute("document.pdfSettings", &json!({"useArtboards": "no"})).unwrap_err(); + assert!(matches!(e, crate::EngineError::BadParams { .. }), "without includeDocument too: {e}"); + + s.execute("select.all", &json!({})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + for p in [json!({"useArtboards": false}), json!({"useArtboards": "no"})] { + let e = s.execute("document.exportPdf", &p).unwrap_err(); + assert!(matches!(e, crate::EngineError::BadParams { .. }), "{p}: {e}"); + } +} + +/// A PDF of the art's bounds carries no Preserve Editing data, through `document.exportPdf`, +/// `document.export` and the Summary's export in memory, and says so in a warning: reopened, its +/// editing data would replace the document's artboards with the one around the art. A PDF of the +/// artboards keeps the data, and it reopens with every artboard. With Preserve Editing off, there +/// is no warning. +#[test] +fn a_pdf_of_the_arts_bounds_carries_no_editing_data() { + let mut s = session(3); + let left_out = |v: &Value| warnings(v).iter().any(|w| w == super::pdf::EDITING_NEEDS_THE_ARTBOARDS); + let art = json!({"useArtboards": false}); + for v in [export(&mut s, art.clone()), s.execute("document.export", &as_export(&art)).unwrap()] { + let pdf = b64(&v); + assert!(vectorcraft_pdf::editing(&pdf).is_none(), "{:?}", warnings(&v)); + assert!(left_out(&v), "{:?}", warnings(&v)); + assert_eq!(pages(&pdf), 1); + } + let summary = s.execute("document.pdfSettings", &json!({"includeDocument": true, "useArtboards": false})).unwrap(); + assert!(left_out(&summary), "{summary}"); + let quiet = export(&mut s, json!({"useArtboards": false, "preserveEditing": false})); + assert!(!left_out(&quiet), "{:?}", warnings(&quiet)); + + for v in [export(&mut s, json!({})), export(&mut s, json!({"useArtboards": true}))] { + let editing = vectorcraft_pdf::editing(&b64(&v)).expect("editing data"); + let reopened = vectorcraft_format::load(&editing.data).unwrap(); + assert_eq!(reopened.artboards.len(), 3); + assert!(!left_out(&v), "{:?}", warnings(&v)); + } +} + +/// While an opacity mask is edited, a PDF of the art's bounds measures the art without the +/// editing layer, as `document.export` does: a mask shape drawn past the masked object doesn't +/// widen the page. +#[test] +fn a_pdf_of_the_art_leaves_out_the_mask_editing_layer() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap(); + let obj = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 200, "height": 200})).unwrap()["id"].clone(); + let mask = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 200})).unwrap()["id"].clone(); + s.execute("paint.setFill", &json!({"color": "#ffffff", "ids": [mask]})).unwrap(); + s.execute("select.set", &json!({"ids": [obj, mask]})).unwrap(); + s.execute("transparency.makeOpacityMask", &json!({})).unwrap(); + s.execute("transparency.editOpacityMask", &json!({})).unwrap(); + s.execute("shape.ellipse", &json!({"x": 250, "y": 250, "width": 40, "height": 40})).unwrap(); + assert!(s.doc().unwrap().doc.mask_edit.is_some()); + let width = |bytes: &[u8]| vectorcraft_pdf::import(bytes).unwrap().artboards[0].rect.width(); + let through_export = width(&b64(&s.execute("document.export", &as_export(&json!({"useArtboards": false}))).unwrap())); + assert!(through_export < 250.0, "{through_export}"); + assert_eq!(width(&b64(&export(&mut s, json!({"useArtboards": false})))), through_export); +} + +/// While an opacity mask is edited, a PDF of the artboards leaves out the editing layer too, as +/// `document.export` does: from the drawn page and from the Preserve Editing data. +#[test] +fn a_pdf_of_the_artboards_leaves_out_the_mask_editing_layer() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap(); + let obj = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 200, "height": 200})).unwrap()["id"].clone(); + let mask = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 200})).unwrap()["id"].clone(); + s.execute("paint.setFill", &json!({"color": "#ffffff", "ids": [mask]})).unwrap(); + s.execute("select.set", &json!({"ids": [obj, mask]})).unwrap(); + s.execute("transparency.makeOpacityMask", &json!({})).unwrap(); + s.execute("transparency.editOpacityMask", &json!({})).unwrap(); + s.execute("shape.ellipse", &json!({"x": 250, "y": 250, "width": 40, "height": 40})).unwrap(); + assert!(s.doc().unwrap().doc.mask_edit.is_some()); + let nodes = |bytes: &[u8]| vectorcraft_pdf::import(bytes).unwrap().node_count(); + let plain = json!({"preserveEditing": false}); + let through_export = nodes(&b64(&s.execute("document.export", &as_export(&plain)).unwrap())); + assert_eq!(nodes(&b64(&export(&mut s, plain))), through_export, "the drawn page"); + let layers = |v: &Value| vectorcraft_format::load(&vectorcraft_pdf::editing(&b64(v)).unwrap().data).unwrap().layers; + let through_export = layers(&s.execute("document.export", &as_export(&json!({}))).unwrap()); + assert_eq!(layers(&export(&mut s, json!({}))), through_export, "the Preserve Editing data"); +} + #[test] fn bad_options_are_refused() { let mut s = session(2); diff --git a/crates/engine/src/cmd/fileio/tests_pdfedit.rs b/crates/engine/src/cmd/fileio/tests_pdfedit.rs index 2970238e38..b7b0ddde59 100644 --- a/crates/engine/src/cmd/fileio/tests_pdfedit.rs +++ b/crates/engine/src/cmd/fileio/tests_pdfedit.rs @@ -15,9 +15,8 @@ fn open(s: &mut Session, name: &str, bytes: &[u8]) -> Value { s.execute("document.open", &json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(bytes)})).unwrap() } -fn tmp(name: &str) -> String { - let dir = std::env::temp_dir().join(format!("vc-pdfedit-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); +/// The path of `name` in the test's folder `dir`. +fn tmp(dir: &std::path::Path, name: &str) -> String { dir.join(name).to_string_lossy().to_string() } @@ -114,8 +113,9 @@ fn the_legacy_payload_name_is_accepted() { #[test] fn ai_files_are_pdfs_that_save_and_reopen_editable() { + let scratch = vectorcraft_testkit::TempDir::new("pdfedit"); let mut s = rich(); - let path = tmp("art.ai"); + let path = tmp(&scratch, "art.ai"); let r = s.execute("document.save", &json!({"path": path, "preserveEditing": false, "range": "1"})).unwrap(); assert_eq!(r["path"], path.as_str()); // As saved (Save stamps the File Info dates). @@ -134,11 +134,11 @@ fn ai_files_are_pdfs_that_save_and_reopen_editable() { let again = vectorcraft_pdf::editing(&std::fs::read(&path).unwrap()).unwrap(); assert_eq!(vectorcraft_format::load(&again.data).unwrap().layers, s.doc().unwrap().doc.layers); // Save As also writes a plain PDF (the document then saves back as PDF); PNG stays an export. - assert_eq!(s.execute("document.save", &json!({"path": tmp("x.pdf")})).unwrap()["format"], "pdf"); - assert!(s.execute("document.save", &json!({"path": tmp("x.png")})).is_err(), "PNG is written with document.export"); + assert_eq!(s.execute("document.save", &json!({"path": tmp(&scratch, "x.pdf")})).unwrap()["format"], "pdf"); + assert!(s.execute("document.save", &json!({"path": tmp(&scratch, "x.png")})).is_err(), "PNG is written with document.export"); // A plain PDF named .ai opens as artwork, without a path to save over. let plain = b64(&s.execute("document.exportPdf", &json!({"preserveEditing": false})).unwrap()); - let plain_path = tmp("plain.ai"); + let plain_path = tmp(&scratch, "plain.ai"); std::fs::write(&plain_path, plain).unwrap(); let r = s.execute("document.open", &json!({"path": plain_path})).unwrap(); assert_eq!(r["restored"], false); @@ -149,9 +149,10 @@ fn ai_files_are_pdfs_that_save_and_reopen_editable() { /// As does, leaving the document's own path alone. #[test] fn exports_write_ai_as_save_as_does() { + let scratch = vectorcraft_testkit::TempDir::new("pdfedit"); let mut s = rich(); let before = comparable(&s.doc().unwrap().doc); - let path = tmp("exported.ai"); + let path = tmp(&scratch, "exported.ai"); let r = s.execute("document.export", &json!({"path": path})).unwrap(); assert_eq!(r["format"], "ai", "{r}"); let bytes = std::fs::read(&path).unwrap(); @@ -225,12 +226,13 @@ fn ait_templates_open_their_document_untitled() { /// from Template opens it as an untitled copy of the document, layers and art included. #[test] fn save_as_template_writes_an_ait_that_new_from_template_opens_untitled() { + let scratch = vectorcraft_testkit::TempDir::new("pdfedit"); let mut s = rich(); s.execute("layer.new", &json!({"name": "Notes"})).unwrap(); s.execute("shape.ellipse", &json!({"x": 20, "y": 120, "width": 40, "height": 30})).unwrap(); let before = comparable(&s.doc().unwrap().doc); assert_eq!(before.layers.len(), 2); - let path = tmp("brochure template.ait"); + let path = tmp(&scratch, "brochure template.ait"); let r = s.execute("file.saveAsTemplate", &json!({"path": path})).unwrap(); assert_eq!(r["format"], "ait", "{r}"); let bytes = std::fs::read(&path).unwrap(); @@ -253,6 +255,7 @@ fn save_as_template_writes_an_ait_that_new_from_template_opens_untitled() { /// writes a `.ait`. #[test] fn save_as_template_names_its_file_after_the_template_format() { + let scratch = vectorcraft_testkit::TempDir::new("pdfedit"); let mut s = rich(); for (name, format, saved) in [ ("card.png", None, "card.vctemplate"), @@ -261,7 +264,7 @@ fn save_as_template_names_its_file_after_the_template_format() { ("card.pdf", Some("ait"), "card.ait"), ("card v1.2", None, "card v1.2.vctemplate"), ] { - let (typed, want) = (tmp(&format!("named/{name}")), tmp(&format!("named/{saved}"))); + let (typed, want) = (tmp(&scratch, &format!("named/{name}")), tmp(&scratch, &format!("named/{saved}"))); let _ = std::fs::create_dir_all(std::path::Path::new(&typed).parent().unwrap()); let _ = std::fs::remove_file(&typed); let _ = std::fs::remove_file(&want); @@ -273,7 +276,7 @@ fn save_as_template_names_its_file_after_the_template_format() { assert!(ait || vectorcraft_format::load(&bytes).is_ok_and(|d| d.template), "{name}: a native template"); assert!(!std::path::Path::new(&typed).exists(), "{name}: nothing written under the typed name"); } - for (cmd, p) in [("file.saveAs", json!({"format": "ait"})), ("document.save", json!({"path": tmp("card.ait")}))] { + for (cmd, p) in [("file.saveAs", json!({"format": "ait"})), ("document.save", json!({"path": tmp(&scratch, "card.ait")}))] { let e = s.execute(cmd, &p).unwrap_err().to_string(); assert!(e.contains("file.saveAsTemplate") && !e.contains("document.export"), "{cmd}: {e}"); } @@ -284,8 +287,9 @@ fn save_as_template_names_its_file_after_the_template_format() { /// nothing writes keeps its own error. #[test] fn exports_of_an_ait_name_save_as_template() { + let scratch = vectorcraft_testkit::TempDir::new("pdfedit"); let mut s = rich(); - let path = tmp("exported.ait"); + let path = tmp(&scratch, "exported.ait"); let _ = std::fs::remove_file(&path); for (cmd, p) in [ ("document.export", json!({"path": path})), @@ -305,8 +309,9 @@ fn exports_of_an_ait_name_save_as_template() { /// file; `aiVersion` "pdf" writes the PDF-compatible template. #[test] fn save_as_template_refuses_a_legacy_ait() { + let scratch = vectorcraft_testkit::TempDir::new("pdfedit"); let mut s = rich(); - let path = tmp("legacy-ait/card.ait"); + let path = tmp(&scratch, "legacy-ait/card.ait"); let dir = std::path::Path::new(&path).parent().unwrap().to_path_buf(); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); @@ -402,28 +407,76 @@ fn ai_export_validates_options_even_when_editing_data_is_omitted() { } } -#[test] -fn ai_export_without_artboards_keeps_art_outside_the_original_pages() { +/// Two artboards, a visible 30 × 20 pt rectangle outside them at (180, 100) and a hidden one. +fn art_outside_the_artboards() -> Session { let mut s = Session::new(); s.execute("file.new", &json!({"width": 100, "height": 80, "artboards": 2})).unwrap(); s.execute("paint.setStroke", &json!({"none": true})).unwrap(); s.execute("shape.rectangle", &json!({"x": 180, "y": 100, "width": 30, "height": 20})).unwrap(); s.execute("shape.rectangle", &json!({"x": 1000, "y": 1000, "width": 50, "height": 40})).unwrap(); s.execute("object.hide", &json!({})).unwrap(); + s +} + +/// Whether the `.ai` file `bytes` carries the editing copy of its art for other apps. +fn carries_private_data(bytes: &[u8]) -> bool { + let opts = LoadOptions { native: false, ..Default::default() }; + load::load_with("a.ai", bytes, &opts).unwrap().editing_data +} + +#[test] +fn an_ai_of_the_arts_bounds_carries_no_editing_data() { + let mut s = art_outside_the_artboards(); let before = comparable(&s.doc().unwrap().doc); - let r = s.execute("document.export", &json!({"format": "ai", "useArtboards": false, "range": "2"})).unwrap(); - let bytes = b64(&r); - let pages = vectorcraft_pdf::import(&bytes).unwrap(); - assert_eq!(pages.artboards.len(), 1); - assert_eq!((pages.artboards[0].rect.width(), pages.artboards[0].rect.height()), (30.0, 20.0)); - let editing = vectorcraft_pdf::editing(&bytes).unwrap(); - let exported = vectorcraft_format::load(&editing.data).unwrap(); - assert_eq!(exported.artboards.len(), 1); - assert_eq!(exported.artboards[0].rect, vectorcraft_geom::Rect::new(180.0, 100.0, 210.0, 120.0)); - assert_eq!(comparable(&s.doc().unwrap().doc), before); + let left_out = |v: &Value| v["warnings"].as_array().unwrap().iter().any(|w| w == super::save::AI_EDITING_NEEDS_THE_ARTBOARDS); + let scratch = vectorcraft_testkit::TempDir::new("pdfedit"); + let path = tmp(&scratch, "art-bounds.ai"); + for extra in [json!({}), json!({"range": "2"}), json!({"editingData": false}), json!({"path": path})] { + let mut params = json!({"format": "ai", "useArtboards": false}); + params.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + let r = s.execute("document.export", ¶ms).unwrap(); + let bytes = if params.get("path").is_some() { std::fs::read(&path).unwrap() } else { b64(&r) }; + // One page, the visible art's bounds, whatever range names. + let pages = vectorcraft_pdf::import(&bytes).unwrap(); + assert_eq!(pages.artboards.len(), 1, "{params}"); + assert_eq!((pages.artboards[0].rect.width(), pages.artboards[0].rect.height()), (30.0, 20.0), "{params}"); + assert!(vectorcraft_pdf::editing(&bytes).is_none(), "{params}"); + assert!(!carries_private_data(&bytes), "{params}"); + assert!(left_out(&r), "{params}: {r}"); + assert_eq!(comparable(&s.doc().unwrap().doc), before); + } + // The artboards keep both editing copies, without the warning. + for params in [json!({"format": "ai"}), json!({"format": "ai", "useArtboards": true})] { + let r = s.execute("document.export", ¶ms).unwrap(); + let bytes = b64(&r); + let editing = vectorcraft_pdf::editing(&bytes).expect("editing data"); + assert_eq!(vectorcraft_format::load(&editing.data).unwrap().artboards.len(), 2, "{params}"); + assert!(carries_private_data(&bytes), "{params}"); + assert!(!left_out(&r), "{params}: {r}"); + } assert!(s.execute("document.export", &json!({"format": "ai", "useArtboards": "yes"})).is_err()); } +#[test] +fn an_ai_of_the_arts_bounds_without_pdf_is_refused() { + let mut s = art_outside_the_artboards(); + let before = comparable(&s.doc().unwrap().doc); + for extra in [json!({}), json!({"editingData": false}), json!({"editingData": true})] { + for command in ["document.export", "document.serialize"] { + let mut params = json!({"format": "ai", "useArtboards": false, "pdfCompatible": false}); + params.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + let e = s.execute(command, ¶ms).unwrap_err().to_string(); + assert!(e.contains(super::save::ART_PAGE_NEEDS_PDF), "{command} {params}: {e}"); + assert_eq!(comparable(&s.doc().unwrap().doc), before); + } + } + // A document with no visible art is still refused for that. + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 80})).unwrap(); + let e = s.execute("document.export", &json!({"format": "ai", "useArtboards": false})).unwrap_err().to_string(); + assert!(e.contains("no visible art"), "{e}"); +} + /// Color Halftone's Max Radius is in pixels of the raster effects resolution since document /// version 3 (#3260). A PDF saved with Preserve Editing carries the native document, so one from /// before that opens with the radius converted, drawing the same dots; one saved since opens as @@ -623,6 +676,7 @@ fn editing_copy(bytes: &[u8]) -> vectorcraft_doc::Document { /// writes the copy; the version 7 `.ai` keeps the compound path and the clipping group. #[test] fn transparency_clipping_and_opacity_masks_come_back_from_the_editing_copy() { + let scratch = vectorcraft_testkit::TempDir::new("pdfedit"); let mut s = see_through_session(); let before = (*s.doc().unwrap().doc).clone(); // The mask's art is one path, and it reads back as that path. @@ -635,7 +689,7 @@ fn transparency_clipping_and_opacity_masks_come_back_from_the_editing_copy() { assert_eq!(see_through_outline(&editing_copy(&bytes)), want, "{opts}"); } // Each artboard in a file of its own: the first holds all the art. - let path = tmp("see-through.ai"); + let path = tmp(&scratch, "see-through.ai"); let r = s.execute("document.save", &json!({"path": path, "separateArtboards": true})).unwrap(); let files: Vec<String> = r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap().to_string()).collect(); assert_eq!(files.len(), 3, "{r}"); @@ -765,7 +819,8 @@ fn image_outline(doc: &vectorcraft_doc::Document) -> Vec<String> { /// the linked image keeps its path and its path relative to the document's folder. #[test] fn images_come_back_from_the_editing_copy() { - let dir = tmp("ai-images"); + let scratch = vectorcraft_testkit::TempDir::new("pdfedit"); + let dir = tmp(&scratch, "ai-images"); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(format!("{dir}/art")).unwrap(); let png = |w: u32, h: u32, f: &dyn Fn(u32, u32) -> [u8; 4]| { @@ -835,6 +890,7 @@ fn type_outline(doc: &vectorcraft_doc::Document) -> Vec<String> { /// for other apps alone as type, with every save option that writes the copy. #[test] fn type_comes_back_from_the_editing_copy() { + let scratch = vectorcraft_testkit::TempDir::new("pdfedit"); let mut s = Session::new(); s.execute("file.new", &json!({"width": 300, "height": 200})).unwrap(); s.execute("text.create", &json!({"x": 20, "y": 40, "text": "Hello\nWorld", "size": 24})).unwrap(); @@ -842,7 +898,7 @@ fn type_comes_back_from_the_editing_copy() { // The new type is selected. s.execute("object.rotate", &json!({"angle": 30})).unwrap(); s.execute("text.create", &json!({"x": 20, "y": 120, "text": "Area type in a frame", "area": {"width": 120, "height": 60}})).unwrap(); - let path = tmp("type.ai"); + let path = tmp(&scratch, "type.ai"); s.execute("document.save", &json!({"path": path})).unwrap(); let before = type_outline(&s.doc().unwrap().doc); assert_eq!(before.len(), 3, "{before:#?}"); @@ -924,6 +980,7 @@ fn gradient_session() -> Session { /// gradient. #[test] fn gradients_and_patterns_come_back_from_the_editing_copy() { + let scratch = vectorcraft_testkit::TempDir::new("pdfedit"); let mut s = gradient_session(); let before = (*s.doc().unwrap().doc).clone(); let want = paint_outline(&before); @@ -943,7 +1000,7 @@ fn gradients_and_patterns_come_back_from_the_editing_copy() { let copy = editing_copy(&b64(&r)); assert_eq!(paint_outline(©), want, "{opts}"); } - let path = tmp("gradients.ai"); + let path = tmp(&scratch, "gradients.ai"); let r = s.execute("document.save", &json!({"path": path, "separateArtboards": true})).unwrap(); let files: Vec<String> = r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap().to_string()).collect(); assert_eq!(files.len(), 3, "{r}"); diff --git a/crates/engine/src/cmd/fileio/tests_pdffidelity.rs b/crates/engine/src/cmd/fileio/tests_pdffidelity.rs index 86cb84cfcb..d3d8a988f8 100644 --- a/crates/engine/src/cmd/fileio/tests_pdffidelity.rs +++ b/crates/engine/src/cmd/fileio/tests_pdffidelity.rs @@ -59,7 +59,7 @@ fn live_texts(s: &Session) -> Vec<String> { #[test] fn pdf_place_keeps_live_text_from_bytes_and_unlinked_paths() { let bytes = live_text_pdf(); - let dir = vectorcraft_testkit::temp_dir("pdf-place-live-text"); + let dir = vectorcraft_testkit::TempDir::new("pdf-place-live-text"); let path = dir.join("text.pdf"); std::fs::write(&path, &bytes).unwrap(); for source in [json!({"name": "text.pdf", "dataBase64": vectorcraft_format::base64_encode(&bytes)}), json!({"path": path, "link": false})] { @@ -71,7 +71,6 @@ fn pdf_place_keeps_live_text_from_bytes_and_unlinked_paths() { assert_eq!(live_texts(&s), ["Second page"], "{r}"); assert!(!r["warnings"].to_string().contains("outlines"), "{r}"); } - std::fs::remove_dir_all(dir).unwrap(); } #[test] diff --git a/crates/engine/src/cmd/fileio/tests_pdfsecurity.rs b/crates/engine/src/cmd/fileio/tests_pdfsecurity.rs index d8c36a9196..09505391af 100644 --- a/crates/engine/src/cmd/fileio/tests_pdfsecurity.rs +++ b/crates/engine/src/cmd/fileio/tests_pdfsecurity.rs @@ -56,3 +56,21 @@ fn permissions_without_a_password_warn_and_a_password_applies_them() { let bytes = vectorcraft_format::base64_decode(locked["dataBase64"].as_str().unwrap()).unwrap(); assert!(String::from_utf8_lossy(&bytes).contains("/Encrypt")); } + +/// The writer notes the permissions it didn't apply before the export notes the type it drew in +/// the fallback font: the reply gives what the file loses first, through both commands. +#[test] +fn the_fallback_font_note_comes_before_the_permissions_note() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 80})).unwrap(); + s.execute("text.create", &json!({"x": 5, "y": 20, "text": "Ab", "font": "Nonexistent Sans Probe"})).unwrap(); + for r in [ + s.execute("document.exportPdf", &json!({"security": {"printing": "none"}})).unwrap(), + s.execute("document.export", &json!({"format": "pdf", "security": {"printing": "none"}})).unwrap(), + ] { + let warnings: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + let at = |s: &str| warnings.iter().position(|w| w.contains(s)); + let (font, permissions) = (at("Nonexistent Sans Probe"), at("permissions need a password")); + assert!(font.is_some() && permissions.is_some() && font < permissions, "{warnings:?}"); + } +} diff --git a/crates/engine/src/cmd/fileio/tests_pict.rs b/crates/engine/src/cmd/fileio/tests_pict.rs new file mode 100644 index 0000000000..513adffbef --- /dev/null +++ b/crates/engine/src/cmd/fileio/tests_pict.rs @@ -0,0 +1,104 @@ +//! PICT pictures through the commands: `document.open` by extension or by content, File › Place as +//! one group clipped to the picture's frame, the dialogs' filters and the format list, and files +//! that aren't pictures, or a PICT export, refused with a message. + +use serde_json::json; +use vectorcraft_doc::NodeKind; + +use super::*; + +fn b64(bytes: &[u8]) -> String { + vectorcraft_format::base64_encode(bytes) +} + +/// A version 2 PICT file of a 200 × 100 pt frame: a red rectangle and a line. +fn picture() -> Vec<u8> { + let words = |v: &[i16]| v.iter().flat_map(|x| x.to_be_bytes()).collect::<Vec<u8>>(); + let mut b = vec![0; 512]; + b.extend(words(&[0, 0, 0, 100, 200])); + b.extend([0x00, 0x11, 0x02, 0xFF, 0x0C, 0x00]); + b.extend(words(&[-1, 0])); + b.extend([0; 20]); + b.extend(words(&[0x1A, -1, 0, 0, 0x31, 10, 20, 50, 80, 0x20, 70, 10, 70, 190, 0xFF])); + b +} + +#[test] +fn document_open_reads_a_picture() { + let mut s = Session::new(); + let r = s.execute("document.open", &json!({"name": "logo.pct", "dataBase64": b64(&picture())})).unwrap(); + assert_eq!((r["format"].as_str(), r["title"].as_str()), (Some("pict"), Some("logo.pct")), "{r}"); + assert_eq!(r["warnings"], json!([])); + let st = s.doc().unwrap(); + assert_eq!(st.doc.artboards[0].rect.size(), (200.0, 100.0).into()); + let mut paths = vec![]; + st.doc.walk(|n| { + if let NodeKind::Path { .. } = n.kind { + paths.push(n.clone()); + } + }); + assert_eq!(paths.len(), 2); + let b = paths[0].geometric_bounds().unwrap(); + assert!((b.x0 - 20.0).abs() < 1e-9 && (b.width() - 60.0).abs() < 1e-9, "{b:?}"); + // Opened as artwork: Save asks for a name. + assert!(st.path.is_none()); + + // A picture opens by its content under a name no format reads, and in each of its names. + for name in ["logo.PICT", "logo.pic", "logo.bin", "logo"] { + let r = Session::new().execute("document.open", &json!({"name": name, "dataBase64": b64(&picture())})).unwrap(); + assert_eq!(r["format"].as_str(), Some("pict"), "{name}: {r}"); + } + assert_eq!(detect("logo.dat", &picture()).map(|f| f.id), Some("pict")); + assert_eq!(detect("bare.dat", &picture()[512..]).map(|f| f.id), Some("pict")); +} + +#[test] +fn file_place_places_a_picture_as_one_clipped_group() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap(); + let p = json!({"name": "logo.pct", "dataBase64": b64(&picture()), "at": [150, 150]}); + let info = s.execute("file.place.info", &p).unwrap(); + assert_eq!(info["format"], "pict", "{info}"); + assert!((info["width"].as_f64().unwrap() - 200.0).abs() < 1e-9, "{info}"); + let r = s.execute("file.place", &p).unwrap(); + assert_eq!((&r["format"], r["ids"].as_array().map(Vec::len)), (&json!("pict"), Some(1)), "{r}"); + let doc = &s.doc().unwrap().doc; + let group = doc.node(vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap())).unwrap(); + assert_eq!(group.name.as_deref(), Some("logo.pct")); + let NodeKind::Group { clip: true, .. } = &group.kind else { panic!("a clipping group, got {:?}", group.kind) }; + let b = group.geometric_bounds().unwrap(); + assert!((b.width() - 200.0).abs() < 1e-6 && (b.height() - 100.0).abs() < 1e-6, "{b:?}"); +} + +#[test] +fn files_that_are_not_pictures_are_refused() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + let e = s.execute("document.open", &json!({"name": "old.pct", "dataBase64": b64(&[0; 600])})).expect_err("refused"); + assert!(e.to_string().contains("not a PICT file"), "{e}"); + assert_eq!(s.doc().unwrap().doc.artboards[0].rect.size(), (100.0, 50.0).into()); + assert!(s.execute("file.place", &json!({"name": "old.pct", "dataBase64": b64(&[0; 600])})).is_err()); + // Other formats' files aren't taken for pictures by their content. + // A file that starts with a PNG signature and holds a picture's version opcodes at byte 522. + let mut png = b"\x89PNG\r\n\x1a\n".to_vec(); + png.extend(&picture()[8..]); + assert!(detect("x.png", &png).is_none_or(|f| f.id != "pict")); + let e = s.execute("document.export", &json!({"format": "pict"})).expect_err("refused").to_string(); + assert!(e.contains("PICT files can be opened but not written"), "{e}"); +} + +#[test] +fn the_dialogs_and_the_format_list_name_pict() { + let exts = ["pct", "pic", "pict"]; + for e in exts { + assert!(OPEN_EXTS.contains(&e) && PLACE_EXTS.contains(&e) && UNASSOCIATED_EXTS.contains(&e), "{e}"); + assert_eq!(format_for_name(&format!("a.{e}")).map(|f| f.id), Some("pict"), "{e}"); + } + let filter = ("PICT", &exts[..]); + assert!(open_filters().any(|f| f == filter) && place_filters().any(|f| f == filter)); + let r = Session::new().execute("document.formats", &json!({})).unwrap(); + let f = r["formats"].as_array().unwrap().iter().find(|f| f["id"] == "pict").unwrap().clone(); + assert_eq!((f["read"].as_bool(), f["write"].as_bool(), f["raster"].as_bool()), (Some(true), Some(false), Some(false)), "{f}"); + assert_eq!(f["mime"], "image/x-pict"); + assert!(writable_format(None, Some("x/logo.pct")).is_err()); +} diff --git a/crates/engine/src/cmd/fileio/tests_psdlayers.rs b/crates/engine/src/cmd/fileio/tests_psdlayers.rs new file mode 100644 index 0000000000..31f670d7ff --- /dev/null +++ b/crates/engine/src/cmd/fileio/tests_psdlayers.rs @@ -0,0 +1,1017 @@ +//! Opening PSD and PSB files with their layers as layers (`document.open`'s `layers` and +//! `hiddenLayers`): names, visibility, opacity, blend modes, groups, layer masks, clipped layers +//! and blend modes VectorCraft lacks merged, 16-bit and PSB files, VectorCraft's own PSD export +//! read back, and damaged files read without a panic. + +use serde_json::{Value, json}; +use vectorcraft_color::BlendMode; +use vectorcraft_doc::{Node, NodeKind}; + +use super::*; + +/// One layer record of a synthetic file. +#[derive(Clone)] +struct L { + name: &'static str, + /// Top, left, bottom, right. + rect: [i32; 4], + /// Red, green, blue and alpha, the same for every pixel. + rgba: [u8; 4], + blend: &'static [u8; 4], + opacity: u8, + clipped: bool, + hidden: bool, + divider: Option<u32>, + /// Rect, default color, flags and the mask's pixels. + mask: Option<([i32; 4], u8, u8, Vec<u8>)>, + /// Extra tagged blocks. + blocks: Vec<([u8; 4], Vec<u8>)>, + /// Zipped channels: with prediction when `true`. + zip: Option<bool>, + /// The record lists no channels, whatever its rect. + bare: bool, + /// The Pascal name's bytes, with no Unicode name block. + legacy: Option<&'static [u8]>, +} + +fn layer(name: &'static str, rect: [i32; 4], rgba: [u8; 4]) -> L { + L { + name, + rect, + rgba, + blend: b"norm", + opacity: 255, + clipped: false, + hidden: false, + divider: None, + mask: None, + blocks: vec![], + zip: None, + bare: false, + legacy: None, + } +} + +fn group_end() -> L { + L { divider: Some(3), ..layer("</Layer group>", [0; 4], [0; 4]) } +} + +fn group(name: &'static str, blend: &'static [u8; 4]) -> L { + L { divider: Some(1), blend, ..layer(name, [0; 4], [0; 4]) } +} + +/// A tagged block, its length padded to even. +fn block(key: &[u8; 4], data: &[u8], psb: bool) -> Vec<u8> { + let mut data = data.to_vec(); + data.resize(data.len().next_multiple_of(2), 0); + let mut b = b"8BIM".to_vec(); + b.extend(key); + if psb && matches!(key, b"Lr16" | b"Lr32") { + b.extend((data.len() as u64).to_be_bytes()); + } else { + b.extend((data.len() as u32).to_be_bytes()); + } + b.extend(data); + b +} + +/// One row of a zipped channel with prediction: each sample stored as the difference from the one +/// before it, and in 32 bits the row's first bytes, then its second bytes and so on, each byte the +/// difference from the byte before it. +fn predict(row: &[u8], depth: u16) -> Vec<u8> { + let bytewise = |b: &[u8]| -> Vec<u8> { b.iter().scan(0u8, |prev, &v| Some(v.wrapping_sub(std::mem::replace(prev, v)))).collect() }; + match depth { + 16 => { + let mut prev = 0u16; + row.chunks(2) + .flat_map(|s| { + let v = u16::from_be_bytes([s[0], s[1]]); + v.wrapping_sub(std::mem::replace(&mut prev, v)).to_be_bytes() + }) + .collect() + } + 32 => bytewise(&(0..4).flat_map(|k| row.chunks(4).map(move |s| s[k])).collect::<Vec<_>>()), + _ => bytewise(row), + } +} + +/// A channel of `n` samples of `v` (in 32 bits, `v` / 255 as a float) at `depth`, raw, zipped +/// (with prediction when `zip` is `Some(true)`) or PackBits rows of `width` when `rle`. +fn channel(v: u8, n: usize, width: usize, depth: u16, rle: bool, psb: bool, zip: Option<bool>) -> Vec<u8> { + let sample = if depth == 32 { (f32::from(v) / 255.0).to_be_bytes().to_vec() } else { vec![v; usize::from(depth / 8)] }; + let row: Vec<u8> = std::iter::repeat_n(sample.as_slice(), width).flatten().copied().collect(); + if let Some(predicted) = zip { + let rows = n.checked_div(width).unwrap_or(0); + let one = if predicted { predict(&row, depth) } else { row }; + let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); + for _ in 0..rows { + std::io::Write::write_all(&mut z, &one).unwrap(); + } + let mut d = vec![0, if predicted { 3 } else { 2 }]; + d.extend(z.finish().unwrap()); + return d; + } + if !rle || n == 0 { + let mut d = vec![0, 0]; + d.extend(std::iter::repeat_n(sample.as_slice(), n).flatten()); + return d; + } + // Each row as literal runs of at most 128 bytes. + let mut packed = vec![]; + for run in row.chunks(128) { + packed.push((run.len() - 1) as u8); + packed.extend(run); + } + let rows = n / width; + let mut d = vec![0, 1]; + for _ in 0..rows { + if psb { + d.extend((packed.len() as u32).to_be_bytes()); + } else { + d.extend((packed.len() as u16).to_be_bytes()); + } + } + for _ in 0..rows { + d.extend(&packed); + } + d +} + +/// The layer info: the count (negative: the merged image has transparency), the records, then +/// their channels. +fn layer_info(layers: &[L], depth: u16, rle: bool, psb: bool) -> Vec<u8> { + let mut records: Vec<u8> = vec![]; + let mut data: Vec<u8> = vec![]; + for l in layers { + let [t, lf, b, r] = l.rect; + let (w, h) = ((r - lf).max(0) as usize, (b - t).max(0) as usize); + let mut channels: Vec<(i16, Vec<u8>)> = [(-1, l.rgba[3]), (0, l.rgba[0]), (1, l.rgba[1]), (2, l.rgba[2])] + .iter() + .filter(|_| !l.bare) + .map(|&(id, v)| (id, channel(v, w * h, w, depth, rle, psb, l.zip))) + .collect(); + let mut mask = vec![]; + if let Some(([mt, ml, mb, mr], default, flags, pixels)) = &l.mask { + let mut d = vec![0, 0]; + for &p in pixels { + d.extend(std::iter::repeat_n(p, usize::from(depth / 8))); + } + channels.push((-2, d)); + for v in [mt, ml, mb, mr] { + mask.extend(v.to_be_bytes()); + } + mask.extend([*default, *flags, 0, 0]); + } + for v in l.rect { + records.extend(v.to_be_bytes()); + } + records.extend((channels.len() as u16).to_be_bytes()); + for (id, d) in &channels { + records.extend(id.to_be_bytes()); + if psb { + records.extend((d.len() as u64).to_be_bytes()); + } else { + records.extend((d.len() as u32).to_be_bytes()); + } + data.extend(d); + } + records.extend(b"8BIM"); + records.extend(l.blend); + records.extend([l.opacity, u8::from(l.clipped), 0x08 | if l.hidden { 2 } else { 0 }, 0]); + let mut extra = (mask.len() as u32).to_be_bytes().to_vec(); + extra.extend(mask); + extra.extend(0u32.to_be_bytes()); + let ascii = l.legacy.unwrap_or(l.name.as_bytes()); + extra.push(ascii.len() as u8); + extra.extend(ascii); + // The Pascal string padded to a multiple of 4 (what comes before it is too). + extra.resize(extra.len().next_multiple_of(4), 0); + if l.legacy.is_none() { + let units: Vec<u16> = l.name.encode_utf16().collect(); + let mut luni = (units.len() as u32).to_be_bytes().to_vec(); + luni.extend(units.iter().flat_map(|u| u.to_be_bytes())); + extra.extend(block(b"luni", &luni, psb)); + } + if let Some(kind) = l.divider { + extra.extend(block(b"lsct", &[&kind.to_be_bytes()[..], b"8BIM", l.blend].concat(), psb)); + } + for (key, d) in &l.blocks { + extra.extend(block(key, d, psb)); + } + records.extend((extra.len() as u32).to_be_bytes()); + records.extend(extra); + } + let mut info = (-(layers.len() as i16)).to_be_bytes().to_vec(); + info.extend(records); + info.extend(data); + info.resize(info.len().next_multiple_of(2), 0); + info +} + +/// An RGB document of `w` × `h` pixels at 72 ppi holding `layers` (bottom first). 16- and 32-bit +/// documents keep their layers in an `Lr16` or `Lr32` block. +fn file(w: u32, h: u32, layers: &[L], depth: u16, rle: bool, psb: bool) -> Vec<u8> { + let info = layer_info(layers, depth, rle, psb); + let length = |n: usize, out: &mut Vec<u8>| { + if psb { + out.extend((n as u64).to_be_bytes()); + } else { + out.extend((n as u32).to_be_bytes()); + } + }; + let mut section = vec![]; + if depth == 8 { + length(info.len(), &mut section); + section.extend(info); + section.extend(0u32.to_be_bytes()); + } else { + length(0, &mut section); + section.extend(0u32.to_be_bytes()); + section.extend(block(if depth == 32 { b"Lr32" } else { b"Lr16" }, &info, psb)); + } + let mut f = b"8BPS".to_vec(); + f.extend(if psb { 2u16 } else { 1 }.to_be_bytes()); + f.extend([0; 6]); + f.extend(4u16.to_be_bytes()); + f.extend(h.to_be_bytes()); + f.extend(w.to_be_bytes()); + f.extend(depth.to_be_bytes()); + f.extend(3u16.to_be_bytes()); + f.extend(0u32.to_be_bytes()); + f.extend(0u32.to_be_bytes()); + length(section.len(), &mut f); + f.extend(section); + // The merged image: raw, mid gray, opaque. + f.extend([0, 0]); + let n = (w * h) as usize * usize::from(depth / 8); + f.extend(std::iter::repeat_n(128, n * 3)); + f.extend(std::iter::repeat_n(255, n)); + f +} + +/// The warning for one hidden layer left out. +const HIDDEN_1: &str = "1 layer was left out (hidden layers and the layers clipped to them)"; + +fn open(f: &[u8], p: Value) -> (Session, Value) { + let mut s = Session::new(); + let r = s.execute("document.open", &merge(json!({"name": "layers.psd", "dataBase64": vectorcraft_format::base64_encode(f)}), p)).unwrap(); + (s, r) +} + +fn name(n: &Node) -> &str { + n.name.as_deref().unwrap_or("") +} + +/// The layer's one image, named as the layer: its place (points) and its pixels. +fn image_of(s: &Session, l: &Node) -> ((f64, f64), image::RgbaImage) { + let Some([c]) = l.children().map(Vec::as_slice) else { panic!("{} holds {:?}", name(l), l.children().map(Vec::len)) }; + assert_eq!(name(c), name(l)); + pixels_of(s, c) +} + +/// An image's place (points) and its pixels. +fn pixels_of(s: &Session, c: &Node) -> ((f64, f64), image::RgbaImage) { + let NodeKind::Image(img) = &c.kind else { panic!("{} isn't an image", name(c)) }; + let blob = &s.doc().unwrap().doc.images[&img.key]; + let px = image::load_from_memory(&blob.bytes).unwrap().to_rgba8(); + assert_eq!((px.width(), px.height()), (img.width, img.height)); + let o = img.xf * kurbo::Point::ZERO; + ((o.x, o.y), px) +} + +/// Bottom, a pass-through group of a multiply layer at 50 % and a hidden layer, a screen group, and +/// a layer at 40 % fill opacity. +fn stack() -> Vec<L> { + let mut fill = layer("Faded", [1, 1, 3, 3], [0, 0, 255, 255]); + fill.blocks.push((*b"iOpa", vec![102])); + vec![ + layer("Bottom", [0, 0, 8, 8], [255, 0, 0, 255]), + group_end(), + L { blend: b"mul ", opacity: 128, ..layer("Inner A", [0, 0, 4, 4], [0, 255, 0, 255]) }, + L { hidden: true, ..layer("Inner B", [4, 4, 8, 8], [0, 0, 255, 255]) }, + group("Folder", b"pass"), + group_end(), + layer("Lit", [2, 2, 6, 6], [10, 20, 30, 128]), + group("Screens", b"scrn"), + fill, + ] +} + +#[test] +fn layers_open_as_layers_with_their_names_visibility_opacity_and_blend_modes() { + let (s, r) = open(&file(8, 8, &stack(), 8, false, false), json!({})); + assert_eq!((&r["format"], &r["warnings"]), (&json!("psd"), &json!([HIDDEN_1])), "{r}"); + let d = &s.doc().unwrap().doc; + assert!((d.artboards[0].rect.width() - 8.0).abs() < 1e-9 && (d.artboards[0].rect.height() - 8.0).abs() < 1e-9); + let names: Vec<&str> = d.layers.iter().map(|l| name(l)).collect(); + assert_eq!(names, ["Bottom", "Folder", "Screens", "Faded"], "bottom first"); + // The bottom layer's image covers the canvas in its color. + let ((x, y), px) = image_of(&s, &d.layers[0]); + assert_eq!(((x, y), px.dimensions(), px.get_pixel(3, 3).0), ((0.0, 0.0), (8, 8), [255, 0, 0, 255])); + // A pass-through group: a layer of sublayers that blend with what is below; its hidden layer + // is left out. + let folder = &d.layers[1]; + assert!(matches!(folder.kind, NodeKind::Layer { .. }) && !folder.isolate && folder.blend == BlendMode::Normal); + let inner: Vec<&str> = folder.children().unwrap().iter().map(|c| name(c)).collect(); + assert_eq!(inner, ["Inner A"]); + let a = &folder.children().unwrap()[0]; + assert!(a.blend == BlendMode::Multiply && (a.opacity - 128.0 / 255.0).abs() < 1e-6 && a.visible); + // Another group mode: isolated, in its mode; a layer keeps its transparency and place. + let screens = &d.layers[2]; + assert!(screens.isolate && screens.blend == BlendMode::Screen); + let ((x, y), px) = image_of(&s, &screens.children().unwrap()[0]); + assert_eq!(((x, y), px.dimensions(), px.get_pixel(0, 0).0), ((2.0, 2.0), (4, 4), [10, 20, 30, 128])); + // Fill opacity multiplies the opacity. + assert!((d.layers[3].opacity - 102.0 / 255.0).abs() < 1e-6, "{}", d.layers[3].opacity); + // Hidden layers come in hidden when asked for. + let (s, r) = open(&file(8, 8, &stack(), 8, false, false), json!({"hiddenLayers": true})); + assert_eq!(r["warnings"], json!([]), "{r}"); + let folder = &s.doc().unwrap().doc.layers[1]; + let inner: Vec<(&str, bool)> = folder.children().unwrap().iter().map(|c| (name(c), c.visible)).collect(); + assert_eq!(inner, [("Inner A", true), ("Inner B", false)]); + // `layers: false` opens the merged image, as before. + let (s, r) = open(&file(8, 8, &stack(), 8, false, false), json!({"layers": false})); + let d = &s.doc().unwrap().doc; + assert_eq!((d.layers.len(), d.layers[0].children().map(Vec::len)), (1, Some(1)), "{r}"); + assert_eq!(pixels_of(&s, &d.layers[0].children().unwrap()[0]).1.get_pixel(0, 0).0, [128, 128, 128, 255]); + let bad = Session::new().execute("document.open", &json!({"name": "a.psd", "dataBase64": "AAAA", "hiddenLayers": "yes"})); + assert!(bad.unwrap_err().to_string().contains("hiddenLayers must be true or false")); +} + +#[test] +fn sixteen_bit_packbits_and_psb_layers_read() { + for (depth, rle, psb) in [(16, false, false), (8, true, false), (8, true, true), (16, true, true)] { + let (s, r) = open(&file(8, 8, &stack(), depth, rle, psb), json!({})); + let d = &s.doc().unwrap().doc; + let names: Vec<&str> = d.layers.iter().map(|l| name(l)).collect(); + assert_eq!(names, ["Bottom", "Folder", "Screens", "Faded"], "{depth} {rle} {psb}: {r}"); + let px = image_of(&s, &d.layers[2].children().unwrap()[0]).1; + assert_eq!(px.get_pixel(1, 1).0, [10, 20, 30, 128], "{depth} {rle} {psb}"); + } +} + +/// Zipped channels, with and without prediction, at 8, 16 and 32 bits (32-bit colors are linear, +/// so the test uses 0 and 1, which sRGB's curve keeps). +#[test] +fn zipped_and_32_bit_layers_read() { + for depth in [8, 16, 32] { + for zip in [None, Some(false), Some(true)] { + if depth != 32 && zip.is_none() { + continue; + } + let layers = [L { zip, ..layer("Back", [0, 0, 4, 4], [0, 0, 255, 255]) }, L { zip, ..layer("Front", [1, 1, 3, 4], [255, 0, 255, 128]) }]; + let (s, r) = open(&file(4, 4, &layers, depth, false, false), json!({})); + let d = &s.doc().unwrap().doc; + let names: Vec<&str> = d.layers.iter().map(|l| name(l)).collect(); + assert_eq!(names, ["Back", "Front"], "{depth} {zip:?}: {r}"); + let ((x, y), px) = image_of(&s, &d.layers[1]); + assert_eq!(((x, y), px.dimensions(), px.get_pixel(2, 1).0), ((1.0, 1.0), (3, 2), [255, 0, 255, 128]), "{depth} {zip:?}"); + } + } +} + +/// A layer without a Unicode name takes the name its Pascal string holds, read as Mac Roman. +#[test] +fn names_without_a_unicode_name_read_as_mac_roman() { + let l = L { legacy: Some(b"Caf\x8E \xD2Old\xD3"), ..layer("", [0, 0, 1, 1], [0, 0, 0, 255]) }; + let (s, r) = open(&file(1, 1, &[l], 8, false, false), json!({})); + assert_eq!(name(&s.doc().unwrap().doc.layers[0]), "Café “Old”", "{r}"); +} + +#[test] +fn layer_masks_become_opacity_masks() { + let mut masked = layer("Masked", [0, 0, 8, 8], [255, 255, 255, 255]); + masked.mask = Some(([2, 2, 4, 4], 0, 0, vec![255, 128, 0, 255])); + let mut shown = layer("Shown outside", [0, 0, 8, 8], [0, 0, 0, 255]); + shown.mask = Some(([0, 0, 1, 2], 255, 0, vec![0, 0])); + let mut off = layer("Off", [0, 0, 8, 8], [0, 0, 0, 255]); + off.mask = Some(([0, 0, 1, 1], 0, 2, vec![0])); + // Flag bit 2: the mask's values and its default color are read inverted. + let mut inverted = layer("Inverted", [0, 0, 8, 8], [0, 0, 0, 255]); + inverted.mask = Some(([0, 0, 1, 2], 0, 4, vec![255, 64])); + let (s, _) = open(&file(8, 8, &[masked, shown, off, inverted], 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + let mask = |i: usize| d.layers[i].extras().mask.as_deref().expect("a mask"); + let m = mask(0); + assert!(m.clip && !m.disabled, "outside a mask with default 0 is hidden"); + let ((x, y), px) = pixels_of(&s, &m.art); + assert_eq!(((x, y), px.dimensions()), ((2.0, 2.0), (2, 2))); + assert_eq!([px.get_pixel(0, 0).0, px.get_pixel(1, 0).0, px.get_pixel(0, 1).0], [[255, 255, 255, 255], [128, 128, 128, 255], [0, 0, 0, 255]]); + assert!(!mask(1).clip, "outside a mask with default 255 shows"); + assert!(mask(2).disabled, "a disabled mask is kept, switched off"); + let m = mask(3); + assert!(!m.clip, "an inverted default of 0 shows outside the mask"); + let px = pixels_of(&s, &m.art).1; + assert_eq!([px.get_pixel(0, 0).0, px.get_pixel(1, 0).0], [[0, 0, 0, 255], [191, 191, 191, 255]]); +} + +#[test] +fn clipped_layers_merge_into_the_layer_below() { + let base = L { opacity: 200, ..layer("Base", [4, 4, 8, 8], [255, 255, 0, 255]) }; + let clipped = L { clipped: true, ..layer("Clipped", [0, 0, 8, 6], [0, 0, 255, 255]) }; + let hidden = L { clipped: true, hidden: true, ..layer("Gone", [0, 0, 8, 8], [0, 255, 0, 255]) }; + let (s, r) = + open(&file(8, 8, &[layer("Under", [0, 0, 2, 2], [1, 2, 3, 255]), base, clipped, hidden], 8, false, false), json!({"hiddenLayers": true})); + let d = &s.doc().unwrap().doc; + let names: Vec<&str> = d.layers.iter().map(|l| name(l)).collect(); + assert_eq!(names, ["Under", "Base + Clipped"], "{r}"); + assert_eq!(r["warnings"], json!([HIDDEN_1]), "a hidden clipped layer is left out: {r}"); + // The base keeps its place, transparency and opacity; the clipped layer shows only on it. + let merged = &d.layers[1]; + assert!((merged.opacity - 200.0 / 255.0).abs() < 1e-6); + let ((x, y), px) = image_of(&s, merged); + assert_eq!(((x, y), px.dimensions()), ((4.0, 4.0), (4, 4))); + assert_eq!((px.get_pixel(0, 0).0, px.get_pixel(3, 3).0), ([0, 0, 255, 255], [255, 255, 0, 255])); + // A base's layer mask stays the merged layer's opacity mask, over the unmasked pixels. + let mut masked = layer("Masked", [0, 0, 4, 4], [255, 255, 0, 255]); + masked.mask = Some(([0, 0, 1, 1], 0, 0, vec![255])); + let clipped = L { clipped: true, ..layer("Clipped", [0, 0, 4, 4], [0, 0, 255, 255]) }; + let (s, r) = open(&file(4, 4, &[masked, clipped], 8, false, false), json!({})); + let merged = &s.doc().unwrap().doc.layers[0]; + assert_eq!(name(merged), "Masked + Clipped", "{r}"); + assert!(merged.extras().mask.as_deref().is_some_and(|m| m.clip && !m.disabled), "{r}"); + let px = image_of(&s, merged).1; + assert_eq!((px.dimensions(), px.get_pixel(3, 3).0), ((4, 4), [0, 0, 255, 255])); + // A hidden base would need the merge: even with hidden layers asked for, it is left out with + // the layers clipped to it. + let hidden_base = L { hidden: true, ..layer("Hidden base", [0, 0, 4, 4], [255, 255, 0, 255]) }; + let clipped = L { clipped: true, ..layer("Clipped", [0, 0, 4, 4], [0, 0, 255, 255]) }; + let layers = [layer("Under", [0, 0, 2, 2], [1, 2, 3, 255]), hidden_base, clipped, layer("Over", [0, 0, 1, 1], [9, 9, 9, 255])]; + for hidden in [false, true] { + let (s, r) = open(&file(4, 4, &layers, 8, false, false), json!({"hiddenLayers": hidden})); + let names: Vec<&str> = s.doc().unwrap().doc.layers.iter().map(|l| name(l)).collect(); + assert_eq!(names, ["Under", "Over"], "{hidden}: {r}"); + assert_eq!(r["warnings"], json!(["2 layers were left out (hidden layers and the layers clipped to them)"]), "{hidden}: {r}"); + } +} + +/// A masked base merged with its clipped layers, then with a layer in a mode VectorCraft lacks, +/// still hides what its mask hides. +#[test] +fn a_merged_base_keeps_its_mask_in_a_later_merge() { + let mut masked = layer("Masked", [0, 0, 4, 4], [255, 0, 0, 255]); + masked.mask = Some(([0, 0, 1, 1], 0, 0, vec![255])); + let clipped = L { clipped: true, ..layer("Clipped", [0, 0, 4, 4], [0, 0, 255, 255]) }; + let dodge = L { blend: b"lddg", ..layer("Dodge", [3, 3, 4, 4], [0, 0, 0, 255]) }; + let layers = [layer("Bottom", [0, 0, 4, 4], [0, 255, 0, 255]), masked, clipped, dodge]; + let (s, r) = open(&file(4, 4, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(name(&d.layers[0]), "Bottom + Masked + Clipped + Dodge", "{r}"); + let px = image_of(&s, &d.layers[0]).1; + // Inside the mask the clipped layer shows; outside it, the layer below. + assert_eq!((px.get_pixel(0, 0).0, px.get_pixel(2, 2).0), ([0, 0, 255, 255], [0, 255, 0, 255])); +} + +#[test] +fn layers_in_modes_vectorcraft_lacks_merge_with_the_layers_below() { + let dodge = L { blend: b"lddg", ..layer("Dodge", [0, 0, 2, 2], [100, 100, 100, 255]) }; + let hidden = L { hidden: true, ..layer("Hidden", [0, 0, 8, 8], [0, 0, 0, 255]) }; + let layers = [layer("Bottom", [0, 0, 8, 8], [100, 50, 0, 255]), hidden, dodge, layer("Top", [6, 6, 8, 8], [0, 0, 0, 255])]; + let (s, r) = open(&file(8, 8, &layers, 8, false, false), json!({"hiddenLayers": true})); + let d = &s.doc().unwrap().doc; + let names: Vec<&str> = d.layers.iter().map(|l| name(l)).collect(); + assert_eq!(names, ["Bottom + Dodge", "Top"], "hidden layers a merge takes in are left out: {r}"); + let (_, px) = image_of(&s, &d.layers[0]); + // Linear Dodge adds: 100 + 100, 50 + 100, 0 + 100. + assert_eq!((px.get_pixel(0, 0).0, px.get_pixel(5, 5).0), ([200, 150, 100, 255], [100, 50, 0, 255])); + assert!(r["warnings"].to_string().contains("Linear Dodge"), "{r}"); + // Darker Color keeps the color whose channels add up to less: (0, 0, 200) over (100, 50, 0) + // has the larger total but the lower luminance, so the base stays. + let darker = L { blend: b"dkCl", ..layer("Darker", [0, 0, 2, 2], [0, 0, 200, 255]) }; + let (s, _) = open(&file(8, 8, &[layer("Bottom", [0, 0, 8, 8], [100, 50, 0, 255]), darker], 8, false, false), json!({})); + let (_, px) = image_of(&s, &s.doc().unwrap().doc.layers[0]); + assert_eq!(px.get_pixel(0, 0).0, [100, 50, 0, 255]); + // A hidden layer in such a mode would need the merge: left out, hidden layers asked for or not. + let hidden_dodge = L { hidden: true, blend: b"lddg", ..layer("Hidden dodge", [0, 0, 2, 2], [100, 100, 100, 255]) }; + let (s, r) = open(&file(8, 8, &[layer("Bottom", [0, 0, 8, 8], [100, 50, 0, 255]), hidden_dodge], 8, false, false), json!({"hiddenLayers": true})); + let names: Vec<&str> = s.doc().unwrap().doc.layers.iter().map(|l| name(l)).collect(); + assert_eq!((names, &r["warnings"]), (vec!["Bottom"], &json!([HIDDEN_1])), "{r}"); +} + +/// A merge whose canvases would need more memory than allowed leaves the layer in the Normal mode, +/// with a warning. +#[test] +fn a_merge_past_the_memory_allowed_leaves_the_layer_normal() { + let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; + let layers = [layer("Bottom", [0, 0, 2, 2], [100, 50, 0, 255]), L { blend: b"lddg", ..layer("Dodge", [2, 2, 4, 4], [100, 100, 100, 255]) }]; + let f = file(4, 4, &layers, 8, false, false); + // Each 2 × 2 layer fits 128 bytes (16 a pixel), and so does the first canvas of the merge with + // the layer beside it; the 4 × 4 canvas of both doesn't. + let (doc, warnings) = psdlayers::import(&f, false, 128, cms).unwrap().unwrap(); + let got: Vec<(&str, BlendMode)> = doc.layers.iter().map(|l| (name(l), l.blend)).collect(); + assert_eq!(got, [("Bottom", BlendMode::Normal), ("Dodge", BlendMode::Normal)]); + assert_eq!(warnings, ["1 layer in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed"]); + // With room for it, the merge is made. + let (doc, _) = psdlayers::import(&f, false, 1 << 20, cms).unwrap().unwrap(); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Bottom + Dodge"]); + // A merge onto a canvas that already covers the layer holds both: two 4 × 4 canvases take 512 + // bytes, past 300, although the canvas of the two 1 × 1 layers below fits (288 bytes). + let layers = [ + layer("Bottom", [0, 0, 1, 1], [100, 50, 0, 255]), + layer("Corner", [3, 3, 4, 4], [0, 50, 100, 255]), + L { blend: b"lddg", ..layer("Dodge", [0, 0, 4, 4], [100, 100, 100, 255]) }, + ]; + let f = file(4, 4, &layers, 8, false, false); + let (doc, warnings) = psdlayers::import(&f, false, 300, cms).unwrap().unwrap(); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Bottom", "Corner", "Dodge"]); + assert_eq!(warnings, ["1 layer in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed"]); + let (doc, _) = psdlayers::import(&f, false, 1 << 20, cms).unwrap().unwrap(); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Bottom + Corner + Dodge"]); + // A group below whose layers each fit, but whose canvas (4 × 4 with both 1 × 1 layers held, 288 + // bytes) doesn't fit 100: the layers stay, and the layer comes in Normal. + let layers = [ + group_end(), + layer("Left", [0, 0, 1, 1], [100, 50, 0, 255]), + layer("Right", [3, 3, 4, 4], [0, 50, 100, 255]), + group("Pair", b"norm"), + L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [100, 100, 100, 255]) }, + ]; + let f = file(4, 4, &layers, 8, false, false); + let (doc, warnings) = psdlayers::import(&f, false, 100, cms).unwrap().unwrap(); + let got: Vec<(&str, BlendMode)> = doc.layers.iter().map(|l| (name(l), l.blend)).collect(); + assert_eq!(got, [("Pair", BlendMode::Normal), ("Dodge", BlendMode::Normal)]); + assert_eq!(doc.layers[0].children().unwrap().iter().map(|c| name(c)).collect::<Vec<_>>(), ["Left", "Right"]); + assert_eq!(warnings, ["1 layer in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed"]); + let (doc, _) = psdlayers::import(&f, false, 1 << 20, cms).unwrap().unwrap(); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Pair + Dodge"]); + // A layer below whose pixels fit (128 bytes) but whose canvas (16 bytes a pixel, 256) doesn't + // fit 200: the same. + let layers = [layer("Big", [0, 0, 4, 4], [100, 50, 0, 255]), L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [100, 100, 100, 255]) }]; + let f = file(4, 4, &layers, 8, false, false); + let (doc, warnings) = psdlayers::import(&f, false, 200, cms).unwrap().unwrap(); + let got: Vec<(&str, BlendMode)> = doc.layers.iter().map(|l| (name(l), l.blend)).collect(); + assert_eq!(got, [("Big", BlendMode::Normal), ("Dodge", BlendMode::Normal)]); + assert_eq!(warnings, ["1 layer in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed"]); + // A clipped layer whose merge doesn't fit (the base's canvas and its transparency, 20 bytes a + // pixel, beside the clipped layer's canvas, 16: 576 bytes, past 300) comes in unclipped. + let layers = [layer("Base", [0, 0, 4, 4], [255, 0, 0, 255]), L { clipped: true, ..layer("Clipped", [0, 0, 4, 4], [0, 0, 255, 255]) }]; + let f = file(4, 4, &layers, 8, false, false); + let (doc, warnings) = psdlayers::import(&f, false, 300, cms).unwrap().unwrap(); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Base", "Clipped"]); + assert_eq!(warnings, ["1 layer clipped to the layer below came in unclipped: the merge needs more memory than allowed"]); + let (doc, _) = psdlayers::import(&f, false, 1 << 20, cms).unwrap().unwrap(); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Base + Clipped"]); +} + +/// A merge that can't be made counts nothing that the merges inside it counted: here the merge +/// in a group at half opacity fails inside the outer merge's attempt (the copy of what is below the +/// group takes the room) and succeeds when the group comes in. +#[test] +fn a_merge_that_cant_be_made_counts_only_itself() { + let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; + let layers = [ + layer("Under", [0, 0, 2, 2], [100, 50, 0, 255]), + group_end(), + layer("Inner", [0, 0, 2, 2], [10, 10, 10, 255]), + L { blend: b"lddg", ..layer("Dodge", [0, 0, 2, 2], [20, 20, 20, 255]) }, + L { opacity: 128, ..group("Pass", b"pass") }, + L { blend: b"diss", ..layer("Top", [0, 0, 2, 2], [0, 0, 0, 255]) }, + ]; + let (doc, warnings) = psdlayers::import(&file(2, 2, &layers, 8, false, false), false, 150, cms).unwrap().unwrap(); + let got: Vec<(&str, BlendMode)> = doc.layers.iter().map(|l| (name(l), l.blend)).collect(); + assert_eq!(got, [("Under", BlendMode::Normal), ("Pass", BlendMode::Normal), ("Top", BlendMode::Normal)]); + assert_eq!(doc.layers[1].children().unwrap().iter().map(|c| name(c)).collect::<Vec<_>>(), ["Inner + Dodge"]); + assert_eq!( + warnings, + [ + "layers in blend modes VectorCraft doesn't have (Linear Dodge) were merged with the layers below them", + "1 layer in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed", + ] + ); +} + +/// Layers in modes VectorCraft lacks, one after another, merge onto the canvas the first merge made +/// without copying it: 300 of them over a 64 × 64 canvas (64 KiB) open within an allowance that a +/// copy for each would pass. Merges that need a copy of that canvas each, past the allowance, open +/// the merged image instead. +#[test] +fn merges_onto_a_merge_reuse_its_canvas() { + let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; + let dodge = |rect: [i32; 4]| L { blend: b"lddg", ..layer("d", rect, [1, 1, 1, 255]) }; + let mut layers = vec![layer("Bottom", [0, 0, 1, 1], [0, 0, 0, 255]), dodge([63, 63, 64, 64])]; + layers.extend((0..300).map(|_| dodge([1, 1, 2, 2]))); + let (doc, warnings) = psdlayers::import(&file(64, 64, &layers, 8, false, false), false, 1 << 20, cms).unwrap().unwrap(); + assert_eq!((doc.layers.len(), warnings.len()), (1, 1), "{warnings:?}"); + assert!(name(&doc.layers[0]).starts_with("Bottom + d + d") && name(&doc.layers[0]).matches(" + d").count() == 301); + // A Normal layer between each pair: every merge copies the 64 KiB canvas, and 150 of them pass + // eight times the allowance of 1 MiB. + let mut layers = vec![layer("Bottom", [0, 0, 1, 1], [0, 0, 0, 255]), dodge([63, 63, 64, 64])]; + for _ in 0..150 { + layers.extend([layer("n", [1, 1, 2, 2], [1, 1, 1, 255]), dodge([2, 2, 3, 3])]); + } + let e = psdlayers::import(&file(64, 64, &layers, 8, false, false), false, 1 << 20, cms).err(); + assert!(e.as_deref().is_some_and(|e| e.contains("take more memory to read than allowed")), "{e:?}"); +} + +/// A Dissolve layer at half opacity merges as pixels of its own color or of the color below, +/// about half of each, and none in between. +#[test] +fn dissolve_layers_merge_as_opaque_or_transparent_pixels() { + let dissolve = L { blend: b"diss", opacity: 128, ..layer("Dissolve", [0, 0, 16, 16], [255, 0, 0, 255]) }; + let layers = [layer("Bottom", [0, 0, 16, 16], [255, 255, 255, 255]), dissolve]; + let (s, r) = open(&file(16, 16, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + let names: Vec<&str> = d.layers.iter().map(|l| name(l)).collect(); + assert_eq!(names, ["Bottom + Dissolve"], "{r}"); + let (_, px) = image_of(&s, &d.layers[0]); + let red = px.pixels().filter(|p| p.0 == [255, 0, 0, 255]).count(); + let white = px.pixels().filter(|p| p.0 == [255, 255, 255, 255]).count(); + assert_eq!(red + white, 256, "every pixel is the layer's color or the color below"); + assert!((96..=160).contains(&red), "{red} of 256 pixels are the layer's"); + // A second Dissolve layer at half opacity over the first has its own pattern: about a quarter + // of the pixels still show the first. + let blue = L { blend: b"diss", opacity: 128, ..layer("Blue", [0, 0, 16, 16], [0, 0, 255, 255]) }; + let layers = [layers[0].clone(), layers[1].clone(), blue]; + let (s, r) = open(&file(16, 16, &layers, 8, false, false), json!({})); + let (_, px) = image_of(&s, &s.doc().unwrap().doc.layers[0]); + let red = px.pixels().filter(|p| p.0 == [255, 0, 0, 255]).count(); + assert!((32..=96).contains(&red), "{red} of 256 pixels show the lower layer: {r}"); +} + +#[test] +fn what_doesnt_come_in_is_said() { + let mut text = layer("Words", [0, 0, 2, 2], [0, 0, 0, 255]); + text.blocks.push((*b"TySh", vec![0; 4])); + let mut adjust = layer("Levels", [0, 0, 0, 0], [0; 4]); + adjust.blocks.push((*b"levl", vec![0; 4])); + let mut fx = layer("Shadowed", [0, 0, 2, 2], [0, 0, 0, 255]); + fx.blocks.push((*b"lfx2", effects(true, true))); + fx.blocks.push((*b"knko", vec![1, 0, 0, 0])); + // Effects with the master switch off, or none switched on, aren't counted. + let mut fx_off = layer("Switched off", [0, 0, 1, 1], [0, 0, 0, 255]); + fx_off.blocks.push((*b"lfx2", effects(false, true))); + let mut fx_none = layer("None on", [0, 0, 1, 1], [0, 0, 0, 255]); + fx_none.blocks.push((*b"lfx2", effects(true, false))); + // An adjustment layer clipped to the layer below draws nothing, and is still counted. + let mut clipped_adjust = L { clipped: true, ..layer("Curves", [0, 0, 0, 0], [0; 4]) }; + clipped_adjust.blocks.push((*b"curv", vec![0; 4])); + let mut solid = layer("Fill", [0, 0, 0, 0], [0; 4]); + let mut soco = vec![0; 8]; + for (key, v) in [(b"Rd doub", 255.0f64), (b"Grn doub", 0.0), (b"Bl doub", 51.0)] { + soco.extend(key); + soco.extend(v.to_be_bytes()); + } + solid.blocks.push((*b"SoCo", soco.clone())); + // A shape layer: a solid color fill with a vector mask and the shape's pixels stored. + let mut shape = layer("Shape", [1, 1, 3, 2], [255, 0, 51, 255]); + shape.blocks.push((*b"SoCo", soco.clone())); + shape.blocks.push((*b"vmsk", vec![0; 8])); + // One with its vector mask only, no pixels: not drawn, rather than its color over the canvas, + // and the layer clipped to it isn't either. + let mut outline = layer("Outline", [0, 0, 0, 0], [0; 4]); + outline.blocks.push((*b"SoCo", soco)); + outline.blocks.push((*b"vsms", vec![0; 8])); + let on_outline = L { clipped: true, ..layer("On outline", [0, 0, 2, 2], [1, 1, 1, 255]) }; + let layers = [solid, text, clipped_adjust, adjust, fx, fx_off, fx_none, shape, outline, on_outline]; + let (s, r) = open(&file(4, 4, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + let names: Vec<&str> = d.layers.iter().map(|l| name(l)).collect(); + assert_eq!(names, ["Fill", "Words", "Shadowed", "Switched off", "None on", "Shape"], "an adjustment layer draws nothing"); + assert_eq!(image_of(&s, &d.layers[0]).1.get_pixel(3, 3).0, [255, 0, 51, 255], "a solid color fill covers the canvas"); + let ((x, y), px) = image_of(&s, &d.layers[5]); + assert_eq!(((x, y), px.dimensions()), ((1.0, 1.0), (1, 2)), "a shape layer comes in as the pixels it stores"); + let w = r["warnings"].to_string(); + for said in [ + "1 type layer came in as pixels", + "2 adjustment layers were not applied", + "1 fill layer was not drawn", + "the layer effects of 1 layer weren't drawn", + "the vector masks of 2 layers", + "the knockout of 1 layer wasn't applied", + "1 layer clipped to a fill layer that wasn't drawn was left out", + ] { + assert!(w.contains(said), "{said}: {w}"); + } +} + +/// An effects descriptor (`lfx2`) with its master switch and one effect's `enab` set: each key after +/// its length (0 for a 4-character key), then `bool` and a byte. +fn effects(master: bool, enabled: bool) -> Vec<u8> { + let mut d = vec![0; 8]; + d.extend(14u32.to_be_bytes()); + d.extend(b"masterFXSwitchbool"); + d.push(u8::from(master)); + d.extend(0u32.to_be_bytes()); + d.extend(b"enabbool"); + d.push(u8::from(enabled)); + d +} + +/// A layer's fill opacity fades only its own pixels when layers are clipped to it: they still show +/// in its shape, and the merged layer keeps the layer's opacity. +#[test] +fn a_clipping_base_fill_opacity_fades_only_its_own_pixels() { + for (fill, size, corner) in [(0u8, (4, 2), None), (128, (4, 4), Some([255, 0, 0, 128]))] { + let mut base = L { opacity: 200, ..layer("Base", [0, 0, 4, 4], [255, 0, 0, 255]) }; + base.blocks.push((*b"iOpa", vec![fill])); + let photo = L { clipped: true, ..layer("Photo", [0, 0, 2, 4], [0, 0, 255, 255]) }; + let (s, r) = open(&file(4, 4, &[base, photo], 8, false, false), json!({})); + let merged = &s.doc().unwrap().doc.layers[0]; + assert_eq!(name(merged), "Base + Photo", "{r}"); + assert!((merged.opacity - 200.0 / 255.0).abs() < 1e-6, "{fill}: {}", merged.opacity); + let ((x, y), px) = image_of(&s, merged); + assert_eq!(((x, y), px.dimensions(), px.get_pixel(0, 0).0), ((0.0, 0.0), size, [0, 0, 255, 255]), "{fill}"); + if let Some(c) = corner { + assert!(px.get_pixel(3, 3).0.iter().zip(c).all(|(&a, b)| a.abs_diff(b) <= 1), "{fill}: {:?}", px.get_pixel(3, 3)); + } + } +} + +/// Layers clipped to an adjustment layer show over the whole canvas of the file, through the +/// adjustment layer's mask. +#[test] +fn layers_clipped_to_an_adjustment_layer_show_over_the_canvas() { + let mut curves = layer("Curves", [0, 0, 0, 0], [0; 4]); + curves.blocks.push((*b"curv", vec![0; 4])); + curves.mask = Some(([0, 0, 1, 1], 255, 0, vec![0])); + let photo = L { clipped: true, ..layer("Photo", [-1, -1, 2, 5], [0, 0, 255, 255]) }; + let (s, r) = open(&file(4, 4, &[layer("Under", [0, 0, 4, 4], [255, 0, 0, 255]), curves, photo], 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + let names: Vec<&str> = d.layers.iter().map(|l| name(l)).collect(); + assert_eq!(names, ["Under", "Curves + Photo"], "{r}"); + // Cut to the canvas: 4 × 2 at its corner. + let ((x, y), px) = image_of(&s, &d.layers[1]); + assert_eq!(((x, y), px.dimensions(), px.get_pixel(1, 1).0), ((0.0, 0.0), (4, 2), [0, 0, 255, 255])); + assert!(d.layers[1].extras().mask.is_some(), "the adjustment layer's mask stays"); + assert!(r["warnings"].to_string().contains("1 adjustment layer was not applied"), "{r}"); +} + +/// Each blend mode VectorCraft lacks merges with the layer below by its formula, from the public +/// descriptions: <https://helpx.adobe.com/photoshop/desktop/repair-retouch/adjust-light-tone/blending-mode-descriptions.html> +/// (Vivid Light, Pin Light, Hard Mix, Darker and Lighter Color) and +/// <https://en.wikipedia.org/wiki/Blend_modes> (Linear Burn, Linear Dodge, Linear Light, Subtract, +/// Divide). Color Dodge, Color Burn and Difference keep their mode. +#[test] +fn every_mode_vectorcraft_lacks_merges_by_its_formula() { + let b = [200u8, 100, 30]; + let s = [60u8, 180, 128]; + let burn = |b: f64, c: f64| if c <= 0.0 { if b >= 1.0 { 1.0 } else { 0.0 } } else { 1.0 - ((1.0 - b) / c).min(1.0) }; + let dodge = |b: f64, c: f64| if c >= 1.0 { if b <= 0.0 { 0.0 } else { 1.0 } } else { (b / (1.0 - c)).min(1.0) }; + let each = |f: &dyn Fn(f64, f64) -> f64| -> [u8; 3] { + [0, 1, 2].map(|i| (f(f64::from(b[i]) / 255.0, f64::from(s[i]) / 255.0).clamp(0.0, 1.0) * 255.0).round() as u8) + }; + let total = |c: [u8; 3]| c.iter().map(|&v| u32::from(v)).sum::<u32>(); + let cases: [(&[u8; 4], [u8; 3]); 10] = [ + (b"lbrn", each(&|b, s| b + s - 1.0)), + (b"lddg", each(&|b, s| b + s)), + (b"vLit", each(&|b, s| if s <= 0.5 { burn(b, 2.0 * s) } else { dodge(b, 2.0 * s - 1.0) })), + (b"lLit", each(&|b, s| b + 2.0 * s - 1.0)), + (b"pLit", each(&|b, s| if s <= 0.5 { b.min(2.0 * s) } else { b.max(2.0 * s - 1.0) })), + (b"hMix", each(&|b, s| if (b + s) * 255.0 >= 254.999 { 1.0 } else { 0.0 })), + (b"fsub", each(&|b, s| b - s)), + (b"fdiv", each(&|b, s| if s <= 0.0 { 1.0 } else { b / s })), + (b"dkCl", if total(s) < total(b) { s } else { b }), + (b"lgCl", if total(s) > total(b) { s } else { b }), + ]; + for (key, want) in cases { + let top = L { blend: key, ..layer("Top", [0, 0, 1, 1], [s[0], s[1], s[2], 255]) }; + let (st, r) = open(&file(1, 1, &[layer("Bottom", [0, 0, 1, 1], [b[0], b[1], b[2], 255]), top], 8, false, false), json!({})); + let d = &st.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Bottom + Top"], "{key:?}: {r}"); + let got = image_of(&st, &d.layers[0]).1.get_pixel(0, 0).0; + assert!( + got[..3].iter().zip(want).all(|(&g, w)| g.abs_diff(w) <= 1) && got[3] == 255, + "{}: {got:?}, want {want:?}", + String::from_utf8_lossy(key) + ); + } + for (key, mode) in [(b"div ", BlendMode::ColorDodge), (b"idiv", BlendMode::ColorBurn), (b"diff", BlendMode::Difference)] { + let top = L { blend: key, ..layer("Top", [0, 0, 1, 1], [s[0], s[1], s[2], 255]) }; + let (st, r) = open(&file(1, 1, &[layer("Bottom", [0, 0, 1, 1], [b[0], b[1], b[2], 255]), top], 8, false, false), json!({})); + let d = &st.doc().unwrap().doc; + let got: Vec<(&str, BlendMode)> = d.layers.iter().map(|l| (name(l), l.blend)).collect(); + assert_eq!(got, [("Bottom", BlendMode::Normal), ("Top", mode)], "{r}"); + } +} + +/// A descriptor's numbers: each key (a 4-character key after a length of 0, a longer one after its +/// length), then `doub` and the value, or for `H `, `UntF`, `#Ang` and the value. +fn descriptor(values: &[(&[u8], f64)]) -> Vec<u8> { + let mut d = vec![0; 8]; + for (key, v) in values { + d.extend(if key.len() == 4 { 0u32 } else { key.len() as u32 }.to_be_bytes()); + d.extend(*key); + d.extend(if *key == b"H " { &b"UntF#Ang"[..] } else { b"doub" }); + d.extend(v.to_be_bytes()); + } + d +} + +/// Solid color fill layers that store no pixels come in as their color in every color model a +/// descriptor uses; one whose color can't be read, and a gradient fill that stores no pixels, are +/// counted; a gradient fill that stores pixels comes in as them. +#[test] +fn solid_color_fills_read_every_color_model() { + let fill = |name: &'static str, values: &[(&[u8], f64)]| { + let mut l = layer(name, [0, 0, 0, 0], [0; 4]); + l.blocks.push((*b"SoCo", descriptor(values))); + l + }; + let mut gradient = layer("Gradient", [0, 0, 0, 0], [0; 4]); + gradient.blocks.push((*b"GdFl", vec![0; 8])); + let mut gradient_shape = layer("Gradient shape", [1, 1, 2, 2], [7, 8, 9, 255]); + gradient_shape.blocks.push((*b"GdFl", vec![0; 8])); + // Bounds, but no channels: it stores no pixels either. + let mut pattern = L { bare: true, ..layer("Pattern", [0, 0, 4, 4], [0; 4]) }; + pattern.blocks.push((*b"PtFl", vec![0; 8])); + let layers = [ + fill("Float", &[(b"redFloat", 0.0), (b"greenFloat", 0.0), (b"blueFloat", 1.0)]), + fill("Cmyk", &[(b"Cyn ", 0.0), (b"Mgnt", 100.0), (b"Ylw ", 100.0), (b"Blck", 0.0)]), + fill("Gray", &[(b"Gry ", 25.0)]), + fill("Lab", &[(b"Lmnc", 100.0), (b"A ", 0.0), (b"B ", 0.0)]), + fill("Hsb", &[(b"H ", 120.0), (b"Strt", 100.0), (b"Brgh", 100.0)]), + fill("Unread", &[(b"Bk ", 1.0)]), + gradient, + gradient_shape, + pattern, + ]; + // A naive CMYK conversion, so that the colors don't depend on the color settings. + let naive = |c: [f32; 4]| [0, 1, 2].map(|i| (1.0 - c[i]) * (1.0 - c[3])); + let (doc, warnings) = psdlayers::import(&file(4, 4, &layers, 8, false, false), false, 1 << 20, naive).unwrap().unwrap(); + let names: Vec<&str> = doc.layers.iter().map(|l| name(l)).collect(); + assert_eq!(names, ["Float", "Cmyk", "Gray", "Lab", "Hsb", "Gradient shape"]); + let mut s = Session::new(); + s.add_document(doc, None); + let d = &s.doc().unwrap().doc; + let colors: Vec<[u8; 4]> = d.layers[..5].iter().map(|l| image_of(&s, l).1.get_pixel(2, 2).0).collect(); + assert_eq!(colors[..3], [[0, 0, 255, 255], [255, 0, 0, 255], [191, 191, 191, 255]]); + assert!(colors[3].iter().all(|&v| v >= 253), "Lab 100, 0, 0 is white: {:?}", colors[3]); + assert_eq!(colors[4], [0, 255, 0, 255]); + assert_eq!(image_of(&s, &d.layers[5]).1.get_pixel(0, 0).0, [7, 8, 9, 255]); + assert_eq!(warnings, ["3 fill layers were not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels)"]); +} + +/// VectorCraft's own PSD export opens with the layers it wrote: groups as layers of sublayers, +/// hidden ones hidden, with their opacity and blend mode. +#[test] +fn psd_exports_open_with_their_layers() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 60, "height": 40})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 30, "height": 40})).unwrap(); + s.execute("layer.new", &json!({"name": "Blue"})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 40, "y": 0, "width": 20, "height": 40})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 50, "blend": "Multiply"})).unwrap(); + s.execute("layer.new", &json!({"name": "Off"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 5, "height": 5})).unwrap(); + let off = s.doc().unwrap().doc.layers.last().unwrap().id; + s.execute("layer.setProps", &json!({"id": off.0, "visible": false})).unwrap(); + for (options, top) in [ + (json!({"hiddenLayers": true}), vec![("Layer 1", true), ("Blue", true), ("Off", false)]), + (json!({"maxEditability": true}), vec![("Layer 1", true), ("Blue", true)]), + ] { + let r = s.execute("document.export", &merge(json!({"format": "psd"}), options.clone())).unwrap(); + let f = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap(); + let (back, r) = open(&f, json!({"hiddenLayers": true})); + let d = &back.doc().unwrap().doc; + let got: Vec<(&str, bool)> = d.layers.iter().map(|l| (name(l), l.visible)).collect(); + assert_eq!(got, top, "{options}: {r}"); + if options["maxEditability"] == true { + // Each layer a group: its objects become sublayers, the rectangle's opacity and blend mode + // on its own. + let blue = d.layers[1].children().unwrap(); + assert_eq!(blue.len(), 1, "{options}"); + assert!(blue[0].blend == BlendMode::Multiply && (blue[0].opacity - 0.5).abs() < 0.01, "{options}"); + } + } +} + +#[test] +fn files_without_layers_or_with_damaged_layers_open_as_their_merged_image() { + // No layer records: the merged image, without a warning. + let flat = { + let mut f = file(2, 2, &[layer("x", [0, 0, 2, 2], [9, 9, 9, 255])], 8, false, false); + // The layer and mask section emptied: 4 length bytes of 0, after the header and two + // empty sections. + let at = 26 + 8; + let len = u32::from_be_bytes(f[at..at + 4].try_into().unwrap()) as usize; + f.splice(at..at + 4 + len, 0u32.to_be_bytes()); + f + }; + let (_, r) = open(&flat, json!({})); + assert_eq!(r["warnings"], json!([]), "{r}"); + // Layer info of just the count (negative: the merged image has transparency) has no layers. + let count_only = { + let mut f = flat.clone(); + let at = 26 + 8; + f.splice(at..at + 4, [&10u32.to_be_bytes()[..], &2u32.to_be_bytes(), &(-1i16).to_be_bytes(), &[0, 0, 0, 0]].concat()); + f + }; + let (s, r) = open(&count_only, json!({})); + assert_eq!((&r["warnings"], s.doc().unwrap().doc.layers[0].children().map(Vec::len)), (&json!([]), Some(1)), "{r}"); + // A channel cut short: the merged image, with a warning. + let mut cut = file(4, 4, &[layer("x", [0, 0, 4, 4], [9, 9, 9, 255])], 8, false, false); + let at = cut.windows(4).position(|w| w == [0, 0, 0, 18]).unwrap(); + cut[at..at + 4].copy_from_slice(&1000u32.to_be_bytes()); + let (s, r) = open(&cut, json!({})); + assert!(r["warnings"][0].as_str().unwrap().starts_with("the layers can't be read"), "{r}"); + assert_eq!(s.doc().unwrap().doc.layers[0].children().map(Vec::len), Some(1)); + // Groups nested past the limit. + let mut deep: Vec<L> = (0..=psdlayers::MAX_DEPTH).map(|_| group_end()).collect(); + deep.push(layer("x", [0, 0, 1, 1], [0, 0, 0, 255])); + let (_, r) = open(&file(2, 2, &deep, 8, false, false), json!({})); + assert!(r["warnings"][0].as_str().unwrap().contains("nested too deeply"), "{r}"); + // Groups within the limit but deeper than a document may nest: the deepest merge into the + // group around them, with the warning. + let mut deep: Vec<L> = (0..40).map(|_| group_end()).collect(); + deep.push(layer("x", [0, 0, 1, 1], [0, 0, 0, 255])); + deep.extend((0..40).map(|_| group("g", b"norm"))); + let (s, r) = open(&file(2, 2, &deep, 8, false, false), json!({})); + assert_eq!(r["warnings"], json!([vectorcraft_doc::depth::merged_note()]), "{r}"); + fn depth(n: &Node) -> usize { + 1 + n.children().map_or(0, |c| c.iter().map(|c| depth(c)).max().unwrap_or(0)) + } + assert!(s.doc().unwrap().doc.layers.iter().map(|l| depth(l)).max().unwrap() <= vectorcraft_doc::MAX_DEPTH); +} + +/// A record whose layer mask or name is cut short opens the merged image with a warning, rather +/// than a layer without its mask or name. +#[test] +fn records_with_a_damaged_mask_or_name_open_as_the_merged_image() { + let good = file(4, 4, &[layer("x", [0, 0, 4, 4], [9, 9, 9, 255])], 8, false, false); + // The record's extra data: an empty mask section, empty blending ranges, then the name. + let at = good.windows(10).position(|w| w == [0, 0, 0, 0, 0, 0, 0, 0, 1, b'x']).unwrap(); + // A mask section of 4 bytes, too short for a mask's place, default color and flags. + let mut short_mask = good.clone(); + short_mask[at + 3] = 4; + // A name longer than the record's extra data. + let mut long_name = good.clone(); + long_name[at + 8] = 0xff; + for f in [short_mask, long_name] { + let (s, r) = open(&f, json!({})); + assert!(r["warnings"][0].as_str().unwrap().starts_with("the layers can't be read"), "{r}"); + assert_eq!(s.doc().unwrap().doc.layers[0].children().map(Vec::len), Some(1), "{r}"); + } +} + +#[test] +fn damaged_layers_never_panic() { + let mut masked = layer("Masked", [0, 0, 3, 3], [1, 2, 3, 255]); + masked.mask = Some(([1, 1, 2, 2], 0, 0, vec![200])); + let layers = [ + layer("A", [0, 0, 3, 3], [255, 0, 0, 255]), + group_end(), + masked, + L { clipped: true, ..layer("C", [0, 0, 3, 3], [0, 0, 255, 255]) }, + L { blend: b"lbrn", ..layer("D", [0, 0, 2, 2], [9, 9, 9, 255]) }, + group("G", b"pass"), + ]; + for (rle, psb) in [(false, false), (true, true)] { + let good = file(3, 3, &layers, 8, rle, psb); + let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; + assert!(psdlayers::import(&good, true, 1 << 30, cms).unwrap().is_some()); + for i in 0..good.len() { + for v in [0, 1, 0x7f, 0x80, 0xff] { + let mut f = good.clone(); + f[i] = v; + let _ = psdlayers::import(&f, true, 1 << 30, cms); + } + } + for n in 0..good.len() { + let _ = psdlayers::import(&good[..n], true, 1 << 30, cms); + } + // A layer past the memory allowed is refused, not read. + assert!(psdlayers::import(&good, true, 64, cms).unwrap_err().contains("too large")); + } + // Many layers that each fit the memory allowed for one image, but not all together (8 bytes a + // pixel to read an 8 × 8 layer; 4 a pixel decoded, against 8 times the allowance). + let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; + let many: Vec<L> = (0..20).map(|_| layer("x", [0, 0, 8, 8], [1, 2, 3, 255])).collect(); + assert!(psdlayers::import(&file(8, 8, &many[..16], 8, false, false), false, 512, cms).unwrap().is_some()); + let e = psdlayers::import(&file(8, 8, &many, 8, false, false), false, 512, cms).err(); + assert!(e.as_deref().is_some_and(|e| e.contains("take more memory to read than allowed")), "{e:?}"); +} + +/// A layer in a mode VectorCraft lacks above a pass-through group merges with the group's layers +/// blending onto what is below the group, as they do without the merge. +#[test] +fn merges_keep_pass_through_groups_blending_with_what_is_below() { + let layers = [ + layer("Bottom", [0, 0, 2, 2], [100, 200, 50, 255]), + group_end(), + L { blend: b"mul ", ..layer("Multiply", [0, 0, 2, 2], [128, 128, 128, 255]) }, + group("Pass", b"pass"), + L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) }, + ]; + let (s, r) = open(&file(2, 2, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + let names: Vec<&str> = d.layers.iter().map(|l| name(l)).collect(); + assert_eq!(names, ["Bottom + Pass + Dodge"], "{r}"); + // 100, 200 and 50 times 128/255. + assert_eq!(image_of(&s, &d.layers[0]).1.get_pixel(1, 1).0, [50, 100, 25, 255]); + // At half opacity, or with a layer mask, the group's layers still blend with what is below + // it, and the result fades back toward it: halfway from (100, 200, 50) to (50, 100, 25). + let mut masked = group("Pass", b"pass"); + masked.mask = Some(([0, 0, 2, 2], 0, 0, vec![128, 128, 128, 128])); + for top in [L { opacity: 128, ..group("Pass", b"pass") }, masked] { + let mut layers = layers.clone(); + layers[3] = top; + let (s, r) = open(&file(2, 2, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Bottom + Pass + Dodge"], "{r}"); + let px = image_of(&s, &d.layers[0]).1.get_pixel(1, 1).0; + assert!(px.iter().zip([75, 150, 38, 255]).all(|(&a, b)| a.abs_diff(b) <= 1), "{px:?}"); + } +} diff --git a/crates/engine/src/cmd/fileio/tests_psdread.rs b/crates/engine/src/cmd/fileio/tests_psdread.rs index d411496b02..08a46f0e10 100644 --- a/crates/engine/src/cmd/fileio/tests_psdread.rs +++ b/crates/engine/src/cmd/fileio/tests_psdread.rs @@ -141,6 +141,31 @@ fn packbits_zip_and_psb_files_read() { zip.extend(z.finish().unwrap()); let px = pixels(&psd(1, 1, (3, 1), 16, 1, &[], &[], &[], &zip)); assert_eq!(px.iter().map(|p| p[0]).collect::<Vec<_>>(), [16, 32, 48]); + // Zipped with prediction, 32 bits: the row's first bytes, then its second bytes and so on, + // each byte stored as the difference from the byte before it. + let samples = [0.0f32, 1.0, 0.0].map(f32::to_be_bytes); + let planes: Vec<u8> = (0..4).flat_map(|k| samples.iter().map(move |s| s[k])).collect(); + let deltas: Vec<u8> = planes.iter().scan(0u8, |prev, &b| Some(b.wrapping_sub(std::mem::replace(prev, b)))).collect(); + let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); + std::io::Write::write_all(&mut z, &deltas).unwrap(); + let mut zip = vec![0, 3]; + zip.extend(z.finish().unwrap()); + let px = pixels(&psd(1, 1, (3, 1), 32, 1, &[], &[], &[], &zip)); + assert_eq!(px.iter().map(|p| p[0]).collect::<Vec<_>>(), [0, 255, 0]); + // The same layout as another implementation writes it: psd-tools 1.26.1 (MIT, + // <https://github.com/psd-tools/psd-tools>), `compression.compress(data, + // Compression.ZIP_WITH_PREDICTION, 3, 2, 32)` of the samples 0, 1, 0.25 and 0.5, 0.125, 1, + // reads as the same samples stored raw. + let theirs = [ + 0x78, 0x9c, 0x63, 0xb0, 0xff, 0x7f, 0xa8, 0x81, 0xa1, 0x81, 0x01, 0x04, 0xec, 0xff, 0x33, 0x1e, 0x64, 0x68, 0x80, 0xb0, 0x01, 0x59, 0xd1, + 0x06, 0x01, + ]; + let mut zip = vec![0, 3]; + zip.extend(theirs); + let samples: Vec<u8> = [0.0f32, 1.0, 0.25, 0.5, 0.125, 1.0].iter().flat_map(|v| v.to_be_bytes()).collect(); + let stored = pixels(&psd(1, 1, (3, 2), 32, 1, &[], &[], &[], &raw(&[&samples]))); + assert_eq!(pixels(&psd(1, 1, (3, 2), 32, 1, &[], &[], &[], &zip)), stored); + assert_eq!(stored.iter().map(|p| p[0]).collect::<Vec<_>>()[..2], [0, 255]); } #[test] diff --git a/crates/engine/src/cmd/fileio/tests_readonly.rs b/crates/engine/src/cmd/fileio/tests_readonly.rs new file mode 100644 index 0000000000..ae9762efc3 --- /dev/null +++ b/crates/engine/src/cmd/fileio/tests_readonly.rs @@ -0,0 +1,51 @@ +//! Save errors retain their type without changing the other filesystem writers (#6146). + +use std::io::{self, ErrorKind}; + +use serde_json::json; + +use super::{SaveMode, access, save_plan, save_with, write_file_with, write_save_file_with}; +use crate::{EngineError, READ_ONLY_LOCATION, Session}; + +#[test] +fn readonly_error_is_typed_and_other_writers_keep_their_error() { + let dir = vectorcraft_testkit::TempDir::new("save-refusal"); + let path = dir.join("Poster.vectorcraft").to_string_lossy().into_owned(); + for kind in [ErrorKind::PermissionDenied, ErrorKind::ReadOnlyFilesystem, ErrorKind::StorageFull, ErrorKind::NotFound, ErrorKind::Other] { + let typed = write_save_file_with(&path, &mut |_| Err(io::Error::new(kind, "injected"))).unwrap_err(); + let ordinary = write_file_with(&path, &mut |_| Err(io::Error::new(kind, "injected"))).unwrap_err(); + let reason = format!("{path}: injected"); + assert!(matches!(&ordinary, EngineError::Other(_))); + assert_eq!(ordinary.to_string(), reason); + if matches!(kind, ErrorKind::PermissionDenied | ErrorKind::ReadOnlyFilesystem) { + assert!(matches!(&typed, EngineError::ReadOnlyLocation(_))); + assert_eq!(typed.to_string(), format!("{READ_ONLY_LOCATION}: {reason}")); + } else { + assert!(matches!(&typed, EngineError::Other(_))); + assert_eq!(typed.to_string(), reason); + } + assert!(!std::path::Path::new(&path).exists()); + } +} + +#[test] +fn readonly_failed_save_keeps_document_and_options() { + let mut session = Session::new(); + session.execute("file.new", &json!({"width": 40, "height": 40})).unwrap(); + session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); + let st = session.doc_mut().unwrap(); + st.path = Some("Poster.svg".into()); + st.format = "svg"; + st.save_options = json!({"decimals": 3}).as_object().unwrap().clone(); + let before = serde_json::to_value(&*st.doc).unwrap(); + let options = st.save_options.clone(); + let plan = save_plan(&session, SaveMode::Save, &json!({"modified": null})).unwrap(); + let e = save_with(&mut session, plan, |path, _| Err(access::save_write_error(path, io::Error::from(ErrorKind::PermissionDenied)))).unwrap_err(); + assert!(matches!(e, EngineError::ReadOnlyLocation(_))); + let st = session.doc().unwrap(); + assert_eq!(st.path.as_deref(), Some("Poster.svg")); + assert_eq!(st.format, "svg"); + assert_eq!(st.save_options, options); + assert!(st.is_dirty()); + assert_eq!(serde_json::to_value(&*st.doc).unwrap(), before); +} diff --git a/crates/engine/src/cmd/fileio/tests_screens.rs b/crates/engine/src/cmd/fileio/tests_screens.rs index b0dcd368ec..51954d8da3 100644 --- a/crates/engine/src/cmd/fileio/tests_screens.rs +++ b/crates/engine/src/cmd/fileio/tests_screens.rs @@ -507,6 +507,22 @@ fn type_in_a_missing_family_is_named_once_for_every_format() { assert!(fallback[0].contains("Nonexistent Sans Probe"), "{fallback:?}"); } +/// What a later file loses comes before a note on the options that an earlier file gave: the +/// first artboard's WebP gives only the lossy WebP note, the second's also says its type doesn't +/// fit. +#[test] +fn what_any_file_loses_comes_before_the_notes_on_the_options() { + let mut s = session(2); + let second = s.doc().unwrap().doc.artboards[1].rect; + let area = json!({"width": 30, "height": 8}); + s.execute("text.create", &json!({"x": second.x0 + 2.0, "y": second.y0 + 2.0, "size": 12, "area": area, "text": "Ab\nCd\nEf\nGh"})).unwrap(); + let r = export(&mut s, json!({"formats": [{"format": "webp", "lossless": false}]})); + let warnings: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + assert_eq!(warnings.len(), 2, "{warnings:?}"); + assert!(warnings[0].contains("doesn't fit its frame"), "{warnings:?}"); + assert!(warnings[1].starts_with("lossy WebP"), "{warnings:?}"); +} + #[test] fn full_document_gives_one_file_per_format() { let mut s = session(3); @@ -667,6 +683,193 @@ fn a_numbered_file_is_written_into_the_first_rows_folder() { assert_eq!(std::fs::read_dir(dir).unwrap().count(), 1, "one sub-folder"); } +/// An export into the folder an export preset keeps, for a client whose read roots don't hold that +/// folder: the reply leaves out the ZIP's path and names the files relative to the folder. A folder +/// inside the read roots, and one the client gives, stay whole. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_presets_folder_outside_the_read_root_is_left_out_of_the_reply() { + use crate::file_access::{AutomationRoots, confine}; + + let mut s = session(1); + let tmp = Folder::new("preset-roots"); + let (inside, out) = (tmp.0.join("in"), tmp.0.join("out")); + for f in [&inside, &out] { + std::fs::create_dir_all(f).unwrap(); + } + let folder = out.to_string_lossy().replace('\\', "/"); + let settings = json!({"formats": [{"format": "png", "folder": "1x"}], "subfolders": true, "folder": folder}); + s.execute("document.exportPresets.save", &json!({"name": "Kept", "settings": settings})).unwrap(); + let write_only = AutomationRoots::new(&[inside.as_path()], &[out.as_path()]).unwrap(); + let both = AutomationRoots::new(&[inside.as_path(), out.as_path()], &[out.as_path()]).unwrap(); + let run = |s: &mut Session, roots: &Option<std::sync::Arc<AutomationRoots>>, p: Value| confine(roots.as_ref(), || export(s, p)); + + let r = run(&mut s, &write_only, json!({"exportPreset": "Kept"})); + assert_eq!(r["files"], json!(["1x/Artboard-1.png"]), "{r}"); + assert!(out.join("1x/Artboard-1.png").is_file()); + let r = run(&mut s, &write_only, json!({"exportPreset": "Kept", "zip": true})); + assert_eq!((r.get("path"), &r["files"]), (None, &json!(["1x/Artboard-1.png"])), "{r}"); + assert!(!r.to_string().contains(&folder), "{r}"); + // Inside the read roots, or given by the client: whole. + assert_eq!(run(&mut s, &both, json!({"exportPreset": "Kept"}))["files"], json!([format!("{folder}/1x/Artboard-1.png")])); + let r = run(&mut s, &write_only, json!({"exportPreset": "Kept", "folder": folder, "zip": true})); + assert!(r["path"].as_str().is_some_and(|p| p.starts_with(&format!("{folder}/")) && p.ends_with(".zip")), "{r}"); +} + +/// An export into the folder an export preset keeps, refused because that folder is outside the +/// client's read and write roots: the error names the folder by its name only. A folder the client +/// gives stays whole in the error. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_refused_export_into_a_presets_folder_outside_the_read_root_names_it_by_its_name() { + use crate::file_access::{AutomationRoots, confine}; + + let mut s = session(1); + let tmp = Folder::new("preset-refused"); + let (inside, out) = (tmp.0.join("in"), tmp.0.join("kept-out")); + for f in [&inside, &out] { + std::fs::create_dir_all(f).unwrap(); + } + let folder = out.to_string_lossy().replace('\\', "/"); + let settings = json!({"formats": [{"format": "png"}], "folder": folder}); + s.execute("document.exportPresets.save", &json!({"name": "Kept", "settings": settings})).unwrap(); + let confined = AutomationRoots::new(&[inside.as_path()], &[inside.as_path()]).unwrap(); + let mut run = |p: Value| confine(confined.as_ref(), || s.execute("document.exportForScreens", &p)).unwrap_err().to_string(); + + let e = run(json!({"exportPreset": "Kept"})); + assert!(e.contains("outside the write root") && e.contains("kept-out") && !e.contains(&folder), "{e}"); + let e = run(json!({"exportPreset": "Kept", "folder": folder})); + assert!(e.contains(&folder), "{e}"); + assert_eq!(std::fs::read_dir(&out).unwrap().count(), 0, "nothing written"); + // A preset folder that holds the write root: the root stays whole in the error. + let parent = tmp.0.to_string_lossy().replace('\\', "/"); + let settings = json!({"formats": [{"format": "png"}], "folder": parent}); + s.execute("document.exportPresets.save", &json!({"name": "Parent", "settings": settings})).unwrap(); + let e = confine(confined.as_ref(), || s.execute("document.exportForScreens", &json!({"exportPreset": "Parent"}))).unwrap_err().to_string(); + let root = crate::cmd::findfiles::plain(inside.canonicalize().unwrap()).display().to_string(); + let name = tmp.0.file_name().unwrap().to_string_lossy().into_owned(); + assert!(e.contains(&format!("root {root}: {name}")), "{e}"); +} + +/// A prepared export into the folder an export preset keeps, prepared for a client whose read roots +/// don't hold that folder and written later outside that client's scope (as on the background +/// thread): its reply leaves out the ZIP's path and names the files relative to the folder, and a +/// refused write names the folder by its name. A folder inside the read roots, and one the client +/// gives, stay whole. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_prepared_export_into_a_presets_folder_outside_the_read_root_leaves_it_out() { + use crate::file_access::{AutomationRoots, confine}; + + let mut s = session(1); + let tmp = Folder::new("prepared-roots"); + let (inside, out) = (tmp.0.join("in"), tmp.0.join("kept-out")); + for f in [&inside, &out] { + std::fs::create_dir_all(f).unwrap(); + } + let folder = out.to_string_lossy().replace('\\', "/"); + let settings = json!({"formats": [{"format": "png", "folder": "1x"}], "subfolders": true, "folder": folder}); + s.execute("document.exportPresets.save", &json!({"name": "Kept", "settings": settings})).unwrap(); + let write_only = AutomationRoots::new(&[inside.as_path()], &[out.as_path()]).unwrap(); + let both = AutomationRoots::new(&[inside.as_path(), out.as_path()], &[out.as_path()]).unwrap(); + let prepare = |s: &mut Session, roots: &Option<std::sync::Arc<AutomationRoots>>, p: Value| { + confine(roots.as_ref(), || s.prepare_screen_export("document.exportForScreens", &p)).unwrap() + }; + + let (r, files) = write_prepared(prepare(&mut s, &write_only, json!({"exportPreset": "Kept"}))); + assert_eq!(r["files"], json!(["1x/Artboard-1.png"]), "{r}"); + assert!(files.contains_key(&format!("{folder}/1x/Artboard-1.png")), "the files are written into the folder"); + let (r, _) = write_prepared(prepare(&mut s, &write_only, json!({"exportPreset": "Kept", "zip": true}))); + assert_eq!((r.get("path"), &r["files"]), (None, &json!(["1x/Artboard-1.png"])), "{r}"); + assert!(!r.to_string().contains(&folder), "{r}"); + // A refused write names the folder by its name. + let refused = prepare(&mut s, &write_only, json!({"exportPreset": "Kept"})); + let e = refused.write(&mut |path, _| Err(crate::EngineError::Other(format!("{path}: access denied")))).unwrap_err().to_string(); + assert!(e.contains("kept-out/1x/Artboard-1.png: access denied") && !e.contains(&folder), "{e}"); + // Inside the read roots, or given by the client: whole. + let (r, _) = write_prepared(prepare(&mut s, &both, json!({"exportPreset": "Kept"}))); + assert_eq!(r["files"], json!([format!("{folder}/1x/Artboard-1.png")]), "{r}"); + let (r, _) = write_prepared(prepare(&mut s, &write_only, json!({"exportPreset": "Kept", "folder": folder, "zip": true}))); + assert!(r["path"].as_str().is_some_and(|p| p.starts_with(&format!("{folder}/")) && p.ends_with(".zip")), "{r}"); + let given = prepare(&mut s, &write_only, json!({"exportPreset": "Kept", "folder": folder})); + let e = given.write(&mut |path, _| Err(crate::EngineError::Other(format!("{path}: access denied")))).unwrap_err().to_string(); + assert!(e.contains(&folder), "{e}"); +} + +/// [`Session::screen_export_folder`]: the client's folder, else the one the export preset keeps, +/// with its own name when the request's read roots don't hold it; none without a folder, for an +/// unknown preset or for `assets.export`, which takes no preset. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn the_export_folder_is_the_clients_else_the_presets() { + use crate::file_access::{AutomationRoots, confine}; + + let mut s = session(1); + let tmp = Folder::new("export-folder"); + let (inside, out) = (tmp.0.join("in"), tmp.0.join("kept-out")); + for f in [&inside, &out] { + std::fs::create_dir_all(f).unwrap(); + } + let folder = out.to_string_lossy().replace('\\', "/"); + let settings = json!({"formats": [{"format": "png"}], "folder": folder}); + s.execute("document.exportPresets.save", &json!({"name": "Kept", "settings": settings})).unwrap(); + let confined = AutomationRoots::new(&[inside.as_path()], &[inside.as_path()]).unwrap(); + let ask = |id: &str, p: Value| confine(confined.as_ref(), || s.screen_export_folder(id, &p)); + + let screens = "document.exportForScreens"; + assert_eq!(ask(screens, json!({"exportPreset": "Kept"})), Some((folder.clone(), Some("kept-out".to_string())))); + assert_eq!(ask(screens, json!({"exportPreset": "Kept", "folder": "/x/y"})), Some(("/x/y".to_string(), None))); + assert_eq!(ask(screens, json!({"exportPreset": "Kept", "folder": ""})), None); + assert_eq!(ask(screens, json!({"exportPreset": "Nope"})), None); + assert_eq!(ask(screens, json!({})), None); + assert_eq!(ask("assets.export", json!({"exportPreset": "Kept"})), None); + assert_eq!(s.screen_export_folder(screens, &json!({"exportPreset": "Kept"})), Some((folder, None)), "unconfined: whole"); +} + +/// The export settings the document keeps and the saved presets, read by a client whose read roots +/// don't hold their folder: `document.exportSettings`, `document.exportPresets.list` and +/// `document.exportPresets.export` (as data and as a file) leave out that folder and keep the rest. +/// Inside the read roots the folder stays. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn kept_settings_leave_out_a_folder_outside_the_read_root() { + use crate::file_access::{AutomationRoots, confine}; + + let mut s = session(1); + let tmp = Folder::new("settings-roots"); + let (inside, out) = (tmp.0.join("in"), tmp.0.join("out")); + for f in [&inside, &out] { + std::fs::create_dir_all(f).unwrap(); + } + let folder = out.to_string_lossy().replace('\\', "/"); + let settings = json!({"formats": [{"format": "svg"}], "folder": folder}); + s.execute("document.exportPresets.save", &json!({"name": "Kept", "settings": settings})).unwrap(); + export(&mut s, json!({"exportPreset": "Kept"})); + let confined = AutomationRoots::new(&[inside.as_path()], &[inside.as_path()]).unwrap(); + let both = AutomationRoots::new(&[inside.as_path(), out.as_path()], &[inside.as_path()]).unwrap(); + let ask = |s: &mut Session, roots: &Option<std::sync::Arc<AutomationRoots>>, cmd: &str, p: Value| { + confine(roots.as_ref(), || s.execute(cmd, &p).unwrap()) + }; + let saved = |list: &Value| list["presets"].as_array().unwrap().iter().find(|p| p["name"] == "Kept").unwrap()["settings"].clone(); + + let r = ask(&mut s, &confined, "document.exportSettings", json!({})); + assert_eq!((r["settings"].get("folder"), &r["settings"]["formats"]), (None, &json!([{"format": "svg"}])), "{r}"); + let r = ask(&mut s, &confined, "document.exportPresets.list", json!({})); + assert_eq!(saved(&r), json!({"formats": [{"format": "svg"}]}), "{r}"); + let r = ask(&mut s, &confined, "document.exportPresets.export", json!({"names": ["Kept"]})); + let data = r["data"].as_str().unwrap(); + assert!(!data.contains(&folder) && data.contains("svg"), "{data}"); + let file = inside.join("kept.vcexportpresets"); + let path = file.to_string_lossy().replace('\\', "/"); + ask(&mut s, &confined, "document.exportPresets.export", json!({"names": ["Kept"], "path": path})); + assert!(!std::fs::read_to_string(&file).unwrap().contains(&folder)); + + // Inside the read roots: whole. + assert_eq!(ask(&mut s, &both, "document.exportSettings", json!({}))["settings"]["folder"], json!(folder)); + assert_eq!(saved(&ask(&mut s, &both, "document.exportPresets.list", json!({})))["folder"], json!(folder)); + assert!(ask(&mut s, &both, "document.exportPresets.export", json!({"names": ["Kept"]}))["data"].as_str().unwrap().contains(&folder)); +} + #[test] fn format_settings_apply_to_their_rows_and_rows_win() { let mut s = session(1); diff --git a/crates/engine/src/cmd/findfiles/tests.rs b/crates/engine/src/cmd/findfiles/tests.rs index ec3ce57e3a..9340e5a8c6 100644 --- a/crates/engine/src/cmd/findfiles/tests.rs +++ b/crates/engine/src/cmd/findfiles/tests.rs @@ -43,12 +43,62 @@ impl Visitor for Blocked { } } +/// A test's folder tree, removed with everything in it when dropped, also when the test panics, +/// and also when the test locked a folder in it. A removal that fails (a walker still holding a +/// file open) is ignored. +struct Tree(PathBuf); + +impl std::ops::Deref for Tree { + type Target = PathBuf; + fn deref(&self) -> &PathBuf { + &self.0 + } +} + +impl Drop for Tree { + fn drop(&mut self) { + if std::fs::remove_dir_all(&self.0).is_err() { + unlock(&self.0); + let _ = std::fs::remove_dir_all(&self.0); + } + } +} + +/// Gives the owner read, write and search permission on `folder` and on every folder in it, so +/// that a tree holding a folder a test locked can be removed. Links are not followed. +#[cfg(unix)] +fn unlock(folder: &Path) { + use std::os::unix::fs::PermissionsExt; + let Ok(meta) = std::fs::symlink_metadata(folder) else { return }; + if !meta.is_dir() { + return; + } + let mode = meta.permissions().mode() & 0o7777; + if mode & 0o700 != 0o700 { + let _ = std::fs::set_permissions(folder, std::fs::Permissions::from_mode(mode | 0o700)); + } + let Ok(entries) = std::fs::read_dir(folder) else { return }; + for entry in entries.flatten() { + if entry.file_type().is_ok_and(|t| t.is_dir()) { + unlock(&entry.path()); + } + } +} + +/// Folders on other systems are removed as they are. +#[cfg(not(unix))] +fn unlock(_: &Path) {} + /// A fresh folder (canonical, as a search reports it) holding `paths`: files, and folders where -/// they end in `/`. -fn tree(tag: &str, paths: &[&str]) -> PathBuf { - let root = vectorcraft_testkit::temp_dir(&format!("findfiles-{tag}")); - let _ = std::fs::remove_dir_all(&root); - std::fs::create_dir_all(&root).unwrap(); +/// they end in `/`. The folder is removed when the returned [`Tree`] is dropped. +fn tree(tag: &str, paths: &[&str]) -> Tree { + let mut root = Tree(vectorcraft_testkit::temp_dir(&format!("findfiles-{tag}"))); + // Empties what a tree whose removal failed left, keeping the folder as `temp_dir` made it + // (owner-only on Unix). + for entry in std::fs::read_dir(&root.0).unwrap().flatten() { + let path = entry.path(); + let _ = if entry.file_type().is_ok_and(|t| t.is_dir()) { std::fs::remove_dir_all(&path) } else { std::fs::remove_file(&path) }; + } for p in paths { let path = root.join(p); if p.ends_with('/') { @@ -58,7 +108,54 @@ fn tree(tag: &str, paths: &[&str]) -> PathBuf { std::fs::write(&path, b"font").unwrap(); } } - plain(std::fs::canonicalize(&root).unwrap()) + root.0 = plain(std::fs::canonicalize(&root.0).unwrap()); + root +} + +#[test] +fn a_tree_is_removed_when_its_test_ends() { + let path = { + let root = tree("removed", &["a/b/one.ttf", "c/"]); + assert!(root.join("a/b/one.ttf").is_file() && root.join("c").is_dir()); + root.to_path_buf() + }; + assert!(!path.exists(), "{} is left", path.display()); +} + +#[test] +fn a_tree_is_removed_when_its_test_panics() { + let mut path = PathBuf::new(); + let r = vectorcraft_testkit::catch_quiet::<()>(|| { + let root = tree("unwound", &["a/b/one.ttf"]); + path = root.to_path_buf(); + panic!("a failed assertion"); + }); + assert_eq!(r.err().as_deref(), Some("a failed assertion")); + assert!(!path.as_os_str().is_empty() && !path.exists(), "{} is left", path.display()); +} + +#[cfg(unix)] +#[test] +fn a_tree_is_private_to_this_user() { + use std::os::unix::fs::PermissionsExt; + let root = tree("private", &["a/one.ttf"]); + let mode = std::fs::metadata(&*root).unwrap().permissions().mode(); + assert_eq!(mode & 0o077, 0, "{}: mode {mode:o}", root.display()); +} + +#[cfg(unix)] +#[test] +fn a_tree_with_a_locked_folder_is_removed_when_its_test_panics() { + use std::os::unix::fs::PermissionsExt; + let mut path = PathBuf::new(); + let r = vectorcraft_testkit::catch_quiet::<()>(|| { + let root = tree("locked", &["a/locked/b/one.ttf"]); + path = root.to_path_buf(); + std::fs::set_permissions(root.join("a/locked"), std::fs::Permissions::from_mode(0o000)).unwrap(); + panic!("a failed assertion"); + }); + assert_eq!(r.err().as_deref(), Some("a failed assertion")); + assert!(!path.as_os_str().is_empty() && !path.exists(), "{} is left", path.display()); } /// The rules of a search of `root`: its `Users/me` is the home folder, `refused` an app's folder. @@ -183,6 +280,16 @@ fn a_picked_folder_inside_other_apps_folders_is_refused() { assert!(p.error().is_some_and(|e| e.ends_with("is not a folder")), "{p:?}"); let p = search(&root, "missing", Limits::default(), 1, &[]); assert!(p.error().is_some_and(|e| e.starts_with(&root.join("missing").display().to_string())), "{p:?}"); + // Each failure has the same reason without the folder's path. + let briefs = [ + ("missing", "the folder can't be read"), + ("file.ttf", "the path isn't a folder"), + ("refused", "VectorCraft doesn't search other apps' or the system's folders"), + ("Users/Public/x", "VectorCraft doesn't search the Shared or Public folder in Users"), + ]; + for (picked, why) in briefs { + assert_eq!(search(&root, picked, Limits::default(), 1, &[]).failure(), Some(why), "{picked}"); + } } #[test] @@ -362,7 +469,7 @@ fn a_picked_folder_that_cant_be_listed_fails_the_search() { let p = search(&root, "locked", Limits::default(), 2, &["y.ttf"]); std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755)).unwrap(); if enforced { - assert!(matches!(&p.end, Some(End::Failed(e)) if e.contains("locked")), "{p:?}"); + assert!(matches!(&p.end, Some(End::Failed(e, "the folder can't be listed")) if e.contains("locked")), "{p:?}"); } else { assert_eq!(found(&root, &p), ["locked/y.ttf"]); } diff --git a/crates/engine/src/cmd/findfiles/walk.rs b/crates/engine/src/cmd/findfiles/walk.rs index 8d35515717..ae05a04838 100644 --- a/crates/engine/src/cmd/findfiles/walk.rs +++ b/crates/engine/src/cmd/findfiles/walk.rs @@ -23,6 +23,13 @@ const CHECK_EVERY: u64 = 1024; /// How a search ends when every walker thread stopped on a bug. const INTERNAL: &str = "every search thread stopped on an internal error (please report this bug)"; +/// Why a search couldn't start, without the folder's path ([`Progress::failure`]). +const UNREADABLE: &str = "the folder can't be read"; +const NOT_A_FOLDER: &str = "the path isn't a folder"; +const SHARED: &str = "VectorCraft doesn't search the Shared or Public folder in Users"; +const APPS: &str = "VectorCraft doesn't search other apps' or the system's folders"; +const UNLISTED: &str = "the folder can't be listed"; + /// What a search looks for. pub trait Visitor: Send + Sync { /// Whether the regular file named `name` is to be read: asked of the files a folder lists until @@ -77,8 +84,9 @@ pub enum End { /// reached their [`Limits`]. Folders deeper than [`Limits::depth`] are skipped and an item /// keeps at most [`Limits::per_item`] files, without ending the search. Limit, - /// It couldn't start: the folder can't be read, isn't a folder or isn't one to search. - Failed(String), + /// It couldn't start: the folder can't be read, isn't a folder or isn't one to search. Why, + /// and the same without the folder's path. + Failed(String, &'static str), } /// Where a search stands ([`Search::progress`]). @@ -114,7 +122,7 @@ impl Progress { None => "searching", Some(End::Done | End::Found) => "done", Some(End::Stopped | End::Time | End::Limit) => "stopped", - Some(End::Failed(_)) => "failed", + Some(End::Failed(..)) => "failed", } } @@ -131,10 +139,38 @@ impl Progress { /// Why a failed search failed. pub fn error(&self) -> Option<&str> { match &self.end { - Some(End::Failed(e)) => Some(e), + Some(End::Failed(e, _)) => Some(e), _ => None, } } + + /// Why a failed search failed, without the folder's path. + pub fn failure(&self) -> Option<&'static str> { + match &self.end { + Some(End::Failed(_, why)) => Some(why), + _ => None, + } + } + + /// Keep what the caller asking now may read under its read roots ([`crate::file_access::current`]), + /// for a reply to it: the files found inside them. Returns the folder searched (`given` until a + /// walker checked it) and why the search failed, when that folder lies inside them too; + /// otherwise no folder and why without its path ([`Self::failure`]). Without read roots in + /// force, everything is kept. + pub fn keep_readable(&mut self, given: &str) -> (Option<String>, Option<String>) { + let folder = if self.folder.as_os_str().is_empty() { given.to_string() } else { self.folder.to_string_lossy().into_owned() }; + if crate::file_access::current().is_none() { + return (Some(folder), self.error().map(str::to_string)); + } + // A path that isn't valid text is never shown: its lossy form names another file. + let readable = |p: &Path| p.to_str().is_some_and(|p| crate::file_access::check_read(p).is_ok()); + self.hits.retain(|(path, _)| readable(path)); + if readable(Path::new(given)) && (self.folder.as_os_str().is_empty() || readable(&self.folder)) { + (Some(folder), self.error().map(str::to_string)) + } else { + (None, self.failure().map(str::to_string)) + } + } } /// Walker threads shared out among searches: all of them together run at most `cap` threads. @@ -306,7 +342,7 @@ pub(crate) fn start_in( return Err("the search couldn't start: try again in a moment".into()); } if w.alive == 0 && w.end.is_none() { - shared.finish(&mut w, End::Failed(INTERNAL.into())); + shared.finish(&mut w, End::Failed(INTERNAL.into(), INTERNAL)); } } Ok(Search { shared }) @@ -401,13 +437,13 @@ impl Shared { fn prepare(&self, root: &Path) { let rules = self.rules.get_or_init(|| self.given.clone().unwrap_or_else(Rules::system)); let path = root.display(); - let checked = match std::fs::canonicalize(root) { - Err(e) => Err(format!("{path}: {e}")), - Ok(folder) if !folder.is_dir() => Err(format!("{path} is not a folder")), + let (checked, brief) = match std::fs::canonicalize(root) { + Err(e) => (Err(format!("{path}: {e}")), UNREADABLE), + Ok(folder) if !folder.is_dir() => (Err(format!("{path} is not a folder")), NOT_A_FOLDER), Ok(folder) => match rules.refusal(&folder) { - None => Ok(folder), - Some(Refusal::Shared) => Err(format!("VectorCraft doesn't search the Shared or Public folder in Users: {path}")), - Some(Refusal::Apps) => Err(format!("VectorCraft doesn't search other apps' or the system's folders: {path}")), + None => (Ok(folder), INTERNAL), + Some(Refusal::Shared) => (Err(format!("VectorCraft doesn't search the Shared or Public folder in Users: {path}")), SHARED), + Some(Refusal::Apps) => (Err(format!("VectorCraft doesn't search other apps' or the system's folders: {path}")), APPS), }, }; let mut w = self.lock(); @@ -416,7 +452,7 @@ impl Shared { w.folder = folder.clone(); w.stack.push((folder, 0)); } - Err(e) => self.finish(&mut w, End::Failed(e)), + Err(e) => self.finish(&mut w, End::Failed(e, brief)), } } @@ -430,7 +466,7 @@ impl Shared { let mut w = self.lock(); // The picked folder itself: the search can't run, and says why. if depth == 0 { - self.finish(&mut w, End::Failed(format!("{}: {e}", plain(dir.to_path_buf()).display()))); + self.finish(&mut w, End::Failed(format!("{}: {e}", plain(dir.to_path_buf()).display()), UNLISTED)); } else { w.unreadable += 1; w.folders += 1; @@ -610,7 +646,7 @@ fn walker(s: &Shared) { if done.is_err() { let mut w = s.lock(); match job { - Job::Prepare(_) => s.finish(&mut w, End::Failed(INTERNAL.into())), + Job::Prepare(_) => s.finish(&mut w, End::Failed(INTERNAL.into(), INTERNAL)), Job::List(..) => w.unreadable += 1, } } @@ -640,7 +676,7 @@ impl Drop for Alive { let mut w = self.0.lock(); w.alive = w.alive.saturating_sub(1); if w.alive == 0 && w.end.is_none() { - self.0.finish(&mut w, End::Failed(INTERNAL.into())); + self.0.finish(&mut w, End::Failed(INTERNAL.into(), INTERNAL)); } drop(w); self.0.pool.release(1); diff --git a/crates/engine/src/cmd/flatten.rs b/crates/engine/src/cmd/flatten.rs index f950f8c1da..02b4097684 100644 --- a/crates/engine/src/cmd/flatten.rs +++ b/crates/engine/src/cmd/flatten.rs @@ -1,7 +1,10 @@ //! Object → Flatten Transparency: transparent art becomes opaque art that looks the same. //! -//! The targets (`ids` or the selection) split into groups of overlapping objects. Groups without -//! transparency stay as they are (their type and strokes are outlined on request). The others are +//! The targets (`ids` or the selection) split into groups: each object with transparency with the +//! objects it overlaps, and the objects without transparency whose stacking order with a member +//! would change when the group takes its topmost object's place. Objects without transparency +//! that overlap only others without it stay as they are (their type and strokes are outlined on +//! request), as do groups without transparency. The others are //! cut into atomic regions: the faces of the planar arrangement of every fill, outlined stroke and //! clipping path in them ([`po::regions`]). The same paints cover each whole region, so its colour //! is exact: those paints composited as the renderer composites them ([`Composer`], blend modes by diff --git a/crates/engine/src/cmd/flatten/analysis.rs b/crates/engine/src/cmd/flatten/analysis.rs index eacd124052..0adb06132a 100644 --- a/crates/engine/src/cmd/flatten/analysis.rs +++ b/crates/engine/src/cmd/flatten/analysis.rs @@ -76,12 +76,13 @@ pub(crate) fn see_through_images(doc: &Document) -> BTreeSet<String> { doc.images.iter().filter(|(_, b)| see_through(b)).map(|(k, _)| k.clone()).collect() } -/// `n` shows an image of `keys` (itself or inside). +/// `n` shows an image of `keys` (itself or inside), a color-masked image's masked pixels counted as +/// what it shows. pub(super) fn draws_image(n: &Node, keys: &BTreeSet<String>) -> bool { !keys.is_empty() && n.visible && match &n.kind { - NodeKind::Image(im) => keys.contains(&im.key), + NodeKind::Image(im) => keys.contains(&im.key) || Document::color_mask_of(n).is_some_and(|m| m.made_for(im) && keys.contains(&m.key)), _ => n.children().is_some_and(|ch| ch.iter().any(|c| draws_image(c, keys))), } } @@ -99,17 +100,80 @@ pub(super) fn masked(n: &Node) -> bool { n.extras().mask.as_ref().is_some_and(|m| !m.disabled) } -/// Where `n` can paint: its visual bounds grown by its effects (and a margin for antialiasing). -pub(super) fn reach(n: &Node) -> Option<Rect> { +/// Where `n` paints: its visual bounds grown by its effects. +pub(super) fn painted(n: &Node) -> Option<Rect> { if !n.visible { return None; } let b = match n.children() { - Some(ch) if !n.clips() && !matches!(n.kind, NodeKind::Compound { .. }) => ch.iter().filter_map(|c| reach(c)).reduce(|a, b| a.union(b))?, + Some(ch) if !n.clips() && !matches!(n.kind, NodeKind::Compound { .. }) => ch.iter().filter_map(|c| painted(c)).reduce(|a, b| a.union(b))?, _ => n.visual_bounds()?, }; let fx = n.appearance.items.iter().map(|i| effects::outset(i.effects(), b)).fold(effects::outset(&n.appearance.effects, b), f64::max); - Some(b.inflate(fx + 1.0, fx + 1.0)) + Some(b.inflate(fx, fx)) +} + +/// Where `n` can paint: where it paints ([`painted`]) and a margin of 1 pt for antialiasing, +/// once, however deep its groups nest. +pub(super) fn reach(n: &Node) -> Option<Rect> { + painted(n).map(|b| b.inflate(1.0, 1.0)) +} + +type Cancelled = vectorcraft_doc::cancel::Cancelled; + +/// Whether `b` has finite coordinates and isn't inside out. +pub(super) fn finite(b: &Rect) -> bool { + [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()) && b.x0 <= b.x1 && b.y0 <= b.y1 +} + +/// Whether boxes `a` and `b` overlap or touch. +fn touch(a: &Rect, b: &Rect) -> bool { + a.x0 <= b.x1 && b.x0 <= a.x1 && a.y0 <= b.y1 && b.y0 <= a.y1 +} + +/// Indices joined into sets, each set knowing whether it holds an object with transparency. +struct Sets { + parent: Vec<usize>, + seeded: Vec<bool>, + /// How many open boxes the sweep's boxes met. + #[cfg(test)] + meets: usize, +} + +impl Sets { + fn find(&mut self, mut i: usize) -> usize { + while self.parent[i] != i { + self.parent[i] = self.parent[self.parent[i]]; + i = self.parent[i]; + } + i + } + + /// Joins the sets of `a` and `b`: → the set they are now, named by its lowest index. + fn join(&mut self, a: usize, b: usize) -> usize { + let (a, b) = (self.find(a), self.find(b)); + let (lo, hi) = (a.min(b), a.max(b)); + self.parent[hi] = lo; + self.seeded[lo] |= self.seeded[hi]; + lo + } + + /// The sets, each in index order, by their first index. + fn groups(&mut self) -> Vec<Vec<usize>> { + let mut groups: Vec<Vec<usize>> = vec![]; + let mut slot: Vec<Option<usize>> = vec![None; self.parent.len()]; + for i in 0..self.parent.len() { + let r = self.find(i); + match slot[r] { + Some(g) => groups[g].push(i), + None => { + slot[r] = Some(groups.len()); + groups.push(vec![i]); + } + } + } + groups + } } /// Indices of `bounds` grouped by overlap (transitively), each group in index order. Boxes that @@ -119,18 +183,25 @@ pub(super) fn reach(n: &Node) -> Option<Rect> { /// tops that knows the lowest bottom below each of its branches, so each box meets only the open /// boxes it overlaps, not every open one (many objects stacked in a column, sharing their /// horizontal extent, would otherwise compare every pair). An open box inside a later box of -/// its group, ending no further right, is closed early: whatever overlaps it overlaps that box. -/// Fails only when cancelled ([`vectorcraft_doc::cancel`]). -pub(super) fn overlapping(bounds: &[Option<Rect>]) -> Result<Vec<Vec<usize>>, vectorcraft_doc::cancel::Cancelled> { - fn find(p: &mut [usize], mut i: usize) -> usize { - while p[i] != i { - p[i] = p[p[i]]; - i = p[i]; - } - i - } - let mut parent: Vec<usize> = (0..bounds.len()).collect(); - let finite = |b: &Rect| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()) && b.x0 <= b.x1 && b.y0 <= b.y1; +/// its group, ending no further right, is closed early, and a box inside an open box of its group, +/// ending no further right, isn't opened: whatever overlaps it overlaps that box. Fails only when +/// cancelled ([`vectorcraft_doc::cancel`]). +pub(super) fn overlapping(bounds: &[Option<Rect>]) -> Result<Vec<Vec<usize>>, Cancelled> { + Ok(sweep(bounds, None)?.groups()) +} + +/// [`overlapping`]'s sweep. With `see_through`, two boxes are joined only when one of them is +/// see-through, and an open box is closed early, or a box isn't opened, only inside a see-through +/// box. The open +/// see-through boxes and the open boxes without transparency are then in trees of their own, and +/// a box without transparency meets only the see-through ones. +fn sweep(bounds: &[Option<Rect>], see_through: Option<&[bool]>) -> Result<Sets, Cancelled> { + let mut sets = Sets { + parent: (0..bounds.len()).collect(), + seeded: (0..bounds.len()).map(|i| see_through.is_some_and(|s| s[i])).collect(), + #[cfg(test)] + meets: 0, + }; let boxes: Vec<(usize, Rect)> = bounds.iter().enumerate().filter_map(|(i, b)| b.filter(finite).map(|b| (i, b))).collect(); let n = boxes.len(); // Each box's place in the tree: by top (then index). @@ -141,9 +212,11 @@ pub(super) fn overlapping(bounds: &[Option<Rect>]) -> Result<Vec<Vec<usize>>, ve for (pos, &k) in by_top.iter().enumerate() { leaf[k] = pos; } - // The lowest bottom of the open boxes below each node (−∞: none open). + // The lowest bottom of the open boxes below each node (−∞: none open), in the tree of the + // boxes without transparency (every box without `see_through`) and the see-through boxes'. let size = n.next_power_of_two().max(1); - let mut low = vec![f64::NEG_INFINITY; 2 * size]; + let mut low = [vec![f64::NEG_INFINITY; 2 * size], if see_through.is_some() { vec![f64::NEG_INFINITY; 2 * size] } else { vec![] }]; + let tree = |k: usize| usize::from(see_through.is_some_and(|s| s[boxes[k].0])); let set = |low: &mut [f64], pos: usize, v: f64| { let mut i = pos + size; low[i] = v; @@ -166,53 +239,184 @@ pub(super) fn overlapping(bounds: &[Option<Rect>]) -> Result<Vec<Vec<usize>>, ve while let Some(&c) = by_right.get(closing) && boxes[c].1.x1 < b.x0 { - set(&mut low, leaf[c], f64::NEG_INFINITY); + set(&mut low[tree(c)], leaf[c], f64::NEG_INFINITY); closing += 1; } - // The open boxes with their top at most this bottom and their bottom at least this top. + // The open boxes it joins with their top at most this bottom and their bottom at least + // this top: every one, or with `see_through` the see-through ones and, for a see-through + // box, the others too. + let shadows = see_through.is_none_or(|s| s[boxes[k].0]); + let looks: &[usize] = match see_through { + None => &[0], + Some(_) if shadows => &[0, 1], + Some(_) => &[1], + }; let below = tops.partition_point(|t| *t <= b.y1); met.clear(); - stack.clear(); - stack.push((1, 0, size)); - while let Some((node, lo, hi)) = stack.pop() { - work += 1; + for &t in looks { + stack.clear(); + stack.push((1, 0, size)); + while let Some((node, lo, hi)) = stack.pop() { + work += 1; + if work.is_multiple_of(4096) { + vectorcraft_doc::cancel::check()?; + } + if lo >= below || low[t][node] < b.y0 { + continue; + } + if hi - lo == 1 { + met.push(by_top[lo]); + continue; + } + let mid = (lo + hi) / 2; + stack.push((2 * node + 1, mid, hi)); + stack.push((2 * node, lo, mid)); + } + } + #[cfg(test)] + { + sets.meets += met.len(); + } + // An open box it met that holds it, ending no further right, and that joins whatever it + // overlaps: whatever later overlaps this box overlaps that one and joins it, so this box + // isn't opened. + let holder = met.iter().copied().find(|&o| { + let ob = boxes[o].1; + see_through.is_none_or(|s| s[boxes[o].0]) && b.x1 <= ob.x1 && ob.y0 <= b.y0 && b.y1 <= ob.y1 + }); + // Whatever overlaps a box inside this one overlaps this one, and joins it when this one is + // see-through. + for &o in &met { + sets.join(boxes[k].0, boxes[o].0); + let ob = boxes[o].1; + if shadows && Some(o) != holder && ob.x1 <= b.x1 && b.y0 <= ob.y0 && ob.y1 <= b.y1 { + set(&mut low[tree(o)], leaf[o], f64::NEG_INFINITY); + } + } + if holder.is_none() { + set(&mut low[tree(k)], leaf[k], b.y1); + } + } + Ok(sets) +} + +/// Boxes in blocks of nearby ones, each block with the box around it, to find the boxes a box +/// touches. +struct Blocks { + order: Vec<usize>, + boxes: Vec<Option<Rect>>, + around: Vec<Rect>, +} + +impl Blocks { + const SIZE: usize = 32; + + /// The finite boxes of `boxes`, in vertical strips by their centers and in blocks down each + /// strip. + fn new(boxes: &[Option<Rect>]) -> Self { + let boxes: Vec<Option<Rect>> = boxes.iter().map(|b| b.filter(finite)).collect(); + let mut order: Vec<usize> = (0..boxes.len()).filter(|&i| boxes[i].is_some()).collect(); + let center = |i: usize| boxes[i].map_or_else(Default::default, |b| b.center()); + order.sort_by(|&a, &b| center(a).x.total_cmp(¢er(b).x)); + let strip = ((order.len() as f64 / Self::SIZE as f64).sqrt().ceil() as usize).max(1) * Self::SIZE; + for s in order.chunks_mut(strip) { + s.sort_by(|&a, &b| center(a).y.total_cmp(¢er(b).y)); + } + let around = order.chunks(Self::SIZE).filter_map(|c| c.iter().filter_map(|&i| boxes[i]).reduce(|a, b| a.union(b))).collect(); + Self { order, boxes, around } + } + + /// Puts the indices of the boxes that touch `q` in `out`. `work` counts the boxes looked at; + /// fails only when cancelled. + fn touching(&self, q: &Rect, out: &mut Vec<usize>, work: &mut usize) -> Result<(), Cancelled> { + out.clear(); + for (b, around) in self.around.iter().enumerate() { + *work += 1; if work.is_multiple_of(4096) { vectorcraft_doc::cancel::check()?; } - if lo >= below || low[node] < b.y0 { + if !touch(around, q) { continue; } - if hi - lo == 1 { - met.push(by_top[lo]); + for &i in &self.order[b * Self::SIZE..((b + 1) * Self::SIZE).min(self.order.len())] { + *work += 1; + if self.boxes[i].is_some_and(|r| touch(&r, q)) { + out.push(i); + } + } + } + Ok(()) + } +} + +/// Objects (in paint order) grouped for flattening, each group in paint order and the groups by +/// their first object; a group takes the place of its topmost object. `reach` is where each +/// object can paint ([`reach`]), `painted` where it paints ([`painted`]), and `see_through` whether +/// it has transparency. An object whose box is missing or not finite is a group of its own. +/// +/// An object joins every see-through object its reach touches. An object without transparency +/// that touches only others without transparency stays a group of its own, unless a group would +/// change its stacking order with it: it joins (and groups join each other) where its reach +/// touches a member's and moving the members to their group's top would put the two the other way +/// round. With a `fringe` (how far a group's image can reach past +/// its art and cover what is under it), an object or group under a group's top whose painted box +/// that far around a member's touches joins it too. Fails only when cancelled +/// ([`vectorcraft_doc::cancel`]). +pub(super) fn flatten_groups( + reach: &[Option<Rect>], + painted: &[Option<Rect>], + see_through: &[bool], + fringe: f64, +) -> Result<Vec<Vec<usize>>, Cancelled> { + let n = reach.len(); + let mut sets = sweep(reach, Some(see_through))?; + let mut members: Vec<Vec<usize>> = vec![vec![]; n]; + for i in 0..n { + let r = sets.find(i); + members[r].push(i); + } + // The topmost object of each set (by its name). + let mut top: Vec<usize> = (0..n).map(|r| members[r].last().copied().unwrap_or(r)).collect(); + let index = Blocks::new(reach); + // Each member of a set with transparency is looked at. + let mut work: Vec<usize> = vec![]; + for i in 0..n { + let r = sets.find(i); + if sets.seeded[r] { + work.push(i); + } + } + let (mut near, mut looked) = (vec![], 0usize); + while let Some(i) = work.pop() { + let Some(q) = reach[i].filter(finite) else { continue }; + // Painted boxes within the fringe have reaches within it too. + index.touching(&q.inflate(fringe, fringe), &mut near, &mut looked)?; + for &k in &near { + let (ri, rk) = (sets.find(i), sets.find(k)); + if ri == rk { continue; } - let mid = (lo + hi) / 2; - stack.push((2 * node + 1, mid, hi)); - stack.push((2 * node, lo, mid)); - } - for &o in &met { - let (a, c) = (find(&mut parent, boxes[k].0), find(&mut parent, boxes[o].0)); - parent[a.max(c)] = a.min(c); - let ob = boxes[o].1; - if ob.x1 <= b.x1 && b.y0 <= ob.y0 && ob.y1 <= b.y1 { - set(&mut low, leaf[o], f64::NEG_INFINITY); + let (ti, tk) = (top[ri], top[rk]); + let crossed = reach[k].is_some_and(|b| touch(&q, &b)) && (i < k) != (ti < tk); + let covered = fringe > 0.0 && tk < ti && painted[i].zip(painted[k]).is_some_and(|(a, b)| touch(&a.inflate(fringe, fringe), &b)); + if !crossed && !covered { + continue; } - } - set(&mut low, leaf[k], b.y1); - } - let mut groups: Vec<Vec<usize>> = vec![]; - let mut slot: Vec<Option<usize>> = vec![None; bounds.len()]; - for i in 0..bounds.len() { - let r = find(&mut parent, i); - match slot[r] { - Some(g) => groups[g].push(i), - None => { - slot[r] = Some(groups.len()); - groups.push(vec![i]); + // The members of a set whose top moves are looked at again, from there. + let t = ti.max(tk); + if ti != t { + work.extend_from_slice(&members[ri]); } + if tk != t { + work.extend_from_slice(&members[rk]); + } + let r = sets.join(ri, rk); + let moved = std::mem::take(&mut members[if r == ri { rk } else { ri }]); + members[r].extend(moved); + top[r] = t; } } - Ok(groups) + Ok(sets.groups()) } #[cfg(test)] @@ -221,6 +425,11 @@ mod tests { /// What [`overlapping`] gives, comparing every pair. fn every_pair(bounds: &[Option<Rect>]) -> Vec<Vec<usize>> { + every_pair_joining(bounds, |_, _| true) + } + + /// The groups of `bounds` comparing every pair, joining overlapping pairs that `joins`. + fn every_pair_joining(bounds: &[Option<Rect>], joins: impl Fn(usize, usize) -> bool) -> Vec<Vec<usize>> { let n = bounds.len(); let mut group: Vec<usize> = (0..n).collect(); let hit = |a: &Rect, b: &Rect| a.x0 <= b.x1 && b.x0 <= a.x1 && a.y0 <= b.y1 && b.y0 <= a.y1; @@ -230,6 +439,7 @@ mod tests { for j in 0..n { if let (Some(a), Some(b)) = (bounds[i], bounds[j]) && hit(&a, &b) + && joins(i, j) && group[j] < group[i] { group[i] = group[j]; @@ -292,4 +502,272 @@ mod tests { let odd = [Some(Rect::new(0.0, 0.0, 10.0, 10.0)), Some(Rect::new(f64::NAN, 0.0, 10.0, 10.0)), Some(Rect::new(5.0, 5.0, 20.0, 20.0))]; assert_eq!(overlapping(&odd).unwrap(), vec![vec![0, 2], vec![1]]); } + + /// `n` boxes sharing their left and top edges, each inside the one before. + fn shrinking_nest(n: usize) -> Vec<Option<Rect>> { + (0..n).map(|i| Some(Rect::new(0.0, 0.0, 2.0 * (n - i) as f64, 2.0 * (n - i) as f64))).collect() + } + + /// Each box of a nest that shrinks to the right and bottom meets only the outermost box, which + /// stays open and holds it, not every box around it. + #[test] + fn a_shrinking_nest_meets_only_its_outermost_box() { + let n = 512; + let bounds = shrinking_nest(n); + let mut sets = sweep(&bounds, None).unwrap(); + assert_eq!(sets.meets, n - 1); + assert_eq!(sets.groups(), every_pair(&bounds)); + assert_eq!(sets.groups(), vec![(0..n).collect::<Vec<_>>()]); + // Equal boxes: the later one isn't opened and the earlier one stays open for the third. + let same = [Some(Rect::new(0.0, 0.0, 10.0, 10.0)), Some(Rect::new(0.0, 0.0, 10.0, 10.0)), Some(Rect::new(9.0, 9.0, 20.0, 20.0))]; + assert_eq!(overlapping(&same).unwrap(), vec![vec![0, 1, 2]]); + // With transparency, an opaque box isn't opened inside a see-through box, and boxes inside + // an opaque box are opened: an opaque box that overlaps only the inner one still joins it + // when that one is see-through. + let see = [true, false]; + let mut sets = sweep(&bounds[..2], Some(&see)).unwrap(); + assert_eq!(sets.groups(), vec![vec![0, 1]]); + let held = [Some(Rect::new(0.0, 0.0, 20.0, 20.0)), Some(Rect::new(0.0, 0.0, 10.0, 10.0)), Some(Rect::new(5.0, 5.0, 8.0, 8.0))]; + let mut sets = sweep(&held, Some(&[false, true, false])).unwrap(); + assert_eq!(sets.groups(), vec![vec![0, 1, 2]]); + let mut sets = sweep(&held, Some(&[true, false, false])).unwrap(); + assert_eq!(sets.groups(), vec![vec![0, 1, 2]]); + let mut sets = sweep(&held, Some(&[false, false, true])).unwrap(); + assert_eq!(sets.groups(), vec![vec![0, 1, 2]]); + let mut sets = sweep(&held, Some(&[false, false, false])).unwrap(); + assert_eq!(sets.groups(), vec![vec![0], vec![1], vec![2]]); + } + + /// Boxes nested at shared corners and placed at random, some see-through, group with and + /// without transparency as comparing every pair groups them. + #[test] + fn nested_and_scattered_boxes_group_as_comparing_every_pair() { + let mut seed = 0x51_7cc1_b727_220au64; + let mut next = |m: f64| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed % 1000) as f64 / 1000.0 * m + }; + for round in 0..40 { + let n = 6 + round * 3; + let bounds: Vec<Option<Rect>> = (0..n) + .map(|_| { + // Corners on a coarse grid so that edges are often shared and boxes often nest. + let (x, y) = ((next(6.0).floor()) * 10.0, (next(6.0).floor()) * 10.0); + let (w, h) = ((next(5.0).floor() + 1.0) * 10.0, (next(5.0).floor() + 1.0) * 10.0); + Some(Rect::new(x, y, x + w, y + h)) + }) + .collect(); + assert_eq!(overlapping(&bounds).unwrap(), every_pair(&bounds), "round {round}"); + let see: Vec<bool> = (0..n).map(|_| next(1.0) < 0.3).collect(); + let mut sets = sweep(&bounds, Some(&see)).unwrap(); + assert_eq!(sets.groups(), every_pair_joining(&bounds, |i, j| see[i] || see[j]), "round {round}, with transparency"); + } + } + + /// A filled rectangle, unstroked. + fn filled(id: u64, r: Rect) -> Node { + let look = vectorcraft_doc::Appearance::basic( + vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)), + vectorcraft_color::Paint::None, + 0.0, + ); + Node::path(vectorcraft_doc::NodeId(id), vectorcraft_geom::shapes::rectangle(r), look) + } + + /// The antialiasing margin goes around the outermost group once, not once per group. + #[test] + fn reach_adds_its_margin_once_however_deep_the_groups() { + let r = Rect::new(10.0, 20.0, 30.0, 50.0); + let inner = Node::group(vectorcraft_doc::NodeId(2), vec![Arc::new(filled(1, r))]); + let outer = Node::group(vectorcraft_doc::NodeId(3), vec![Arc::new(inner)]); + assert_eq!(painted(&outer), Some(r)); + assert_eq!(reach(&outer), Some(r.inflate(1.0, 1.0))); + assert_eq!(reach(&filled(1, r)), reach(&outer)); + } + + /// The group of each object, the topmost object of each group and whether it is see-through. + fn sets_of(groups: &[Vec<usize>], n: usize, see_through: &[bool]) -> (Vec<usize>, Vec<usize>, Vec<bool>) { + let mut of = vec![usize::MAX; n]; + for (g, ids) in groups.iter().enumerate() { + for &i in ids { + of[i] = g; + } + } + let top = groups.iter().map(|g| *g.last().unwrap()).collect(); + let seeded = groups.iter().map(|g| g.iter().any(|&i| see_through[i])).collect(); + (of, top, seeded) + } + + /// What [`flatten_groups`] must give: every object in one group, in paint order, the groups by + /// their first object; see-through objects with all that their reach touches; groups without + /// transparency of one object; no two objects that paint over each other the other way round + /// once each group takes its top's place; nothing within `fringe` of a member of a group under + /// that group's top. + fn check(reach: &[Option<Rect>], painted: &[Option<Rect>], see: &[bool], fringe: f64, groups: &[Vec<usize>], what: &str) { + let n = reach.len(); + let mut all: Vec<usize> = groups.iter().flatten().copied().collect(); + all.sort_unstable(); + assert_eq!(all, (0..n).collect::<Vec<_>>(), "{what}: every object once"); + assert!(groups.iter().all(|g| g.is_sorted()) && groups.windows(2).all(|w| w[0][0] < w[1][0]), "{what}: in order"); + let (of, top, seeded) = sets_of(groups, n, see); + for (g, ids) in groups.iter().enumerate() { + assert!(seeded[g] || ids.len() == 1, "{what}: {ids:?} has no transparency"); + } + for i in 0..n { + for j in 0..n { + if i == j || of[i] == of[j] { + continue; + } + let (gi, gj) = (of[i], of[j]); + if let (Some(a), Some(b)) = (reach[i], reach[j]) { + assert!(!(touch(&a, &b) && (see[i] || see[j])), "{what}: {i} and {j} touch, one see-through"); + if seeded[gi] && touch(&a, &b) { + assert_eq!(i < j, top[gi] < top[gj], "{what}: {i} and {j} change places"); + } + } + let (Some(a), Some(b)) = (painted[i], painted[j]) else { continue }; + if seeded[gi] && fringe > 0.0 && touch(&a.inflate(fringe, fringe), &b) { + assert!(top[gj] > top[gi], "{what}: {j} under the image of {i}'s group"); + } + } + } + } + + /// Boxes of many sizes, some see-through, group as they must, with and without a fringe. + #[test] + fn flatten_groups_keep_stacking_order_and_leave_opaque_art_alone() { + let mut seed = 0x9e37_79b9_7f4a_7c15u64; + let mut next = |m: f64| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed % 1000) as f64 / 1000.0 * m + }; + for round in 0..60 { + let n = 4 + round; + let painted: Vec<Option<Rect>> = (0..n) + .map(|i| { + if i % 13 == 5 { + return None; + } + let (x, y) = (next(120.0).round(), next(120.0).round()); + Some(Rect::new(x, y, x + next(25.0).round(), y + next(25.0).round())) + }) + .collect(); + let reach: Vec<Option<Rect>> = painted.iter().map(|b| b.map(|b| b.inflate(1.0, 1.0))).collect(); + let see: Vec<bool> = (0..n).map(|_| next(1.0) < 0.15).collect(); + for fringe in [0.0, 0.7] { + let groups = flatten_groups(&reach, &painted, &see, fringe).unwrap(); + check(&reach, &painted, &see, fringe, &groups, &format!("round {round}, fringe {fringe}")); + } + } + } + + /// A row of opaque boxes whose reaches touch, with see-through ones at its ends and far from + /// it: only the boxes next to a see-through one join it. + #[test] + fn an_opaque_row_stays_apart_from_the_see_through_boxes_at_its_ends() { + let n = 200; + // 10 pt boxes 1.5 pt apart: their 1 pt reaches overlap. + let painted: Vec<Option<Rect>> = (0..n).map(|i| Some(Rect::new(11.5 * i as f64, 0.0, 11.5 * i as f64 + 10.0, 10.0))).collect(); + let reach: Vec<Option<Rect>> = painted.iter().map(|b| b.map(|b| b.inflate(1.0, 1.0))).collect(); + let mut see = vec![false; n]; + see[0] = true; + see[n - 1] = true; + let groups = flatten_groups(&reach, &painted, &see, 0.0).unwrap(); + check(&reach, &painted, &see, 0.0, &groups, "row"); + assert_eq!(groups[0], vec![0, 1]); + assert_eq!(groups.last(), Some(&vec![n - 2, n - 1])); + assert_eq!(groups.len(), n - 2); + // Without transparency every box is a group of its own. + assert_eq!(flatten_groups(&reach, &painted, &vec![false; n], 0.0).unwrap().len(), n); + } + + /// A small see-through box, then `n` opaque boxes nested around it, each inside the one + /// before and sharing its left and top edges. + fn nest_around_a_see_through_box(n: usize) -> (Vec<Option<Rect>>, Vec<bool>) { + let mut bounds = vec![Some(Rect::new(0.0, 0.0, 1.0, 1.0))]; + bounds.extend((0..n).map(|i| Some(Rect::new(0.0, 0.0, 2.0 * (n - i) as f64 + 1.0, 2.0 * (n - i) as f64 + 1.0)))); + let mut see = vec![false; n + 1]; + see[0] = true; + (bounds, see) + } + + /// Opaque boxes nested in each other around a see-through box each meet only the see-through + /// box, not the open opaque boxes they can't join, and all join it. + #[test] + fn nested_opaque_boxes_meet_only_the_see_through_box() { + let n = 512; + let (bounds, see) = nest_around_a_see_through_box(n); + let mut sets = sweep(&bounds, Some(&see)).unwrap(); + assert_eq!(sets.meets, n); + assert_eq!(sets.groups(), vec![(0..=n).collect::<Vec<_>>()]); + // The unfiltered sweep that runs before it meets each box once too. + let mut sets = sweep(&bounds, None).unwrap(); + assert_eq!(sets.meets, n); + assert_eq!(sets.groups(), vec![(0..=n).collect::<Vec<_>>()]); + let (painted, see) = nest_around_a_see_through_box(40); + let reach: Vec<Option<Rect>> = painted.iter().map(|b| b.map(|b| b.inflate(1.0, 1.0))).collect(); + for fringe in [0.0, 0.7] { + let groups = flatten_groups(&reach, &painted, &see, fringe).unwrap(); + check(&reach, &painted, &see, fringe, &groups, &format!("nest, fringe {fringe}")); + assert_eq!(groups, vec![(0..=40).collect::<Vec<_>>()]); + } + } + + /// An opaque box inside a later see-through box is closed: later boxes meet the see-through + /// box instead, and join the opaque one through it. + #[test] + fn a_see_through_box_closes_an_opaque_box_inside_it() { + // An opaque box, a see-through box around it, a see-through box over both and an opaque + // box over the first. + let bounds = [ + Some(Rect::new(0.0, 0.0, 10.0, 10.0)), + Some(Rect::new(0.0, 0.0, 20.0, 20.0)), + Some(Rect::new(5.0, 5.0, 30.0, 30.0)), + Some(Rect::new(8.0, 8.0, 12.0, 12.0)), + ]; + let see = [false, true, true, false]; + let mut sets = sweep(&bounds, Some(&see)).unwrap(); + // The second box meets the first; the third meets the second; the fourth meets the second + // and the third. + assert_eq!(sets.meets, 4); + assert_eq!(sets.groups(), vec![vec![0, 1, 2, 3]]); + // Opaque boxes alone meet nothing. + let mut sets = sweep(&bounds, Some(&[false; 4])).unwrap(); + assert_eq!(sets.meets, 0); + assert_eq!(sets.groups().len(), 4); + } + + /// An opaque box between a member and its group's top that paints over the member joins, and + /// so on along a chain; one under the member stays, but for one within the fringe. + #[test] + fn boxes_the_group_would_cross_join_it() { + // In paint order: D under A, A, B over A, C over B, then the see-through T over A. + let d = Rect::new(40.0, 80.0, 65.0, 120.0); + let a = Rect::new(60.0, 50.0, 105.0, 90.0); + let b = Rect::new(20.0, 20.0, 65.0, 55.0); + let c = Rect::new(0.0, 0.0, 25.0, 25.0); + let t = Rect::new(100.0, 50.0, 140.0, 90.0); + let painted = [Some(d), Some(a), Some(b), Some(c), Some(t)]; + let reach: Vec<Option<Rect>> = painted.iter().map(|b| b.map(|b| b.inflate(1.0, 1.0))).collect(); + let see = [false, false, false, false, true]; + let groups = flatten_groups(&reach, &painted, &see, 0.0).unwrap(); + assert_eq!(groups, vec![vec![0], vec![1, 2, 3, 4]]); + // C away from B: it stays. + let far = [Some(d), Some(a), Some(b), Some(Rect::new(0.0, 0.0, 10.0, 10.0)), Some(t)]; + let reach_far: Vec<Option<Rect>> = far.iter().map(|b| b.map(|b| b.inflate(1.0, 1.0))).collect(); + assert_eq!(flatten_groups(&reach_far, &far, &see, 0.0).unwrap(), vec![vec![0], vec![1, 2, 4], vec![3]]); + // B 0.5 pt above A, not overlapping it: their antialiased edges can share pixels, so B joins. + let gap = [Some(d), Some(a), Some(Rect::new(20.0, 20.0, 65.0, 49.5)), Some(Rect::new(0.0, 0.0, 10.0, 10.0)), Some(t)]; + let reach_gap: Vec<Option<Rect>> = gap.iter().map(|b| b.map(|b| b.inflate(1.0, 1.0))).collect(); + assert_eq!(flatten_groups(&reach_gap, &gap, &see, 0.0).unwrap(), vec![vec![0], vec![1, 2, 4], vec![3]]); + // D a little left of A, under it: the fringe takes it in. + let near = [Some(Rect::new(40.0, 80.0, 59.8, 120.0)), Some(a), Some(b), Some(c), Some(t)]; + let reach_near: Vec<Option<Rect>> = near.iter().map(|b| b.map(|b| b.inflate(1.0, 1.0))).collect(); + assert_eq!(flatten_groups(&reach_near, &near, &see, 0.0).unwrap()[0], vec![0]); + assert_eq!(flatten_groups(&reach_near, &near, &see, 0.24).unwrap(), vec![vec![0, 1, 2, 3, 4]]); + } } diff --git a/crates/engine/src/cmd/flatten/apply.rs b/crates/engine/src/cmd/flatten/apply.rs index c1366dba3c..ef8425b362 100644 --- a/crates/engine/src/cmd/flatten/apply.rs +++ b/crates/engine/src/cmd/flatten/apply.rs @@ -1,4 +1,4 @@ -use super::analysis::{Scratch, has_effects, masked, outlined_text, overlapping, reach}; +use super::analysis::{Scratch, finite, flatten_groups, has_effects, masked, outlined_text, overlapping, painted, reach}; use super::compose::{Builder, CLEAR, Composer, Elem, Fill, Kind, Px, WHITE}; use super::options::FlattenOptions; use super::{ @@ -115,7 +115,7 @@ pub(super) fn plan(src: &Document, roots: &[NodeId], o: &FlattenOptions, render: let mut out = Plan { flat: vec![], kept: vec![], transparent: roots.iter().zip(&see_through).filter(|(_, t)| **t).map(|(id, _)| *id).collect() }; // Baking above stopped early when cancelled; each group is a place to stop (a plan changes nothing). vectorcraft_doc::cancel::check()?; - let mut queue = overlapping(&reaches)?; + let mut queue = groups(src, roots, &plain, &reaches, &see_through, o)?; queue.reverse(); while let Some(g) = queue.pop() { vectorcraft_doc::cancel::check()?; @@ -196,6 +196,46 @@ pub(super) fn plan(src: &Document, roots: &[NodeId], o: &FlattenOptions, render: Ok(out) } +/// `roots` of `src` (`plain`: as plain art; `reaches`: where each can paint, clipped) in the +/// groups that flatten together ([`flatten_groups`]), each in paint order, by their first object. +/// Objects that overlap (as [`overlapping`] groups them) stay in one group when one of them is +/// inside a clip group or clipping layer: [`inside_and_under`] and [`place_of`] then decide where +/// they go. +fn groups( + src: &Document, + roots: &[NodeId], + plain: &[Node], + reaches: &[Option<Rect>], + see_through: &[bool], + o: &FlattenOptions, +) -> Result<Vec<Vec<usize>>> { + // An image clipped to its regions, opaque over white, reaches a pixel past them; a group's + // image is no larger than the art it overlaps, so its pixels are no wider than this. + let opaque_edge = o.no_transparency.is_some() && o.clip_complex_regions && !o.preserve_alpha; + let ppi = o.line_art_ppi.min(o.gradient_ppi).max(1.0); + let extent = |ids: &mut dyn Iterator<Item = usize>| ids.filter_map(|i| reaches[i].filter(finite)).reduce(|a, b| a.union(b)).unwrap_or_default(); + // Where the widest such pixel is wider than the margins of two reaches, objects that close + // overlap too. + let widest = if opaque_edge { 1.0 / raster_scale(extent(&mut (0..reaches.len())), ppi) } else { 0.0 }; + let grow = ((widest - 2.0) / 2.0).max(0.0); + let near: Vec<Option<Rect>> = reaches.iter().map(|b| b.map(|b| b.inflate(grow, grow))).collect(); + let mut out = vec![]; + for g in overlapping(if grow > 0.0 { &near } else { reaches })? { + let clipped = || clips_count() && g.iter().any(|&i| !clip_ancestors(src, roots[i]).is_empty()); + if g.len() < 2 || !g.iter().any(|&i| see_through[i]) || clipped() { + out.push(g); + continue; + } + let fringe = if opaque_edge { 1.0 / raster_scale(extent(&mut g.iter().copied()), ppi) } else { 0.0 }; + let local = |v: &[Option<Rect>]| g.iter().map(|&i| v[i]).collect::<Vec<_>>(); + let painted: Vec<Option<Rect>> = g.iter().map(|&i| painted(&plain[i])).collect(); + let see: Vec<bool> = g.iter().map(|&i| see_through[i]).collect(); + out.extend(flatten_groups(&local(reaches), &painted, &see, fringe)?.into_iter().map(|l| l.into_iter().map(|k| g[k]).collect::<Vec<_>>())); + } + out.sort_by_key(|g| g.first().copied()); + Ok(out) +} + /// `plain` (object `id` of `src` as plain art) inside a clip group for each clip group and /// clipping layer around `id`, innermost first, each clipped by that group's or layer's clipping /// path. `plain` itself when nothing around it clips. With `fills` (clipping paths, and an area), @@ -482,11 +522,7 @@ fn region_fill(elems: &[Elem], sources: &[usize], o: &FlattenOptions, cmyk: bool /// amounts (a CMYK TIFF), so its CMYK colours keep their numbers (#2160); other images are PNGs. /// Fails when the image can't be encoded. fn render_raster(doc: &Document, art: &[Node], rect: Rect, ppi: f64, clip: Option<PathData>, o: &FlattenOptions) -> Result<Raster> { - let mut scale = ppi / 72.0; - scale = scale.min((MAX_PIXELS / (rect.width() * rect.height()).max(1.0)).sqrt()); - // No side longer than the renderer draws: the image grows by a pixel on each side and is - // rounded up to whole pixels below. - scale = scale.min((f64::from(vectorcraft_render::MAX_RASTER_SIDE) - 4.0) / rect.width().max(rect.height()).max(1.0)); + let scale = raster_scale(rect, ppi); let px = 1.0 / scale; let rect = rect.inflate(px, px); let clip = clip.map(|c| Some(po::offset_path(&c, px, po::Join::Miter, 4.0)).filter(|g| !g.is_empty()).unwrap_or(c)); @@ -559,6 +595,14 @@ fn render_raster(doc: &Document, art: &[Node], rect: Rect, ppi: f64, clip: Optio Ok(Raster { blob: ImageBlob::new("image/png", png), width: img.width, height: img.height, xf, clip }) } +/// Pixels per point of an image of `rect` at `ppi`: lower when the image would be larger than +/// [`MAX_PIXELS`], or have a side longer than the renderer draws (the image grows by a pixel on +/// each side and is rounded up to whole pixels). +fn raster_scale(rect: Rect, ppi: f64) -> f64 { + let scale = (ppi / 72.0).min((MAX_PIXELS / (rect.width() * rect.height()).max(1.0)).sqrt()); + scale.min((f64::from(vectorcraft_render::MAX_RASTER_SIDE) - 4.0) / rect.width().max(rect.height()).max(1.0)) +} + /// `n` at full opacity with Normal blending throughout (objects, fills and strokes). pub(super) fn opaque(n: &mut Node) { n.opacity = 1.0; @@ -877,4 +921,42 @@ mod tests { assert_eq!(flat.parent_of(g), Some(layer)); assert_eq!(flat.children(Some(layer)).and_then(|c| c.last()).map(|c| c.id), Some(g)); } + + /// In a file without transparency with Clip Complex Regions on, art under a group's opaque + /// image within one of its pixels joins the group, also where a long image is made at a lower + /// resolution and its pixels are wider than at the preset's. + #[test] + fn art_under_the_edge_of_a_long_opaque_image_joins_its_group() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 31000, "height": 100})).unwrap(); + let rect = |s: &mut Session, x: f64, w: f64| { + let id = s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": w, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setStroke", &json!({"none": true, "ids": [id]})).unwrap(); + NodeId(id) + }; + // 0.5 pt left of A: wider than a pixel at 300 ppi, narrower than one of a 30,000 pt image. + let d = rect(&mut s, 40.0, 19.5); + let a = rect(&mut s, 60.0, 40.0); + let t = rect(&mut s, 95.0, 30_000.0); + s.execute("transparency.set", &json!({"ids": [t.0], "opacity": 50})).unwrap(); + let o = FlattenOptions { no_transparency: Some(Default::default()), clip_complex_regions: true, ..FlattenOptions::default() }; + let doc = &s.doc().unwrap().doc; + let long = plan(doc, &[d, a, t], &o, false).unwrap(); + assert!(long.kept.is_empty(), "{:?}", long.kept); + assert_eq!(long.flat.iter().map(|f| f.roots.clone()).collect::<Vec<_>>(), vec![vec![d, a, t]]); + // Short, the image has 300 ppi pixels: D stays. + let short = rect(&mut s, 95.0, 40.0); + s.execute("transparency.set", &json!({"ids": [short.0], "opacity": 50})).unwrap(); + let doc = &s.doc().unwrap().doc; + assert_eq!(plan(doc, &[d, a, short], &o, false).unwrap().kept, vec![d]); + // 100,000 pt long, its pixels are over 3 pt wide: art 3 pt away, whose reach doesn't touch + // A's, joins too. + let far = rect(&mut s, 40.0, 17.0); + let longer = rect(&mut s, 95.0, 100_000.0); + s.execute("transparency.set", &json!({"ids": [longer.0], "opacity": 50})).unwrap(); + let doc = &s.doc().unwrap().doc; + let p = plan(doc, &[far, a, longer], &o, false).unwrap(); + assert!(p.kept.is_empty(), "{:?}", p.kept); + assert_eq!(p.flat.iter().map(|f| f.roots.clone()).collect::<Vec<_>>(), vec![vec![far, a, longer]]); + } } diff --git a/crates/engine/src/cmd/flatten/options.rs b/crates/engine/src/cmd/flatten/options.rs index a5881c76ef..16cf8e5de7 100644 --- a/crates/engine/src/cmd/flatten/options.rs +++ b/crates/engine/src/cmd/flatten/options.rs @@ -155,7 +155,8 @@ impl FlattenOptions { /// the paint ([`vectorcraft_doc::ImageBlob::takes_colorize`]) never counts: it draws uncolorized. pub(crate) fn counts_colorize(&self, d: &Document, n: &Node) -> bool { let NodeKind::Image(im) = &n.kind else { return true }; - let blob = d.image_blob(im); + let shown = d.shown_image(n, im); + let blob = d.image_blob(&shown); if blob.is_some_and(|b| !b.takes_colorize()) { return false; } diff --git a/crates/engine/src/cmd/fontfiles.rs b/crates/engine/src/cmd/fontfiles.rs index 309347985c..fde85dd92d 100644 --- a/crates/engine/src/cmd/fontfiles.rs +++ b/crates/engine/src/cmd/fontfiles.rs @@ -67,7 +67,7 @@ pub fn specs() -> Vec<CommandSpec> { "Missing Fonts", [], None, - "{} → {fonts: [{family, style, status: missing|substitute, resolved: {family, style}}] (sorted by name; at most 1000), count, fontsNextToDocument?} the fonts the active document's type uses, in its layers and its symbols (for type in a composite font, the fonts of the parts its characters are drawn in), that aren't available as named: missing (the family is unknown and the fallback family stands in) or substitute (the family is there but not the style; resolved names the stand-in), as text.fonts says. CSS generic families such as sans-serif and names longer than 256 bytes are left out. fontsNextToDocument: the Fonts folder next to the saved document (File › Package writes it), when there is one and a search may start there (not in another app's folders, such as a mail app's attachments)", + "{} → {fonts: [{family, style, status: missing|substitute, resolved: {family, style}}] (sorted by name; at most 1000), count, fontsNextToDocument?} the fonts the active document's type uses, in its layers, its symbols and its patterns, opacity masks included (for type in a composite font, the fonts of the parts its characters are drawn in), that aren't available as named: missing (the family is unknown and the fallback family stands in) or substitute (the family is there but not the style; resolved names the stand-in), as text.fonts says. CSS generic families such as sans-serif and names longer than 256 bytes are left out. fontsNextToDocument: the Fonts folder next to the saved document (File › Package writes it), when there is one and a search may start there (not in another app's folders, such as a mail app's attachments)", has_doc, missing ), @@ -76,7 +76,7 @@ pub fn specs() -> Vec<CommandSpec> { "Find Font Files", [], None, - "{folder?: an absolute path, fonts?: [{family, style?}] (1 to 1000; default: the active document's missing fonts, as text.missingFonts lists them), maxSeconds?: 60 (1 to 600), stop?: false (true: stop the last search)} with folder: look in it and its subfolders for font files that make the fonts available, on separate threads, and answer at once (state: searching); without folder: the last search's state, with the files found so far. A search reads the table directories and the name, fvar and OS/2 tables of .ttf, .otf, .ttc and .otc files of at most 256 MB and, on macOS, of suitcase fonts (files without an extension or with .suit, whose fonts are in a resource fork of at most 8 MB), and lists a file for a font when the file, added with text.addFontFiles, makes the font resolve exactly as text.fonts resolves it; fonts that resolve exactly already are left out. It doesn't enter app packages, folders named Program Files (also x86 and Arm), ProgramData, $Recycle.Bin or System Volume Information, the system's folders at the root of a volume, the Shared and Public folders in Users, a home folder's Library, AppData, Applications, snap and dot folders, a Library folder's app data folders or the folders the environment names for apps' data, and a search of a folder inside one of them fails; the walk also skips other hidden folders, folders whose contents are in the cloud and folders more than 64 levels deep, and follows no links (a picked path is resolved through its links); none on the web → {id (absent while idle), state: idle|searching|done|stopped|failed, folder?, fonts: [{family, style, status, files: [paths]}], searched?: {folders, files, fontFiles}, skipped?, unreadable?, stopped?: stop|time|limit, error?, seconds?}", + "{folder?: an absolute path, fonts?: [{family, style?}] (1 to 1000; default: the active document's missing fonts, as text.missingFonts lists them), maxSeconds?: 60 (1 to 600), stop?: false (true: stop the last search)} with folder: look in it and its subfolders for font files that make the fonts available, on separate threads, and answer at once (state: searching); without folder: the last search's state, with the files found so far. A search reads the table directories and the name, fvar and OS/2 tables of .ttf, .otf, .ttc and .otc files of at most 256 MB and, on macOS, of suitcase fonts (files without an extension or with .suit, whose fonts are in a resource fork of at most 8 MB), and lists a file for a font when the file, added with text.addFontFiles, makes the font resolve exactly as text.fonts resolves it; fonts that resolve exactly already are left out. It doesn't enter app packages, folders named Program Files (also x86 and Arm), ProgramData, $Recycle.Bin or System Volume Information, the system's folders at the root of a volume, the Shared and Public folders in Users, a home folder's Library, AppData, Applications, snap and dot folders, a Library folder's app data folders or the folders the environment names for apps' data, and a search of a folder inside one of them fails; the walk also skips other hidden folders, folders whose contents are in the cloud and folders more than 64 levels deep, and follows no links (a picked path is resolved through its links). With automation read roots, a reply leaves out the files found outside the caller's roots, and the folder when it is outside them (error then gives the reason without the path); none on the web → {id (absent while idle), state: idle|searching|done|stopped|failed, folder?, fonts: [{family, style, status, files: [paths]}], searched?: {folders, files, fontFiles}, skipped?, unreadable?, stopped?: stop|time|limit, error?, seconds?}", always, find ), @@ -85,7 +85,7 @@ pub fn specs() -> Vec<CommandSpec> { "Add Font Files", [], None, - "{files: [paths the last text.findFontFiles search found] (1 to 1000)} copy the font files into VectorCraft's own Fonts folder (next to the preferences; the desktop app and vectorcraft-cli read it), never replacing a file there: the names Name.otf, Name 2.otf … Name 99.otf are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is kept; then scan the fonts again, as text.rescanFonts does, and type set in them redraws. Only regular .ttf, .otf, .ttc, .otc, .woff and .woff2 files and suitcase fonts (with their resource fork) are copied, at most 256 MB a file and 1 GB in all; any other file is skipped. Add only fonts you own or are licensed to install; none on the web → {folder, copied: [{from, to}], kept: [{from, to}], skipped: [{file, reason}], families?, faces?}", + "{files: [paths the last text.findFontFiles search found] (1 to 1000)} copy the font files into VectorCraft's own Fonts folder (next to the preferences; the desktop app and vectorcraft-cli read it), never replacing a file there: the names Name.otf, Name 2.otf … Name 99.otf are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is kept; then scan the fonts again, as text.rescanFonts does, and type set in them redraws. Only regular .ttf, .otf, .ttc, .otc, .woff and .woff2 files and suitcase fonts (with their resource fork) are copied, at most 256 MB a file and 1 GB in all; any other file is skipped. Add only fonts you own or are licensed to install. With automation read roots, folder is null when the Fonts folder is outside them, and a to or file path outside them is given as its file name; none on the web → {folder, copied: [{from, to}], kept: [{from, to}], skipped: [{file, reason}], families?, faces?}", always, add ), @@ -103,7 +103,7 @@ pub struct MissingFont { pub resolved: Option<(String, String)>, } -/// The fonts the type of `d` uses, in its layers and its symbols (a composite font's parts, those +/// The fonts the type of `d` uses, in its layers, symbols and patterns, opacity masks included (a composite font's parts, those /// its characters are drawn in, in place of its name), that aren't available as named (sorted by family and style, each once whatever version its type names; at most 1000). CSS generic families such as `sans-serif` /// ([`GENERIC_FAMILIES`]) and names longer than 256 bytes are left out. pub fn missing_fonts(d: &Document) -> Vec<MissingFont> { @@ -275,7 +275,9 @@ fn find(s: &mut Session, p: &Value) -> Result<Value> { /// Where the session's last search stands (`text.findFontFiles` without `folder`). fn state(s: &Session) -> Value { let Some(f) = &s.font_search else { return json!({ "state": "idle", "fonts": [] }) }; - let p = f.search.progress(); + let mut p = f.search.progress(); + // Only what the caller asking now may read: a search another caller started can hold more. + let (folder, error) = p.keep_readable(&f.folder); let mut files: Vec<Vec<String>> = vec![vec![]; f.fonts.len()]; for (path, items) in &p.hits { for i in items { @@ -293,16 +295,18 @@ fn state(s: &Session) -> Value { json!({ "family": font.family, "style": font.style, "status": font.status.as_str(), "files": files }) }) .collect(); - let folder = if p.folder.as_os_str().is_empty() { f.folder.clone() } else { p.folder.to_string_lossy().into_owned() }; let mut out = json!({ - "id": f.id, "state": p.state(), "folder": folder, "fonts": fonts, + "id": f.id, "state": p.state(), "fonts": fonts, "searched": { "folders": p.folders, "files": p.files, "fontFiles": p.read }, "skipped": p.skipped, "unreadable": p.unreadable, "seconds": (p.seconds * 10.0).round() / 10.0, }); + if let Some(folder) = folder { + out["folder"] = json!(folder); + } if let Some(why) = p.stopped() { out["stopped"] = json!(why); } - if let Some(e) = p.error() { + if let Some(e) = error { out["error"] = json!(e); } out @@ -348,12 +352,16 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { // VectorCraft's own Fonts folder: no automation root applies to it. crate::file_access::unconfined(|| super::fileio::create_dir(&dir.to_string_lossy()))?; let report = copy_into(&files, dir); - let pairs = |v: &[(PathBuf, PathBuf)]| { - v.iter().map(|(from, to)| json!({ "from": from.to_string_lossy(), "to": to.to_string_lossy() })).collect::<Vec<_>>() + // The caller sees the Fonts folder and the copies in it only where its read roots reach. + let readable = |p: &Path| crate::file_access::current().is_none() || p.to_str().is_some_and(|p| crate::file_access::check_read(p).is_ok()); + let shown = |p: &Path| -> String { + let shown = if readable(p) { Some(p.as_os_str()) } else { p.file_name() }; + shown.map(|s| s.to_string_lossy().into_owned()).unwrap_or_default() }; + let pairs = |v: &[(PathBuf, PathBuf)]| v.iter().map(|(from, to)| json!({ "from": from.to_string_lossy(), "to": shown(to) })).collect::<Vec<_>>(); let mut out = json!({ - "folder": dir.to_string_lossy(), "copied": pairs(&report.copied), "kept": pairs(&report.kept), - "skipped": report.skipped.iter().map(|(file, why)| json!({ "file": file.to_string_lossy(), "reason": why })).collect::<Vec<_>>(), + "folder": readable(dir).then(|| dir.to_string_lossy()), "copied": pairs(&report.copied), "kept": pairs(&report.kept), + "skipped": report.skipped.iter().map(|(file, why)| json!({ "file": shown(file), "reason": why })).collect::<Vec<_>>(), }); if !report.copied.is_empty() || !report.kept.is_empty() { // The fonts are cataloged and type set in them redraws, as Refresh Font List does it. diff --git a/crates/engine/src/cmd/fonts.rs b/crates/engine/src/cmd/fonts.rs index 2a6d1cb0df..005427ded8 100644 --- a/crates/engine/src/cmd/fonts.rs +++ b/crates/engine/src/cmd/fonts.rs @@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> { "Fonts in Document", [], None, - "{selectionOnly?} (the type in the art of the symbols in scope included: all of the document's, or those the selected instances show) → [{family, style, runs, objects, missing, status: exact|substitute|missing, resolved: {family, style}, missingGlyphs, version?: the installed version the type names (when it names one)}] sorted by name. A font is found by any of its names (ヒラギノ角ゴシック = Hiragino Sans) among the loaded and installed fonts; substitute: the family is there but not the style (resolved names the stand-in); missing: the family is unknown (the fallback family stands in); missingGlyphs: characters of its text the resolved font lacks (drawn by a fallback font). For a composite font, status is the worst among the parts its characters are drawn in, and missingGlyphs counts the characters their part's font lacks", + "{selectionOnly?} (the type in the opacity masks of the objects in scope and in the art of the symbols and patterns in scope included: all of the document's, a pattern swatch that nothing paints included, or those the selected objects show through their instances and paints; disabled masks too) → [{family, style, runs, objects, missing, status: exact|substitute|missing, resolved: {family, style}, missingGlyphs, version?: the installed version the type names (when it names one)}] sorted by name. A font is found by any of its names (ヒラギノ角ゴシック = Hiragino Sans) among the loaded and installed fonts; substitute: the family is there but not the style (resolved names the stand-in); missing: the family is unknown (the fallback family stands in); missingGlyphs: characters of its text the resolved font lacks (drawn by a fallback font). For a composite font, status is the worst among the parts its characters are drawn in, and missingGlyphs counts the characters their part's font lacks", has_doc, fonts ), @@ -30,7 +30,7 @@ pub fn specs() -> Vec<CommandSpec> { "Replace Font", [], None, - "{from: {family, style?}, to: {family (any of its names; stored as the font's own family name, a composite font's as its own name), style?}, selectionOnly?} (style omitted: every style of the family / keep the closest style); the type in the art of the symbols in scope changes too (all of the document's, or those the selected instances show, so every instance of them follows); text that is hidden or locked, in a hidden or locked group or layer (or group of a symbol's art), or on a locked artboard keeps its font; when no run changes (text already set in the new font, or none to change), the document and its undo history stay as they are → {runs: the runs changed, skipped?: the text objects left in the font, warning?: text (some text was left in its font, or the style set isn't available: its type is drawn in the family's closest style)}", + "{from: {family, style?}, to: {family (any of its names; stored as the font's own family name, a composite font's as its own name), style?}, selectionOnly?} (style omitted: every style of the family / keep the closest style); the type in the opacity masks of the objects in scope (disabled masks too) and in the art of the symbols and patterns in scope changes too (all of the document's, or those the selected objects show through their instances and paints, so every instance of a symbol and every object a pattern paints follows); text that is hidden or locked, in a hidden or locked group or layer (or group of a symbol's, pattern's or mask's art), in the mask of a hidden or locked object, or on a locked artboard keeps its font; when no run changes (text already set in the new font, or none to change), the document and its undo history stay as they are → {runs: the runs changed, skipped?: the text objects left in the font, warning?: text (some text was left in its font, or the style set isn't available: its type is drawn in the family's closest style)}", has_doc, replace ), @@ -39,7 +39,7 @@ pub fn specs() -> Vec<CommandSpec> { "Select Text by Font", [], None, - "{family, style?, scope?: \"document\" (default) | {artboards: [index, …] (0-based)} | {layers: [id, …] (layers or sublayers)}} select the text objects using the font, and the instances of the symbols whose art uses it, that are not hidden or locked, in a hidden or locked group or layer, or on a locked artboard; with scope, only those on one of the artboards (as All on Active Artboard takes them: their bounds overlap it or their center is on it) or in one of the layers → {count}", + "{family, style?, scope?: \"document\" (default) | {artboards: [index, …] (0-based)} | {layers: [id, …] (layers or sublayers)}} select the text objects using the font, the instances of the symbols whose art uses it, the text whose inline graphics draw such a symbol, the objects painted with a pattern whose art uses it (by a visible fill or stroke whose opacity is above 0, a stroke wider than 0) and the objects whose opacity mask uses it (in type that is not hidden or locked in that art), that are not hidden or locked, in a hidden or locked group or layer, or on a locked artboard; a pattern swatch that nothing paints, or a layer's mask, selects nothing; with scope, only those on one of the artboards (as All on Active Artboard takes them: their bounds overlap it or their center is on it) or in one of the layers → {count}", has_doc, select_font ), @@ -64,15 +64,23 @@ pub fn specs() -> Vec<CommandSpec> { ] } -/// Text objects in scope: the selection's (and their descendants') or the whole document's. -fn scope(s: &Session, selection_only: bool, selected: Option<&[NodeId]>) -> Result<Vec<NodeId>> { +/// Text objects in scope: the selection's (and their descendants') or the whole document's, and +/// the objects among them that have an opacity mask (not the object whose mask is being edited: +/// its art is on the editing layer). +fn scope(s: &Session, selection_only: bool, selected: Option<&[NodeId]>) -> Result<(Vec<NodeId>, Vec<NodeId>)> { let st = s.doc()?; - let mut v = vec![]; + let editing = st.doc.mask_edit.map(|m| m.object); + let (mut texts, mut masked) = (vec![], vec![]); let mut seen = HashSet::new(); let mut add = |n: &vectorcraft_doc::Node| { n.walk(&mut |c| { - if matches!(c.kind, NodeKind::Text(_)) && seen.insert(c.id) { - v.push(c.id); + if seen.insert(c.id) { + if matches!(c.kind, NodeKind::Text(_)) { + texts.push(c.id); + } + if c.extras().mask.is_some() && Some(c.id) != editing { + masked.push(c.id); + } } }) }; @@ -87,7 +95,7 @@ fn scope(s: &Session, selection_only: bool, selected: Option<&[NodeId]>) -> Resu add(l); } } - Ok(v) + Ok((texts, masked)) } /// Whether `name` is the symbol being edited, whose art is on the editing layer. @@ -95,106 +103,333 @@ fn being_edited(d: &Document, name: &str) -> bool { d.symbol_edit.as_ref().is_some_and(|e| e.symbol == name) } -/// The symbols that the selected objects of `s` show: those of the instances among them and their -/// descendants, and of the instances in those symbols' art that are not hidden or locked, nor in a -/// hidden or locked group of the art. Returned as (all of them, those shown by instances the -/// Selection tool can reach: not hidden or locked, as `Document::editable` says). -fn selected_symbols(s: &Session, selected: Option<&[NodeId]>) -> Result<(BTreeSet<String>, BTreeSet<String>)> { - fn open_instances(n: &Node, out: &mut BTreeSet<String>) { +/// Whether `name` is the pattern being edited, whose tile art is on the editing layer. +fn pattern_being_edited(d: &Document, name: &str) -> bool { + d.pattern_edit.as_ref().is_some_and(|e| e.pattern == name) +} + +/// Whether fill or stroke `i` paints: it is visible, its opacity is above 0 and, a stroke, it is +/// wider than 0. +fn paints(i: &AppearanceItem) -> bool { + i.visible() && i.opacity() > 0.0 && !matches!(i, AppearanceItem::Stroke(s) if s.width <= 0.0) +} + +/// The name of pattern paint `p`. +fn pattern_name(p: &Paint) -> Option<&str> { + match p { + Paint::Pattern { pattern, .. } => Some(pattern.as_str()), + _ => None, + } +} + +/// Whether `r` is laid out as an inline graphic: it has one and holds only its character. +fn draws_inline(r: &TextRun) -> bool { + r.inline.is_some() && vectorcraft_text::edit::is_inline_text(&r.text) +} + +/// The fill and, when it is wider than 0, the stroke of the characters of `r`. +fn run_paints(r: &TextRun) -> impl Iterator<Item = &Paint> { + [Some(&r.style.fill), (r.style.stroke_width > 0.0).then_some(&r.style.stroke)].into_iter().flatten() +} + +/// [`run_paints`] of run `r` of `t` when its characters draw with them. The characters of an +/// inline graphic draw no glyph: their fill and stroke paint only their underline and +/// strikethrough (not on a path or in vertical type, see `vectorcraft_text::decorations`) and the +/// ruby readings that layout draws with their run (`ruby`, as [`ruby_runs`] finds them). +fn drawn_run_paints<'a>(t: &TextObject, ruby: &HashSet<*const TextRun>, r: &'a TextRun) -> impl Iterator<Item = &'a Paint> { + let drawn = !draws_inline(r) || inline_decorated(t, ruby, r); + run_paints(r).filter(move |_| drawn) +} + +/// The inline graphic runs of `t` that layout draws a ruby reading with. A reading takes the run +/// of the first base character on its line, and type on a path has no ruby. `t` is laid out only +/// when it has ruby and an inline graphic painted with a pattern. +fn ruby_runs(t: &TextObject) -> HashSet<*const TextRun> { + let patterned = |r: &TextRun| draws_inline(r) && run_paints(r).any(|p| pattern_name(p).is_some()); + if t.ruby.is_empty() || !t.runs.iter().any(patterned) { + return HashSet::new(); + } + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + lay.ruby.iter().filter_map(|g| t.runs.get(g.run)).filter(|r| draws_inline(r)).map(std::ptr::from_ref).collect() +} + +/// Whether inline graphic run `r` of `t` has an underline or strikethrough that draws, or a ruby +/// reading that layout draws with it (it is in `ruby`). +fn inline_decorated(t: &TextObject, ruby: &HashSet<*const TextRun>, r: &TextRun) -> bool { + let bars = !t.vertical && !matches!(t.kind, TextKind::OnPath { .. }); + if bars && (r.style.underline || r.style.strikethrough) { + return true; + } + ruby.contains(&std::ptr::from_ref(r)) +} + +/// The patterns that the fills and strokes `n` draws name (of a text object, also those of its +/// characters): those that [`paints`] holds for, and the character paints of the runs that draw +/// (as [`drawn_runs`] finds them: not the overset runs of area type or type on a path) where they +/// draw (as [`drawn_run_paints`] says). +fn paint_patterns(n: &Node) -> Vec<&str> { + let mut out: Vec<&str> = n.appearance.items.iter().filter(|i| paints(i)).filter_map(|i| pattern_name(i.paint())).collect(); + if let NodeKind::Text(t) = &n.kind + && t.runs.iter().flat_map(run_paints).any(|p| pattern_name(p).is_some()) + { + let ruby = ruby_runs(t); + out.extend(drawn_runs(t).0.into_iter().flat_map(|r| drawn_run_paints(t, &ruby, r)).filter_map(pattern_name)); + } + out +} + +/// The symbols that the inline graphics in the type of `n` draw (as [`drawn_runs`] finds them: not +/// those in the overset runs of area type or type on a path). +fn inline_symbols(n: &Node) -> Vec<&str> { + match &n.kind { + NodeKind::Text(t) if t.runs.iter().any(draws_inline) => { + drawn_runs(t).0.into_iter().filter(|r| draws_inline(r)).filter_map(|r| r.inline.as_ref().map(|art| art.symbol.as_str())).collect() + } + _ => vec![], + } +} + +/// Symbols and patterns, by name: those whose art is in scope. +#[derive(Clone, Debug, Default)] +struct Resources { + symbols: BTreeSet<String>, + patterns: BTreeSet<String>, +} + +impl Resources { + /// Adds what `n` itself shows: the symbol of an instance, the symbols of the inline graphics in + /// its type, the patterns its paints name, and what the art of its opacity mask shows (not + /// hidden or locked objects of that art). + fn add_own(&mut self, n: &Node) { + if let NodeKind::SymbolInstance { symbol, .. } = &n.kind { + self.symbols.insert(symbol.clone()); + } + self.symbols.extend(inline_symbols(n).into_iter().map(str::to_string)); + self.patterns.extend(paint_patterns(n).into_iter().map(str::to_string)); + if let Some(m) = n.extras().mask.as_deref() { + self.add(&m.art); + } + } + + /// Adds what `n` and its descendants show, leaving out hidden or locked objects and what they + /// hold. + fn add(&mut self, n: &Node) { if !n.visible || n.locked { return; } - if let NodeKind::SymbolInstance { symbol, .. } = &n.kind { - out.insert(symbol.clone()); - } + self.add_own(n); for c in n.children().map(Vec::as_slice).unwrap_or_default() { - open_instances(c, out); + self.add(c); } } - let expand = |names: &mut BTreeSet<String>, d: &Document| loop { - let mut more = BTreeSet::new(); - for sym in d.symbols.iter().filter(|sym| names.contains(&sym.name)) { - open_instances(&sym.art, &mut more); + + /// Adds what the art of the symbols and patterns named shows, until nothing more is added; each + /// symbol and pattern is read once, so art that shows itself ends. + fn expand(&mut self, d: &Document) { + let mut symbols: Vec<String> = self.symbols.iter().cloned().collect(); + let mut patterns: Vec<String> = self.patterns.iter().cloned().collect(); + while !symbols.is_empty() || !patterns.is_empty() { + let mut more = Resources::default(); + for name in symbols.drain(..) { + if let Some(sym) = d.symbols.iter().find(|sym| sym.name == name) { + more.add(&sym.art); + } + } + for name in patterns.drain(..) { + for art in d.pattern(&name).map(|p| p.art.as_slice()).unwrap_or_default() { + more.add(art); + } + } + symbols.extend(more.symbols.into_iter().filter(|name| self.symbols.insert(name.clone()))); + patterns.extend(more.patterns.into_iter().filter(|name| self.patterns.insert(name.clone()))); } - let before = names.len(); - names.extend(more); - if names.len() == before { - break; + } + + /// The symbols and patterns of `self` that are not in `other`. + fn difference(&self, other: &Self) -> Self { + Self { + symbols: self.symbols.difference(&other.symbols).cloned().collect(), + patterns: self.patterns.difference(&other.patterns).cloned().collect(), } - }; + } +} + +/// The symbols and patterns that the selected objects of `s` show: those of the instances among +/// them and their descendants and the patterns their paints name (also in the art of their +/// opacity masks), and those that the art of these symbols and patterns shows through objects that +/// are not hidden or locked, nor in a hidden or locked group of the art. Returned as (all of them, +/// those shown by objects the Selection tool can reach: not hidden or locked, as +/// `Document::editable` says). +fn selected_art(s: &Session, selected: Option<&[NodeId]>) -> Result<(Resources, Resources)> { let st = s.doc()?; - let (mut all, mut open) = (BTreeSet::new(), BTreeSet::new()); + let (mut all, mut open) = (Resources::default(), Resources::default()); let editable = st.doc.editable(); for id in selected.unwrap_or(&st.selection.objects) { if let Some(n) = st.doc.node(*id) { n.walk(&mut |c| { - if let NodeKind::SymbolInstance { symbol, .. } = &c.kind { - all.insert(symbol.clone()); - if editable(c.id) { - open.insert(symbol.clone()); - } + all.add_own(c); + if editable(c.id) { + open.add_own(c); } }); } } drop(editable); - expand(&mut all, &st.doc); - expand(&mut open, &st.doc); + all.expand(&st.doc); + open.expand(&st.doc); Ok((all, open)) } -/// The text objects in the art of `d`'s symbols (with `only`, of those it names), each with -/// whether it is open: neither it nor a group around it in the art is hidden or locked. The symbol -/// being edited is left out: its art is on the editing layer. -pub(super) fn symbol_texts<'a>(d: &'a Document, only: Option<&BTreeSet<String>>) -> Vec<(&'a TextObject, bool)> { - fn visit<'a>(n: &'a Node, open: bool, out: &mut Vec<(&'a TextObject, bool)>) { - let open = open && n.visible && !n.locked; - if let NodeKind::Text(t) = &n.kind { - out.push((&**t, open)); - } - for c in n.children().map(Vec::as_slice).unwrap_or_default() { - visit(c, open, out); - } +/// A text object found in art: its id, the text and whether it is open (neither it nor a group +/// around it, nor an object whose opacity mask holds it, is hidden or locked). +pub(super) type ArtText<'a> = (NodeId, &'a TextObject, bool); + +/// Adds the text objects of `n` and its descendants, the art of their opacity masks included, to +/// `out`; each is open when `open` holds and [`ArtText`] says so. +fn art_texts<'a>(n: &'a Node, open: bool, out: &mut Vec<ArtText<'a>>) { + let open = open && n.visible && !n.locked; + if let NodeKind::Text(t) = &n.kind { + out.push((n.id, &**t, open)); } + if let Some(m) = n.extras().mask.as_deref() { + art_texts(&m.art, open, out); + } + for c in n.children().map(Vec::as_slice).unwrap_or_default() { + art_texts(c, open, out); + } +} + +/// The text objects in the art of the opacity masks of the objects `masked` (each with whether +/// the object is open: when it isn't, none of its mask's text is). +fn mask_texts<'a>(d: &'a Document, masked: &[(NodeId, bool)]) -> Vec<ArtText<'a>> { let mut out = vec![]; - for s in d.symbols.iter().filter(|s| !being_edited(d, &s.name) && only.is_none_or(|o| o.contains(&s.name))) { - visit(&s.art, true, &mut out); + for (id, open) in masked { + if let Some(m) = d.node(*id).and_then(|n| n.extras().mask.as_deref()) { + art_texts(&m.art, *open, &mut out); + } } out } -/// Calls `f` on each text object in the art of `d`'s symbols (with `only`, of those it names) for -/// which `wants(text, open)` holds (open as in [`symbol_texts`]), the symbol being edited left out. -/// Art without such text is left as it is. -pub(super) fn edit_symbol_texts( - d: &mut Document, - only: Option<&BTreeSet<String>>, - wants: &impl Fn(&TextObject, bool) -> bool, - f: &mut impl FnMut(&mut TextObject), -) { - fn wanted(n: &Node, open: bool, wants: &impl Fn(&TextObject, bool) -> bool) -> bool { - let open = open && n.visible && !n.locked; - matches!(&n.kind, NodeKind::Text(t) if wants(t, open)) || n.children().is_some_and(|ch| ch.iter().any(|c| wanted(c, open, wants))) +/// The text objects in the art of `d`'s symbols and patterns (with `only`, of those it names, a +/// pattern's art read once however many objects it paints), opacity masks in that art included. +/// The symbol and the pattern being edited are left out: their art is on the editing layer. +fn resource_texts<'a>(d: &'a Document, only: Option<&Resources>) -> Vec<ArtText<'a>> { + let mut out = vec![]; + for s in d.symbols.iter().filter(|s| !being_edited(d, &s.name) && only.is_none_or(|o| o.symbols.contains(&s.name))) { + art_texts(&s.art, true, &mut out); } - fn visit(n: &mut Node, open: bool, wants: &impl Fn(&TextObject, bool) -> bool, f: &mut impl FnMut(&mut TextObject)) { - let open = open && n.visible && !n.locked; - if let NodeKind::Text(t) = &mut n.kind - && wants(t, open) - { - f(t); + for p in d.patterns.iter().filter(|p| !pattern_being_edited(d, &p.name) && only.is_none_or(|o| o.patterns.contains(&p.name))) { + for art in &p.art { + art_texts(art, true, &mut out); } - for c in n.children_mut().into_iter().flatten() { - if wanted(c, open, wants) { - visit(Arc::make_mut(c), open, wants, f); + } + out +} + +/// The text objects in the art of `d`'s symbols (with `only`, of those it names), as +/// [`resource_texts`] finds them, each with whether it is open. +#[cfg(test)] +pub(super) fn symbol_texts<'a>(d: &'a Document, only: Option<&BTreeSet<String>>) -> Vec<(&'a TextObject, bool)> { + let mut out = vec![]; + for s in d.symbols.iter().filter(|s| !being_edited(d, &s.name) && only.is_none_or(|o| o.contains(&s.name))) { + art_texts(&s.art, true, &mut out); + } + out.into_iter().map(|(_, t, open)| (t, open)).collect() +} + +/// Whether `n` or a descendant (the art of their opacity masks included) holds a text object for +/// which `wants(text, open)` holds, open as [`ArtText`] says. +fn wanted(n: &Node, open: bool, wants: &impl Fn(&TextObject, bool) -> bool) -> bool { + let open = open && n.visible && !n.locked; + matches!(&n.kind, NodeKind::Text(t) if wants(t, open)) + || n.extras().mask.as_deref().is_some_and(|m| wanted(&m.art, open, wants)) + || n.children().is_some_and(|ch| ch.iter().any(|c| wanted(c, open, wants))) +} + +/// Calls `f` on each text object of `n` and its descendants (the art of their opacity masks +/// included) for which `wants(text, open)` holds; only the nodes on the way to such text are +/// copied. +fn edit_art(n: &mut Node, open: bool, wants: &impl Fn(&TextObject, bool) -> bool, f: &mut impl FnMut(&mut TextObject)) { + let open = open && n.visible && !n.locked; + if let NodeKind::Text(t) = &mut n.kind + && wants(t, open) + { + f(t); + } + if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) + && wanted(&m.art, open, wants) + { + edit_art(Arc::make_mut(&mut m.art), open, wants, f); + } + for c in n.children_mut().into_iter().flatten() { + if wanted(c, open, wants) { + edit_art(Arc::make_mut(c), open, wants, f); + } + } +} + +/// Calls `f` on each text object in the opacity masks of the objects `masked` (as [`mask_texts`] +/// finds them) for which `wants(text, open)` holds. Masks without such text are left as they are. +fn edit_mask_texts(d: &mut Document, masked: &[(NodeId, bool)], wants: &impl Fn(&TextObject, bool) -> bool, f: &mut impl FnMut(&mut TextObject)) { + for (id, open) in masked { + if d.node(*id).and_then(|n| n.extras().mask.as_deref()).is_some_and(|m| wanted(&m.art, *open, wants)) + && let Some(m) = d.node_mut(*id).and_then(|n| n.extras_if_any()).and_then(|e| e.mask.as_mut()) + { + edit_art(Arc::make_mut(&mut m.art), *open, wants, f); + } + } +} + +/// Calls `f` on each text object in the art of `d`'s symbols and patterns (as [`resource_texts`] +/// finds them) for which `wants(text, open)` holds. Art without such text is left as it is. +fn edit_resource_texts(d: &mut Document, only: Option<&Resources>, wants: &impl Fn(&TextObject, bool) -> bool, f: &mut impl FnMut(&mut TextObject)) { + let symbol = d.symbol_edit.as_ref().map(|e| e.symbol.clone()); + let pattern = d.pattern_edit.as_ref().map(|e| e.pattern.clone()); + for s in &mut d.symbols { + if symbol.as_ref() != Some(&s.name) && only.is_none_or(|o| o.symbols.contains(&s.name)) && wanted(&s.art, true, wants) { + edit_art(Arc::make_mut(&mut s.art), true, wants, f); + } + } + for p in &mut d.patterns { + if pattern.as_ref() != Some(&p.name) && only.is_none_or(|o| o.patterns.contains(&p.name)) { + for art in &mut p.art { + if wanted(art, true, wants) { + edit_art(Arc::make_mut(art), true, wants, f); + } } } } - let edited = d.symbol_edit.as_ref().map(|e| e.symbol.clone()); - for s in &mut d.symbols { - if edited.as_ref() != Some(&s.name) && only.is_none_or(|o| o.contains(&s.name)) && wanted(&s.art, true, wants) { - visit(Arc::make_mut(&mut s.art), true, wants, f); +} + +/// Every text object of `d` outside the objects of its layers: in the opacity masks of the +/// objects on its layers, and in the art of its symbols and patterns (as [`mask_texts`] and +/// [`resource_texts`] find them, each mask's text open). +pub(super) fn art_texts_of(d: &Document) -> Vec<ArtText<'_>> { + let masked = masked_objects(d); + let mut out = mask_texts(d, &masked); + out.extend(resource_texts(d, None)); + out +} + +/// Calls `f` on each text object of [`art_texts_of`] for which `wants(text)` holds. +pub(super) fn edit_art_texts_of(d: &mut Document, wants: &impl Fn(&TextObject) -> bool, f: &mut impl FnMut(&mut TextObject)) { + let masked = masked_objects(d); + edit_mask_texts(d, &masked, &|t, _| wants(t), f); + edit_resource_texts(d, None, &|t, _| wants(t), f); +} + +/// The objects on the layers of `d` that have an opacity mask (not the object whose mask is being +/// edited), each as open. +fn masked_objects(d: &Document) -> Vec<(NodeId, bool)> { + let editing = d.mask_edit.map(|m| m.object); + let mut out = vec![]; + d.walk(|n| { + if n.extras().mask.is_some() && Some(n.id) != editing { + out.push((n.id, true)); } - } + }); + out } /// A font as type names it: family, style and, when it names one, the installed version. @@ -218,14 +453,16 @@ pub(super) fn run_fonts(r: &TextRun) -> Vec<UsedFont> { } } -/// The fonts (family, style, version) the type in the layers and symbols of `d` is drawn in, a -/// composite font's parts in place of its name ([`run_fonts`]). +/// The fonts (family, style, version) the type in the layers, symbols and patterns of `d` is drawn +/// in, the type in opacity masks included, a composite font's parts in place of its name +/// ([`run_fonts`]). pub(super) fn used_fonts(d: &Document) -> BTreeSet<UsedFont> { art_fonts(d, &[]) } -/// The fonts (family, style, version) of the type in the layers and symbols of `d` and in `art` -/// (art read from a file, its resources in `d`). +/// The fonts (family, style, version) of the type in the layers, symbols and patterns of `d` and +/// in `art` (art read from a file, its resources in `d`), the type in opacity masks included. The +/// pattern being edited is read from the editing layer only. pub(super) fn art_fonts(d: &Document, art: &[Node]) -> BTreeSet<UsedFont> { let mut fonts = BTreeSet::new(); let mut add = |n: &Node| { @@ -233,12 +470,9 @@ pub(super) fn art_fonts(d: &Document, art: &[Node]) -> BTreeSet<UsedFont> { fonts.extend(t.runs.iter().flat_map(run_fonts)); } }; - d.walk(&mut add); - for s in &d.symbols { - s.art.walk(&mut add); - } - for n in art { - n.walk(&mut add); + let patterns = d.patterns.iter().filter(|p| !pattern_being_edited(d, &p.name)).flat_map(|p| p.art.iter().map(|a| &**a)); + for n in d.layers.iter().map(|l| &**l).chain(d.symbols.iter().map(|s| &*s.art)).chain(patterns).chain(art) { + vectorcraft_doc::swatches::walk_with_masks(n, &mut add); } fonts } @@ -316,17 +550,16 @@ impl Printed<'_> { NodeKind::Text(t) => drawn_runs(t), _ => (vec![], false), }; - let items: Vec<&AppearanceItem> = - n.appearance.items.iter().filter(|i| i.visible() && !matches!(i, AppearanceItem::Stroke(s) if s.width <= 0.0)).collect(); - let patterns: Vec<&str> = items - .iter() - .map(|i| i.paint()) - .chain(runs.iter().flat_map(|r| [Some(&r.style.fill), (r.style.stroke_width > 0.0).then_some(&r.style.stroke)]).flatten()) - .filter_map(|p| match p { - Paint::Pattern { pattern, .. } => Some(pattern.as_str()), - _ => None, - }) - .collect(); + let items: Vec<&AppearanceItem> = n.appearance.items.iter().filter(|i| paints(i)).collect(); + let ruby = match &n.kind { + NodeKind::Text(t) => ruby_runs(t), + _ => HashSet::new(), + }; + let run_patterns = runs.iter().flat_map(|r| match &n.kind { + NodeKind::Text(t) => Some(drawn_run_paints(t, &ruby, r)), + _ => None, + }); + let patterns: Vec<&str> = items.iter().map(|i| i.paint()).chain(run_patterns.flatten()).filter_map(pattern_name).collect(); let brushed = vectorcraft_brush::has_brush(n); if (mask.is_some() || !patterns.is_empty() || brushed) && areas.is_none_or(|a| !open || self.meets(n, a)) { if let Some(m) = mask { @@ -357,7 +590,7 @@ impl Printed<'_> { for r in runs { self.fonts.extend(run_fonts(r)); // Inline graphics draw their symbols' art. - if let Some(art) = &r.inline { + if let Some(art) = r.inline.as_ref().filter(|_| draws_inline(r)) { self.symbol(&art.symbol); } } @@ -513,50 +746,78 @@ impl Session { pub fn skipped_font_ids(&self, params: &Value, selected: Option<&[NodeId]>) -> Result<Vec<NodeId>> { let (family, style) = font_param(params, "from", "text.replaceFont")?; let selection_only = bool_or(params, "selectionOnly", false); - let selected_symbols = selection_only.then(|| selected_symbols(self, selected)).transpose()?; - let d = &self.doc()?.doc; - let other: Vec<NodeId> = { - let editable = d.editable(); - scope(self, selection_only, selected)?.into_iter().filter(|id| !editable(*id)).collect() - }; + let in_scope = ReplaceScope::read(self, selection_only, selected)?; let uses = |t: &TextObject| { t.runs.iter().any(|r| { r.style.font_family.eq_ignore_ascii_case(&family) && style.as_ref().is_none_or(|name| r.style.font_style.eq_ignore_ascii_case(name)) }) }; - let mut ids = other.into_iter().filter(|id| text(d, *id).is_some_and(uses)).collect::<Vec<_>>(); - fn visit(n: &Node, open: bool, closed: bool, uses: &impl Fn(&TextObject) -> bool, ids: &mut Vec<NodeId>) { - let open = open && n.visible && !n.locked; - if let NodeKind::Text(t) = &n.kind - && (!open || closed) - && uses(t) - { - ids.push(n.id); - } - for child in n.children().map(Vec::as_slice).unwrap_or_default() { - visit(child, open, closed, uses, ids); - } + Ok(in_scope.skipped(&self.doc()?.doc, &uses)) + } +} + +/// What Replace Font looks at: the text objects in scope that the Selection tool can reach and +/// those it can't, the objects with an opacity mask (each with whether it can reach them), and the +/// symbols and patterns whose art is in scope (`None`: all of the document's) with those shown +/// only by hidden or locked objects of the selection. +struct ReplaceScope { + ids: Vec<NodeId>, + other: Vec<NodeId>, + masked: Vec<(NodeId, bool)>, + resources: Option<Resources>, + closed: Resources, +} + +impl ReplaceScope { + fn read(s: &Session, selection_only: bool, selected: Option<&[NodeId]>) -> Result<Self> { + // With selectionOnly: the symbols and patterns the selection shows; those shown only by + // hidden or locked objects keep their type, counted in `skipped`. + let (resources, closed) = if selection_only { + let (all, open) = selected_art(s, selected)?; + let closed = all.difference(&open); + (Some(open), closed) + } else { + (None, Resources::default()) + }; + let d = &s.doc()?.doc; + let editable = d.editable(); + let (texts, masked) = scope(s, selection_only, selected)?; + let (ids, other): (Vec<NodeId>, Vec<NodeId>) = texts.into_iter().partition(|id| editable(*id)); + let masked = masked.into_iter().map(|id| (id, editable(id))).collect(); + Ok(Self { ids, other, masked, resources, closed }) + } + + /// The text objects in the art of opacity masks, symbols and patterns in scope. + fn art<'a>(&self, d: &'a Document) -> Vec<ArtText<'a>> { + let mut texts = mask_texts(d, &self.masked); + texts.extend(resource_texts(d, self.resources.as_ref())); + texts + } + + /// The text objects in scope set in a font `uses` matches that Replace Font leaves as they are: + /// those the Selection tool can't reach, hidden or locked text in art, and the text of the + /// symbols and patterns shown only by hidden or locked objects of the selection. + fn skipped(&self, d: &Document, uses: &impl Fn(&TextObject) -> bool) -> Vec<NodeId> { + let mut ids: Vec<NodeId> = self.other.iter().copied().filter(|id| text(d, *id).is_some_and(uses)).collect(); + ids.extend(self.art(d).into_iter().filter(|(_, t, open)| !open && uses(t)).map(|(id, ..)| id)); + if !self.closed.symbols.is_empty() || !self.closed.patterns.is_empty() { + ids.extend(resource_texts(d, Some(&self.closed)).into_iter().filter(|(_, t, _)| uses(t)).map(|(id, ..)| id)); } - for symbol in d - .symbols - .iter() - .filter(|symbol| !being_edited(d, &symbol.name) && selected_symbols.as_ref().is_none_or(|(all, _)| all.contains(&symbol.name))) - { - let closed = selected_symbols.as_ref().is_some_and(|(_, open)| !open.contains(&symbol.name)); - visit(&symbol.art, true, closed, &uses, &mut ids); - } - Ok(ids) + ids } } fn font_inventory(s: &Session, selected: Option<&[NodeId]>) -> Result<Value> { - let ids = scope(s, selected.is_some(), selected)?; + let (ids, masked) = scope(s, selected.is_some(), selected)?; let d = &s.doc()?.doc; let db = vectorcraft_text::FontDb::global(); - // The type in the art of the symbols in scope too: all of them, or those the selection shows. - let symbols = if selected.is_some() { Some(selected_symbols(s, selected)?.0) } else { None }; + // The type in the art of the opacity masks of the objects in scope, and of the symbols and + // patterns in scope: all of them, or those the selection shows. + let resources = if selected.is_some() { Some(selected_art(s, selected)?.0) } else { None }; let mut texts: Vec<&TextObject> = ids.iter().filter_map(|id| text(d, *id)).collect(); - texts.extend(symbol_texts(d, symbols.as_ref()).into_iter().map(|(t, _)| t)); + let masked: Vec<(NodeId, bool)> = masked.into_iter().map(|id| (id, true)).collect(); + texts.extend(mask_texts(d, &masked).into_iter().map(|(_, t, _)| t)); + texts.extend(resource_texts(d, resources.as_ref()).into_iter().map(|(_, t, _)| t)); // Each font's runs, objects and the text of its runs. let mut found: BTreeMap<UsedFont, (usize, usize, Vec<&str>)> = BTreeMap::new(); for t in texts { @@ -617,21 +878,6 @@ fn font_param(p: &Value, k: &str, c: &str) -> Result<(String, Option<String>)> { Ok((family.to_string(), v.get("style").and_then(Value::as_str).map(str::to_string))) } -fn skipped_font_texts( - d: &Document, - other: &[NodeId], - symbols: &[(&TextObject, bool)], - closed: &BTreeSet<String>, - uses: &impl Fn(&TextObject) -> bool, -) -> usize { - let mut skipped = other.iter().filter(|id| text(d, **id).is_some_and(uses)).count(); - skipped += symbols.iter().filter(|(t, open)| !open && uses(t)).count(); - if !closed.is_empty() { - skipped += symbol_texts(d, Some(closed)).into_iter().filter(|(t, _)| uses(t)).count(); - } - skipped -} - fn replace(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "text.replaceFont"; let (ff, fs) = font_param(p, "from", C)?; @@ -660,35 +906,25 @@ fn replace(s: &mut Session, p: &Value) -> Result<Value> { }; // Only text the Selection tool can reach changes: not hidden or locked, in a hidden or locked // group or layer, or on a locked artboard. The text left in the font is counted. The type in - // the art of the symbols in scope (all of them, or those the selection shows) changes too, - // unless it or a group around it in the art is hidden or locked. + // the opacity masks of the objects in scope, and in the art of the symbols and patterns in + // scope (all of them, or those the selection shows), changes too, unless it, a group around it + // in the art or the object whose mask holds it is hidden or locked. let selection_only = bool_or(p, "selectionOnly", false); - // With selectionOnly: the symbols the selection shows; those shown only by hidden or locked - // instances keep their type, counted in `skipped`. - let (symbols, closed) = if selection_only { - let (all, open) = selected_symbols(s, None)?; - let closed: BTreeSet<String> = all.difference(&open).cloned().collect(); - (Some(open), closed) - } else { - (None, BTreeSet::new()) - }; let uses = |t: &TextObject| t.runs.iter().any(|r| matches(&r.style)); // Whether a run of `t` changes. let changes = |t: &TextObject| t.runs.iter().any(|r| new_style(&r.style).is_some()); - let (ids, skipped, in_symbols) = { + let in_scope = ReplaceScope::read(s, selection_only, None)?; + let (ids, skipped, in_art) = { let d = &s.doc()?.doc; - let editable = d.editable(); - let (ids, other): (Vec<NodeId>, Vec<NodeId>) = scope(s, selection_only, None)?.into_iter().partition(|id| editable(*id)); - let texts = symbol_texts(d, symbols.as_ref()); - let skipped = skipped_font_texts(d, &other, &texts, &closed, &uses); + let skipped = in_scope.skipped(d, &uses).len(); // The text that changes: when none does, the document and its undo history stay as they are. - let ids: Vec<NodeId> = ids.into_iter().filter(|id| text(d, *id).is_some_and(changes)).collect(); - let in_symbols = texts.iter().any(|(t, open)| *open && changes(t)); - (ids, skipped, in_symbols) + let ids: Vec<NodeId> = in_scope.ids.iter().copied().filter(|id| text(d, *id).is_some_and(changes)).collect(); + let in_art = in_scope.art(d).iter().any(|(_, t, open)| *open && changes(t)); + (ids, skipped, in_art) }; // The fonts the replaced runs are set in, for the warning. let mut set = BTreeSet::new(); - let n = if ids.is_empty() && !in_symbols { + let n = if ids.is_empty() && !in_art { 0 } else { s.edit("Replace Font", |d, _| { @@ -717,7 +953,9 @@ fn replace(s: &mut Session, p: &Value) -> Result<Value> { replace_in(t); } } - edit_symbol_texts(d, symbols.as_ref(), &|t, open| open && changes(t), &mut replace_in); + let wants = |t: &TextObject, open: bool| open && changes(t); + edit_mask_texts(d, &in_scope.masked, &wants, &mut replace_in); + edit_resource_texts(d, in_scope.resources.as_ref(), &wants, &mut replace_in); Ok(n) })? }; @@ -734,13 +972,28 @@ fn replace(s: &mut Session, p: &Value) -> Result<Value> { Ok(out) } +/// Whether `n` or a descendant that is not hidden or locked, nor in a hidden or locked group, +/// shows type in a font `uses` matches: text set in it, an instance of a symbol in `found`, an +/// inline graphic of a symbol in `found`, a paint naming a pattern in `found`, or such type in the +/// art of its opacity mask. +fn reaches(n: &Node, uses: &impl Fn(&TextObject) -> bool, found: &Resources) -> bool { + n.visible + && !n.locked + && (matches!(&n.kind, NodeKind::Text(t) if uses(t)) + || matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if found.symbols.contains(symbol)) + || inline_symbols(n).into_iter().any(|sym| found.symbols.contains(sym)) + || paint_patterns(n).into_iter().any(|p| found.patterns.contains(p)) + || n.extras().mask.as_deref().is_some_and(|m| reaches(&m.art, uses, found)) + || n.children().is_some_and(|ch| ch.iter().any(|c| reaches(c, uses, found)))) +} + /// What Replace Font says when it left text in the font that it can't reach. const REPLACE_SKIPPED: &str = "some text is hidden or locked, so its font wasn't replaced"; fn select_font(s: &mut Session, p: &Value) -> Result<Value> { let family = str_param(p, "family").ok_or_else(|| bad("select.font", "missing `family`"))?.to_string(); let style = str_param(p, "style").map(str::to_string); - let ids = scope(s, false, None)?; + let (ids, masked) = scope(s, false, None)?; let d = &s.doc()?.doc; let within = FontScope::read(d, p)?; // Only text the Selection tool can reach: not hidden or locked, in a hidden or locked group @@ -752,37 +1005,42 @@ fn select_font(s: &mut Session, p: &Value) -> Result<Value> { .any(|r| r.style.font_family.eq_ignore_ascii_case(&family) && style.as_ref().is_none_or(|x| r.style.font_style.eq_ignore_ascii_case(x))) }; let mut hits: Vec<NodeId> = ids.into_iter().filter(|id| editable(*id) && text(d, *id).is_some_and(uses)).collect(); - // The symbols whose art uses the font in type that is not hidden or locked, nor in a hidden or - // locked group of the art, also through the instances of other symbols it holds. - fn reaches(n: &Node, uses: &impl Fn(&TextObject) -> bool, symbols: &BTreeSet<&str>) -> bool { - n.visible - && !n.locked - && match &n.kind { - NodeKind::Text(t) => uses(t), - NodeKind::SymbolInstance { symbol, .. } => symbols.contains(symbol.as_str()), - _ => n.children().is_some_and(|ch| ch.iter().any(|c| reaches(c, uses, symbols))), - } - } - let mut symbols: BTreeSet<&str> = BTreeSet::new(); + // The symbols and patterns whose art uses the font in type that is not hidden or locked, nor in + // a hidden or locked group of the art, also through the instances, patterns and opacity masks + // it holds. The pattern being edited is left out: its art is on the editing layer. + let mut found = Resources::default(); loop { - let found: Vec<&str> = d + let symbols: Vec<String> = d .symbols .iter() - .filter(|sym| !symbols.contains(sym.name.as_str()) && reaches(&sym.art, &uses, &symbols)) - .map(|sym| sym.name.as_str()) + .filter(|sym| !found.symbols.contains(&sym.name) && reaches(&sym.art, &uses, &found)) + .map(|sym| sym.name.clone()) .collect(); - if found.is_empty() { + let patterns: Vec<String> = d + .patterns + .iter() + .filter(|p| !pattern_being_edited(d, &p.name) && !found.patterns.contains(&p.name) && p.art.iter().any(|a| reaches(a, &uses, &found))) + .map(|p| p.name.clone()) + .collect(); + if symbols.is_empty() && patterns.is_empty() { break; } - symbols.extend(found); + found.symbols.extend(symbols); + found.patterns.extend(patterns); } - // Their instances the Selection tool can reach. - if !symbols.is_empty() { + // The objects the Selection tool can reach that show such type: the instances of those + // symbols, the text whose inline graphics draw them, the objects that those patterns paint, + // and the objects whose opacity mask holds it (not layers, which the Selection tool doesn't + // select). + let masked: HashSet<NodeId> = masked.into_iter().collect(); + if !found.symbols.is_empty() || !found.patterns.is_empty() || !masked.is_empty() { + let texts: HashSet<NodeId> = hits.iter().copied().collect(); d.walk(&mut |n: &Node| { - if let NodeKind::SymbolInstance { symbol, .. } = &n.kind - && symbols.contains(symbol.as_str()) - && editable(n.id) - { + let shows = matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if found.symbols.contains(symbol)) + || inline_symbols(n).into_iter().any(|sym| found.symbols.contains(sym)) + || paint_patterns(n).into_iter().any(|p| found.patterns.contains(p)) + || (masked.contains(&n.id) && n.extras().mask.as_deref().is_some_and(|m| reaches(&m.art, &uses, &found))); + if shows && !n.is_layer() && !texts.contains(&n.id) && editable(n.id) { hits.push(n.id); } }); @@ -878,6 +1136,37 @@ fn font_list(_: &mut Session, p: &Value) -> Result<Value> { } } +/// Gives the inline graphics in the type of [`art_texts_of`] the current bounds of their symbols' +/// art, and lays out again the type whose inline graphics changed. A symbol drawn inline in the +/// art of another symbol takes one more round, so there is at most one round per symbol. +fn resolve_art_inline(doc: &mut Document) { + for _ in 0..=doc.symbols.len() { + let names: BTreeSet<String> = + art_texts_of(doc).iter().flat_map(|(_, t, _)| t.runs.iter().filter_map(|r| r.inline.as_ref().map(|a| a.symbol.clone()))).collect(); + let bounds: BTreeMap<String, Option<Rect>> = names + .into_iter() + .map(|name| { + let b = doc.symbol_art_bounds(&name); + (name, b) + }) + .collect(); + let stale = |t: &TextObject| t.runs.iter().any(|r| r.inline.as_ref().is_some_and(|a| bounds.get(&a.symbol).is_some_and(|b| *b != a.bounds))); + let mut changed = false; + edit_art_texts_of(doc, &stale, &mut |t| { + for a in t.runs.iter_mut().filter_map(|r| r.inline.as_mut()) { + if let Some(b) = bounds.get(&a.symbol) { + a.bounds = *b; + } + } + refresh_bounds(t); + changed = true; + }); + if !changed { + break; + } + } +} + pub(crate) fn rescan(s: &mut Session, _: &Value) -> Result<Value> { let db = vectorcraft_text::FontDb::global(); #[cfg(not(target_arch = "wasm32"))] @@ -885,7 +1174,9 @@ pub(crate) fn rescan(s: &mut Session, _: &Value) -> Result<Value> { #[cfg(target_arch = "wasm32")] let faces = 0; // The canvas redraws type in the fonts available now (renderers lay it out again when the - // fonts change), and the bounds follow; that isn't an edit to save. + // fonts change), and the bounds follow, also of the type in opacity masks and in the art of + // symbols and patterns; that isn't an edit to save. The type in art is laid out first, and the + // inline graphics of the type on the layers then take the new bounds of their symbols' art. for d in &mut s.docs { let mut texts = vec![]; d.doc.walk(|n| { @@ -893,9 +1184,12 @@ pub(crate) fn rescan(s: &mut Session, _: &Value) -> Result<Value> { texts.push(n.id); } }); - if !texts.is_empty() { + if !texts.is_empty() || !art_texts_of(&d.doc).is_empty() { d.change_unsaved(|doc| { let doc = std::sync::Arc::make_mut(doc); + edit_art_texts_of(doc, &|_| true, &mut refresh_bounds); + resolve_art_inline(doc); + doc.resolve_inline_art(); for id in texts { if let Some(NodeKind::Text(t)) = doc.node_mut(id).map(|n| &mut n.kind) { refresh_bounds(t); @@ -1311,6 +1605,558 @@ mod tests { assert_eq!(s.execute("text.replaceFont", &serif_to_sans).unwrap(), json!({"runs": 0})); } + /// Moves object `art` of the layers into the opacity mask of `owner` (a layer or an object). + fn mask_with(s: &mut Session, owner: u64, art: u64) { + s.edit("Mask", |d, _| { + let art = d.remove(NodeId(art))?; + d.node_mut(NodeId(owner)).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*art).clone(), true))); + Ok(()) + }) + .unwrap(); + } + + /// The font families of the first runs of the text in the opacity mask of `owner`. + fn mask_families(s: &Session, owner: u64) -> Vec<String> { + let d = &s.doc().unwrap().doc; + mask_texts(d, &[(NodeId(owner), true)]).iter().map(|(_, t, _)| t.runs[0].style.font_family.clone()).collect() + } + + /// The font families of the first runs of the text in the art of pattern `name`. + fn pattern_families(s: &Session, name: &str) -> Vec<String> { + let d = &s.doc().unwrap().doc; + let mut out = vec![]; + for art in &d.pattern(name).unwrap().art { + art_texts(art, true, &mut out); + } + out.iter().map(|(_, t, _)| t.runs[0].style.font_family.clone()).collect() + } + + /// The rows of `text.fonts` with `p`: family, runs and objects. + fn font_rows(s: &mut Session, p: Value) -> Vec<(String, u64, u64)> { + let fonts = s.execute("text.fonts", &p).unwrap(); + fonts + .as_array() + .unwrap() + .iter() + .map(|f| (f["family"].as_str().unwrap().to_string(), f["runs"].as_u64().unwrap(), f["objects"].as_u64().unwrap())) + .collect() + } + + /// Find Font lists, selects and changes the type in opacity masks: on objects, on a layer, + /// disabled and inside the art of another mask. The type in the mask of a locked object is + /// listed and left in its font; Find selects the objects whose mask holds the type. + #[test] + fn find_font_reaches_the_type_in_opacity_masks() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let text = |s: &mut Session, y: i32| { + s.execute("text.create", &json!({"x": 10, "y": y, "text": "Serif", "font": "Source Serif 4"})).unwrap()["id"].as_u64().unwrap() + }; + let rect = |s: &mut Session, y: i32| { + s.execute("shape.rectangle", &json!({"x": 0, "y": y, "width": 50, "height": 20})).unwrap()["id"].as_u64().unwrap() + }; + let mut owners = vec![]; + for y in [20, 50, 80] { + let owner = rect(&mut s, y); + let t = text(&mut s, y); + mask_with(&mut s, owner, t); + owners.push(owner); + } + let (open, locked, disabled) = (owners[0], owners[1], owners[2]); + s.execute("select.set", &json!({"ids": [locked]})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [disabled]})).unwrap(); + s.execute("transparency.disableOpacityMask", &json!({})).unwrap(); + // A mask whose art is an object with a mask of its own, and a layer's mask. + let nested = rect(&mut s, 110); + let inner = rect(&mut s, 110); + let t = text(&mut s, 110); + mask_with(&mut s, inner, t); + mask_with(&mut s, nested, inner); + let layer = s.doc().unwrap().doc.layers[0].id.0; + let t = text(&mut s, 140); + mask_with(&mut s, layer, t); + let mut on_layers = 0; + s.doc().unwrap().doc.walk(|n| on_layers += usize::from(matches!(n.kind, NodeKind::Text(_)))); + assert_eq!(on_layers, 0, "the type is only in masks"); + assert_eq!(font_rows(&mut s, json!({})), [("Source Serif 4".to_string(), 5, 5)]); + s.execute("select.set", &json!({"ids": [open]})).unwrap(); + assert_eq!(font_rows(&mut s, json!({"selectionOnly": true})), [("Source Serif 4".to_string(), 1, 1)]); + // Find selects the objects whose mask holds the type, not the locked one or the layer. + assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 3); + let mut selected = s.doc().unwrap().selection.objects.clone(); + selected.sort(); + assert_eq!(selected, [NodeId(open), NodeId(disabled), NodeId(nested)]); + assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4", "scope": {"artboards": [0]}})).unwrap()["count"], 3); + // Change All: one undo step, the locked object's mask left in its font and counted. + let steps = |s: &Session| s.doc().unwrap().history.undo.len(); + let before = steps(&s); + let serif_to_sans = json!({"from": {"family": "Source Serif 4"}, "to": {"family": "Source Sans 3"}}); + let r = s.execute("text.replaceFont", &serif_to_sans).unwrap(); + assert_eq!((r["runs"].as_u64(), r["skipped"].as_u64()), (Some(4), Some(1)), "{r}"); + assert_eq!(steps(&s), before + 1); + for owner in [open, disabled, nested, layer] { + assert_eq!(mask_families(&s, owner), ["Source Sans 3"], "the mask of {owner}"); + } + assert_eq!(mask_families(&s, locked), ["Source Serif 4"]); + let r = s.execute("text.replaceFont", &serif_to_sans).unwrap(); + assert_eq!(r, json!({"runs": 0, "skipped": 1, "warning": REPLACE_SKIPPED})); + assert_eq!(steps(&s), before + 1); + s.execute("edit.undo", &json!({})).unwrap(); + for owner in [open, disabled, nested, layer] { + assert_eq!(mask_families(&s, owner), ["Source Serif 4"], "the mask of {owner} after Undo"); + } + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(mask_families(&s, nested), ["Source Sans 3"]); + // While a mask is edited, its type on the editing layer is counted and changed once. + s.execute("transparency.editOpacityMask", &json!({"id": open})).unwrap(); + assert_eq!(font_rows(&mut s, json!({})), [("Source Sans 3".to_string(), 4, 4), ("Source Serif 4".to_string(), 1, 1)]); + let r = s.execute("text.replaceFont", &json!({"from": {"family": "Source Sans 3"}, "to": {"family": "Inter"}})).unwrap(); + assert_eq!(r["runs"].as_u64(), Some(4), "{r}"); + let families: Vec<String> = used_fonts(&s.doc().unwrap().doc).into_iter().map(|(family, ..)| family).collect(); + assert_eq!(families, ["Inter", "Source Serif 4"], "the edited mask is written back after each edit"); + s.execute("transparency.stopEditingOpacityMask", &json!({})).unwrap(); + assert_eq!(mask_families(&s, open), ["Inter"]); + } + + /// Find Font lists the type in pattern swatches once, also when nothing paints with them; + /// Find selects the objects the pattern paints, and Change changes the pattern's art once for + /// every object it paints. While a pattern is edited, its type is taken from the editing layer. + #[test] + fn find_font_reaches_the_type_in_patterns() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let pattern = |s: &mut Session, name: &str, font: &str| { + let t = s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Ab", "font": font})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.pattern.make", &json!({"ids": [t], "name": name, "edit": false})).unwrap(); + s.execute("select.set", &json!({"ids": [t]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + }; + pattern(&mut s, "Dots", "Source Serif 4"); + pattern(&mut s, "Unused", "Inter"); + let mut on_layers = 0; + s.doc().unwrap().doc.walk(|n| on_layers += usize::from(matches!(n.kind, NodeKind::Text(_)))); + assert_eq!(on_layers, 0, "the type is only in patterns"); + let all = [("Inter".to_string(), 1, 1), ("Source Serif 4".to_string(), 1, 1)]; + assert_eq!(font_rows(&mut s, json!({})), all); + assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 0); + let mut painted = vec![]; + for y in [20, 60] { + painted.push(s.execute("shape.rectangle", &json!({"x": 0, "y": y, "width": 50, "height": 20})).unwrap()["id"].as_u64().unwrap()); + } + s.execute("paint.setFill", &json!({"swatch": "Dots", "ids": painted})).unwrap(); + assert_eq!(font_rows(&mut s, json!({})), all, "a pattern's type counts once"); + assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 2); + assert_eq!(s.doc().unwrap().selection.objects, [NodeId(painted[0]), NodeId(painted[1])]); + assert_eq!(s.execute("select.font", &json!({"family": "Inter"})).unwrap()["count"], 0); + // Only the selection: the patterns the selected objects paint with. + s.execute("select.set", &json!({"ids": [painted[0]]})).unwrap(); + assert_eq!(font_rows(&mut s, json!({"selectionOnly": true})), [("Source Serif 4".to_string(), 1, 1)]); + let steps = |s: &Session| s.doc().unwrap().history.undo.len(); + let before = steps(&s); + let r = s + .execute("text.replaceFont", &json!({"from": {"family": "Source Serif 4"}, "to": {"family": "Source Sans 3"}, "selectionOnly": true})) + .unwrap(); + assert_eq!(r, json!({"runs": 1})); + assert_eq!(steps(&s), before + 1); + assert_eq!(pattern_families(&s, "Dots"), ["Source Sans 3"]); + assert_eq!(pattern_families(&s, "Unused"), ["Inter"]); + // No run changes: no undo step. + let r = s.execute("text.replaceFont", &json!({"from": {"family": "Source Sans 3"}, "to": {"family": "Source Sans 3"}})).unwrap(); + assert_eq!(r, json!({"runs": 0})); + assert_eq!(steps(&s), before + 1); + // Change All reaches the swatch nothing paints with. + let r = s.execute("text.replaceFont", &json!({"from": {"family": "Inter"}, "to": {"family": "Source Serif 4"}})).unwrap(); + assert_eq!(r, json!({"runs": 1})); + assert_eq!(pattern_families(&s, "Unused"), ["Source Serif 4"]); + // A pattern in a hidden fill doesn't show: Find doesn't select the object for its type. + let hidden = s.execute("shape.rectangle", &json!({"x": 100, "y": 20, "width": 50, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"swatch": "Unused", "ids": [hidden]})).unwrap(); + assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 1); + s.edit("Hide the fill", |d, _| { + for it in d.node_mut(NodeId(hidden)).unwrap().appearance.items.iter_mut() { + if let AppearanceItem::Fill(f) = it { + f.visible = false; + } + } + Ok(()) + }) + .unwrap(); + assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 0); + // Nor does a pattern on a stroke of no width. + s.execute("paint.setStroke", &json!({"swatch": "Unused", "ids": [hidden]})).unwrap(); + assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 1); + s.edit("Thin the stroke", |d, _| { + for it in d.node_mut(NodeId(hidden)).unwrap().appearance.items.iter_mut() { + if let AppearanceItem::Stroke(st) = it { + st.width = 0.0; + } + } + Ok(()) + }) + .unwrap(); + assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 0); + // A locked painted object: its pattern's type is listed and left in its font. + s.execute("select.set", &json!({"ids": [painted[1]]})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [painted[1]]})).unwrap(); + let r = + s.execute("text.replaceFont", &json!({"from": {"family": "Source Sans 3"}, "to": {"family": "Inter"}, "selectionOnly": true})).unwrap(); + assert_eq!((r["runs"].as_u64(), r["skipped"].as_u64()), (Some(0), Some(1)), "{r}"); + assert_eq!(s.execute("select.font", &json!({"family": "Source Sans 3"})).unwrap()["count"], 1); + assert_eq!(s.doc().unwrap().selection.objects, [NodeId(painted[0])]); + // While the pattern is edited, its type on the editing layer is counted and changed once. + s.execute("object.pattern.edit", &json!({"name": "Dots"})).unwrap(); + let rows = font_rows(&mut s, json!({})); + assert_eq!(rows, [("Source Sans 3".to_string(), 1, 1), ("Source Serif 4".to_string(), 1, 1)]); + let r = s.execute("text.replaceFont", &json!({"from": {"family": "Source Sans 3"}, "to": {"family": "Inter"}})).unwrap(); + assert_eq!(r, json!({"runs": 1})); + let families: Vec<String> = used_fonts(&s.doc().unwrap().doc).into_iter().map(|(family, ..)| family).collect(); + assert_eq!(families, ["Inter", "Source Serif 4"], "the pattern's stored art is left out while it is edited"); + s.execute("object.pattern.done", &json!({})).unwrap(); + assert_eq!(pattern_families(&s, "Dots"), ["Inter"]); + } + + /// A pattern whose art holds a symbol instance, painting objects inside and outside a symbol: + /// Find Font lists each pattern's and symbol's type once and reaches the symbol's type through + /// the pattern. + #[test] + fn find_font_reaches_symbols_through_patterns() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let inter = s.execute("text.create", &json!({"x": 10, "y": 20, "text": "In", "font": "Inter"})).unwrap()["id"].clone(); + s.execute("symbol.new", &json!({"name": "Mark", "ids": [inter]})).unwrap(); + let instance = s.doc().unwrap().selection.objects[0].0; + let serif = s.execute("text.create", &json!({"x": 10, "y": 60, "text": "Se", "font": "Source Serif 4"})).unwrap()["id"].as_u64().unwrap(); + let tile = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 80})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.pattern.make", &json!({"ids": [tile, serif, instance], "name": "Loop", "edit": false})).unwrap(); + s.execute("select.set", &json!({"ids": [tile, serif, instance]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + // Another object paints with the pattern too: its type is still read once. + let other = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"swatch": "Loop", "ids": [other]})).unwrap(); + s.execute("symbol.new", &json!({"name": "Outer", "ids": [other]})).unwrap(); + let outer = s.doc().unwrap().selection.objects[0]; + let painted = s.execute("shape.rectangle", &json!({"x": 0, "y": 100, "width": 50, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"swatch": "Loop", "ids": [painted]})).unwrap(); + let both = [("Inter".to_string(), 1, 1), ("Source Serif 4".to_string(), 1, 1)]; + assert_eq!(font_rows(&mut s, json!({})), both); + s.execute("select.set", &json!({"ids": [painted]})).unwrap(); + assert_eq!(font_rows(&mut s, json!({"selectionOnly": true})), both); + // Find reaches the symbol's type through the pattern, and through a symbol whose art paints + // with the pattern. + assert_eq!(s.execute("select.font", &json!({"family": "Inter"})).unwrap()["count"], 2); + assert_eq!(s.doc().unwrap().selection.objects, [outer, NodeId(painted)]); + s.execute("select.set", &json!({"ids": [painted]})).unwrap(); + let r = + s.execute("text.replaceFont", &json!({"from": {"family": "Inter"}, "to": {"family": "Source Sans 3"}, "selectionOnly": true})).unwrap(); + assert_eq!(r, json!({"runs": 1})); + assert_eq!(symbol_texts(&s.doc().unwrap().doc, None)[0].0.runs[0].style.font_family, "Source Sans 3"); + } + + /// A pattern in a fill whose opacity is 0 paints nothing: Find doesn't select the object for + /// the pattern's type, a selection-only Change leaves that type in its font, and Print doesn't + /// count its font. + #[test] + fn find_font_skips_patterns_at_an_opacity_of_0() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let t = s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Ab", "font": "Source Serif 4"})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.pattern.make", &json!({"ids": [t], "name": "Dots", "edit": false})).unwrap(); + s.execute("select.set", &json!({"ids": [t]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + let painted = s.execute("shape.rectangle", &json!({"x": 0, "y": 20, "width": 50, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"swatch": "Dots", "ids": [painted]})).unwrap(); + let printed = |s: &Session| { + let d = &s.doc().unwrap().doc; + printed_type(d, &d.layers, &[Rect::new(-1000.0, -1000.0, 1000.0, 1000.0)]).0.into_iter().map(|(family, ..)| family).collect::<Vec<_>>() + }; + assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 1); + assert_eq!(printed(&s), ["Source Serif 4"]); + s.edit("Clear the fill", |d, _| { + for it in d.node_mut(NodeId(painted)).unwrap().appearance.items.iter_mut() { + if let AppearanceItem::Fill(f) = it { + f.opacity = 0.0; + } + } + Ok(()) + }) + .unwrap(); + assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 0); + assert!(printed(&s).is_empty(), "{:?}", printed(&s)); + s.execute("select.set", &json!({"ids": [painted]})).unwrap(); + let r = s + .execute("text.replaceFont", &json!({"from": {"family": "Source Serif 4"}, "to": {"family": "Source Sans 3"}, "selectionOnly": true})) + .unwrap(); + assert_eq!(r, json!({"runs": 0})); + assert_eq!(pattern_families(&s, "Dots"), ["Source Serif 4"]); + } + + /// Characters of area type that don't fit its frame paint nothing: their pattern's type isn't + /// found through them until they are drawn. + #[test] + fn find_font_skips_patterns_of_overset_characters() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let t = s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Ab", "font": "Source Serif 4"})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.pattern.make", &json!({"ids": [t], "name": "Dots", "edit": false})).unwrap(); + s.execute("select.set", &json!({"ids": [t]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + let area = s + .execute( + "text.create", + &json!({"x": 10, "y": 60, "text": "A\nB", "font": "Source Sans 3", "size": 20, "area": {"width": 100, "height": 40}}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("text.setRangeStyle", &json!({"id": area, "start": 2, "end": 3, "font": "Inter"})).unwrap(); + let paint_run = |s: &mut Session, letter: &'static str| { + s.edit("Paint a run with the pattern", |d, _| { + if let Some(NodeKind::Text(t)) = d.node_mut(NodeId(area)).map(|n| &mut n.kind) { + for r in t.runs.iter_mut().filter(|r| r.text.contains(letter)) { + r.style.fill = Paint::Pattern { pattern: "Dots".into(), xf: Default::default() }; + } + } + Ok(()) + }) + .unwrap(); + }; + paint_run(&mut s, "B"); + let laid = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), text(&s.doc().unwrap().doc, NodeId(area)).unwrap()); + assert!(laid.overflow, "the second line doesn't fit the frame"); + assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 0); + paint_run(&mut s, "A"); + assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 1); + } + + /// An inline graphic that doesn't fit its area type draws nothing, and neither does an inline + /// graphic named on a run of other characters: Find doesn't select the text for its symbol. + #[test] + fn find_font_skips_undrawn_inline_graphics() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let t = s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Ab", "font": "Source Serif 4"})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.pattern.make", &json!({"ids": [t], "name": "Dots", "edit": false})).unwrap(); + s.execute("select.set", &json!({"ids": [t]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + let mark = s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Se", "font": "Inter"})).unwrap()["id"].clone(); + s.execute("symbol.new", &json!({"name": "Mark", "ids": [mark]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + let area = s + .execute( + "text.create", + &json!({"x": 10, "y": 60, "text": "A\nB", "font": "Source Sans 3", "size": 20, "area": {"width": 100, "height": 40}}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("text.insertInline", &json!({"id": area, "at": 3, "symbol": "Mark"})).unwrap(); + let laid = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), text(&s.doc().unwrap().doc, NodeId(area)).unwrap()); + assert!(laid.overflow && laid.inlines.is_empty(), "the inline graphic doesn't fit the frame"); + assert_eq!(s.execute("select.font", &json!({"family": "Inter"})).unwrap()["count"], 0); + let point = s.execute("text.create", &json!({"x": 10, "y": 140, "text": "Hi", "font": "Source Sans 3"})).unwrap()["id"].as_u64().unwrap(); + s.execute("text.insertInline", &json!({"id": point, "at": 0, "symbol": "Mark"})).unwrap(); + assert_eq!(s.execute("select.font", &json!({"family": "Inter"})).unwrap()["count"], 1); + assert_eq!(s.doc().unwrap().selection.objects, [NodeId(point)]); + // A run that names an inline graphic but holds other characters is laid out as those + // characters: its fill paints them, and it draws no symbol. + let plain = s.execute("text.create", &json!({"x": 10, "y": 180, "text": "Ok", "font": "Source Sans 3"})).unwrap()["id"].as_u64().unwrap(); + let art = text(&s.doc().unwrap().doc, NodeId(point)).unwrap().runs.iter().find_map(|r| r.inline.clone()).unwrap(); + s.edit("Name an inline graphic on plain characters", |d, _| { + if let Some(NodeKind::Text(t)) = d.node_mut(NodeId(plain)).map(|n| &mut n.kind) { + for r in &mut t.runs { + r.inline = Some(art.clone()); + r.style.fill = Paint::Pattern { pattern: "Dots".into(), xf: Default::default() }; + } + } + Ok(()) + }) + .unwrap(); + assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 1); + assert_eq!(s.doc().unwrap().selection.objects, [NodeId(plain)]); + assert_eq!(s.execute("select.font", &json!({"family": "Inter"})).unwrap()["count"], 1); + assert_eq!(s.doc().unwrap().selection.objects, [NodeId(point)]); + } + + /// The characters of an inline graphic draw no glyph: their pattern fill paints only their + /// underline, strikethrough or ruby reading. Without one, Find doesn't select the text for the + /// pattern's type and Print doesn't count its font. + #[test] + fn find_font_skips_patterns_of_undecorated_inline_graphics() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let t = s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Ab", "font": "Source Serif 4"})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.pattern.make", &json!({"ids": [t], "name": "Dots", "edit": false})).unwrap(); + s.execute("select.set", &json!({"ids": [t]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + let mark = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone(); + s.execute("symbol.new", &json!({"name": "Mark", "ids": [mark]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + let point = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "Hi", "font": "Source Sans 3"})).unwrap()["id"].as_u64().unwrap(); + s.execute("text.insertInline", &json!({"id": point, "at": 1, "symbol": "Mark"})).unwrap(); + let style = |s: &mut Session, f: &dyn Fn(&mut TextObject)| { + s.edit("Style the inline graphic", |d, _| { + if let Some(NodeKind::Text(t)) = d.node_mut(NodeId(point)).map(|n| &mut n.kind) { + f(t); + } + Ok(()) + }) + .unwrap(); + }; + let found = |s: &mut Session| s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"].as_u64(); + let printed = |s: &Session| { + let d = &s.doc().unwrap().doc; + printed_type(d, &d.layers, &[Rect::new(-1000.0, -1000.0, 1000.0, 1000.0)]).0.into_iter().map(|(family, ..)| family).collect::<Vec<_>>() + }; + style(&mut s, &|t| { + for r in t.runs.iter_mut().filter(|r| r.inline.is_some()) { + r.style.fill = Paint::Pattern { pattern: "Dots".into(), xf: Default::default() }; + } + }); + assert_eq!(found(&mut s), Some(0)); + assert_eq!(printed(&s), ["Source Sans 3"]); + // An underline paints with the pattern. + style(&mut s, &|t| t.runs.iter_mut().filter(|r| r.inline.is_some()).for_each(|r| r.style.underline = true)); + assert_eq!(found(&mut s), Some(1)); + assert_eq!(printed(&s), ["Source Sans 3", "Source Serif 4"]); + // Vertical type draws no underline. + style(&mut s, &|t| t.vertical = true); + assert_eq!(found(&mut s), Some(0)); + // A ruby reading that starts over the character before the inline graphic draws with that + // character's paint. + style(&mut s, &|t| { + assert!(t.runs[1].inline.is_some(), "the inline graphic is the second run"); + t.ruby.push(vectorcraft_doc::RubySpan { + start: 0, + end: t.runs[0].text.len() + t.runs[1].text.len(), + text: "x".into(), + position: Default::default(), + align: Default::default(), + size_percent: 50.0, + overhang: true, + }); + }); + assert_eq!(found(&mut s), Some(0)); + // A ruby reading that starts over the inline graphic paints with the pattern. + style(&mut s, &|t| t.ruby[0].start = t.runs[0].text.len()); + assert_eq!(found(&mut s), Some(1)); + } + + /// Text whose inline graphic draws a symbol shows the symbol's type: Find selects that text + /// and the objects painted with a pattern whose art holds it, and a selection-only Change + /// changes the symbol's type. + #[test] + fn find_font_reaches_symbols_through_inline_graphics() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let serif = s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Se", "font": "Source Serif 4"})).unwrap()["id"].clone(); + s.execute("symbol.new", &json!({"name": "Mark", "ids": [serif]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + let inline = |s: &mut Session, y: i32| { + let id = s.execute("text.create", &json!({"x": 10, "y": y, "text": "In", "font": "Inter"})).unwrap()["id"].as_u64().unwrap(); + s.execute("text.insertInline", &json!({"id": id, "at": 0, "symbol": "Mark"})).unwrap(); + id + }; + let listed = inline(&mut s, 60); + let tiled = inline(&mut s, 100); + s.execute("object.pattern.make", &json!({"ids": [tiled], "name": "Loop", "edit": false})).unwrap(); + s.execute("select.set", &json!({"ids": [tiled]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + let painted = s.execute("shape.rectangle", &json!({"x": 0, "y": 140, "width": 50, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"swatch": "Loop", "ids": [painted]})).unwrap(); + let mut instances = 0; + s.doc().unwrap().doc.walk(|n| instances += usize::from(matches!(n.kind, NodeKind::SymbolInstance { .. }))); + assert_eq!(instances, 0, "the symbol is drawn only by inline graphics"); + assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 2); + let mut selected = s.doc().unwrap().selection.objects.clone(); + selected.sort(); + assert_eq!(selected, [NodeId(listed), NodeId(painted)]); + s.execute("select.set", &json!({"ids": [painted]})).unwrap(); + let rows = font_rows(&mut s, json!({"selectionOnly": true})); + assert_eq!(rows, [("Inter".to_string(), 2, 1), ("Source Serif 4".to_string(), 1, 1)]); + let r = s + .execute("text.replaceFont", &json!({"from": {"family": "Source Serif 4"}, "to": {"family": "Source Sans 3"}, "selectionOnly": true})) + .unwrap(); + assert_eq!(r, json!({"runs": 1})); + assert_eq!(symbol_texts(&s.doc().unwrap().doc, None)[0].0.runs[0].style.font_family, "Source Sans 3"); + } + + /// Refresh Font List lays out again the type in opacity masks and in the art of symbols and + /// patterns, as it does the type on the layers, and the inline graphics of the type on the + /// layers follow the symbols' type as laid out again. + #[test] + fn rescanning_fonts_refreshes_the_bounds_of_type_in_art() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let owner = s.execute("shape.rectangle", &json!({"x": 0, "y": 20, "width": 50, "height": 20})).unwrap()["id"].as_u64().unwrap(); + let masked = s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Mask", "font": "Inter"})).unwrap()["id"].as_u64().unwrap(); + mask_with(&mut s, owner, masked); + let tiled = s.execute("text.create", &json!({"x": 10, "y": 60, "text": "Tile", "font": "Inter"})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.pattern.make", &json!({"ids": [tiled], "name": "Dots", "edit": false})).unwrap(); + s.execute("select.set", &json!({"ids": [tiled]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + let stale = Rect::new(0.0, 0.0, 1.0, 1.0); + s.edit("Make the bounds stale", |d, _| { + edit_art_texts_of(d, &|_| true, &mut |t| t.cached_bounds = Some(stale)); + Ok(()) + }) + .unwrap(); + let bounds = |s: &Session| art_texts_of(&s.doc().unwrap().doc).iter().map(|(_, t, _)| t.cached_bounds).collect::<Vec<_>>(); + assert_eq!(bounds(&s), [Some(stale), Some(stale)]); + s.execute("text.rescanFonts", &json!({})).unwrap(); + let after = bounds(&s); + assert_eq!(after.len(), 2); + assert!(after.iter().all(|b| b.is_some_and(|b| b != stale && b.width() > 1.0)), "{after:?}"); + let marked = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "Se", "font": "Inter"})).unwrap()["id"].clone(); + s.execute("symbol.new", &json!({"name": "Mark", "ids": [marked]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + let line = s.execute("text.create", &json!({"x": 10, "y": 140, "text": "In", "font": "Inter"})).unwrap()["id"].as_u64().unwrap(); + s.execute("text.insertInline", &json!({"id": line, "at": 0, "symbol": "Mark"})).unwrap(); + s.edit("Make the bounds stale", |d, _| { + edit_art_texts_of(d, &|_| true, &mut |t| t.cached_bounds = Some(stale)); + d.resolve_inline_art(); + Ok(()) + }) + .unwrap(); + let resolved = |s: &Session| { + let d = &s.doc().unwrap().doc; + matches!(d.inline_resolved(text(d, NodeId(line)).unwrap()), std::borrow::Cow::Borrowed(_)) + }; + assert!(resolved(&s), "the inline graphic took the stale bounds"); + s.execute("text.rescanFonts", &json!({})).unwrap(); + assert!(resolved(&s), "the inline graphic follows the symbol's type laid out again"); + // So does an inline graphic in the art of another symbol. + let held = s.execute("text.create", &json!({"x": 10, "y": 180, "text": "Out", "font": "Inter"})).unwrap()["id"].as_u64().unwrap(); + s.execute("text.insertInline", &json!({"id": held, "at": 0, "symbol": "Mark"})).unwrap(); + s.execute("symbol.new", &json!({"name": "Outer", "ids": [held]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + s.edit("Make the bounds stale", |d, _| { + edit_art_texts_of(d, &|_| true, &mut |t| t.cached_bounds = Some(stale)); + Ok(()) + }) + .unwrap(); + let shrunk = s.doc().unwrap().doc.symbol_art_bounds("Mark"); + s.edit("Take the stale bounds", |d, _| { + edit_art_texts_of(d, &|_| true, &mut |t| { + for a in t.runs.iter_mut().filter_map(|r| r.inline.as_mut()) { + a.bounds = shrunk; + } + }); + Ok(()) + }) + .unwrap(); + let nested = |s: &Session| { + let d = &s.doc().unwrap().doc; + art_texts_of(d).iter().flat_map(|(_, t, _)| t.runs.iter().filter_map(|r| r.inline.as_ref().map(|a| a.bounds))).collect::<Vec<_>>() + }; + assert_eq!(nested(&s), [shrunk]); + s.execute("text.rescanFonts", &json!({})).unwrap(); + let mark = s.doc().unwrap().doc.symbol_art_bounds("Mark"); + assert_ne!(mark, shrunk); + assert_eq!(nested(&s), [mark], "the inline graphic in the art of Outer follows Mark's type laid out again"); + } + /// The font family of text object `id`'s first run. fn text_family(s: &Session, id: u64) -> String { text(&s.doc().unwrap().doc, NodeId(id)).unwrap().runs[0].style.font_family.clone() diff --git a/crates/engine/src/cmd/globaledit.rs b/crates/engine/src/cmd/globaledit.rs index 4a42f03d4f..98f53b102e 100644 --- a/crates/engine/src/cmd/globaledit.rs +++ b/crates/engine/src/cmd/globaledit.rs @@ -20,6 +20,9 @@ //! and they lie the same way relative to each other: the group as a whole is moved or scaled. //! With Appearance on, each of those objects must have the same fill and stroke too; with Size, //! the groups the same width and height. +//! - Selecting one of the repeated objects with the Selection tool highlights the similar objects +//! at once, before Global Edit starts. Here they are the objects Start Global Edit would take +//! with the current Global Edit Options ([`similar`]). //! - While Global Edit is on, an edit made to one of the found objects is made to all of them, //! each in proportion to its own size: halving the height of a 100 pt object halves a 20 pt //! match to 10 pt. Stop Global Edit (or Escape) ends it. @@ -780,18 +783,55 @@ pub(crate) fn propagate(before: &Document, d: &mut Document, ge: &GlobalEdit, se /// The outlines of the members of the active document's Global Edit that are not selected, hold /// no selected object and sit inside no selected object, in their layer's colour: the canvas -/// highlights them while Global Edit is on. +/// highlights them while Global Edit is on. While it is off, with one supported object selected, +/// they are the outlines of the objects Start Global Edit would take with the Global Edit Options +/// ([`similar`]). pub fn highlights(s: &Session) -> Outlines { let Some(st) = s.active() else { return vec![] }; - let Some(ge) = &st.global_edit else { return vec![] }; + let Some(ge) = &st.global_edit else { return similar(s) }; if let Some((rev, out)) = &*ge.outlines.borrow() && *rev == st.revision { return out.clone(); } + let out = outlines(st, &ge.members); + *ge.outlines.borrow_mut() = Some((st.revision, out.clone())); + out +} + +/// [`similar`]'s outlines as of a document revision and the options they were found with. +pub type SimilarCache = std::cell::RefCell<Option<(u64, Options, Outlines)>>; + +/// Before Global Edit starts: with one supported object selected, the outlines of the other +/// objects Start Global Edit would take now with the session's Global Edit Options, so the canvas +/// shows them as soon as the object is selected. None while an interaction (a drag) is in +/// progress, or when fewer than two objects would be taken. Kept per document revision and +/// options, as finding them walks the whole document. +pub fn similar(s: &Session) -> Outlines { + let Some(st) = s.active() else { return vec![] }; + if st.global_edit.is_some() || st.interaction.is_some() || st.selection.objects.len() != 1 { + return vec![]; + } + let o = &s.global_edit_options; + if let Some((rev, opts, out)) = &*st.similar_outlines.borrow() + && *rev == st.revision + && opts == o + { + return out.clone(); + } + let out = match matches(s, o) { + Ok(m) if m.len() >= 2 => outlines(st, &m), + _ => vec![], + }; + *st.similar_outlines.borrow_mut() = Some((st.revision, o.clone(), out.clone())); + out +} + +/// The outlines of `members` that are not selected, hold no selected object and sit inside no +/// selected object, in their layer's color. +fn outlines(st: &crate::DocState, members: &[(NodeId, Affine)]) -> Outlines { let symbols = st.doc.symbol_boxes(); - let out: Vec<_> = ge - .members + members .iter() .filter_map(|(id, _)| { let n = st.doc.node(*id).filter(|n| !holds(n, &st.selection.objects))?; @@ -804,9 +844,7 @@ pub fn highlights(s: &Session) -> Outlines { }; Some((path, st.doc.layer_color(*id))) }) - .collect(); - *ge.outlines.borrow_mut() = Some((st.revision, out.clone())); - out + .collect() } #[cfg(test)] diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index 9676c3b825..18bb3469b9 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -1,7 +1,8 @@ //! The Gradient panel and the Gradient tool: in-place gradient edits and the gradient vector. use serde_json::{Value, json}; -use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientMethod, GradientPaint, GradientStop, Paint}; +use vectorcraft_color::gradient::MAX_REPEATS; +use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientMethod, GradientPaint, GradientSpread, GradientStop, Paint}; use vectorcraft_doc::appearance::stroke_paint_bounds; use vectorcraft_doc::{Document, Node, NodeKind, StrokeGradientMode}; use vectorcraft_geom::{Affine, Point, Rect}; @@ -23,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> { "Gradient", ["Window", "Gradient"], None, - "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual (how the colours between the stops mix: in display RGB, or perceptually (OKLab) so the steps look even; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial or conic, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial and conic: the vector turns about the center), aspect?: % (radial and conic; a negative one mirrors a conic's sweep and is an error for the other kinds), reverse?: bool, dither?: bool (fills only: a linear, radial or conic gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient", + "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient", has_doc, edit_gradient ), @@ -32,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> { "Gradient Vector", [], None, - "{start?: [x,y], end?: [x,y] (document coordinates; both or neither: omitted, the vector stays), aspect?: % (radial and conic: the extent ellipse's height / width, a negative one mirroring a conic's sweep and an error for the other kinds; default: kept), focal?: [x,y] (document coordinates) | null (radial: the focal point, where the first stop sits, pulled inside the extent ellipse; null centres it; default: it keeps its place in the ellipse; an error on a conic gradient), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (alias: index; omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\", index?: appearance item index (as item)} set the gradient vector, aspect ratio and focal point (solid paints become the default gradient; type objects set it on their runs, in text space)", + "{start?: [x,y], end?: [x,y] (document coordinates; both or neither: omitted, the vector stays), aspect?: % (radial, conic and diamond: the extent's height / width across the vector, a negative one mirroring a conic's sweep and an error for the other kinds; default: kept), focal?: [x,y] (document coordinates) | null (radial: the focal point, where the first stop sits, pulled inside the extent ellipse; null centres it; default: it keeps its place in the ellipse; an error on a conic or diamond gradient), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (alias: index; omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\", index?: appearance item index (as item)} set the gradient vector, aspect ratio and focal point (solid paints become the default gradient; type objects set it on their runs, in text space)", has_doc, set_gradient_geom ), @@ -118,14 +119,48 @@ type Parsed<T> = std::result::Result<T, String>; /// Parse a kind name. fn parse_kind(k: &str) -> Parsed<GradientKind> { - GradientKind::parse(k).ok_or_else(|| format!("unknown gradient kind `{k}` (linear, radial, conic, freeform)")) + GradientKind::parse(k).ok_or_else(|| format!("unknown gradient kind `{k}` (linear, radial, conic, diamond, freeform)")) } /// The `method` param of `p`, if given: how the colours between the stops mix. fn method_param(p: &Value) -> Parsed<Option<GradientMethod>> { match p.get("method") { None | Some(Value::Null) => Ok(None), - Some(v) => v.as_str().and_then(GradientMethod::parse).map(Some).ok_or_else(|| "`method` must be classic or perceptual".into()), + Some(v) => v + .as_str() + .and_then(GradientMethod::parse) + .map(Some) + .ok_or_else(|| "`method` must be classic, perceptual, hue-clockwise or hue-counterclockwise".into()), + } +} + +/// The `spread` param of `p`, if given: what the gradient paints past the ends of its stops. +fn spread_param(p: &Value) -> Parsed<Option<GradientSpread>> { + match p.get("spread") { + None | Some(Value::Null) => Ok(None), + Some(v) => v.as_str().and_then(GradientSpread::parse).map(Some).ok_or_else(|| "`spread` must be pad, repeat or reflect".into()), + } +} + +/// The `repeats` param of `p`, if given: how many times the stops run along the vector with +/// Repeat and Reflect, a whole number from 1 to [`MAX_REPEATS`]. +fn repeats_param(p: &Value) -> Parsed<Option<u32>> { + match p.get("repeats") { + None | Some(Value::Null) => Ok(None), + Some(v) => v + .as_f64() + .filter(|n| n.fract() == 0.0 && (1.0..=f64::from(MAX_REPEATS)).contains(n)) + .map(|n| Some(n as u32)) + .ok_or_else(|| format!("`repeats` must be a whole number from 1 to {MAX_REPEATS}")), + } +} + +/// An error when `p` gives a spread other than pad for a gradient of `kind` that has no ends to +/// spread past (freeform). +fn spread_for(kind: GradientKind, p: &Value) -> Parsed<()> { + match spread_param(p)? { + Some(s) if !s.is_pad() && kind == GradientKind::Freeform => Err("`spread` applies to linear, radial, conic and diamond gradients".into()), + _ => Ok(()), } } @@ -271,11 +306,14 @@ pub(crate) fn parse_gradient(g: &Value) -> Parsed<GradientPaint> { Some(v) => v.as_bool().ok_or("`dither` must be true or false")?, }; gp.gradient.method = method_param(g)?.unwrap_or_default(); + spread_for(kind, g)?; + gp.gradient.spread = spread_param(g)?.unwrap_or_default(); + gp.gradient.repeats = repeats_param(g)?.unwrap_or(1); gp.angle = f64_or(g, "angle", 0.0); gp.swatch = str_param(g, "swatch").map(str::to_string); let geom = GeomEdit::parse(g)?; let aspect = geom.aspect.map(|a| aspect_for(kind, a)).transpose()?; - if kind == GradientKind::Conic { + if matches!(kind, GradientKind::Conic | GradientKind::Diamond) { no_focal(&geom)?; } if let Some((start, end)) = geom.vector { @@ -315,7 +353,7 @@ fn aspect_for(kind: GradientKind, a: f64) -> Parsed<f64> { Ok(a) } -/// An error when `e` gives a focal point: a conic gradient has none (`null` is allowed). +/// An error when `e` gives a focal point: a conic or diamond gradient has none (`null` is allowed). fn no_focal(e: &GeomEdit) -> Parsed<()> { match e.focal { Some(Some(_)) => Err("`focal` applies to radial gradients".into()), @@ -422,6 +460,13 @@ fn apply_gradient_edit_in_model( if let Some(m) = method_param(p)? { gp.gradient.method = m; } + spread_for(gp.gradient.kind, p)?; + if let Some(sp) = spread_param(p)? { + gp.gradient.spread = sp; + } + if let Some(n) = repeats_param(p)? { + gp.gradient.repeats = n; + } // Angle and aspect edits keep the focal point in its place in the extent ellipse. let before = gp.geom; if let Some(a) = p.get("angle").and_then(Value::as_f64) { @@ -516,6 +561,18 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> { } _ => std::borrow::Cow::Borrowed(p), }; + // A spread for selected gradients leaves a freeform default (which has no ends) as it is. + let spreads = matches!(spread_param(p), Ok(Some(sp)) if !sp.is_pad()); + let for_default = match for_default { + q if spreads && !ids.is_empty() && default_kind == Some(GradientKind::Freeform) => { + let mut q = q.into_owned(); + if let Some(o) = q.as_object_mut() { + o.remove("spread"); + } + std::borrow::Cow::Owned(q) + } + q => q, + }; let new_default = apply_gradient_edit_in_model(&default_paint, &with_stored_stops(&for_default, &default_paint, &stored), None, &|_| true, model) .map_err(|e| bad(C, e))?; let freeform = str_param(p, "kind").and_then(GradientKind::parse) == Some(GradientKind::Freeform); @@ -645,7 +702,7 @@ impl GeomEdit { /// the paint's space (text space for type runs) to the document and `bounds` (in that space) fits /// an unplaced gradient, so what the document shows carries over where `e` keeps it. An error /// when `e` gives what the gradient's kind can't take (a negative aspect other than a conic's, or -/// a conic's focal point). +/// a conic's or diamond's focal point). fn vector_paint( cur: &Paint, e: &GeomEdit, @@ -656,7 +713,7 @@ fn vector_paint( let mut gp = gradient_for_edit(cur, model); let kind = gp.gradient.kind; let edit_aspect = e.aspect.map(|a| aspect_for(kind, a)).transpose()?; - if kind == GradientKind::Conic { + if matches!(kind, GradientKind::Conic | GradientKind::Diamond) { no_focal(e)?; } let Some(from_doc) = invert(to_doc) else { return Ok(None) }; diff --git a/crates/engine/src/cmd/gradpresets.rs b/crates/engine/src/cmd/gradpresets.rs index 2f69a9df39..037033ea8a 100644 --- a/crates/engine/src/cmd/gradpresets.rs +++ b/crates/engine/src/cmd/gradpresets.rs @@ -4,7 +4,7 @@ //! The built-in presets are the gradient swatches of the built-in swatch libraries //! ([`vectorcraft_color::libraries`]: the app's own computed palettes), each listed under its //! library's name. Saved presets are kept with the preferences ([`crate::Prefs::gradient_presets`]), -//! so every document has them. A preset is the colour ramp (type, stops, method, dither), not a +//! so every document has them. A preset is the color ramp (type, stops, method, dither, spread), not a //! placement: applying one edits the gradient in place, as `paint.editGradient` does. use serde::{Deserialize, Serialize}; @@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> { "Gradient Presets", [], None, - "{} → {presets: [{name, library: the built-in library (theme) it comes from, null for a saved one, builtIn, gradient: {kind, stops, method?, dither?} (as paint.setFill's `gradient`)}]} the Gradient panel's presets: the built-in ones by library, then the saved ones; names are unique", + "{} → {presets: [{name, library: the built-in library (theme) it comes from, null for a saved one, builtIn, gradient: {kind, stops, method?, dither?, spread?, repeats?} (as paint.setFill's `gradient`)}]} the Gradient panel's presets: the built-in ones by library, then the saved ones; names are unique", always, list ), @@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> { "Apply Gradient Preset", [], None, - "{name: a preset's name (gradient.presets.list), stroke?, item?, ids?|id?, target? (as paint.editGradient)} give the gradient behind the active proxy (or the targeted fill or stroke) the preset's type, stops and method, and a fill its dither, keeping its placement; a solid or no paint becomes the gradient. One undo step, as paint.editGradient → {name, ids: the objects painted (none: only the default changed)}", + "{name: a preset's name (gradient.presets.list), stroke?, item?, ids?|id?, target? (as paint.editGradient)} give the gradient behind the active proxy (or the targeted fill or stroke) the preset's type, stops, method, spread and repeats (a freeform preset's: the first three), and a fill its dither, keeping its placement; a solid or no paint becomes the gradient. One undo step, as paint.editGradient → {name, ids: the objects painted (none: only the default changed)}", has_doc, apply ), @@ -42,7 +42,7 @@ pub fn specs() -> Vec<CommandSpec> { "Save Gradient Preset", [], None, - "{name?: (default: a new \"Gradient Preset N\"; unique, any case, and not a built-in preset's)} save the gradient behind the active proxy (paint.toggleActive picks Fill or Stroke) as a preset, kept with the preferences: its type, stops, method and dither (stops linked to a swatch keep their colour, unlinked) → {name}", + "{name?: (default: a new \"Gradient Preset N\"; unique, any case, and not a built-in preset's)} save the gradient behind the active proxy (paint.toggleActive picks Fill or Stroke) as a preset, kept with the preferences: its type, stops, method, dither, spread and repeats (stops linked to a swatch keep their colour, unlinked) → {name}", can_save, save ), @@ -90,12 +90,13 @@ fn builtin_presets() -> impl Iterator<Item = GradientPresetEntry> { }) } -/// Do `a` and `b` have the same colour ramp (type, method, dither and stops), swatch links aside? +/// Do `a` and `b` have the same color ramp (type, method, dither, spread as it paints and stops), +/// swatch links aside? fn same_ramp(a: &Gradient, b: &Gradient) -> bool { let stop = |x: &vectorcraft_color::GradientStop, y: &vectorcraft_color::GradientStop| { (x.offset, x.color, x.opacity, x.midpoint) == (y.offset, y.color, y.opacity, y.midpoint) }; - (a.kind, a.method, a.dither) == (b.kind, b.method, b.dither) + (a.kind, a.method, a.dither, a.painted_spread()) == (b.kind, b.method, b.dither, b.painted_spread()) && a.stops.len() == b.stops.len() && a.stops.iter().zip(&b.stops).all(|(x, y)| stop(x, y)) } @@ -109,6 +110,40 @@ fn unlinked(g: &Gradient) -> Gradient { g } +/// Give each saved preset in `saved` a name no built-in preset or earlier saved one has (any case): +/// a clash becomes the first free "<name> N", N from 2. Returns the renames as (old, new). +pub(crate) fn rename_clashing_presets(saved: &mut [GradientPreset]) -> Vec<(String, String)> { + if saved.is_empty() { + return vec![]; + } + let builtin: std::collections::HashSet<String> = builtin_presets().map(|e| e.name.to_ascii_lowercase()).collect(); + let mut taken: std::collections::HashSet<String> = + builtin.iter().cloned().chain(saved.iter().map(|p| p.name.trim().to_ascii_lowercase())).collect(); + let mut kept = std::collections::HashSet::new(); + // The next suffix to try for each name, so many presets with one name take linear time. + let mut next: std::collections::HashMap<String, u64> = std::collections::HashMap::new(); + let mut renamed = vec![]; + for p in saved { + let key = p.name.trim().to_ascii_lowercase(); + if !builtin.contains(&key) && kept.insert(key.clone()) { + continue; + } + let base = p.name.trim(); + let n = next.entry(key).or_insert(2); + let name = loop { + let candidate = format!("{base} {n}"); + *n += 1; + if !taken.contains(&candidate.to_ascii_lowercase()) { + break candidate; + } + }; + taken.insert(name.to_ascii_lowercase()); + kept.insert(name.to_ascii_lowercase()); + renamed.push((std::mem::replace(&mut p.name, name.clone()), name)); + } + renamed +} + impl Session { /// The Gradient panel's presets: the built-in ones by library, then the saved ones. pub fn gradient_presets(&self) -> Vec<GradientPresetEntry> { @@ -180,7 +215,12 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> { o.insert("stroke".into(), json!(stroke)); o.insert("kind".into(), json!(g.kind.label().to_lowercase())); o.insert("stops".into(), stops_json(&g.stops)); - o.insert("method".into(), json!(g.method.label().to_lowercase())); + o.insert("method".into(), json!(g.method.id())); + // A freeform preset takes no spread (paint.editGradient refuses one). + if g.kind != vectorcraft_color::GradientKind::Freeform { + o.insert("spread".into(), json!(g.spread.label().to_lowercase())); + o.insert("repeats".into(), json!(g.repeat_count())); + } // Dither is a fill's (paint.editGradient refuses it on a stroke). if !stroke { o.insert("dither".into(), json!(g.dither)); diff --git a/crates/engine/src/cmd/graph.rs b/crates/engine/src/cmd/graph.rs index 2c42494160..c45bbf5a67 100644 --- a/crates/engine/src/cmd/graph.rs +++ b/crates/engine/src/cmd/graph.rs @@ -46,7 +46,8 @@ use generate::generate; use series::default_series_color; pub(crate) use series::{ capture_label_anti_alias, capture_label_paragraphs, capture_label_styles, capture_series_object_opacity, capture_series_opacity, - capture_series_paints, capture_series_top_paints, paint_targets, series_object_opacity_differs, shown_paint, + capture_series_paints, capture_series_top_paints, paint_targets, series_group_marks, series_group_marks_where, series_object_opacity_differs, + shown_paint, }; #[cfg(test)] diff --git a/crates/engine/src/cmd/graph/series.rs b/crates/engine/src/cmd/graph/series.rs index 229a4d4b42..99a7ec084b 100644 --- a/crates/engine/src/cmd/graph/series.rs +++ b/crates/engine/src/cmd/graph/series.rs @@ -79,6 +79,11 @@ struct SeriesRef { index: usize, } +/// How many series groups `spec`'s graph has: a group whose index is past it (the index comes from the file) is not one. +fn series_count(spec: &GraphSpec) -> usize { + spec.rows.iter().map(Vec::len).max().unwrap_or(0).clamp(1, vectorcraft_doc::MAX_GRAPH_SERIES) +} + /// Every node in a graph's series groups (the groups too), found in one pass over the document. /// Axes, the legend and groups whose index is past the graph's series (the index comes from the /// file) are left out. @@ -86,7 +91,7 @@ fn series_members(doc: &Document) -> HashMap<NodeId, SeriesRef> { let mut out = HashMap::new(); doc.walk(|n| { let Some(spec) = n.extras().graph.as_deref() else { return }; - let count = spec.rows.iter().map(Vec::len).max().unwrap_or(0).clamp(1, vectorcraft_doc::MAX_GRAPH_SERIES); + let count = series_count(spec); for group in n.children().into_iter().flatten() { let Some(index) = group.extras().series_index.and_then(|i| usize::try_from(i).ok()).filter(|i| *i < count) else { continue }; let r = SeriesRef { graph: n.id, group: group.id, index }; @@ -124,6 +129,38 @@ pub(crate) fn paint_targets(doc: &Document, ids: &[NodeId]) -> Vec<NodeId> { out } +/// `ids` with each graph series group replaced by the paths directly inside it, as [`paint_targets`] reads a series +/// group: the graph draws its series groups again with no rows of their own. A series group with no such path, other +/// ids and the art of a graph design pass through, and the order of `ids` is kept. +pub(crate) fn series_group_marks(doc: &Document, ids: &[NodeId]) -> Vec<NodeId> { + series_group_marks_where(doc, ids, |_| true) +} + +/// [`series_group_marks`] for the series groups `stands` accepts; the others pass through. +pub(crate) fn series_group_marks_where(doc: &Document, ids: &[NodeId], stands: impl Fn(&Node) -> bool) -> Vec<NodeId> { + // A series group is a child of a graph with one of the graph's series indexes ([`series_members`]). Each id is + // looked up through its parent, with no pass over the document: the panels call this while they draw. + let is_series_group = |n: &Node| { + let Some(index) = n.extras().series_index.and_then(|i| usize::try_from(i).ok()) else { return false }; + let graph = doc.parent_of(n.id).and_then(|parent| doc.node(parent)).and_then(|parent| parent.extras().graph.as_deref()); + graph.is_some_and(|spec| index < series_count(spec)) + }; + let mut seen = std::collections::HashSet::new(); + let mut out = Vec::new(); + for id in ids { + match doc.node(*id) { + Some(group) if is_series_group(group) && stands(group) => { + let marks: Vec<NodeId> = + group.children().into_iter().flatten().filter(|m| matches!(m.kind, NodeKind::Path { .. })).map(|m| m.id).collect(); + if marks.is_empty() { out.push(*id) } else { out.extend(marks) } + } + _ => out.push(*id), + } + } + out.retain(|id| seen.insert(*id)); + out +} + /// Copy the paint just applied to generated series art into that series' fill or stroke. Called /// inside the same document edit, so the visible paint and future regeneration undo together. /// Gradients, patterns and swatch links are kept as [`Paint`], not reduced to a solid colour. diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index aef1918a6d..e847326e88 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -1034,6 +1034,85 @@ fn an_opaque_pick_replaces_the_opacity_the_series_stores() { assert_eq!(spec(&s, id).series_paints[0].fill_opacity, None); } +/// A column graph whose series 0 stores the 40% Multiply fill set on its first mark, and a mark of series 1 whose top fill +/// row has no paint and is opaque and Normal: the session, the graph, series 0's marks and that source. +fn marks_and_unpainted_source() -> (Session, NodeId, Vec<NodeId>, NodeId) { + let (mut s, id, _, marks) = column_marks(); + let source = series(s.doc().unwrap().doc.node(id).unwrap(), 1).children().unwrap()[0].id; + s.execute("appearance.setItem", &json!({"ids": [source.0], "index": top_row(&s, source, true), "none": true})).unwrap(); + let fill = top_row(&s, marks[0], true); + s.execute("appearance.setItem", &json!({"ids": [marks[0].0], "index": fill, "opacity": 40, "blend": "multiply"})).unwrap(); + let kept = spec(&s, id).series_paints[0].clone(); + assert_eq!((kept.fill_opacity, kept.fill_blend), (Some(0.4), Some(BlendMode::Multiply))); + (s, id, marks, source) +} + +/// An Eyedropper pick from a fill row without paint onto a mark whose fill had paint replaces the fill opacity and blend +/// mode another mark of the series stored: the series is drawn opaque and Normal again. +#[test] +fn an_eyedropper_pick_that_unpaints_a_series_fill_clears_its_stored_transparency() { + let (mut s, id, marks, source) = marks_and_unpainted_source(); + let mark = s.doc().unwrap().doc.node(marks[1]).unwrap().appearance.fill().unwrap().clone(); + assert_eq!((mark.paint.is_none(), mark.opacity, mark.blend), (false, 1.0, BlendMode::Normal), "the target's fill row"); + s.execute("appearance.copyFrom", &json!({"source": source.0, "ids": [marks[1].0]})).unwrap(); + let picked = s.doc().unwrap().doc.node(marks[1]).unwrap().appearance.fill().unwrap().clone(); + assert_eq!((picked.paint.is_none(), picked.opacity, picked.blend), (true, 1.0, BlendMode::Normal)); + let kept = spec(&s, id).series_paints[0].clone(); + assert_eq!((kept.fill_opacity, kept.fill_blend), (None, None)); + s.execute("graph.setData", &json!({"rows": [[1, 2], [3, 4]]})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let fills: Vec<_> = series(&n, 0).children().unwrap().iter().filter_map(|m| m.appearance.fill().map(|f| (f.opacity, f.blend))).collect(); + assert!(fills.iter().all(|f| *f == (1.0, BlendMode::Normal)), "{fills:?}"); +} + +/// An Eyedropper pick from a fill row without paint onto a mark whose fill had no paint before the pick either leaves the +/// fill opacity and blend mode another mark of the series stored. +#[test] +fn an_eyedropper_pick_of_an_already_unpainted_row_leaves_series_transparency() { + let (mut s, id, marks, source) = marks_and_unpainted_source(); + s.execute("appearance.setItem", &json!({"ids": [marks[1].0], "index": top_row(&s, marks[1], true), "none": true})).unwrap(); + let kept = spec(&s, id).series_paints[0].clone(); + assert_eq!((kept.fill_opacity, kept.fill_blend), (Some(0.4), Some(BlendMode::Multiply)), "a color set to None writes no opacity"); + s.execute("appearance.copyFrom", &json!({"source": source.0, "ids": [marks[1].0]})).unwrap(); + let kept = spec(&s, id).series_paints[0].clone(); + assert_eq!((kept.fill_opacity, kept.fill_blend), (Some(0.4), Some(BlendMode::Multiply))); +} + +/// A whole Eyedropper pick from a source with no fill row, or no stroke row, removes that row from the mark. Where the +/// mark's row had paint, the pick replaces the opacity and blend mode another mark of the series stored for that kind +/// of row. Where the mark's row had no paint, the stored values stay. +#[test] +fn a_whole_eyedropper_pick_that_removes_a_painted_row_clears_its_stored_transparency() { + let stored = |s: &Session, id: NodeId, fill: bool| { + let kept = spec(s, id).series_paints[0].clone(); + if fill { (kept.fill_opacity, kept.fill_blend) } else { (kept.stroke_opacity, kept.stroke_blend) } + }; + for (fill, painted) in [(true, true), (false, true), (false, false)] { + let (mut s, id, _, marks) = column_marks(); + let row = top_row(&s, marks[0], fill); + if painted { + s.execute("appearance.setItem", &json!({"ids": [marks[1].0], "index": row, "color": "#ff0000"})).unwrap(); + } + s.execute("appearance.setItem", &json!({"ids": [marks[0].0], "index": row, "color": "#ff0000", "opacity": 40, "blend": "multiply"})).unwrap(); + assert_eq!(stored(&s, id, fill), (Some(0.4), Some(BlendMode::Multiply)), "fill {fill}, painted {painted}"); + let source = series(s.doc().unwrap().doc.node(id).unwrap(), 1).children().unwrap()[0].id; + s.execute("appearance.removeItem", &json!({"ids": [source.0], "index": top_row(&s, source, fill)})).unwrap(); + let was = spec(&s, id).series_paints; + s.execute("appearance.copyFrom", &json!({"source": source.0, "ids": [marks[1].0]})).unwrap(); + let mark = s.doc().unwrap().doc.node(marks[1]).unwrap().clone(); + assert!(!mark.appearance.items.iter().any(|it| it.is_fill() == fill), "the pick removed the row: fill {fill}"); + let want = if painted { (None, None) } else { (Some(0.4), Some(BlendMode::Multiply)) }; + assert_eq!(stored(&s, id, fill), want, "fill {fill}, painted {painted}"); + if painted { + let after = spec(&s, id).series_paints; + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(spec(&s, id).series_paints, was); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(spec(&s, id).series_paints, after); + } + } +} + /// An appearance moved between two marks of one series leaves the series with the target's paint, not the source's /// empty one, and the series still shows when the graph is drawn again. #[test] @@ -1251,6 +1330,45 @@ fn a_style_that_removes_a_marks_stroke_replaces_the_kept_stroke_opacity() { } } +/// An Eyedropper pick from a stroke row without paint onto a marker whose stroke had paint replaces the stroke opacity and +/// blend mode the series' Filled Lines band left, in the pick's undo step: the band's outline is drawn opaque and Normal +/// again. A pick onto a marker whose stroke had no paint before the pick leaves them as they are. +#[test] +fn an_eyedropper_pick_that_unpaints_a_series_stroke_clears_its_stored_transparency() { + for stroked in [true, false] { + let (mut s, id, band) = band_graph(); + let parts = series_parts(&s, id, 0); + let (marker, source) = (parts[1].id, parts[2].id); + let st = parts[2].appearance.stroke().unwrap(); + assert_eq!((st.paint.is_none(), st.opacity, st.blend), (true, 1.0, BlendMode::Normal), "the source's stroke row"); + if stroked { + let row = top_row(&s, marker, false); + s.execute("appearance.setItem", &json!({"ids": [marker.0], "index": row, "color": "#ff0000"})).unwrap(); + } + let row = top_row(&s, band, false); + s.execute("appearance.setItem", &json!({"ids": [band.0], "index": row, "opacity": 40, "blend": "multiply"})).unwrap(); + let was = spec(&s, id).series_paints; + assert_eq!((was[0].stroke_opacity, was[0].stroke_blend), (Some(0.4), Some(BlendMode::Multiply))); + s.execute("appearance.copyFrom", &json!({"source": source.0, "ids": [marker.0]})).unwrap(); + let picked = s.doc().unwrap().doc.node(marker).unwrap().appearance.stroke().unwrap().clone(); + assert_eq!((picked.paint.is_none(), picked.opacity, picked.blend), (true, 1.0, BlendMode::Normal), "stroked {stroked}"); + let kept = spec(&s, id).series_paints[0].clone(); + let want = if stroked { (None, None) } else { (Some(0.4), Some(BlendMode::Multiply)) }; + assert_eq!((kept.stroke_opacity, kept.stroke_blend), want, "stroked {stroked}"); + if stroked { + let after = spec(&s, id).series_paints; + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(spec(&s, id).series_paints, was); + assert!(!s.doc().unwrap().doc.node(marker).unwrap().appearance.stroke_paint().is_none(), "the undo took back the pick"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(spec(&s, id).series_paints, after); + } + redrawn_band(&mut s, id); + let st = series_parts(&s, id, 0)[0].appearance.stroke().unwrap().clone(); + assert_eq!((Some(st.opacity).filter(|o| *o < 1.0), Some(st.blend).filter(|b| *b != BlendMode::Normal)), want, "stroked {stroked}"); + } +} + /// A Filled Lines band's stroke row removed with the Appearance panel or set to None with `paint.setStroke` leaves the /// band its color: an empty stored stroke is not a color for the band. #[test] @@ -1686,6 +1804,364 @@ fn redefining_a_graphic_style_from_a_series_mark_keeps_the_paint_another_mark_st assert_eq!(spec(&s, id).series_paints, was); } +/// Series 0's group, and whether it is as the graph draws it: the group has no rows of its own and each path directly +/// inside it has rows. +fn series_0_group(s: &Session, id: NodeId) -> (NodeId, bool) { + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let g = series(&n, 0); + let drawn = g.appearance.items.is_empty() && g.children().unwrap().iter().all(|m| !m.appearance.items.is_empty()); + (g.id, drawn) +} + +/// `appearance.setItem` given a series group's id edits the paths directly inside it, so the graph stores the color and +/// opacity and every mark has them after the graph is drawn again. The group keeps no rows of its own. +#[test] +fn an_appearance_item_set_on_a_series_group_edits_its_marks() { + let (mut s, id, _, marks) = column_marks(); + let (group, drawn) = series_0_group(&s, id); + assert!(drawn); + let was = spec(&s, id).series_paints; + let row = top_row(&s, marks[0], true); + s.execute("appearance.setItem", &json!({"ids": [group.0], "index": row, "color": "#0000ff", "opacity": 40})).unwrap(); + assert!(series_0_group(&s, id).1, "the group has no rows of its own"); + let blue = s.doc().unwrap().doc.node(marks[0]).unwrap().appearance.fill_paint(); + let kept = spec(&s, id).series_paints[0].clone(); + assert_eq!((kept.fill.clone(), kept.fill_opacity), (Some(blue.clone()), Some(0.4))); + let (stroke, weight) = { + let m = s.doc().unwrap().doc.node(marks[0]).unwrap().clone(); + (m.appearance.stroke_paint(), m.appearance.stroke_width()) + }; + series_0_is(&mut s, id, (&blue, 0.4, &stroke, weight), &was); +} + +/// The other Appearance commands given a series group's id, picked with Group Selection or given in `ids`, edit the +/// paths directly inside it, and the graph stores what they change: Add New Fill, Clear Appearance, Move Appearance onto +/// the group, and an opacity set on a row with `transparency.set`. +#[test] +fn appearance_commands_given_a_series_group_edit_its_marks() { + let (mut s, id, marks) = stored_red_stroke(); + let (group, _) = series_0_group(&s, id); + s.execute("select.set", &json!({"ids": [group.0]})).unwrap(); + s.execute("appearance.addFill", &json!({})).unwrap(); + assert!(series_0_group(&s, id).1, "Add New Fill on the selected group"); + let rows = s.doc().unwrap().doc.node(marks[0]).unwrap().appearance.items.iter().filter(|it| it.is_fill()).count(); + assert_eq!(rows, 2, "each mark has a new fill row"); + s.execute("edit.undo", &json!({})).unwrap(); + + let row = top_row(&s, marks[0], true); + s.execute("transparency.set", &json!({"ids": [group.0], "item": row, "opacity": 30})).unwrap(); + assert!(series_0_group(&s, id).1); + assert_eq!(spec(&s, id).series_paints[0].fill_opacity, Some(0.3)); + s.execute("edit.undo", &json!({})).unwrap(); + + s.execute("appearance.clear", &json!({"ids": [group.0]})).unwrap(); + assert_eq!(spec(&s, id).series_paints[0].fill, Some(Paint::None)); + s.execute("edit.undo", &json!({})).unwrap(); + + let (rect, blue) = blue_style(&mut s, "Blue", false); + let was = spec(&s, id).series_paints; + s.execute("object.setProps", &json!({"ids": [group.0], "opacity": 50})).unwrap(); + s.execute("appearance.transfer", &json!({"source": rect.0, "target": group.0, "copy": true})).unwrap(); + assert!(series_0_group(&s, id).1); + assert_eq!(s.doc().unwrap().doc.node(group).unwrap().opacity, 1.0, "the appearance replaces the group's own opacity"); + let kept = spec(&s, id).series_paints[0].clone(); + assert_eq!((kept.fill.clone(), kept.fill_opacity, kept.stroke), (Some(blue.clone()), Some(0.5), Some(Paint::None))); + series_0_is(&mut s, id, (&blue, 0.5, &Paint::None, 0.0), &was); +} + +/// Moving the Contents row of a series group as the graph draws it, with no rows of its own, moves the group's own +/// row: the paths inside it have none. +#[test] +fn moving_a_series_groups_contents_row_moves_its_own_row() { + let (mut s, id, _, _) = column_marks(); + let (group, drawn) = series_0_group(&s, id); + assert!(drawn); + let out = s.execute("appearance.moveItem", &json!({"ids": [group.0], "from": "contents", "to": 0})).unwrap(); + assert_eq!(out["contents"], json!(0)); +} + +/// Add New Stroke, Duplicate Item, Reorder Appearance Item and Remove Item given a series group's id edit the rows of +/// the paths directly inside it, and the group keeps no rows of its own. +#[test] +fn row_commands_given_a_series_group_edit_its_marks_rows() { + let (mut s, id, _, marks) = column_marks(); + let (group, _) = series_0_group(&s, id); + let count = |s: &Session, fill: bool| -> Vec<usize> { + let d = &s.doc().unwrap().doc; + marks.iter().map(|m| d.node(*m).unwrap().appearance.items.iter().filter(|it| it.is_fill() == fill).count()).collect() + }; + let (fills, strokes) = (count(&s, true), count(&s, false)); + s.execute("appearance.addStroke", &json!({"ids": [group.0]})).unwrap(); + assert_eq!(count(&s, false), strokes.iter().map(|n| n + 1).collect::<Vec<_>>(), "each mark has a new stroke row"); + let fill = top_row(&s, marks[0], true); + s.execute("appearance.duplicateItem", &json!({"ids": [group.0], "index": fill})).unwrap(); + assert_eq!(count(&s, true), fills.iter().map(|n| n + 1).collect::<Vec<_>>(), "each mark has a copy of its fill row"); + let rows = s.doc().unwrap().doc.node(marks[0]).unwrap().appearance.items.len(); + let out = s.execute("appearance.moveItem", &json!({"ids": [group.0], "from": 0, "to": rows - 1})).unwrap(); + assert_eq!(out["index"], json!(rows - 1)); + s.execute("appearance.removeItem", &json!({"ids": [group.0], "index": top_row(&s, marks[0], true)})).unwrap(); + assert_eq!(count(&s, true), fills); + assert!(series_0_group(&s, id).1, "the group has no rows of its own"); +} + +/// Reduce to Basic Appearance given a series group's id reduces the paths directly inside it and drops an effect the +/// group holds. +#[test] +fn reducing_a_series_group_reduces_its_marks_and_drops_its_own_effect() { + let (mut s, id, _, marks) = column_marks(); + let (group, _) = series_0_group(&s, id); + s.execute("appearance.addFill", &json!({"ids": [group.0]})).unwrap(); + s.execute("effect.apply", &json!({"ids": [group.0], "effect": "distort.twist"})).unwrap(); + s.execute("appearance.reduceToBasic", &json!({"ids": [group.0]})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.node(group).unwrap().appearance.effects.is_empty(), "the group's effect is dropped"); + assert!(marks.iter().all(|m| d.node(*m).unwrap().appearance.items.iter().filter(|it| it.is_fill()).count() == 1)); + assert!(series_0_group(&s, id).1); +} + +/// A graphic style added on top (Alt-click) given a series group's id adds its rows to the paths directly inside the +/// group and unlinks a group that held a style link. +#[test] +fn a_graphic_style_added_to_a_series_group_adds_rows_to_its_marks_and_unlinks_the_group() { + let (mut s, id, _, marks) = column_marks(); + let (group, _) = series_0_group(&s, id); + blue_style(&mut s, "Blue", false); + let style = s.doc().unwrap().doc.graphic_style("Blue").unwrap().id; + s.edit("Link", |d, _| { + d.node_mut(group).unwrap().extras_mut().graphic_style = Some(style); + Ok(()) + }) + .unwrap(); + let fills = |s: &Session, m: NodeId| s.doc().unwrap().doc.node(m).unwrap().appearance.items.iter().filter(|it| it.is_fill()).count(); + let was = fills(&s, marks[0]); + s.execute("graphicStyle.apply", &json!({"name": "Blue", "ids": [group.0], "add": true})).unwrap(); + assert!(marks.iter().all(|m| fills(&s, *m) == was + 1), "each mark has the style's fill on top"); + assert!(series_0_group(&s, id).1, "the group takes no rows of the style"); + assert_eq!(s.doc().unwrap().doc.node(group).unwrap().extras().graphic_style, None, "the group is unlinked"); +} + +/// Move Appearance from one of a series group's paths onto the group gives the other paths its look and leaves that +/// path as it was. When the path is the only one directly in the group, the command is refused and the group takes no +/// rows. +#[test] +fn moving_an_appearance_from_a_mark_onto_its_own_series_group_keeps_the_mark() { + let (mut s, id, _, marks) = column_marks(); + let (group, _) = series_0_group(&s, id); + s.execute("appearance.setItem", &json!({"ids": [marks[0].0], "index": top_row(&s, marks[0], true), "color": "#00ff00"})).unwrap(); + let green = s.doc().unwrap().doc.node(marks[0]).unwrap().appearance.fill_paint(); + s.execute("appearance.transfer", &json!({"source": marks[0].0, "target": group.0})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(marks.iter().all(|m| d.node(*m).unwrap().appearance.fill_paint() == green), "every mark, the source too, is green"); + assert_eq!(spec(&s, id).series_paints[0].fill, Some(green)); + + s.edit("One path", |d, _| { + d.children_mut(Some(group)).unwrap().truncate(1); + Ok(()) + }) + .unwrap(); + let only = s.doc().unwrap().doc.node(group).unwrap().children().unwrap()[0].id; + let err = s.execute("appearance.transfer", &json!({"source": only.0, "target": group.0})).unwrap_err(); + assert!(err.to_string().contains("only path"), "{err}"); + assert!(series_0_group(&s, id).1, "the group has no rows of its own"); +} + +/// A series group that holds an opacity and an effect of its own is read itself as a source, as any group is: a new +/// graphic style and Move Appearance take the group's opacity and effect, and the group, not a path, is linked. +#[test] +fn a_series_group_with_a_look_of_its_own_is_read_itself_as_a_source() { + let (mut s, id, _, marks) = column_marks(); + let (group, _) = series_0_group(&s, id); + s.execute("transparency.set", &json!({"ids": [group.0], "opacity": 50, "item": null})).unwrap(); + s.execute("effect.apply", &json!({"ids": [group.0], "effect": "distort.twist"})).unwrap(); + s.execute("graphicStyle.new", &json!({"id": group.0, "name": "Series"})).unwrap(); + let d = &s.doc().unwrap().doc; + let style = d.graphic_style("Series").unwrap(); + assert_eq!((style.opacity, style.appearance.effects.len()), (0.5, 1)); + assert_eq!(d.node(group).unwrap().extras().graphic_style, Some(style.id)); + assert!(marks.iter().all(|m| d.node(*m).unwrap().extras().graphic_style.is_none())); + + let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()); + s.execute("appearance.transfer", &json!({"source": group.0, "target": rect.0, "copy": true})).unwrap(); + let r = s.doc().unwrap().doc.node(rect).unwrap().clone(); + assert_eq!((r.opacity, r.appearance.effects.len()), (0.5, 1)); +} + +/// Clear Appearance and Show All Hidden Attributes given a series group's id also reach an effect the group holds, and +/// Break Link to Graphic Style unlinks the paths a style applied to the group linked. +#[test] +fn whole_appearance_commands_given_a_series_group_edit_the_group_and_its_marks() { + let (mut s, id, marks) = stored_red_stroke(); + let (group, _) = series_0_group(&s, id); + let effects = |s: &Session| s.doc().unwrap().doc.node(group).unwrap().appearance.effects.clone(); + s.execute("effect.apply", &json!({"ids": [group.0], "effect": "distort.twist"})).unwrap(); + s.execute("effect.setParams", &json!({"ids": [group.0], "index": 0, "visible": false, "item": null})).unwrap(); + assert!(!effects(&s)[0].visible); + let shown = s.execute("appearance.showAllHidden", &json!({"ids": [group.0]})).unwrap(); + assert_eq!(shown["ids"], json!([group.0])); + assert!(effects(&s)[0].visible); + s.execute("appearance.clear", &json!({"ids": [group.0]})).unwrap(); + assert!(effects(&s).is_empty(), "the group's effect is cleared with its marks' rows"); + assert_eq!(spec(&s, id).series_paints[0].fill, Some(Paint::None)); + s.execute("edit.undo", &json!({})).unwrap(); + + blue_style(&mut s, "Blue", false); + s.execute("select.set", &json!({"ids": [group.0]})).unwrap(); + s.execute("graphicStyle.apply", &json!({"name": "Blue"})).unwrap(); + assert_eq!(s.selection_graphic_style().map(|(g, linked)| (g.name.clone(), linked)), Some(("Blue".into(), true))); + s.execute("graphicStyle.breakLink", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(marks.iter().all(|m| d.node(*m).unwrap().extras().graphic_style.is_none()), "each mark is unlinked"); + assert!(s.selection_graphic_style().is_none()); +} + +/// Redefine Graphic Style on a selected series group whose paths a style links takes the look of the topmost of them. +#[test] +fn redefining_a_graphic_style_from_a_selected_series_group_reads_its_topmost_mark() { + let (mut s, id, marks) = stored_red_stroke(); + let (group, _) = series_0_group(&s, id); + blue_style(&mut s, "Blue", false); + s.execute("select.set", &json!({"ids": [group.0]})).unwrap(); + s.execute("graphicStyle.apply", &json!({"name": "Blue"})).unwrap(); + let top = *marks.last().unwrap(); + s.execute("appearance.setItem", &json!({"ids": [top.0], "index": top_row(&s, top, true), "color": "#00ff00"})).unwrap(); + let green = s.doc().unwrap().doc.node(top).unwrap().appearance.fill_paint(); + s.execute("graphicStyle.redefine", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!(d.graphic_style("Blue").unwrap().appearance.fill_paint(), green); + assert!(marks.iter().all(|m| d.node(*m).unwrap().appearance.fill_paint() == green), "the marks still linked follow"); +} + +/// A series group as the graph draws it, read as a source, gives the look of the topmost path directly inside it: New +/// Graphic Style keeps that path's fill and links it, Move Appearance copies it, and a move clears every path of the +/// group. +#[test] +fn a_series_group_read_as_a_source_gives_its_topmost_marks_look() { + let (mut s, id, marks) = stored_red_stroke(); + let (group, _) = series_0_group(&s, id); + let top = *marks.last().unwrap(); + s.execute("appearance.setItem", &json!({"ids": [group.0], "index": top_row(&s, marks[0], true), "color": "#0000ff", "opacity": 30})).unwrap(); + s.execute("appearance.setItem", &json!({"ids": [marks[0].0], "index": top_row(&s, marks[0], true), "color": "#00ff00"})).unwrap(); + let look = s.doc().unwrap().doc.node(top).unwrap().appearance.clone(); + assert_ne!(look.fill_paint(), s.doc().unwrap().doc.node(marks[0]).unwrap().appearance.fill_paint()); + s.execute("graphicStyle.new", &json!({"id": group.0, "name": "Series"})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!(d.graphic_style("Series").unwrap().appearance.fill_paint(), look.fill_paint()); + assert_eq!(d.node(top).unwrap().extras().graphic_style, Some(d.graphic_style("Series").unwrap().id)); + + let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()); + s.execute("appearance.transfer", &json!({"source": group.0, "target": rect.0})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!(d.node(rect).unwrap().appearance.fill_paint(), look.fill_paint()); + assert!(marks.iter().all(|m| d.node(*m).unwrap().appearance.fill_paint() == Paint::None), "the move clears each mark"); + assert_eq!(spec(&s, id).series_paints[0].fill, Some(Paint::None)); +} + +/// A series group that has a row of its own, as a document saved earlier can hold, is edited itself: the Appearance +/// panel lists that row and edits it by its index. +#[test] +fn a_series_group_with_a_row_of_its_own_is_edited_itself() { + let (mut s, id, _, marks) = column_marks(); + let (group, _) = series_0_group(&s, id); + s.edit("Row", |d, _| { + let g = d.node_mut(group).unwrap(); + g.appearance = vectorcraft_doc::Appearance::basic(Paint::None, Paint::None, 1.0).into(); + Ok(()) + }) + .unwrap(); + let was = s.doc().unwrap().doc.node(marks[0]).unwrap().appearance.clone(); + s.execute("appearance.setItem", &json!({"ids": [group.0], "index": top_row(&s, group, true), "color": "#0000ff"})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_ne!(d.node(group).unwrap().appearance.fill_paint(), Paint::None); + assert_eq!(d.node(marks[0]).unwrap().appearance, was, "the marks keep their rows"); +} + +/// A graphic style applied to a series group's id styles and links the paths directly inside it, and the graph stores +/// the style's fill and stroke. +#[test] +fn a_graphic_style_applied_to_a_series_group_styles_its_marks() { + let (mut s, id, marks) = stored_red_stroke(); + let (group, _) = series_0_group(&s, id); + let (_, blue) = blue_style(&mut s, "Blue", false); + let was = spec(&s, id).series_paints; + let own = json!({"ids": [group.0], "opacity": 50, "blend": "multiply", "isolate": true, "knockout": "on", "item": null}); + s.execute("transparency.set", &own).unwrap(); + s.execute("effect.apply", &json!({"ids": [group.0], "effect": "distort.twist"})).unwrap(); + let g = s.doc().unwrap().doc.node(group).unwrap().clone(); + assert!(g.isolate && g.knockout != Default::default() && g.blend != vectorcraft_color::BlendMode::Normal); + s.execute("graphicStyle.apply", &json!({"name": "Blue", "ids": [group.0]})).unwrap(); + assert!(series_0_group(&s, id).1, "the group takes no rows of the style"); + let g = s.doc().unwrap().doc.node(group).unwrap().clone(); + assert_eq!((g.opacity, g.isolate), (1.0, false), "the style replaces the group's own opacity and isolation"); + assert_eq!((g.blend, g.knockout), (vectorcraft_color::BlendMode::Normal, Default::default()), "and its blend mode and knockout"); + assert!(g.appearance.effects.is_empty(), "and its effects"); + let style = s.doc().unwrap().doc.graphic_style("Blue").unwrap().id; + let d = &s.doc().unwrap().doc; + assert!(marks.iter().all(|m| d.node(*m).unwrap().extras().graphic_style == Some(style)), "each mark is linked to the style"); + assert_eq!(d.node(group).unwrap().extras().graphic_style, None); + let kept = spec(&s, id).series_paints[0].clone(); + assert_eq!((kept.fill.clone(), kept.fill_opacity, kept.stroke), (Some(blue.clone()), Some(0.5), Some(Paint::None))); + series_0_is(&mut s, id, (&blue, 0.5, &Paint::None, 0.0), &was); +} + +/// Redefine Graphic Style on a series group linked to the style (as a file can hold it) restyles the paths directly +/// inside the group and links them, and the graph stores the new look; the group goes back to no rows of its own. +#[test] +fn redefining_a_graphic_style_restyles_the_marks_of_a_linked_series_group() { + let (mut s, id, marks) = stored_red_stroke(); + let (group, _) = series_0_group(&s, id); + let (rect, _) = blue_style(&mut s, "Blue", false); + let style = s.doc().unwrap().doc.graphic_style("Blue").unwrap().clone(); + s.edit("Link", |d, _| { + let g = d.node_mut(group).unwrap(); + g.appearance = style.appearance.clone().into(); + g.extras_mut().graphic_style = Some(style.id); + Ok(()) + }) + .unwrap(); + s.execute("appearance.setItem", &json!({"ids": [rect.0], "index": top_row(&s, rect, true), "color": "#00ff00", "opacity": 100})).unwrap(); + let green = s.doc().unwrap().doc.node(rect).unwrap().appearance.fill_paint(); + let was = spec(&s, id).series_paints; + s.execute("graphicStyle.redefine", &json!({"name": "Blue", "id": rect.0})).unwrap(); + assert!(series_0_group(&s, id).1, "the group has no rows of its own"); + let d = &s.doc().unwrap().doc; + assert_eq!(d.node(group).unwrap().extras().graphic_style, None); + assert!(marks.iter().all(|m| d.node(*m).unwrap().extras().graphic_style == Some(style.id))); + assert!(marks.iter().all(|m| d.node(*m).unwrap().appearance.fill_paint() == green)); + let kept = spec(&s, id).series_paints[0].clone(); + assert_eq!((kept.fill.clone(), kept.fill_opacity, kept.stroke), (Some(green.clone()), None, Some(Paint::None))); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(spec(&s, id).series_paints, was, "one undo takes back the redefinition and what the graph stored"); + s.execute("edit.redo", &json!({})).unwrap(); + series_0_is(&mut s, id, (&green, 1.0, &Paint::None, 0.0), &was); +} + +/// Redefine Graphic Style on a linked series group leaves a path of the group that is linked to the style but no +/// longer has its look as it is, unlinked, and restyles the group's other paths. +#[test] +fn redefining_a_graphic_style_keeps_an_edited_mark_of_a_linked_series_group() { + let (mut s, id, _, marks) = column_marks(); + let (group, _) = series_0_group(&s, id); + let (rect, _) = blue_style(&mut s, "Blue", false); + let style = s.doc().unwrap().doc.graphic_style("Blue").unwrap().clone(); + s.edit("Link", |d, _| { + let g = d.node_mut(group).unwrap(); + g.appearance = style.appearance.clone().into(); + g.extras_mut().graphic_style = Some(style.id); + d.node_mut(marks[0]).unwrap().extras_mut().graphic_style = Some(style.id); + Ok(()) + }) + .unwrap(); + let edited = s.doc().unwrap().doc.node(marks[0]).unwrap().appearance.clone(); + s.execute("appearance.setItem", &json!({"ids": [rect.0], "index": top_row(&s, rect, true), "color": "#00ff00", "opacity": 100})).unwrap(); + let green = s.doc().unwrap().doc.node(rect).unwrap().appearance.fill_paint(); + s.execute("graphicStyle.redefine", &json!({"name": "Blue", "id": rect.0})).unwrap(); + let d = &s.doc().unwrap().doc; + let first = d.node(marks[0]).unwrap(); + assert_eq!((&first.appearance, first.extras().graphic_style), (&edited, None), "the edited mark keeps its look, unlinked"); + assert!(marks[1..].iter().all(|m| d.node(*m).unwrap().appearance.fill_paint() == green)); + assert!(marks[1..].iter().all(|m| d.node(*m).unwrap().extras().graphic_style == Some(style.id))); +} + /// Default Fill and Stroke on a series mark stores a white fill and a 1 pt black stroke, both opaque, on the graph. #[test] fn default_fill_and_stroke_on_a_series_mark_is_kept() { @@ -1800,7 +2276,7 @@ fn series_colours_survive_native_save_open_and_export() { let second = group(s.doc().unwrap().doc.node(id).unwrap(), "2025").id; s.execute("paint.setFill", &json!({"ids": [first.0], "color": "#f00"})).unwrap(); s.execute("paint.setFill", &json!({"ids": [second.0], "color": "#008080"})).unwrap(); - let dir = vectorcraft_testkit::temp_dir("graph-palette"); + let dir = vectorcraft_testkit::TempDir::new("graph-palette"); let path = dir.join("palette.vectorcraft"); s.execute("document.save", &json!({"path": path})).unwrap(); s.execute("document.open", &json!({"path": path})).unwrap(); @@ -2214,7 +2690,8 @@ fn series_types_survive_save_and_open_and_older_files_have_none() { s.execute("file.new", &json!({})).unwrap(); let id = graph(&mut s, "column"); s.execute("graph.setType", &json!({"seriesIndexes": [1], "type": "line"})).unwrap(); - let path = vectorcraft_testkit::temp_dir("graph-kinds").join("kinds.vectorcraft"); + let dir = vectorcraft_testkit::TempDir::new("graph-kinds"); + let path = dir.join("kinds.vectorcraft"); s.execute("document.save", &json!({"path": path})).unwrap(); s.execute("document.open", &json!({"path": path})).unwrap(); assert_eq!(spec(&s, id).series_kinds, [None, Some(GraphKind::Line)]); @@ -2342,7 +2819,8 @@ fn value_axis_options_survive_save_and_open_and_are_left_out_when_unset() { let id = two_scale_graph(&mut s); s.execute("graph.setType", &json!({"valueAxis": "both", "separateScales": true, "rightAxisMin": 0, "rightAxisMax": 2000})).unwrap(); s.execute("graph.setType", &json!({"seriesIndexes": [1], "valueAxis": "right"})).unwrap(); - let path = vectorcraft_testkit::temp_dir("graph-axes").join("axes.vectorcraft"); + let dir = vectorcraft_testkit::TempDir::new("graph-axes"); + let path = dir.join("axes.vectorcraft"); s.execute("document.save", &json!({"path": path})).unwrap(); s.execute("document.open", &json!({"path": path})).unwrap(); let g = spec(&s, id); @@ -2544,7 +3022,8 @@ fn tick_and_label_options_survive_save_and_open_and_are_left_out_when_unset() { &json!({"tickLength": "full", "tickMarks": 3, "categoryTickLength": "short", "ticksBetweenLabels": true, "suffix": "%"}), ) .unwrap(); - let path = vectorcraft_testkit::temp_dir("graph-ticks").join("ticks.vectorcraft"); + let dir = vectorcraft_testkit::TempDir::new("graph-ticks"); + let path = dir.join("ticks.vectorcraft"); s.execute("document.save", &json!({"path": path})).unwrap(); s.execute("document.open", &json!({"path": path})).unwrap(); let g = spec(&s, id); @@ -2783,7 +3262,8 @@ fn designs_and_markers_survive_save_and_open() { save_design(&mut s, "Pill"); let id = graph(&mut s, "line"); s.execute("graph.marker", &json!({"seriesIndexes": [0], "design": "Pill"})).unwrap(); - let path = vectorcraft_testkit::temp_dir("graph-designs").join("designs.vectorcraft"); + let dir = vectorcraft_testkit::TempDir::new("graph-designs"); + let path = dir.join("designs.vectorcraft"); s.execute("document.save", &json!({"path": path})).unwrap(); s.execute("document.open", &json!({"path": path})).unwrap(); assert_eq!(s.execute("graph.design", &json!({})).unwrap()["designs"], json!(["Pill"])); @@ -3181,7 +3661,8 @@ fn column_designs_survive_save_and_open_and_follow_their_design() { assert!(series_parts(&s, id, 1).iter().all(|n| matches!(n.kind, NodeKind::Path { .. })), "the line series"); let v = s.execute("graph.column", &json!({"id": id.0, "seriesIndexes": [0]})).unwrap(); assert_eq!(v, json!({"designs": ["Coin"], "design": "Coin", "columnType": "repeating", "each": 2.5, "fractions": "scale"})); - let path = vectorcraft_testkit::temp_dir("graph-column-designs").join("columns.vectorcraft"); + let dir = vectorcraft_testkit::TempDir::new("graph-column-designs"); + let path = dir.join("columns.vectorcraft"); s.execute("document.save", &json!({"path": path})).unwrap(); s.execute("document.open", &json!({"path": path})).unwrap(); let options = ColumnDesign { design: "Coin".into(), column_type: ColumnType::Repeating, each: 2.5, fractions: Fractions::Scale }; @@ -3703,7 +4184,8 @@ fn legends_in_wedges_put_the_series_labels_inside_the_pie() { s.execute("graph.setType", &json!({"legend": true})).unwrap(); assert!(!spec(&s, id).pie_legend_in_wedges); assert!(s.execute("graph.setType", &json!({"pieLegend": "inside"})).is_err()); - let path = vectorcraft_testkit::temp_dir("graph-pie").join("pie.vectorcraft"); + let dir = vectorcraft_testkit::TempDir::new("graph-pie"); + let path = dir.join("pie.vectorcraft"); s.execute("graph.setType", &json!({"pieLegend": "wedges", "piePosition": "stacked", "pieSort": "all"})).unwrap(); s.execute("document.save", &json!({"path": path})).unwrap(); s.execute("document.open", &json!({"path": path})).unwrap(); @@ -3844,7 +4326,8 @@ fn the_legend_across_top_runs_in_rows_above_the_plot() { assert!(ys.iter().all(|y| *y + 8.0 <= 100.0 - 8.0 + 1e-6), "{ys:?}"); let xs: Vec<f64> = (0..6).map(|i| swatch(&s, i).x1).collect(); assert!(xs.iter().all(|x| *x <= 400.0), "{xs:?}"); - let path = vectorcraft_testkit::temp_dir("graph-top").join("top.vectorcraft"); + let dir = vectorcraft_testkit::TempDir::new("graph-top"); + let path = dir.join("top.vectorcraft"); s.execute("graph.setType", &json!({"dropShadow": true})).unwrap(); s.execute("document.save", &json!({"path": path})).unwrap(); s.execute("document.open", &json!({"path": path})).unwrap(); @@ -3963,7 +4446,8 @@ fn filled_lines_are_bands_in_the_series_colour() { s.execute("paint.setFill", &json!({"ids": [grp.0], "color": "#ff0000"})).unwrap(); s.execute("graph.setData", &json!({"id": id.0, "rows": [[2], [3], [2]]})).unwrap(); assert_eq!(series_parts(&s, id, 0)[0].appearance.fill_paint().color().unwrap().to_hex(), "#ff0000"); - let path = vectorcraft_testkit::temp_dir("graph-filled").join("filled.vectorcraft"); + let dir = vectorcraft_testkit::TempDir::new("graph-filled"); + let path = dir.join("filled.vectorcraft"); s.execute("graph.setType", &json!({"firstRowInFront": true, "firstColumnInFront": true})).unwrap(); s.execute("document.save", &json!({"path": path})).unwrap(); s.execute("document.open", &json!({"path": path})).unwrap(); @@ -4090,7 +4574,8 @@ fn a_graph_labels_anti_aliasing_method_survives_it_being_drawn_again() { s.execute("edit.undo", &json!({})).unwrap(); assert_eq!(spec(&s, id).label_styles.categories_anti_alias, None); s.execute("edit.redo", &json!({})).unwrap(); - let path = vectorcraft_testkit::temp_dir("graph-label-anti-alias").join("labels.vectorcraft"); + let dir = vectorcraft_testkit::TempDir::new("graph-label-anti-alias"); + let path = dir.join("labels.vectorcraft"); s.execute("document.save", &json!({"path": path})).unwrap(); s.execute("document.open", &json!({"path": path})).unwrap(); assert_eq!(spec(&s, id).label_styles.categories_anti_alias, Some(TypeAntiAlias::Strong)); @@ -4133,7 +4618,8 @@ fn formatting_one_label_keeps_that_kind_of_label() { assert_eq!(look("0").2, "#0000ff", "every value axis number"); assert_eq!(look("0").1, 9.0); // Kept through save and open; nothing written when unset. - let path = vectorcraft_testkit::temp_dir("graph-labels").join("labels.vectorcraft"); + let dir = vectorcraft_testkit::TempDir::new("graph-labels"); + let path = dir.join("labels.vectorcraft"); s.execute("document.save", &json!({"path": path})).unwrap(); s.execute("document.open", &json!({"path": path})).unwrap(); assert_eq!(spec(&s, id).label_styles.categories.as_ref().unwrap().size, 14.0); @@ -4302,7 +4788,8 @@ fn paragraph_formats_are_kept_when_the_graph_is_drawn_again() { let v = text_id(&s, col, "Axes", "4"); s.execute("select.set", &json!({"ids": [v.0]})).unwrap(); s.execute("text.setFormat", &json!({"composer": "singleLine"})).unwrap(); - let path = vectorcraft_testkit::temp_dir("graph-label-paras").join("labels.vectorcraft"); + let dir = vectorcraft_testkit::TempDir::new("graph-label-paras"); + let path = dir.join("labels.vectorcraft"); s.execute("document.save", &json!({"path": path})).unwrap(); s.execute("document.open", &json!({"path": path})).unwrap(); s.execute("select.set", &json!({"ids": [col.0]})).unwrap(); diff --git a/crates/engine/src/cmd/interactivity.rs b/crates/engine/src/cmd/interactivity.rs index 4bcc123dcf..359c2d00d6 100644 --- a/crates/engine/src/cmd/interactivity.rs +++ b/crates/engine/src/cmd/interactivity.rs @@ -3,10 +3,14 @@ //! document links (`svgInteractivity.addFile`, `removeFile`). SVG export writes the events as //! event attributes (`onclick="…"`) and the files as `<script xlink:href>` elements; SVG import //! reads both back as text. The panel reads everything with `svgInteractivity.info`. +//! +//! While read roots are in force, a reply names a linked file outside them by its file name alone +//! ([`links::shown_script`]), and `removeFile` also takes that name for it. use serde_json::{Value, json}; -use vectorcraft_doc::{Document, MAX_SVG_SCRIPTS, NodeId, SVG_EVENTS}; +use vectorcraft_doc::{Document, LinkInfo, MAX_SVG_SCRIPTS, NodeId, SVG_EVENTS}; +use super::links::{self, LinkBase}; use super::overprint::edit_counted; use super::{CommandSpec, Result, Session, bad, cmd, has_doc, str_param, targets}; @@ -17,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> { "SVG Interactivity", [], None, - "{ids?|id?} → {ids, events: [{event, script}…] in the panel's order | null (the objects' events differ), files: [the linked JavaScript files…], eventNames: [the events the panel lists…]} the SVG Interactivity panel's values for ids or the selection", + "{ids?|id?} → {ids, events: [{event, script}…] in the panel's order | null (the objects' events differ), files: [the linked JavaScript files…; with automation read roots in force, a file outside them by its file name alone, a URL as it is], eventNames: [the events the panel lists…]} the SVG Interactivity panel's values for ids or the selection", has_doc, info ), @@ -53,7 +57,7 @@ pub fn specs() -> Vec<CommandSpec> { "Add JavaScript File", [], None, - "{file: path or URL (written as given, without surrounding spaces)} link a JavaScript file to the document, after the others: SVG export writes a <script xlink:href> for each linked file. A file already linked stays where it is; a document links at most 64 files → {files}", + "{file: path or URL (written as given, without surrounding spaces)} link a JavaScript file to the document, after the others: SVG export writes a <script xlink:href> for each linked file. A file already linked (the same text) stays where it is; a document links at most 64 files → {files} (as svgInteractivity.info gives them)", has_doc, add_file ), @@ -62,7 +66,7 @@ pub fn specs() -> Vec<CommandSpec> { "Remove JavaScript File", [], None, - "{file} unlink a JavaScript file from the document → {files}", + "{file} unlink a JavaScript file from the document: the file linked as `file` or, with automation read roots in force, a file outside them whose file name is `file`; an error, unlinking nothing, when `file` fits more than one → {files} (as svgInteractivity.info gives them)", has_doc, remove_file ), @@ -111,7 +115,8 @@ fn edit_events(s: &mut Session, p: &Value, cmd: &str, label: &str, f: impl Fn(&m fn info(s: &mut Session, p: &Value) -> Result<Value> { let ids = targets(s, p)?; - let d = &s.doc()?.doc; + let st = s.doc()?; + let d = &st.doc; let lists: Vec<Vec<(String, String)>> = ids.iter().map(|id| events_of(d, *id)).collect(); let events = lists .first() @@ -120,7 +125,7 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> { Ok(json!({ "ids": ids.iter().map(|id| id.0).collect::<Vec<_>>(), "events": events, - "files": d.svg_scripts, + "files": shown_files(st), "eventNames": SVG_EVENTS, })) } @@ -157,8 +162,14 @@ fn file_param(p: &Value, cmd: &str) -> Result<String> { f.map(str::to_string).ok_or_else(|| bad(cmd, "give `file`, the JavaScript file's path or URL")) } +/// The JavaScript files `st` links, in order, as a reply to the caller asking now may name them +/// ([`links::shown_script`]). +fn shown_files(st: &crate::DocState) -> Vec<String> { + st.doc.svg_scripts.iter().map(|f| links::shown_script(st, f).into_owned()).collect() +} + fn files(s: &Session) -> Result<Value> { - Ok(json!({ "files": s.doc()?.doc.svg_scripts })) + Ok(json!({ "files": shown_files(s.doc()?) })) } fn add_file(s: &mut Session, p: &Value) -> Result<Value> { @@ -180,11 +191,21 @@ fn add_file(s: &mut Session, p: &Value) -> Result<Value> { fn remove_file(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "svgInteractivity.removeFile"; let file = file_param(p, C)?; - if !s.doc()?.doc.svg_scripts.contains(&file) { - return Err(bad(C, format!("{file:?} isn't linked"))); - } + let st = s.doc()?; + let linked = &st.doc.svg_scripts; + // A file a reply names by its file name alone is also unlinked by that name, unless the name + // also fits another linked file. + let doc_path = LinkBase::of(st).doc; + let named: Vec<&String> = + linked.iter().filter(|f| **f != file && LinkInfo::new(f.as_str()).name() == file && links::script_hidden(f, doc_path)).collect(); + let stored = match (linked.contains(&file), named.as_slice()) { + (true, []) => file, + (false, [f]) => (*f).clone(), + (false, []) => return Err(bad(C, format!("{file:?} isn't linked"))), + _ => return Err(bad(C, format!("{file:?} names more than one linked JavaScript file"))), + }; s.edit("Remove JavaScript File", |d, _| { - d.svg_scripts.retain(|f| *f != file); + d.svg_scripts.retain(|f| *f != stored); Ok(()) })?; files(s) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 49b1015bf4..f589ea62da 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -14,8 +14,8 @@ use vectorcraft_doc::{Artboard, ArtboardSide, Document, LAYER_COLORS, LayerColor use vectorcraft_geom::{Affine, Rect}; use super::{ - CommandSpec, Result, Session, bad, bool_or, check_numbers, check_switches, checked_id, checked_ids_param, cmd, color_value, f64_or, has_doc, - has_selection, id_param, ids_param, index, ok, str_param, switch_or, + CommandSpec, Result, Session, bad, bool_or, check_numbers, check_switches, checked_id, checked_ids_param, checked_node, checked_nodes_param, cmd, + color_value, f64_or, has_doc, has_selection, ids_param, index, object_param, ok, str_param, switch_or, }; use crate::EngineError; @@ -83,7 +83,7 @@ pub fn specs() -> Vec<CommandSpec> { "Layer Options…", ["Window", "Layers"], None, - "{ids?|id? (default: the highlighted rows, else the current layer), name? (with prefs.identifyObjectsBy xmlId: a valid XML ID, stored as the object name), visible?, locked?, template?, printable?, preview?, dimImages?: 0..100|false, color?: index 0..26|\"#rrggbb\"|preset name (a hex color with an alpha part, #rrggbbaa or #rgba, is an error)} Layer Options; rows that are not layers take name, visible and locked. Template on also locks the layer and dims its images to 50% (unless given); off unlocks it and stops dimming. One undo step", + "{ids?|id? (default: the highlighted rows, else the current layer), name? (with prefs.identifyObjectsBy xmlId: a valid XML ID, stored as the object name), visible?, locked?, template?, printable?, preview?, dimImages?: 0..100|false, color?: index 0..26|\"#rrggbb\"|preset name (a hex color with an alpha part, #rrggbbaa or #rgba, is an error)} Layer Options; rows that are not layers take name, visible and locked, and `ids` may name ruler guides (their `guide.list` id), which hide or lock on their own. Template on also locks the layer and dims its images to 50% (unless given); off unlocks it and stops dimming. One undo step", has_doc, set_props ), @@ -128,7 +128,7 @@ pub fn specs() -> Vec<CommandSpec> { "New Artboard", ["Window", "Artboards"], None, - "{x?, y?, width?, height?, name?, color?: color (its background color, as artboard.setProps takes it, #rrggbbaa and #rgba refused; default: none), guideLabel?: name | \"#rrggbb\" | null (its guide label, as artboard.setProps takes it; default: none), showCenterMark?: bool, showCrossHairs?: bool, showVideoSafeAreas?: bool (as artboard.setProps takes them; default false), videoRulerPixelAspectRatio?: number 0.1–10 (as artboard.setProps takes it; default 1), side?: \"left\"|\"right\"|\"top\"|\"bottom\" (the size of artboard `beside`, 20 pt from that side of it; refused with x, y, width or height), beside?: n (the artboard `side` places it by; default the last)} (default place: right of the last)", + "{x?, y?, width?, height? (each more than 0 and at most 3,999,856 pt, as file.new takes them), name?, color?: color (its background color, as artboard.setProps takes it, #rrggbbaa and #rgba refused; default: none), guideLabel?: name | \"#rrggbb\" | null (its guide label, as artboard.setProps takes it; default: none), showCenterMark?: bool, showCrossHairs?: bool, showVideoSafeAreas?: bool (as artboard.setProps takes them; default false), videoRulerPixelAspectRatio?: number 0.1–10 (as artboard.setProps takes it; default 1), side?: \"left\"|\"right\"|\"top\"|\"bottom\" (the size of artboard `beside`, 20 pt from that side of it; refused with x, y, width or height), beside?: n (the artboard `side` places it by; default the last)} (default place: right of the last)", has_doc, artboard_new ), @@ -200,7 +200,7 @@ pub fn specs() -> Vec<CommandSpec> { "Paste Remembers Layers", ["Window", "Layers"], None, - "{on?} (default: toggle) the document option: on, the Paste commands put objects back into the layers they were copied from (by name; a missing one is made on top), off into the current layer; one undo step when it changes (document.inspect → pasteRemembersLayers) → {on}", + "{on?} (default: toggle) the document option: on, the Paste commands put objects back into the layers or sublayers they were copied from (in that document while they are still there, else by the names of the layer and the layers around it, the topmost match first; a missing sublayer is made inside its layer, a missing top-level layer on top; a hidden or locked one is an error and nothing is pasted), off into the current layer; one undo step when it changes (document.inspect → pasteRemembersLayers) → {on}", has_doc, paste_remembers_layers ), @@ -210,11 +210,16 @@ pub fn specs() -> Vec<CommandSpec> { /// The rows a panel command acts on: `ids` or `id`, else the highlighted rows, else the current /// layer (capped at [`MAX_ROWS`]). pub(crate) fn rows_param(s: &Session, p: &Value, command: &str) -> Result<Vec<NodeId>> { + rows_or_guides_param(s, p, command, false) +} + +/// The rows [`rows_param`] reads; given ruler guide ids are taken too when `guides`, else refused. +fn rows_or_guides_param(s: &Session, p: &Value, command: &str, guides: bool) -> Result<Vec<NodeId>> { // Presence is explicit intent: validate every target before fallback, truncation or edits. let mut ids = if p.get("ids").is_some() { - checked_ids_param(s, p, "ids", command)? + checked_nodes_param(s, p, "ids", command, guides)? } else if let Some(id) = p.get("id") { - vec![checked_id(s, id, command)?] + vec![checked_node(s, id, command, guides)?] } else { let st = s.doc()?; let rows = st.highlighted_rows(); @@ -426,7 +431,7 @@ fn paste_remembers_layers(s: &mut Session, p: &Value) -> Result<Value> { /// The Layers panel's target circle. fn target(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "layer.target"; - let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; let st = s.doc()?; let n = st.doc.node(id).ok_or(EngineError::NoNode(id))?; if !st.doc.is_editable(id) { @@ -594,7 +599,7 @@ fn duplicate_rows(s: &mut Session, p: &Value) -> Result<Value> { fn set_current(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "layer.setCurrent"; - let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; let st = s.doc_mut()?; let layer = st.doc.layer_containing(id).ok_or(EngineError::NoNode(id))?; st.active_layer = Some(layer); @@ -637,7 +642,8 @@ fn set_props(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "layer.setProps"; let xml_id = s.prefs.identify_objects_by == "xmlId"; check_options(C, p, xml_id)?; - let ids = rows_param(s, p, C)?; + // A ruler guide's row takes visible and locked: its own eye and lock. + let ids = rows_or_guides_param(s, p, C, true)?; if ids.is_empty() { return Err(bad(C, "no rows")); } @@ -700,7 +706,7 @@ fn in_isolation(doc: &Document, isolation: Option<NodeId>, id: NodeId) -> bool { /// The selection column: select a row's art. fn select_art(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "layer.selectAll"; - let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; let add = switch_or(p, "add", false, C)?; let st = s.doc()?; let n = st.doc.node(id).ok_or(EngineError::NoNode(id))?; @@ -747,9 +753,12 @@ enum Place { /// Drag rows in the Layers panel. fn move_rows(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "layer.move"; - let mut ids = ids_param(p, "ids", C)?.or_else(|| id_param(p, "id").map(|i| vec![i])).ok_or_else(|| bad(C, "missing ids"))?; + let mut ids = match ids_param(p, "ids", C)? { + Some(ids) => ids, + None => vec![object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing ids"))?], + }; ids.truncate(MAX_ROWS); - let target = id_param(p, "target").ok_or_else(|| bad(C, "missing target"))?; + let target = object_param(p, "target", C)?.ok_or_else(|| bad(C, "missing target"))?; let place = match str_param(p, "place").unwrap_or("inside") { "above" => Place::Above, "below" => Place::Below, @@ -831,8 +840,8 @@ fn move_rows(s: &mut Session, p: &Value) -> Result<Value> { fn move_node(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "node.move"; - let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?; - let parent = id_param(p, "parent"); + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; + let parent = object_param(p, "parent", C)?; let index = p.get("index").and_then(Value::as_u64).map_or(usize::MAX, index); let d = &s.doc()?.doc; let n = d.node(id).ok_or(EngineError::NoNode(id))?; @@ -847,14 +856,23 @@ fn move_node(s: &mut Session, p: &Value) -> Result<Value> { ok() } -fn rect_from(p: &Value, default: Rect) -> Rect { +/// The rectangle from `x`, `y`, `width` and `height`, each defaulting to `default`'s. Sides are kept as given. +fn rect_unclamped(p: &Value, default: Rect) -> Rect { let x = f64_or(p, "x", default.x0); let y = f64_or(p, "y", default.y0); - let w = f64_or(p, "width", default.width()).max(1.0); - let h = f64_or(p, "height", default.height()).max(1.0); + let w = f64_or(p, "width", default.width()); + let h = f64_or(p, "height", default.height()); Rect::new(x, y, x + w, y + h) } +/// [`rect_unclamped`] with each supplied side raised to at least 1 pt, as `artboard.setProps` uses it. +/// A side left out keeps `default`'s, even below 1 pt. +fn rect_from(p: &Value, default: Rect) -> Rect { + let r = rect_unclamped(p, default); + let floor = |key: &str, side: f64| if p.get(key).and_then(Value::as_f64).is_some() { side.max(1.0) } else { side }; + Rect::new(r.x0, r.y0, r.x0 + floor("width", r.width()), r.y0 + floor("height", r.height())) +} + /// An artboard command's `color` param, its background color: None when absent, `Some(None)` for /// null (no color), else `Some(Some(color))`. fn artboard_color(p: &Value, cmd: &str) -> Result<Option<Option<vectorcraft_color::Color>>> { @@ -923,6 +941,9 @@ fn artboard_new(s: &mut Session, p: &Value) -> Result<Value> { let guide_label = artboard_guide_label(p, "artboard.new")?.flatten(); check_switches(p, &["showCenterMark", "showCrossHairs", "showVideoSafeAreas"], "artboard.new")?; check_numbers(p, &["x", "y", "width", "height"], "artboard.new")?; + if ["width", "height"].iter().filter_map(|k| p.get(*k).and_then(Value::as_f64)).any(|side| !super::newdoc::side_in_range(side)) { + return Err(super::newdoc::side_error("artboard.new", d0.units)); + } let r = match artboard_side(p, "artboard.new")? { Some(side) => { if ["x", "y", "width", "height"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) { @@ -936,8 +957,12 @@ fn artboard_new(s: &mut Session, p: &Value) -> Result<Value> { src + side.offset(src) } None if p.get("beside").is_some_and(|v| !v.is_null()) => return Err(bad("artboard.new", "`beside` needs `side`")), - None => rect_from(p, def), + None => rect_unclamped(p, def), }; + // A size taken from another artboard (`side`, or width or height left out) keeps to the limit too. + if !super::newdoc::side_in_range(r.width()) || !super::newdoc::side_in_range(r.height()) { + return Err(super::newdoc::side_error("artboard.new", d0.units)); + } let given = artboard_str(p, "name", "artboard.new")?.map(str::trim).filter(|n| !n.is_empty()); let (show_center_mark, show_cross_hairs) = (bool_or(p, "showCenterMark", false), bool_or(p, "showCrossHairs", false)); let show_video_safe_areas = bool_or(p, "showVideoSafeAreas", false); diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rs index a6d2cbf518..ae8a7ef6b2 100644 --- a/crates/engine/src/cmd/library.rs +++ b/crates/engine/src/cmd/library.rs @@ -346,6 +346,36 @@ impl Library { } } + /// Name item `r` `name`, in its place in its kind's list; an item keyed by its name keeps its + /// group under the new name (a graphic is keyed by its id, which stays). + fn rename_item(&mut self, r: &ItemRef, name: &str) { + fn set<'a>(mut names: impl Iterator<Item = &'a mut String>, from: &str, to: &str) { + if let Some(n) = names.find(|n| n.as_str() == from) { + *n = to.to_string(); + } + } + let from = r.item.as_str(); + match r.kind { + ItemKind::Color => set(self.colors.iter_mut().map(|c| &mut c.name), from, name), + ItemKind::Gradient => set(self.gradients.iter_mut().map(|g| &mut g.name), from, name), + ItemKind::Pattern => set(self.patterns.iter_mut().map(|p| &mut p.name), from, name), + ItemKind::CharStyle => set(self.char_styles.iter_mut().map(|t| &mut t.name), from, name), + ItemKind::ParaStyle => set(self.para_styles.iter_mut().map(|t| &mut t.name), from, name), + ItemKind::Graphic => { + if let Some(g) = self.graphics.iter_mut().find(|g| g.id == from) { + g.name = name.to_string(); + } + return; + } + ItemKind::Unknown => return, + } + for x in self.groups.iter_mut().flat_map(|g| g.items.iter_mut()) { + if x == r { + x.item = name.to_string(); + } + } + } + /// Move item `r` next to `to`, an item of its kind: just before it, or just after it when /// `after`, in their kind's list (the order the panel shows them in). fn place_next_to(&mut self, r: &ItemRef, to: &ItemRef, after: bool) { @@ -683,7 +713,7 @@ pub fn specs() -> Vec<CommandSpec> { "Use Library Item", [], None, - "{library?, kind, item: name (graphic: id or name), center?: [x, y] (graphic; default: the first artboard's centre), to?: fill|stroke (colors, gradients, patterns; default: the kind's), recorded?: the item as it was when used (recorded in the journal so a replay matches)} graphic: place a copy centred on `center`, its resources pasted along, selected, one undo step; colors and gradients: paint the selection (and the defaults) as paint.setFill/paint.setStroke, a gradient fitting each object; a spot color links to the document's spot swatch of its ink's name, added when the document has none of that colour (a name taken by another colour gets a number), one undo step; patterns: add the pattern and its swatch to the document (a name the document gives another pattern gets a number; the same pattern is reused) and paint the selection (and the defaults) with it, one undo step; charStyle/paraStyle: add the style to the document (a name taken by different attributes gets a number) and apply it to the selected text, one undo step → {kind, ids?, style?}", + "{library?, kind, item: name (graphic: id or name), center?: [x, y] (graphic; default: the first artboard's centre), to?: fill|stroke (colors, gradients, patterns; default: the kind's), recorded?: the item as it was when used (recorded in the journal so a replay matches)} graphic: place a copy centred on `center`, its resources pasted along, selected, one undo step; colors and gradients: paint the selection (and the defaults) as paint.setFill/paint.setStroke, a gradient fitting each object; a spot color links to the document's spot swatch of its ink's name, added when the document has none of that colour (a name taken by another colour gets a number), one undo step; patterns: add the pattern and its swatch to the document (a name the document gives another pattern gets a number; the same pattern is reused) and paint the selection (and the defaults) with it, one undo step; charStyle/paraStyle: add the style to the document (a name taken by different attributes gets a number; a character style's color linked to a swatch that isn't a global or spot swatch of the document keeps the color it shows, unlinked) and apply it to the selected text, one undo step → {kind, ids?, style?}", has_doc, use_item ), @@ -696,6 +726,24 @@ pub fn specs() -> Vec<CommandSpec> { always, remove_item ), + cmd!( + "library.renameItem", + "Rename Library Item", + [], + None, + "{library?, kind, item: name (graphic: id or name), name: string (trimmed; 1 to 256 characters)} rename an item; it keeps its place and its group; another item of its kind with that name is an error, and its own name changes nothing; not undoable → {library, kind, item: its key now (graphic: its id), name}", + always, + rename_item + ), + cmd!( + "library.addToCharacterStyles", + "Add to Character Styles", + [], + None, + "{library?, item: a character style's name, recorded?: the style as it was when added (recorded in the journal so a replay matches)} add a library character style to the document's character styles without applying it (no text needs to be selected): a document style of that name with the same attributes is reused, a name taken by different attributes gets a number; a color linked to a swatch that isn't a global or spot swatch of the document keeps the color it shows, unlinked; a new style is one undo step, a reused one none → {style: its name in the document, existing: bool}", + has_doc, + add_to_char_styles + ), cmd!( "library.createGroup", "New Library Group", @@ -1231,8 +1279,13 @@ fn use_item(s: &mut Session, p: &Value) -> Result<Value> { Kind::CharStyle | Kind::ParaStyle => { let para = kind == Kind::ParaStyle; let name = data.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()).unwrap_or("Style").to_string(); - let attrs = data.get("attrs").and_then(Value::as_object).cloned().unwrap_or_default(); + let mut attrs = data.get("attrs").and_then(Value::as_object).cloned().unwrap_or_default(); let doc = &s.doc()?.doc; + if !para { + unlink_missing_swatches(doc, &mut attrs); + } + // Compared in the form the document stores them in. + let attrs = super::textstyles::stored_style_attrs(doc, para, &attrs).unwrap_or(attrs); // The document's style of that name when it is the same; else a new one. let same = super::textstyles::style_attrs(doc, para, &name).is_some_and(|a| a == attrs); let style = if same { name } else { unique(&name, |n| super::textstyles::style_attrs(doc, para, n).is_some()) }; @@ -1361,6 +1414,109 @@ fn remove_item(s: &mut Session, p: &Value) -> Result<Value> { ok() } +fn rename_item(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "library.renameItem"; + let (id, kind, item) = item_param(s, p, C)?; + let name = match p.get("name") { + None | Some(Value::Null) => return Err(bad(C, "missing `name`")), + Some(Value::String(n)) => n.trim().to_string(), + Some(_) => return Err(bad(C, "`name` must be a string")), + }; + if name.is_empty() { + return Err(bad(C, "missing `name`")); + } + if name.chars().count() > MAX_NAME { + let (label, max) = ("`name`", MAX_NAME); + return Err(bad(C, format!("{label} must be at most {max} characters"))); + } + let lib = s.libraries.get(&id).ok_or_else(|| bad(C, format!("no library `{id}`")))?; + let r = lib.item_ref(kind.item_kind(), item).ok_or_else(|| bad(C, format!("the library has no item `{item}`")))?; + // The item's name now, and whether another item of its kind has the new one. + let mut same = false; + let mut taken = false; + for (_, key, shown) in lib.items().filter(|(k, ..)| *k == r.kind) { + if key == r.item { + same = shown == name; + } else if shown == name { + taken = true; + } + } + let key = if r.kind == ItemKind::Graphic { r.item.clone() } else { name.clone() }; + let out = json!({ "library": id, "kind": str_param(p, "kind"), "item": key, "name": name }); + if same { + return Ok(out); + } + if taken { + return Err(bad(C, format!("the library has another item of that kind named `{name}`"))); + } + s.libraries.change(&id, |lib| { + lib.rename_item(&r, &name); + Ok(()) + })?; + Ok(out) +} + +fn add_to_char_styles(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "library.addToCharacterStyles"; + // A replay (the journal) carries what the style was, so it doesn't depend on the library. + let data = match p.get("recorded").cloned() { + Some(r) => r, + None => { + let id = library_id(s, p, C)?; + let item = str_param(p, "item").ok_or_else(|| bad(C, "missing `item`"))?; + let lib = s.libraries.get(&id).ok_or_else(|| bad(C, format!("no library `{id}`")))?; + let t = lib.char_styles.iter().find(|t| t.name == item).ok_or_else(|| bad(C, format!("the library has no item `{item}`")))?; + let data = json!({ "name": t.name, "attrs": t.attrs }); + s.note_journal("recorded", data.clone()); + data + } + }; + let name = data.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()).unwrap_or("Style").to_string(); + let mut attrs = data.get("attrs").and_then(Value::as_object).cloned().ok_or_else(|| bad(C, "the library item is damaged"))?; + let doc = &s.doc()?.doc; + unlink_missing_swatches(doc, &mut attrs); + // Compared in the form the document stores them in. + let attrs = super::textstyles::stored_style_attrs(doc, false, &attrs).unwrap_or(attrs); + // The document's style of that name when it is the same; else a new one, which isn't applied. + if super::textstyles::style_attrs(doc, false, &name).is_some_and(|a| a == attrs) { + return Ok(json!({ "style": name, "existing": true })); + } + let style = unique(&name, |n| super::textstyles::style_attrs(doc, false, n).is_some()); + s.execute("charStyle.new", &json!({ "name": style, "attrs": attrs }))?; + Ok(json!({ "style": style, "existing": false })) +} + +/// Unlink a library character style's `fill` and `stroke` colors (solid, and each gradient stop) +/// from swatches that are not global or spot swatches of `doc`: an unlinked color keeps the color +/// it shows at full tint, as [`clean_gradient`] keeps a library gradient's stops. A link to a +/// global or spot swatch `doc` has stays, and takes that swatch's color. +fn unlink_missing_swatches(doc: &vectorcraft_doc::Document, attrs: &mut Map<String, Value>) { + let keep = |name: &str| doc.global_color(name).is_some(); + for key in ["fill", "stroke"] { + let Some(mut paint) = attrs.get(key).and_then(|v| serde_json::from_value::<Paint>(v.clone()).ok()) else { continue }; + let mut changed = false; + let mut unlink = |swatch: &mut Option<String>, tint: &mut f32| { + if swatch.as_deref().is_some_and(|n| !keep(n)) { + *swatch = None; + *tint = 1.0; + changed = true; + } + }; + match &mut paint { + Paint::Solid { swatch, tint, .. } => unlink(swatch, tint), + Paint::Gradient(g) => { + for st in &mut g.gradient.stops { + unlink(&mut st.swatch, &mut st.tint); + } + } + _ => {} + } + if changed && let Ok(v) = serde_json::to_value(&paint) { + attrs.insert(key.to_string(), v); + } + } +} + /// `p`'s `name`, trimmed and clipped, else `default`. fn name_param(p: &Value, default: &str) -> String { let mut name = str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).unwrap_or(default).to_string(); diff --git a/crates/engine/src/cmd/linkfiles.rs b/crates/engine/src/cmd/linkfiles.rs index 5b5a6aa48a..99295e5c79 100644 --- a/crates/engine/src/cmd/linkfiles.rs +++ b/crates/engine/src/cmd/linkfiles.rs @@ -13,7 +13,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::NodeKind; use super::findfiles::{self, Limits, Visitor}; -use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, bool_or, checked_ids_param, cmd}; +use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, bool_or, cmd, ids_param}; /// The most linked files one search looks for. const MAX_LINKS: usize = 1_000; @@ -29,7 +29,7 @@ pub fn specs() -> Vec<CommandSpec> { "Find Linked Files", [], None, - "{folder?: an absolute path, ids?: [image or placed document ids] (default: the active document's missing links), maxSeconds?: 60 (1 to 600), stop?: false (true: stop the last search)} with folder: look in it and its subfolders, on separate threads, for files with the names of the linked files (in any letter case), and answer at once with the search's state (searching while it runs); without folder: the last search's state, with the files found so far. Each linked file's files come best first: same (the size and hash saved with the link), size (the saved size, where there is no saved hash or the file is larger than 1 GiB), then name. Within each kind, a file whose name has the link's letter case comes first. Then each file's folder names are compared with the saved path's, from the innermost outward up to the first one that differs, and a file with more matching names comes first; files that still tie are listed by path. Before the comparison, the saved path's parent-folder steps (.., or the empty components of a classic Mac :: run) are resolved, and . components in a slash path are skipped. A search looks for at most 1000 linked files and keeps the first 10 files of each one's name, and up to 10 that are the same file; it ends once every linked file has its same file, and searches only the folders text.findFontFiles may search, with the same maxSeconds, depth and count limits; none on the web → {id (absent while idle), state: idle|searching|done|stopped|failed, folder?, links: [{name, path, ids, files: [{path, size, match: same|size|name, caseDiffers?: true}]}], searched?: {folders, files, read}, skipped?, unreadable?, stopped?: stop|time|limit, error?, seconds?}", + "{folder?: an absolute path, ids?: [image or placed document ids] (default: the active document's missing links), maxSeconds?: 60 (1 to 600), stop?: false (true: stop the last search)} with folder: look in it and its subfolders, on separate threads, for files with the names of the linked files (in any letter case), and answer at once with the search's state (searching while it runs); without folder: the last search's state, with the files found so far. Each linked file's files come best first: same (the size and hash saved with the link), size (the saved size, where there is no saved hash or the file is larger than 1 GiB), then name. Within each kind, a file whose name has the link's letter case comes first. Then each file's folder names are compared with the saved path's, from the innermost outward up to the first one that differs, and a file with more matching names comes first; files that still tie are listed by path. Before the comparison, the saved path's parent-folder steps (.., or the empty components of a classic Mac :: run) are resolved, and . components in a slash path are skipped. A search looks for at most 1000 linked files and keeps the first 10 files of each one's name, and up to 10 that are the same file; it ends once every linked file has its same file, and searches only the folders text.findFontFiles may search, with the same maxSeconds, depth and count limits. With automation read roots, a reply leaves out the files found outside the caller's roots, a link's path outside them, and the folder when it is outside them (error then gives the reason without the path); none on the web → {id (absent while idle), state: idle|searching|done|stopped|failed, folder?, links: [{name, path?, ids, files: [{path, size, match: same|size|name, caseDiffers?: true}]}], searched?: {folders, files, read}, skipped?, unreadable?, stopped?: stop|time|limit, error?, seconds?}", always, find )] @@ -52,6 +52,8 @@ pub(crate) struct LinkSearch { pub(crate) id: u64, /// The folder as given. pub(crate) folder: String, + /// The path of the document the links were taken from, which a relative link path starts from. + pub(crate) doc: Option<String>, pub(crate) links: Vec<Sought>, /// The size of each file read, by the path the search reports ([`LinkFiles::sizes`]). pub(crate) sizes: Arc<Mutex<HashMap<PathBuf, u64>>>, @@ -141,8 +143,14 @@ fn find(s: &mut Session, p: &Value) -> Result<Value> { let ids = match p.get("ids") { None | Some(Value::Null) => None, Some(_) => { - let ids = checked_ids_param(s, p, "ids", C)?; - let linkable = |id: &NodeId| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Image(_) | NodeKind::PlacedDocument(_))); + // Images and placed documents in opacity-mask art and in the art of symbols, graph + // designs and patterns are named by their ids too (`links.list`). + let ids = ids_param(p, "ids", C)?.unwrap_or_default(); + let kind = |id: &NodeId| st.doc.stored_node(*id).map(|(n, _)| &n.kind); + if let Some(value) = ids.iter().find(|id| kind(id).is_none()).map(|id| id.0) { + return Err(bad(C, format!("no such object id {value}"))); + } + let linkable = |id: &NodeId| matches!(kind(id), Some(NodeKind::Image(_) | NodeKind::PlacedDocument(_))); if let Some(id) = ids.iter().find(|id| !linkable(id)) { return Err(bad(C, format!("object {} is not an image or a linked file", id.0))); } @@ -163,6 +171,7 @@ fn find(s: &mut Session, p: &Value) -> Result<Value> { if links.is_empty() { return Err(bad(C, if ids.is_some() { "these objects show no linked files" } else { "no linked files are missing" })); } + let doc = super::links::LinkBase::of(st).doc.map(str::to_string); // A new search stops the last one. s.link_search = None; let threads = s.search_threads.unwrap_or_else(findfiles::threads); @@ -171,7 +180,7 @@ fn find(s: &mut Session, p: &Value) -> Result<Value> { let visitor = Arc::new(LinkFiles::new(&links, sizes.clone())); let search = findfiles::start(PathBuf::from(&folder), s.search_rules.clone(), limits, threads, 2 * links.len(), visitor).map_err(EngineError::Other)?; - s.link_search = Some(LinkSearch { id: NEXT.fetch_add(1, Ordering::Relaxed), folder, links, sizes, search }); + s.link_search = Some(LinkSearch { id: NEXT.fetch_add(1, Ordering::Relaxed), folder, doc, links, sizes, search }); Ok(state(s)) } @@ -209,7 +218,9 @@ fn shared_folders(saved: &str, found: &Path) -> usize { /// Where the session's last search stands (`links.findFiles` without `folder`). fn state(s: &Session) -> Value { let Some(l) = &s.link_search else { return json!({ "state": "idle", "links": [] }) }; - let p = l.search.progress(); + let mut p = l.search.progress(); + // Only what the caller asking now may read: a search another caller started can hold more. + let (folder, error) = p.keep_readable(&l.folder); let n = l.links.len(); let sizes = lock(&l.sizes).clone(); // Per linked file: the files found, each with whether it is the same file. @@ -267,19 +278,23 @@ fn state(s: &Session) -> Value { f }) .collect(); - json!({ "name": link.name, "path": link.path, "ids": link.ids, "files": files }) + let mut row = json!({ "name": link.name, "ids": link.ids, "files": files }); + super::links::note_path(&mut row, "path", &link.path, l.doc.as_deref()); + row }) .collect(); - let folder = if p.folder.as_os_str().is_empty() { l.folder.clone() } else { p.folder.to_string_lossy().into_owned() }; let mut out = json!({ - "id": l.id, "state": p.state(), "folder": folder, "links": links, + "id": l.id, "state": p.state(), "links": links, "searched": { "folders": p.folders, "files": p.files, "read": p.read }, "skipped": p.skipped, "unreadable": p.unreadable, "seconds": (p.seconds * 10.0).round() / 10.0, }); + if let Some(folder) = folder { + out["folder"] = json!(folder); + } if let Some(why) = p.stopped() { out["stopped"] = json!(why); } - if let Some(e) = p.error() { + if let Some(e) = error { out["error"] = json!(e); } out diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 020b483f3a..3e1bc8b2ef 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -28,11 +28,14 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_doc::links::{Align, Preserve, hash_bytes}; -use vectorcraft_doc::{Appearance, Document, ImageBlob, ImageObject, LinkInfo, Node, NodeId, NodeKind, PageBox, PlacedDocument, PlacementOptions}; -use vectorcraft_geom::{Affine, PathData, Rect, shapes}; +use vectorcraft_doc::{ + Appearance, DataValue, Document, ImageBlob, ImageObject, LinkInfo, Node, NodeId, NodeKind, PageBox, PlacedDocument, PlacementOptions, + StoredPlace, StoredRoot, +}; +use vectorcraft_geom::{Affine, FillRule, PathData, Rect, shapes}; use super::fileio::{self, RasterImage, absolute_path, file_created, file_stamp, read_file, write_file}; -use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, ids_param, object_param, str_param}; +use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, ids_param, object_param, str_param, switch_or}; pub fn specs() -> Vec<CommandSpec> { vec![ @@ -41,7 +44,7 @@ pub fn specs() -> Vec<CommandSpec> { "Check Links", [], None, - "{ids?: [image or placed document ids] (default: every linked image and placed document)} where each linked file is and whether it changed since it was read → {links: [{name, path, status: ok|modified|missing, ids, found?: path (found away from its path: relative to the document, or by name in its folder), preview: true (showing the low-resolution preview, not the file), refused?: why the path is not followed (another computer, a device or a URL: it counts as missing)}], missing, modified}", + "{ids?: [image or placed document ids] (default: every linked image and placed document, in the layers and in opacity-mask art, symbols, graph designs and patterns)} where each linked file is and whether it changed since it was read → {links: [{name, path?, status: ok|modified|missing, ids, found?: path (found away from its path: relative to the document, or by name in its folder), preview: true (showing the low-resolution preview, not the file), refused?: why the path is not followed (another computer, a device or a URL: it counts as missing)}], missing, modified}; under automation read roots, path and found are left out when the file they name is outside the roots", has_doc, check ), @@ -50,7 +53,7 @@ pub fn specs() -> Vec<CommandSpec> { "Update Links", [], None, - "{ids?: [image or placed document ids] (default: the linked images whose file was modified or is showing its preview, and placed documents whose file was modified)} read their linked files again; each keeps its bounds. The images and placed documents inside symbols, graph designs, patterns and opacity masks that show the same content are read again too (by default also those only that art shows); they have no ids to list. One undo step → {updated: [ids], missing: [ids]}", + "{ids?: [image or placed document ids] (default: the linked images whose file was modified or is showing its preview, and placed documents whose file was modified)} read their linked files again; each keeps its bounds. Images and placed documents inside symbols, graph designs, patterns and opacity masks have ids of their own, as links.list gives them; those that show the same content as one read again are read again too. One undo step → {updated: [ids], missing: [ids], warnings?: [a DCS file's spot plate whose ink a swatch of the document already names, as file.place warns]}", has_doc, update ), @@ -68,7 +71,7 @@ pub fn specs() -> Vec<CommandSpec> { "Relink", [], None, - "{ids?: [image or placed document ids] (default: the selected ones; with folder and nothing selected, every missing link), path | folder, scope?: selected (default: ids) | all (ids and every other object in the layers linked to the same file as one of them) | missingInFolder (with path: ids, then every other missing link whose file name is in path's folder, each to the file of its name there; names not there are in notFound; with copy, only images are looked for) | each (with paths), paths?: [{ids, path}] (with scope each, in place of ids, path and folder: each link to its own file; an id in two entries is an error), copy?: false (with path or paths, for images of a saved document: copy the file into the document's folder and link to the copy; the names Name.png, Name 2.png … Name 99.png are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is used), preserve?: transforms|bounds|fileDimensions|fit|fill (how the new file takes each image's place this time, as links.placementOptions describes; default: each image's Placement Options; fit keeps the new file's aspect ratio inside the old bounds: Replace)} link images (or placed documents, each showing the same artboard or page of the new file) to the file at path, or each to the file of its link's name in folder; embedded images become linked; each keeps its bounds. One undo step → {relinked: [ids], notFound: [file names], copied?: [{from, to}], kept?: [{from, to}] (with copy)}", + "{ids?: [image or placed document ids] (default: the selected ones; with folder and nothing selected, every missing link), path | folder, scope?: selected (default: ids) | all (ids and every other object linked to the same file as one of them, in the layers, opacity-mask art, symbols, graph designs and patterns) | missingInFolder (with path: ids, then every other missing link whose file name is in path's folder, each to the file of its name there; names not there are in notFound; with copy, only images are looked for) | each (with paths), paths?: [{ids, path}] (with scope each, in place of ids, path and folder: each link to its own file; an id in two entries is an error), copy?: false (with path or paths, for images of a saved document: copy the file into the document's folder and link to the copy; the names Name.png, Name 2.png … Name 99.png are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is used; an error for a DCS file that reads plate files of its own), preserve?: transforms|bounds|fileDimensions|fit|fill (how the new file takes each image's place this time, as links.placementOptions describes; default: each image's Placement Options; fit keeps the new file's aspect ratio inside the old bounds: Replace)} link images (or placed documents, each showing the same artboard or page of the new file) to the file at path, or each to the file of its link's name in folder; embedded images become linked; each keeps its bounds. One undo step → {relinked: [ids], notFound: [file names], copied?: [{from, to}], kept?: [{from, to}] (with copy; to is the file name alone when the document's folder is outside the automation read roots), warnings?: (as links.update's)}", has_doc, relink ), @@ -77,7 +80,7 @@ pub fn specs() -> Vec<CommandSpec> { "Links", [], None, - "{show?: all (default)|missing|modified|embedded, sort?: name|kind (file format)|status (missing, modified, ok, embedded); default: stacking order; top first} every image object and placed document in the layers, as the Links panel lists them → {links: [{id, name, linked, status: ok|modified|missing|embedded, format, pixelWidth, pixelHeight, path?, found?: path (found away from its path), page?, preview?: true (showing the saved preview), note?: said of an image past the decode allowance (shown at reduced size, or too large to draw), document?: true (a placed document: pageWidth and pageHeight in pt instead of pixels)}], missing, modified, embedded}", + "{show?: all (default)|missing|modified|embedded, sort?: name|kind (file format)|status (missing, modified, ok, embedded); default: stacking order; top first, dcsTransparency?: false (Show DCS Transparency Interactions: mark the images placed from DCS files that are transparent, themselves or a group or layer holding them, or that overlap a visible object with its own transparency; it looks at every object, so it takes longer)} every image object and placed document the document stores, as the Links panel lists them: those in the layers, then those in opacity-mask art and in the art of symbols, graph designs and patterns (one row per stored object, never one per symbol instance or pattern tile) → {links: [{id, name, linked, status: ok|modified|missing|embedded, format (DCS for an image placed from a DCS file), pixelWidth, pixelHeight, path?, found?: path (found away from its path), page?, preview?: true (showing the saved preview), note?: said of an image past the decode allowance (shown at reduced size, or too large to draw), document?: true (a placed document: pageWidth and pageHeight in pt instead of pixels), dcsTransparency?: true (with dcsTransparency), owner?: {kind: layers|symbol|graphDesign|pattern, name? (of the symbol, graph design or pattern), maskOf?: id (in the opacity-mask art of that object)} (an object outside the layer tree)}], missing, modified, embedded}; under automation read roots, path and found are left out when the file they name is outside the roots", has_doc, list ), @@ -86,7 +89,7 @@ pub fn specs() -> Vec<CommandSpec> { "Go To Link", [], None, - "{id?} select image or placed document `id` (default: the first selected one); the Links panel scrolls it into view → {id, bounds: [x0, y0, x1, y1]}", + "{id?} select image or placed document `id` (default: the first selected one); the Links panel scrolls it into view → {id, bounds: [x0, y0, x1, y1], onCanvas: true}; one in opacity-mask art or in the art of a symbol, graph design or pattern has no place of its own on the canvas: the selection is cleared → {id, onCanvas: false, owner} (owner as links.list gives it)", has_doc, go_to ), @@ -95,7 +98,7 @@ pub fn specs() -> Vec<CommandSpec> { "Embed Image", [], None, - "{ids?: [image or placed document ids] (default: the selected linked ones)} break the links (the Links panel's Break Link): images keep the linked files' pixels in the document; a placed document becomes an editable copy of its art, as placing its file without link gives (its symbols, patterns, swatches and images joining the document). An image whose file can't be found and that shows the saved preview, or a placed document whose file can't be read or changed, stays linked: relink or update it first. One undo step → {embedded: [ids], missing: [ids]}", + "{ids?: [image or placed document ids] (default: the selected linked ones)} break the links (the Links panel's Break Link): images keep the linked files' pixels in the document; a placed document becomes an editable copy of its art, as placing its file without link gives (its symbols, patterns, swatches and images joining the document). An image whose file can't be found and that shows the saved preview, or a placed document whose file can't be read or changed, stays linked: relink or update it first. An image placed from a DCS file can't be embedded (an error, and nothing changes). One undo step → {embedded: [ids], missing: [ids]}", has_doc, embed ), @@ -113,7 +116,7 @@ pub fn specs() -> Vec<CommandSpec> { "Link Info", [], None, - "{id?} an image's or placed document's Link Info (default: the one selected) → image.info's fields (id, name, linked, link, colorMode, pixelWidth, pixelHeight, width, height) and status: ok|modified|missing|embedded, format, ppi: [x, y] (the file's), effectivePpi: [x, y] (at its placed size), scale: [x%, y%] (of its 100% size), rotation (degrees, counter-clockwise), placement: {preserve, align, clip}; linked images also fileName, location (its folder), page?, fileSize? (bytes), modified?, created? (ms since the Unix epoch), refused? (why the path is not followed); a placed document has document: true, pageWidth and pageHeight (pt) instead of pixels, ppi and colorMode, and its scale is of its artboard's or page's 100% size", + "{id?} an image's or placed document's Link Info (default: the one selected) → image.info's fields (id, name, linked, link, colorMode, pixelWidth, pixelHeight, width, height) and status: ok|modified|missing|embedded, format, ppi: [x, y] (the file's), effectivePpi: [x, y] (at its placed size), scale: [x%, y%] (of its 100% size), rotation (degrees, counter-clockwise), placement: {preserve, align, clip}; linked images also fileName, location (its folder), page?, fileSize? (bytes), modified?, created? (ms since the Unix epoch), refused? (why the path is not followed); a placed document has document: true, pageWidth and pageHeight (pt) instead of pixels, ppi and colorMode, and its scale is of its artboard's or page's 100% size; under automation read roots, a link whose file is outside the roots has no link, path or location, and fileSize and modified come only from the file", has_doc, info ), @@ -154,10 +157,13 @@ impl Status { struct Group { link: LinkInfo, key: String, - /// The objects in the layers (images in symbols and patterns share the content, not an id). + /// The stored objects showing it: in the layers, in opacity-mask art and in the art of symbols, + /// graph designs and patterns ([`Document::visit_stored`]), each once. ids: Vec<NodeId>, /// Placed documents: what they show. document: Option<Shown>, + /// An image placed from a DCS file: the plate files of their own its plates were read from. + plate_files: Vec<vectorcraft_doc::separated::PlateFile>, } /// What a placed document shows: whether the art's bounds (not the artboard or page) are shown, @@ -173,13 +179,24 @@ fn linked(n: &Node) -> Option<(&LinkInfo, &str, Option<Shown>)> { } } -/// Every linked file of `d` with the ids of the objects showing it (for [`crate::link_watch`]). +/// Every linked file of `d` with the ids of the objects showing it, wherever they are stored (for +/// [`crate::link_watch`]): an image placed from a DCS file has its plate files of their own too, +/// beside its file. pub(crate) fn linked_groups(d: &Document) -> Vec<(String, Vec<u64>)> { - groups(d, None).into_iter().filter(|g| !g.ids.is_empty()).map(|g| (g.link.path, ids_json(&g.ids))).collect() + let mut out = vec![]; + for g in groups(d, None).into_iter().filter(|g| !g.ids.is_empty()) { + let ids = ids_json(&g.ids); + let plates: Vec<String> = g.plate_files.iter().filter_map(|f| super::place::dcs::plate_file_path(&g.link.path, &f.name)).collect(); + out.push((g.link.path, ids.clone())); + out.extend(plates.into_iter().map(|p| (p, ids.clone()))); + } + out } -/// The linked images and placed documents of `d` by file and content: those in the layers (only `ids` when -/// given), then, without `ids`, the ones only symbols and patterns show. +/// The linked images and placed documents of `d` by file and content, wherever they are stored +/// (only `ids` when given), in [`Document::visit_stored`] order. An object whose id an object +/// visited before it has (art being edited on a layer and its definition) counts once, by its +/// first place; without `ids` its content is still grouped. fn groups(d: &Document, ids: Option<&[NodeId]>) -> Vec<Group> { let mut out: Vec<Group> = vec![]; let mut index: BTreeMap<(String, String, bool), usize> = BTreeMap::new(); @@ -187,31 +204,59 @@ fn groups(d: &Document, ids: Option<&[NodeId]>) -> Vec<Group> { let wanted: Option<std::collections::HashSet<NodeId>> = ids.map(|ids| ids.iter().copied().collect()); let mut add = |link: &LinkInfo, key: &str, document: Option<Shown>, id: Option<NodeId>| { let i = *index.entry((link.path.clone(), key.to_string(), document.is_some())).or_insert_with(|| { - out.push(Group { link: link.clone(), key: key.to_string(), ids: vec![], document }); + let plate_files = match document { + None => d.images.get(key).map(ImageBlob::plate_files).unwrap_or_default(), + Some(_) => vec![], + }; + out.push(Group { link: link.clone(), key: key.to_string(), ids: vec![], document, plate_files }); out.len() - 1 }); if let (Some(id), Some(g)) = (id, out.get_mut(i)) { g.ids.push(id); } }; - d.walk(|n| { - if let Some((l, key, document)) = linked(n) - && wanted.as_ref().is_none_or(|ids| ids.contains(&n.id)) - { + let mut seen = std::collections::HashSet::new(); + d.visit_stored(|n, _| { + let Some((l, key, document)) = linked(n) else { return }; + // Id 0 names no object. + let first = n.id.0 != 0 && seen.insert(n.id); + if first && wanted.as_ref().is_none_or(|ids| ids.contains(&n.id)) { add(l, key, document, Some(n.id)); + } else if ids.is_none() { + add(l, key, document, None); } }); - if ids.is_none() { - d.visit_images(|_, im| { - if let Some(l) = &im.link { - add(l, &im.key, None, None); - } - }); - d.visit_placed(|_, p| add(&p.link, &p.key, Some((p.bounding, p.page_box)), None)); - } out } +/// Stored object `id` of `d` ([`Document::stored_node`]). +fn stored(d: &Document, id: NodeId) -> Option<&Node> { + d.stored_node(id).map(|(n, _)| &**n) +} + +/// Of `ids`, the objects of `d` outside the layer tree (where [`Document::node`] finds none). +fn nested_ids(d: &Document, ids: &[NodeId]) -> std::collections::HashSet<NodeId> { + ids.iter().copied().filter(|id| d.node(*id).is_none()).collect() +} + +/// `links.list`'s `owner` of an object stored at `place` of `d`, when it is not in the layer tree +/// itself: `{kind: layers|symbol|graphDesign|pattern, name?, maskOf?}`. +fn owner_json(d: &Document, place: StoredPlace) -> Option<Value> { + if place.in_layers() { + return None; + } + let mut owner = match place.root { + StoredRoot::Layer(_) => json!({ "kind": "layers" }), + StoredRoot::Symbol(i) => json!({ "kind": "symbol", "name": d.symbols.get(i).map(|s| s.name.as_str()) }), + StoredRoot::GraphDesign(i) => json!({ "kind": "graphDesign", "name": d.graph_designs.get(i).map(|g| g.name.as_str()) }), + StoredRoot::Pattern { pattern, .. } => json!({ "kind": "pattern", "name": d.patterns.get(pattern).map(|p| p.name.as_str()) }), + }; + if let Some(m) = place.mask_of { + owner["maskOf"] = json!(m.0); + } + Some(owner) +} + /// A linked file where it was found. struct Found { path: String, @@ -333,10 +378,14 @@ fn refused(link: &LinkInfo, doc_path: Option<&str>) -> Option<craft_docpath::Ref } /// Where the file of group `g` (of a document looking from `base`) is and whether it still has -/// the content shown. Its bytes are read only when its size or modification time changed. +/// the content shown. Its bytes are read only when its size or modification time changed. An image +/// placed from a DCS file is modified when one of its plate files of their own changed. fn probe(g: &Group, base: LinkBase) -> (Status, Option<Found>) { let Some(mut f) = locate(&g.link, base) else { return (Status::Missing, None) }; let l = &g.link; + if !g.plate_files.is_empty() && super::place::dcs::plate_files_changed(&g.plate_files, &f.path) { + return (Status::Modified, Some(f)); + } if l.size == Some(f.size) && l.modified.is_some() && l.modified == f.modified { return (Status::Ok, Some(f)); } @@ -344,7 +393,7 @@ fn probe(g: &Group, base: LinkBase) -> (Status, Option<Found>) { let same = match &l.hash { Some(h) => *h == hash_bytes(&bytes), // Linked before links kept a hash: the image the file decodes to. - None => g.document.is_none() && fileio::raster_image(&bytes).is_ok_and(|img| img.key == g.key), + None => g.document.is_none() && super::place::dcs::raster(&bytes, Some(&f.path)).is_ok_and(|img| img.key == g.key), }; f.bytes = Some(bytes); (if same { Status::Ok } else { Status::Modified }, Some(f)) @@ -367,6 +416,26 @@ fn keep_eps_preview(low_res_proxy_eps: bool, g: &Group, d: &Document) -> bool { low_res_proxy_eps && g.document.is_none() && linked_eps(&g.link) && previewing(d, &g.key) } +/// Is the linked file `f` found a DCS file? Only the start of the file is read, unless a binary EPS +/// header puts its PostScript further on; a DCS file read in full stays in `f`. A file that can't +/// be read is not one. +fn is_dcs_file(f: &mut Found) -> bool { + use super::place::dcs; + if let Some(b) = &f.bytes { + return dcs::is_dcs(b); + } + let Ok(head) = fileio::read_file_head(&f.path, dcs::HEAD_BYTES) else { return false }; + if let Some(is) = dcs::head_is_dcs(&head, f.size) { + return is; + } + let Ok(b) = f.read() else { return false }; + let is = dcs::is_dcs(&b); + if is { + f.bytes = Some(b); + } + is +} + /// Does group `g` of `d` show something other than its file: an image its preview, a placed /// document nothing (its file's bytes are gone)? fn stale(d: &Document, g: &Group) -> bool { @@ -431,12 +500,12 @@ pub(crate) fn full_linked_images<'a>(d: &'a Document, base: LinkBase) -> (Cow<'a previews.insert(key); continue; }; - let Ok(img) = fileio::raster_image(&bytes) else { + let Ok(img) = super::place::dcs::raster(&bytes, Some(&f.path)) else { previews.insert(key); continue; }; let preview = d.images.get(&key).map(|b| b.bytes.clone()); - // A file read as it is keeps its own type; one turned upright (EXIF orientation) is the PNG it became. + // A file read as it is keeps its own type; one turned upright by its orientation is the PNG, or CMYK TIFF, it became. let mime = match fileio::format_for_name(g.link.name()) { Some(f) if img.blob.bytes.as_slice() == bytes.as_slice() => f.mime.to_string(), _ => img.blob.mime.clone(), @@ -453,8 +522,8 @@ pub(crate) fn full_linked_images<'a>(d: &'a Document, base: LinkBase) -> (Cow<'a } /// The linked files of the open document `st` that `links.findFiles` looks for, each with the -/// objects in the layers that show it: the files of objects `ids` whatever their status, else the -/// files that can't be found. +/// stored objects that show it: the files of objects `ids` whatever their status, else the files +/// that can't be found. pub(crate) fn files_to_find(st: &crate::DocState, ids: Option<&[NodeId]>) -> Vec<(LinkInfo, Vec<NodeId>)> { groups(&st.doc, ids) .into_iter() @@ -510,10 +579,11 @@ pub(crate) fn readable_and_kept(blob: ImageBlob, unread: bool, linked: bool) -> Ok(blob) } -/// The linked image file `bytes`, read ([`fileio::raster_image`]) with its preview; an error when -/// its pixels can't be read ([`readable`]). -fn linked_image(bytes: &[u8]) -> Result<RasterImage> { - let mut img = fileio::raster_image(bytes)?; +/// The linked image file `bytes` (read from `path`, when there is one), read with its preview: a +/// DCS file's plates, else its image ([`super::place::dcs::raster`]); an error when its pixels +/// can't be read ([`readable`]). +fn linked_image(bytes: &[u8], path: Option<&str>) -> Result<RasterImage> { + let mut img = super::place::dcs::raster(bytes, path)?; img.blob = readable(img.blob, kept_unread(bytes), true)?; Ok(img) } @@ -534,7 +604,7 @@ fn read_image(f: &mut Found, base: &LinkInfo, reads: &mut ImageReads) -> Result< let img = match reads.get(&f.path) { Some((h, img)) if *h == hash => img.clone(), _ => { - let img = linked_image(&bytes)?; + let img = linked_image(&bytes, Some(&f.path))?; reads.insert(f.path.clone(), (hash.clone(), img.clone())); img } @@ -584,12 +654,93 @@ fn clip_shape((frame, room): Clip) -> PathData { shapes::rectangle(Rect::new(0.0, 0.0, room.0, room.1)).transformed(frame) } +/// What happens to the clip of an object a link update remakes. +enum ClipTo { + /// It stays as it is. + Keep, + /// It is clipped to this path (Placement Options' clip): the clipping path of the clip group + /// holding just it changes, else it goes into a new clip group. + Path(PathData), + /// It is clipped to this path, the clipping path its DCS file draws it through: as [`ClipTo::Path`], + /// except that a plain group holding just it (as [`ClipTo::Off`] leaves one) becomes a clip group + /// again. + File(PathData), + /// It goes into a new clip group of this path, inside the clip group that holds it. + Nest(PathData), + /// The clipping path of the clip group holding just it goes (a DCS file's clipping path that + /// its new file lacks): the group stays as a plain group of it, with its id, name, visibility + /// and transparency. + Off, +} + +/// The clipping path, with its fill rule, of the clip group holding just object `id` of `d`, when +/// one holds it. +fn clip_path_of(d: &Document, id: NodeId) -> Option<(&PathData, FillRule)> { + let g = d.node(d.parent_of(id)?)?; + match &g.kind { + NodeKind::Group { children, clip: true } => match &children[..] { + [c, o] if o.id == id => match &c.kind { + NodeKind::Path { path, rule, clipping: true, .. } => Some((path, *rule)), + _ => None, + }, + _ => None, + }, + _ => None, + } +} + +/// Do `a` and `b` have the same subpaths, each closed or open alike, and the same anchors, each +/// within a thousandth of a point? +fn same_path(a: &PathData, b: &PathData) -> bool { + let near = |p: vectorcraft_geom::Point, q: vectorcraft_geom::Point| p.distance(q) < 1e-3; + a.anchor_count() == b.anchor_count() + && a.subpaths.len() == b.subpaths.len() + && a.subpaths.iter().zip(&b.subpaths).all(|(x, y)| x.closed == y.closed) + && a.anchors() + .zip(b.anchors()) + .all(|((si, ai, x), (sj, aj, y))| si == sj && ai == aj && near(x.p, y.p) && near(x.h_in, y.h_in) && near(x.h_out, y.h_out)) +} + +/// The clip an image placed with `old_xf` takes when it shows `img`, read from a file, placed with +/// `new_xf`: Placement Options' clip `clip` when they clip it, else the clipping path a DCS file +/// draws `img` through. When neither clips it, a clip group holding just it whose clipping path +/// `held` is its old DCS file's (`old_clip`, in the old pixels, under the nonzero rule its clip +/// groups get) goes. +fn clip_to( + old_xf: Affine, + old_clip: Option<&PathData>, + clip: Option<Clip>, + img: &RasterImage, + new_xf: Affine, + held: Option<(&PathData, FillRule)>, +) -> ClipTo { + if let Some(clip) = clip { + return ClipTo::Path(clip_shape(clip)); + } + // Whether the clip group holding just the image is the old DCS file's: a clipping path whose + // fill rule was changed in the document is not. + let file_held = match (old_clip, held) { + (Some(old), Some((held, rule))) => rule == FillRule::NonZero && same_path(&old.transformed(old_xf), held), + _ => false, + }; + match img.clip.as_ref().map(|path| path.transformed(new_xf)) { + // A clipping mask made in the document stays, with the file's clip group inside it. + Some(path) if held.is_some() && !file_held => ClipTo::Nest(path), + Some(path) => ClipTo::File(path), + None if file_held => ClipTo::Off, + None => ClipTo::Keep, + } +} + +/// The object an object becomes, and what happens to its clip, given the clipping path of the clip +/// group holding just it ([`ClipTo`]). +type Remake<'a> = dyn FnMut(&Node, Option<(&PathData, FillRule)>) -> (Node, ClipTo) + 'a; + /// Remakes the linked objects outside the layer tree (in symbols, graph designs, patterns and -/// opacity masks, where [`Document::node`] finds no ids) that `pick` holds for. +/// opacity masks, where [`Document::node`] does not find them) that `pick` holds for. struct Nested<'a> { pick: &'a dyn Fn(&Node) -> bool, - /// The object an object becomes, and the clip it takes ([`placed_xf`]). - make: &'a mut dyn FnMut(&Node) -> (Node, Option<Clip>), + make: &'a mut Remake<'a>, /// The next node id for a clip group (taken from the document after the walk). next: u64, } @@ -620,12 +771,12 @@ impl Nested<'_> { if !(self.pick)(n) { return self.update(n, true); } - let (new, clip) = (self.make)(n); + let (new, clip) = (self.make)(n, None); let mut new = Arc::new(new); self.update(&mut new, true); *n = match clip { - Some(clip) => Arc::new(self.clip_group(new, clip)), - None => new, + ClipTo::Path(path) | ClipTo::File(path) | ClipTo::Nest(path) => Arc::new(self.clip_group(new, path)), + ClipTo::Keep | ClipTo::Off => new, }; } @@ -638,12 +789,18 @@ impl Nested<'_> { (!Arc::ptr_eq(&art, &m.art)).then_some(art) }); let mut slots: Vec<(usize, Arc<Node>)> = vec![]; + // The object a clip group that loses its clipping path holds alone. + let mut declipped = None; + // The clipping path and object of a plain group holding just the object, which becomes a + // clip group again. + let mut reclipped = None; if let Some(children) = n.children() { // A clip group holding just the object: its clipping path changes. let clip_path = match (&n.kind, &children[..]) { (NodeKind::Group { clip: true, .. }, [c, _]) if matches!(c.kind, NodeKind::Path { clipping: true, .. }) => Some(c), _ => None, }; + let plain = matches!((&n.kind, &children[..]), (NodeKind::Group { clip: false, .. }, [_])); for (i, c) in children.iter().enumerate() { if !(nested && (self.pick)(c)) { let mut new = Arc::clone(c); @@ -653,32 +810,54 @@ impl Nested<'_> { } continue; } - let (new, clip) = (self.make)(c); + let held = clip_path.filter(|_| i == 1).and_then(|p| match &p.kind { + NodeKind::Path { path, rule, .. } => Some((path, *rule)), + _ => None, + }); + let (new, clip) = (self.make)(c, held); let mut new = Arc::new(new); self.update(&mut new, true); match (clip, clip_path) { - (None, _) => slots.push((i, new)), - (Some(clip), Some(path)) if i == 1 => { + (ClipTo::Keep, _) => slots.push((i, new)), + (ClipTo::Path(clip) | ClipTo::File(clip), Some(path)) if i == 1 => { let mut path = Node::clone(path); if let NodeKind::Path { path: p, .. } = &mut path.kind { - *p = clip_shape(clip); + *p = clip; } slots.extend([(0, Arc::new(path)), (1, new)]); } - (Some(clip), _) => { + (ClipTo::File(clip), None) if plain => reclipped = Some((clip, new)), + (ClipTo::Path(clip) | ClipTo::File(clip) | ClipTo::Nest(clip), _) => { let group = self.clip_group(new, clip); slots.push((i, Arc::new(group))); } + (ClipTo::Off, Some(_)) if i == 1 => declipped = Some(new), + (ClipTo::Off, _) => slots.push((i, new)), } } } - if mask.is_none() && slots.is_empty() { + if mask.is_none() && slots.is_empty() && declipped.is_none() && reclipped.is_none() { return; } + let reclipped = reclipped.map(|(clip, object)| (Arc::new(self.clipping_path(clip)), object)); let n = Arc::make_mut(n); if let (Some(art), Some(m)) = (mask, n.extras_if_any().and_then(|e| e.mask.as_mut())) { m.art = art; } + // A plain group of just the object that becomes a clip group again. + if let Some((path, object)) = reclipped { + if let NodeKind::Group { children, clip } = &mut n.kind { + (*children, *clip) = (vec![path, object], true); + } + return; + } + // A clip group that stays as a plain group of just the object. + if let Some(object) = declipped { + if let NodeKind::Group { children, clip } = &mut n.kind { + (*children, *clip) = (vec![object], false); + } + return; + } if let Some(children) = n.children_mut() { for (i, c) in slots { if let Some(slot) = children.get_mut(i) { @@ -688,23 +867,26 @@ impl Nested<'_> { } } - /// A clip group of `object` clipped to `clip`, as [`clip_image`] makes one in the layers. - fn clip_group(&mut self, object: Arc<Node>, clip: Clip) -> Node { - let (path_id, group_id) = (NodeId(self.next), NodeId(self.next + 1)); - self.next += 2; - let none = vectorcraft_color::Paint::None; - let mut path = Node::path(path_id, clip_shape(clip), Appearance::basic(none.clone(), none, 0.0)); - if let NodeKind::Path { clipping, .. } = &mut path.kind { - *clipping = true; - } + /// A clip group of `object` clipped to `clip`, as [`clip_image_to`] makes one in the layers. + fn clip_group(&mut self, object: Arc<Node>, clip: PathData) -> Node { + let path = self.clipping_path(clip); + let group_id = NodeId(self.next); + self.next += 1; Node::new(group_id, NodeKind::Group { children: vec![Arc::new(path), object], clip: true }) } + + /// A clipping path of `clip`, with the next node id. + fn clipping_path(&mut self, clip: PathData) -> Node { + let id = NodeId(self.next); + self.next += 1; + clipping_path(id, clip) + } } -/// Placed documents `ids` show `src`, read from the file `link` points at, each placed as its -/// Placement Options say (`force`: as that Preserve choice says, whatever they say); with `also` -/// (a file's path and the content shown), so do the placed documents outside the layer tree that -/// show that content. +/// Placed documents `ids` (in the layers or outside them) show `src`, read from the file `link` +/// points at, each placed as its Placement Options say (`force`: as that Preserve choice says, +/// whatever they say); with `also` (a file's path and the content shown), so do the placed +/// documents outside the layer tree that show that content. fn install_document( d: &mut Document, ids: &[NodeId], @@ -719,15 +901,17 @@ fn install_document( let o = PlacementOptions { preserve: force.unwrap_or(p.placement.preserve), ..p.placement }; placed_xf(p.xf, (p.width, p.height), (1.0, 1.0), (w, h), (1.0, 1.0), o) }; - if let Some(also) = also { - let pick = |n: &Node| shows(n, also, true); - let mut make = |n: &Node| { + let nested = nested_ids(d, ids); + if also.is_some() || !nested.is_empty() { + let pick = + |n: &Node| matches!(n.kind, NodeKind::PlacedDocument(_)) && (nested.contains(&n.id) || also.is_some_and(|also| shows(n, also, true))); + let mut make = |n: &Node, _: Option<(&PathData, FillRule)>| { let mut n = n.clone(); - let mut clip = None; + let mut clip = ClipTo::Keep; if let NodeKind::PlacedDocument(p) = &mut n.kind { let (xf, c) = placed(p); (p.key, p.width, p.height, p.xf, p.link) = (src.key.clone(), w, h, xf, link.clone()); - clip = c; + clip = c.map_or(ClipTo::Keep, |c| ClipTo::Path(clip_shape(c))); } (n, clip) }; @@ -799,10 +983,9 @@ fn placed_xf(xf: Affine, old: (f64, f64), old_pt: (f64, f64), new: (f64, f64), n (frame * at * Affine::scale_non_uniform(size.0 / nw, size.1 / nh), (o.clip && over).then_some((frame, room))) } -/// Clip image `id` of `d` to `room` in `frame`: the clipping path of the clip group holding just -/// it changes, else the image goes into a new clip group. -fn clip_image(d: &mut Document, id: NodeId, clip: Clip) -> Result<()> { - let path = clip_shape(clip); +/// The clipping path of the clip group of `d` holding just object `id` becomes `path`; false when +/// no such clip group holds it. +fn set_clip_path(d: &mut Document, id: NodeId, path: PathData) -> bool { let clip_path = d.parent_of(id).and_then(|p| match &d.node(p)?.kind { NodeKind::Group { children, clip: true } => match &children[..] { [c, im] if im.id == id && matches!(c.kind, NodeKind::Path { clipping: true, .. }) => Some(c.id), @@ -810,19 +993,63 @@ fn clip_image(d: &mut Document, id: NodeId, clip: Clip) -> Result<()> { }, _ => None, }); - if let Some(c) = clip_path { - if let Some(Node { kind: NodeKind::Path { path: p, .. }, .. }) = d.node_mut(c) { - *p = path; - } + let Some(c) = clip_path else { return false }; + if let Some(Node { kind: NodeKind::Path { path: p, .. }, .. }) = d.node_mut(c) { + *p = path; + } + true +} + +/// Clip image `id` of `d` to `room` in `frame`: the clipping path of the clip group holding just +/// it changes, else the image goes into a new clip group. +fn clip_image(d: &mut Document, id: NodeId, clip: Clip) -> Result<()> { + clip_image_to(d, id, clip_shape(clip)) +} + +/// Clip object `id` of `d` to `path`: the clipping path of the clip group holding just it changes, +/// else it goes into a new clip group. +fn clip_image_to(d: &mut Document, id: NodeId, path: PathData) -> Result<()> { + if set_clip_path(d, id, path.clone()) { return Ok(()); } - let (par, index, _) = d.position(id).ok_or(EngineError::NoNode(id))?; - let image = d.remove(id)?; + new_clip_group(d, id, path) +} + +/// Clip object `id` of `d` to `path`, the clipping path its DCS file draws it through: the clipping +/// path of the clip group holding just it changes, a plain group holding just it (as [`unclip`] +/// leaves one) becomes a clip group again, else it goes into a new clip group. +fn clip_file_to(d: &mut Document, id: NodeId, path: PathData) -> Result<()> { + if set_clip_path(d, id, path.clone()) { + return Ok(()); + } + let plain = d.parent_of(id).filter(|g| match d.node(*g).map(|n| &n.kind) { + Some(NodeKind::Group { children, clip: false }) => matches!(&children[..], [o] if o.id == id), + _ => false, + }); + let Some(g) = plain else { return new_clip_group(d, id, path) }; + let clip = clipping_path(d.alloc_id(), path); + d.insert(Some(g), 0, clip)?; + if let Some(Node { kind: NodeKind::Group { clip, .. }, .. }) = d.node_mut(g) { + *clip = true; + } + Ok(()) +} + +/// A clipping path `id` of `path`, unpainted. +fn clipping_path(id: NodeId, path: PathData) -> Node { let none = vectorcraft_color::Paint::None; - let mut clip = Node::path(d.alloc_id(), path, Appearance::basic(none.clone(), none, 0.0)); + let mut clip = Node::path(id, path, Appearance::basic(none.clone(), none, 0.0)); if let NodeKind::Path { clipping, .. } = &mut clip.kind { *clipping = true; } + clip +} + +/// Put object `id` of `d` into a new clip group of `path`, where it is. +fn new_clip_group(d: &mut Document, id: NodeId, path: PathData) -> Result<()> { + let (par, index, _) = d.position(id).ok_or(EngineError::NoNode(id))?; + let image = d.remove(id)?; + let clip = clipping_path(d.alloc_id(), path); let group = Node::new(d.alloc_id(), NodeKind::Group { children: vec![std::sync::Arc::new(clip), image], clip: true }); d.insert(par, index, group)?; Ok(()) @@ -837,29 +1064,44 @@ pub(crate) fn set_image_from_path(d: &mut Document, id: NodeId, path: &str, doc_ // the app connect to another computer. let path = fileio::document_path(path, doc_path).map_err(|r| EngineError::Other(format!("the image `{path}` isn't followed: {r}")))?; let bytes = read_file(&path)?; - let read = (link_info(&path, &bytes), linked_image(&bytes)?); + let read = (link_info(&path, &bytes), linked_image(&bytes, Some(&path))?); install(d, &[id], read, Some(Preserve::Bounds), None) } -/// Image objects `ids` show the file read for `link` (`img`), each placed as its Placement -/// Options say (`force`: as that Preserve choice says, whatever they say); with `also` (a file's -/// path and the content shown), so do the images outside the layer tree that show that content. +/// Image objects `ids` (in the layers or outside them) show the file read for `link` (`img`), each +/// placed as its Placement Options say (`force`: as that Preserve choice says, whatever they say); +/// with `also` (a file's path and the content shown), so do the images outside the layer tree that +/// show that content. fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Option<Preserve>, also: Option<(&str, &str)>) -> Result<()> { let new_pt = super::place::pt_per_px(img.ppi); let mut clips = vec![]; - if let Some(also) = also { - // Every image picked shows content `also.1`, so one resolution serves them all. - let old_pt = file_pt(d, also.1); - let pick = |n: &Node| shows(n, also, false); - let mut make = |n: &Node| { + let nested = nested_ids(d, ids); + if also.is_some() || !nested.is_empty() { + let pick = |n: &Node| matches!(n.kind, NodeKind::Image(_)) && (nested.contains(&n.id) || also.is_some_and(|also| shows(n, also, false))); + // The resolution of each content the images picked show, and the clipping path its DCS file + // drew it through, looked up once each. + let mut old: BTreeMap<String, ((f64, f64), Option<PathData>)> = BTreeMap::new(); + d.visit_stored(|n, _| { + if let NodeKind::Image(im) = &n.kind + && pick(n) + && !old.contains_key(&im.key) + { + old.insert(im.key.clone(), (file_pt(d, &im.key), d.images.get(&im.key).and_then(ImageBlob::separated_clip))); + } + }); + let mut make = |n: &Node, held: Option<(&PathData, FillRule)>| { let mut n = n.clone(); - let mut clip = None; + let mut clip = ClipTo::Keep; if let NodeKind::Image(im) = &mut n.kind { let o = PlacementOptions { preserve: force.unwrap_or(im.placement.preserve), ..im.placement }; let size = |w: u32, h: u32| (w as f64, h as f64); + let (old_pt, old_clip) = match old.get(&im.key) { + Some((pt, clip)) => (*pt, clip.as_ref()), + None => (super::place::pt_per_px(None), None), + }; let (xf, c) = placed_xf(im.xf, size(im.width, im.height), old_pt, size(img.width, img.height), new_pt, o); + clip = clip_to(im.xf, old_clip, c, &img, xf, held); (im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, Some(link.clone())); - clip = c; } (n, clip) }; @@ -870,29 +1112,89 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio let o = PlacementOptions { preserve: force.unwrap_or(im.placement.preserve), ..im.placement }; let size = |w: u32, h: u32| (w as f64, h as f64); let (xf, clip) = placed_xf(im.xf, size(im.width, im.height), file_pt(d, &im.key), size(img.width, img.height), new_pt, o); + // Placement Options' clip, else a DCS file's clipping path, read again with its plates. + let old_clip = d.images.get(&im.key).and_then(ImageBlob::separated_clip); + clips.push((*id, clip_to(im.xf, old_clip.as_ref(), clip, &img, xf, clip_path_of(d, *id)))); if let Some(n) = d.node_mut(*id) && let NodeKind::Image(im) = &mut n.kind { (im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, Some(link.clone())); } - clips.extend(clip.map(|c| (*id, c))); } + // A DCS file's spot plates print on spot swatches of their inks. + super::place::dcs::add_spot_swatches(d, &img.blob.spot_plates()); store_image(d, &img.key, img.blob, true); - clips.into_iter().try_for_each(|(id, clip)| clip_image(d, id, clip)) + clips.into_iter().try_for_each(|(id, clip)| match clip { + ClipTo::Keep => Ok(()), + ClipTo::Path(path) => clip_image_to(d, id, path), + ClipTo::File(path) => clip_file_to(d, id, path), + ClipTo::Nest(path) => new_clip_group(d, id, path), + ClipTo::Off => unclip(d, id), + }) +} + +/// Take the clipping path of the clip group holding just object `id` of `d` away: the group stays +/// as a plain group of the object, with its id, name, visibility and transparency as they were. +fn unclip(d: &mut Document, id: NodeId) -> Result<()> { + let Some((g, clip)) = d.parent_of(id).and_then(|g| match &d.node(g)?.kind { + NodeKind::Group { children, clip: true } => match &children[..] { + [c, o] if o.id == id && matches!(c.kind, NodeKind::Path { clipping: true, .. }) => Some((g, c.id)), + _ => None, + }, + _ => None, + }) else { + return Ok(()); + }; + d.remove(clip)?; + if let Some(Node { kind: NodeKind::Group { clip, .. }, .. }) = d.node_mut(g) { + *clip = false; + } + Ok(()) } /// Groups (of the document saved at `doc_path`) as `{name, path, ids}` rows (those with objects in -/// the layers), with `refused`: why the path isn't followed, when it isn't. +/// the layers), with `refused`: why the path isn't followed, when it isn't. `path` is left out +/// where [`path_shown`] says so. fn rows<'a>(gs: impl Iterator<Item = &'a Group>, doc_path: Option<&str>) -> Vec<Value> { gs.filter(|g| !g.ids.is_empty()) .map(|g| { - let mut row = json!({ "name": g.link.name(), "path": g.link.path, "ids": ids_json(&g.ids) }); + let mut row = json!({ "name": g.link.name(), "ids": ids_json(&g.ids) }); + note_path(&mut row, "path", &g.link.path, doc_path); note_refused(&mut row, &g.link, doc_path); row }) .collect() } +/// May a reply to the caller asking now carry the link path `path` (of the document saved at +/// `doc_path`)? Always without read roots in force; with them, only when the file it names (a +/// relative path taken from the document's folder) lies inside them. +pub(crate) fn path_shown(path: &str, doc_path: Option<&str>) -> bool { + crate::file_access::current().is_none() || fileio::document_path(path, doc_path).is_ok_and(|p| crate::file_access::check_read(&p).is_ok()) +} + +/// Is the linked JavaScript file `f` (of the document saved at `doc_path`) named by its file name +/// alone in a reply to the caller asking now? Only a path [`path_shown`] does not allow; a URL is +/// always shown as it is. +pub(crate) fn script_hidden(f: &str, doc_path: Option<&str>) -> bool { + !path_shown(f, doc_path) && !matches!(fileio::document_path(f, doc_path), Err(craft_docpath::Refused::Url)) +} + +/// The linked JavaScript file `f` of the open document `st` as a reply to the caller asking now +/// may name it: as it is, or by its file name alone where [`script_hidden`] says so. +pub fn shown_script<'a>(st: &crate::DocState, f: &'a str) -> Cow<'a, str> { + if script_hidden(f, LinkBase::of(st).doc) { Cow::Owned(LinkInfo::new(f).name().to_string()) } else { Cow::Borrowed(f) } +} + +/// `row[key] = path` when [`path_shown`] says so; otherwise `row` has no `key`. +pub(crate) fn note_path(row: &mut Value, key: &str, path: &str, doc_path: Option<&str>) { + if path_shown(path, doc_path) { + row[key] = json!(path); + } else if let Some(o) = row.as_object_mut() { + o.remove(key); + } +} + /// `row["refused"]`: why the path of `link` isn't followed, when it isn't ([`refused`]). fn note_refused(row: &mut Value, link: &LinkInfo, doc_path: Option<&str>) { if let Some(r) = refused(link, doc_path) { @@ -981,6 +1283,9 @@ pub fn resolve(d: &mut Document, base: LinkBase, update: bool, low_res_proxy_eps } (Status::Ok, Some(mut f)) => { let preview = previewing(d, &g.key); + // A DCS file is read in full even with the proxy: its plates print and separate on + // their own inks. + let eps_preview = eps_preview && !is_dcs_file(&mut f); if let Some((blob, hash)) = read_images.get(&f.path).filter(|_| preview && !eps_preview).cloned() { store_image(d, &g.key, blob, true); let link = f.link_hashed(hash, &g.link); @@ -993,7 +1298,7 @@ pub fn resolve(d: &mut Document, base: LinkBase, update: bool, low_res_proxy_eps // Read when the images show the preview, or when the file's details changed. let bytes = if (preview && !eps_preview) || f.bytes.is_some() { f.read().ok() } else { None }; if preview && !eps_preview { - let Some((b, img)) = bytes.as_deref().and_then(|b| Some((b, linked_image(b).ok()?))) else { + let Some((b, img)) = bytes.as_deref().and_then(|b| Some((b, linked_image(b, Some(&f.path)).ok()?))) else { out.missing.extend(row); continue; }; @@ -1019,7 +1324,7 @@ pub fn resolve(d: &mut Document, base: LinkBase, update: bool, low_res_proxy_eps } } // The objects in symbols, graph designs, patterns and opacity masks that show the same file and - // content, which have no ids here, whatever else their links hold. + // content, whatever else their links hold, those whose id an earlier object has included. if !moved.is_empty() { let mut by_path: BTreeMap<String, Vec<(String, bool, LinkInfo)>> = BTreeMap::new(); for (path, key, document, new) in moved { @@ -1031,15 +1336,17 @@ pub fn resolve(d: &mut Document, base: LinkBase, update: bool, low_res_proxy_eps m.iter().find(|(k, doc, _)| k == key && *doc == document.is_some()).map(|(_, _, new)| new) }; let pick = |n: &Node| new(n).is_some(); - let mut make = |n: &Node| { + let mut make = |n: &Node, _: Option<(&PathData, FillRule)>| { let mut out = n.clone(); if let (Some(link), Some(l)) = (new(n), link_mut(&mut out)) { *l = link.clone(); } - (out, None) + (out, ClipTo::Keep) }; Nested { pick: &pick, make: &mut make, next: 0 }.run(d); } + // Color masks of images whose files were read again are made for the new pixels. + super::refresh_color_masks(None, d); out } @@ -1052,13 +1359,25 @@ fn link_mut(n: &mut Node) -> Option<&mut LinkInfo> { } } -/// Linked image objects (or placed documents) `ids` link to `link`. +/// Linked image objects (or placed documents) `ids`, in the layers or outside them, link to `link`. fn set_links(d: &mut Document, ids: &[NodeId], link: &LinkInfo) { - for id in ids { + let nested = nested_ids(d, ids); + for id in ids.iter().filter(|id| !nested.contains(id)) { if let Some(l) = d.node_mut(*id).and_then(link_mut) { *l = link.clone(); } } + if !nested.is_empty() { + let pick = |n: &Node| nested.contains(&n.id) && linked(n).is_some(); + let mut make = |n: &Node, _: Option<(&PathData, FillRule)>| { + let mut out = n.clone(); + if let Some(l) = link_mut(&mut out) { + *l = link.clone(); + } + (out, ClipTo::Keep) + }; + Nested { pick: &pick, make: &mut make, next: 0 }.run(d); + } } /// Placed documents of the document saved at `path` (document `saved` of `s`) in the other open @@ -1081,14 +1400,17 @@ pub(crate) fn refresh_placed(s: &mut Session, saved: u64, path: &str) { if targets.is_empty() { return; } - // Each document is updated as the active one, without switching tools. + // Each document is updated as the active one, through its own profiles, without switching + // tools. let back = s.active; for i in targets { s.active = Some(i); + s.sync_front_profiles(); // A file that can't be read leaves what its objects show: links.check reports it. let _ = update_where(s, None, Some(&path)); } s.active = back; + s.sync_front_profiles(); } // ---------- relative paths ---------- @@ -1177,6 +1499,82 @@ pub(crate) fn with_found_paths(d: &mut Document, base: LinkBase) { }); } +/// `d`, a document saved at `doc_path`, as a reply to the caller asking now may show it: without +/// read roots in force, `d` itself; with them, a copy in which each link [`path_shown`] does not +/// allow names its file alone, without its relative path or the size and date kept of its file, +/// and each data set's image value and linked JavaScript file (`svg_scripts`) it does not allow +/// names its file alone too, while a JavaScript file given as a URL stays as it is. The folder Export +/// for Screens last wrote to is left out of the export settings when it is outside the read roots. +/// A link whose path is allowed but whose relative path leads outside the read roots loses its +/// relative path. Links in the layers, symbols, graph designs, patterns, the pattern being edited +/// as it was before, opacity masks and the art of the stored brushes are all checked. A stored +/// brush entry that does not read as a brush is left out of the copy, since its links cannot be +/// checked, and a stored brush library that is not a list becomes an empty one. +pub(crate) fn with_hidden_paths_named<'a>(d: &'a Document, base: LinkBase) -> Cow<'a, Document> { + if crate::file_access::current().is_none() { + return Cow::Borrowed(d); + } + let doc_path = base.doc; + // A stored relative path is followed from the folder of the file the document was read from, + // and a link is also looked for from the document's own folder: it is shown only when both + // places it names are inside the read roots. + let relative_hidden = |r: &str| [base.relative, base.doc].into_iter().any(|from| !path_shown(r, from)); + let mut d = d.clone(); + // The pattern being edited as it was before is checked as one more pattern, then put back. + let original = d.pattern_edit.as_mut().and_then(|e| e.original.take()); + let edited = original.is_some(); + d.patterns.extend(original); + // The art of each stored brush is checked as more layers, then put back. + let stored = d.unknown.get(vectorcraft_brush::DOC_KEY).map(|v| v.as_array().cloned().unwrap_or_default()); + let mut brushes: Vec<vectorcraft_brush::Brush> = + stored.iter().flatten().filter_map(|raw| vectorcraft_brush::Brush::from_json(raw.clone()).ok()).collect(); + let layers = d.layers.len(); + d.layers.extend(brushes.iter().flat_map(|b| b.art()).map(|n| Arc::new(n.clone()))); + d.update_links_where( + |l| !path_shown(&l.path, base.doc) || l.relative.as_deref().is_some_and(relative_hidden), + |l| { + if path_shown(&l.path, base.doc) { + l.relative = None; + } else { + let name = l.name().to_string(); + *l = LinkInfo { path: name, relative: None, modified: None, size: None, ..l.clone() }; + } + }, + ); + let mut checked = d.layers.split_off(layers).into_iter(); + if edited && let (Some(def), Some(e)) = (d.patterns.pop(), d.pattern_edit.as_mut()) { + e.original = Some(def); + } + if stored.is_some() { + // Each brush is written as it reads, so fields it does not read are left out too. + let mut kept = vec![]; + for b in &mut brushes { + for (slot, art) in b.art_mut().into_iter().zip(&mut checked) { + *slot = Arc::unwrap_or_clone(art); + } + kept.extend(serde_json::to_value(&*b).ok()); + } + d.unknown.insert(vectorcraft_brush::DOC_KEY.into(), Value::Array(kept)); + } + if d.export_settings.get("folder").and_then(Value::as_str).is_some_and(|f| crate::file_access::check_read(f).is_err()) { + d.export_settings.remove("folder"); + } + let hidden = |v: &DataValue| matches!(v, DataValue::Image(path) if !path_shown(path, doc_path)); + if d.variables.datasets.iter().any(|set| set.values.values().any(hidden)) { + for v in d.variables.datasets.iter_mut().flat_map(|set| set.values.values_mut()) { + if hidden(&*v) + && let DataValue::Image(path) = v + { + *path = LinkInfo::new(path.as_str()).name().to_string(); + } + } + } + for f in d.svg_scripts.iter_mut().filter(|f| script_hidden(f, doc_path)) { + *f = LinkInfo::new(f.as_str()).name().to_string(); + } + Cow::Owned(d) +} + // ---------- commands ---------- fn check(s: &mut Session, p: &Value) -> Result<Value> { @@ -1188,10 +1586,12 @@ fn check(s: &mut Session, p: &Value) -> Result<Value> { let (status, found) = probe(g, LinkBase::of(st)); missing += usize::from(status == Status::Missing); modified += usize::from(status == Status::Modified); - let mut row = json!({ "name": g.link.name(), "path": g.link.path, "status": status.as_str(), "ids": ids_json(&g.ids) }); - note_refused(&mut row, &g.link, LinkBase::of(st).doc); + let doc_path = LinkBase::of(st).doc; + let mut row = json!({ "name": g.link.name(), "status": status.as_str(), "ids": ids_json(&g.ids) }); + note_path(&mut row, "path", &g.link.path, doc_path); + note_refused(&mut row, &g.link, doc_path); if let Some(f) = found.filter(|f| f.path != g.link.path) { - row["found"] = json!(f.path); + note_path(&mut row, "found", &f.path, doc_path); } if stale(&st.doc, g) { row["preview"] = json!(true); @@ -1208,7 +1608,7 @@ fn update(s: &mut Session, p: &Value) -> Result<Value> { /// Update Links in the active document of `s` for objects `ids` (default: the linked files that /// changed or show their preview), or with `path`, for the placed documents of the file at `path` /// whatever their status. The objects in symbols, graph designs, patterns and opacity masks that -/// show the same content are read again too, and have no ids to report. +/// show the same content are read again too. fn update_where(s: &mut Session, ids: Option<Vec<NodeId>>, path: Option<&str>) -> Result<Value> { let st = s.doc()?; let (mut reads, mut missing) = (vec![], vec![]); @@ -1227,10 +1627,44 @@ fn update_where(s: &mut Session, ids: Option<Vec<NodeId>>, path: Option<&str>) - } } let updated: Vec<u64> = reads.iter().flat_map(|(g, _)| ids_json(&g.ids)).collect(); + let warnings = spot_swatch_notes(&st.doc, reads.iter().map(|(_, read)| read)); if !reads.is_empty() { s.edit("Update Links", |d, _| reads.into_iter().try_for_each(|(g, read)| install_read(d, &g.ids, read, None, Some(&g))))?; } - Ok(json!({ "updated": updated, "missing": missing })) + let mut out = json!({ "updated": updated, "missing": missing }); + if !warnings.is_empty() { + out["warnings"] = json!(warnings); + } + Ok(out) +} + +/// The warnings for the spot plates of the DCS files in `reads` whose ink a swatch of `d` already +/// names in another color, or as a process color ([`super::place::dcs::swatch_notes`]), or that an +/// earlier file of `reads` adds as a spot swatch in another color, each once. +fn spot_swatch_notes<'a>(d: &Document, reads: impl Iterator<Item = &'a Read>) -> Vec<String> { + let mut out: Vec<String> = vec![]; + // The spot swatches the reads add, in the order they are installed. + let mut added: Vec<(String, [f32; 4])> = vec![]; + for read in reads { + let Read::Image((_, img)) = read else { continue }; + let spots = img.blob.spot_plates(); + let mut notes = super::place::dcs::swatch_notes(d, &spots); + for (name, cmyk) in spots.into_iter().filter(|(name, _)| d.swatch(name).is_none()) { + match added.iter().find(|(n, _)| *n == name) { + Some((_, first)) if first.iter().zip(cmyk).any(|(a, b)| (a - b).abs() >= 0.005) => { + notes.push(format!("the document's swatch `{name}` is kept: it is a different color")); + } + Some(_) => {} + None => added.push((name, cmyk)), + } + } + for note in notes { + if !out.contains(¬e) { + out.push(note); + } + } + } + out } /// Which links `links.relink` points at the new file (the Replace choice of Relink). @@ -1240,7 +1674,7 @@ enum Scope { Each, /// The objects given or selected. Selected, - /// Every object in the layers linked to the same file as one given or selected. + /// Every stored object linked to the same file as one given or selected. All, /// The objects given or selected, then every other missing link whose file name is in the new /// file's folder. @@ -1317,12 +1751,14 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> { (true, false) => return Err(bad(C, "copy needs path: the file to copy into the document's folder")), (true, true) => { let doc = st.path.as_deref().map(absolute_path).ok_or_else(|| bad(C, "save the document first: copy puts the file in its folder"))?; - Some(Path::new(&doc).parent().map(Path::to_path_buf).ok_or_else(|| bad(C, format!("{doc} has no folder")))?) + // The document's path is not the client's: the error names it as the request may see it. + let no_folder = || fileio::naming_in_error(bad(C, format!("{doc} has no folder")), &doc); + Some(Path::new(&doc).parent().map(Path::to_path_buf).ok_or_else(no_folder)?) } }; // An image or a placed document, with its link. let image = |id: &NodeId| { - st.doc.node(*id).and_then(|n| match &n.kind { + stored(&st.doc, *id).and_then(|n| match &n.kind { NodeKind::Image(im) => Some(im.link.as_ref()), NodeKind::PlacedDocument(p) => Some(Some(&p.link)), _ => None, @@ -1347,22 +1783,23 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> { if ids.is_empty() { return Err(bad(C, "select the images to relink, or pass ids")); } - // All Instances: the other objects in the layers linked to the same files. + // All Instances: the other stored objects linked to the same files, each once. if scope == Scope::All { let paths: BTreeSet<&str> = ids.iter().filter_map(|id| image(id).flatten()).map(|l| l.path.as_str()).collect(); - let given: BTreeSet<NodeId> = ids.iter().copied().collect(); + let mut given: BTreeSet<NodeId> = ids.iter().copied().collect(); let mut more = vec![]; - st.doc.walk(|n| { + st.doc.visit_stored(|n, _| { if let Some((l, _, _)) = linked(n) && paths.contains(l.path.as_str()) - && !given.contains(&n.id) + && n.id.0 != 0 + && given.insert(n.id) { more.push(n.id); } }); ids.extend(more); } - if copy_to.is_some() && ids.iter().any(|id| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::PlacedDocument(_)))) { + if copy_to.is_some() && ids.iter().any(|id| matches!(stored(&st.doc, *id).map(|n| &n.kind), Some(NodeKind::PlacedDocument(_)))) { return Err(bad(C, "copy takes images only: relink placed documents where their files are")); } // (ids, the file) per file to read. @@ -1398,7 +1835,7 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> { let mut images = vec![]; let mut documents: Vec<((u32, bool, PageBox), Vec<NodeId>)> = vec![]; for id in ids { - match st.doc.node(id).map(|n| &n.kind) { + match stored(&st.doc, id).map(|n| &n.kind) { Some(NodeKind::PlacedDocument(pl)) => { let k = (pl.page(), pl.bounding, pl.page_box); match documents.iter_mut().find(|(e, _)| *e == k) { @@ -1410,7 +1847,11 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> { } } // Read before it is copied: a file that can't be shown isn't copied. - let img = if images.is_empty() { None } else { Some(linked_image(&bytes).map_err(|e| bad(C, format!("{path}: {e}")))?) }; + let img = if images.is_empty() { None } else { Some(linked_image(&bytes, Some(&path)).map_err(|e| bad(C, format!("{path}: {e}")))?) }; + // A copy beside the document would point at plate files it can't find there. + if copy_to.is_some() && img.as_ref().is_some_and(|img| !img.blob.plate_files().is_empty()) { + return Err(bad(C, format!("{path}: copy takes a DCS file only when its plates are inside it; relink to it where its plate files are"))); + } let mut sources = vec![]; for ((page, bounding, page_box), ids) in documents { sources.push((page, ids, super::place::document::source(&path, &bytes, Some(&path), page, bounding, page_box, C)?)); @@ -1445,13 +1886,23 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> { } } let relinked: Vec<u64> = reads.iter().flat_map(|(ids, _)| ids_json(ids)).collect(); + let warnings = spot_swatch_notes(&s.doc()?.doc, reads.iter().map(|(_, read)| read)); if !reads.is_empty() { s.edit("Relink", |d, _| reads.into_iter().try_for_each(|(ids, read)| install_read(d, &ids, read, preserve, None)))?; } not_found.sort(); not_found.dedup(); let mut out = json!({ "relinked": relinked, "notFound": not_found }); + if !warnings.is_empty() { + out["warnings"] = json!(warnings); + } if copy_to.is_some() { + // The copies are in the document's folder, which the client did not give. + for pair in copied.iter_mut().chain(kept.iter_mut()) { + if let Some(to) = pair.get("to").and_then(Value::as_str).map(str::to_string) { + pair["to"] = json!(fileio::shown_path(&to)); + } + } out["copied"] = json!(copied); out["kept"] = json!(kept); } @@ -1501,9 +1952,14 @@ fn copy_into_folder(from: &str, bytes: &[u8], dir: &Path) -> Result<(String, boo use std::io::Write as _; let source = Path::new(from); let name = source.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); - // Each name it takes is checked against the automation roots in force. + // Each name it takes is checked against the automation roots in force. The folder is the + // document's, so a refusal names it and the file as the request may see them. let create = |to: &Path| { - crate::file_access::check_write(&to.to_string_lossy()).map_err(|e| std::io::Error::new(std::io::ErrorKind::PermissionDenied, e))?; + let to_text = to.to_string_lossy(); + crate::file_access::check_write(&to_text).map_err(|e| { + let e = fileio::naming_in_error(EngineError::Other(e), &to_text); + std::io::Error::new(std::io::ErrorKind::PermissionDenied, e.to_string()) + })?; vectorcraft_format::write_new_with(to, |f| f.write_all(bytes)) }; // A file there that automation may not read isn't taken for the same file. @@ -1514,7 +1970,10 @@ fn copy_into_folder(from: &str, bytes: &[u8], dir: &Path) -> Result<(String, boo Ok(Some(fileio::Placed::Copied(to))) => Ok((to.to_string_lossy().into_owned(), true)), Ok(Some(fileio::Placed::Kept(to))) => Ok((to.to_string_lossy().into_owned(), false)), Ok(None) => Err(EngineError::Other(format!("every numbered name for {name} is taken in the document's folder"))), - Err(e) => Err(EngineError::Other(format!("{}: {e}", dir.display()))), + Err(e) => { + let dir = dir.to_string_lossy(); + Err(fileio::naming_in_error(EngineError::Other(format!("{dir}: {e}")), &dir)) + } } } @@ -1526,9 +1985,9 @@ fn copy_into_folder(_: &str, _: &[u8], _: &Path) -> Result<(String, bool)> { // ---------- the Links panel ---------- -/// Image object `id` of `d`. +/// Image object `id` of `d`, wherever it is stored. fn image_of(d: &Document, id: NodeId) -> Option<&ImageObject> { - match &d.node(id)?.kind { + match &stored(d, id)?.kind { NodeKind::Image(im) => Some(im), _ => None, } @@ -1546,7 +2005,7 @@ fn image_param(st: &crate::DocState, p: &Value, cmd: &str) -> Result<NodeId> { .ok_or_else(|| bad(cmd, "select an image, or pass id"))?; match image_of(&st.doc, id) { Some(_) => Ok(id), - None if st.doc.node(id).is_none() => Err(crate::EngineError::NoNode(id)), + None if stored(&st.doc, id).is_none() => Err(crate::EngineError::NoNode(id)), None => Err(bad(cmd, format!("object {} is not an image", id.0))), } } @@ -1560,9 +2019,9 @@ fn placement_mut(n: &mut Node) -> Option<&mut PlacementOptions> { } } -/// The Placement Options of image or placed document `id` of `d`. +/// The Placement Options of image or placed document `id` of `d`, wherever it is stored. fn placement_of(d: &Document, id: NodeId) -> Option<PlacementOptions> { - match &d.node(id)?.kind { + match &stored(d, id)?.kind { NodeKind::Image(im) => Some(im.placement), NodeKind::PlacedDocument(p) => Some(p.placement), _ => None, @@ -1575,12 +2034,12 @@ fn linked_param(st: &crate::DocState, p: &Value, cmd: &str) -> Result<NodeId> { let id = object_param(p, "id", cmd)?.or_else(first).ok_or_else(|| bad(cmd, "select an image, or pass id"))?; match placement_of(&st.doc, id) { Some(_) => Ok(id), - None if st.doc.node(id).is_none() => Err(crate::EngineError::NoNode(id)), + None if stored(&st.doc, id).is_none() => Err(crate::EngineError::NoNode(id)), None => Err(bad(cmd, format!("object {} is not an image or a linked file", id.0))), } } -/// Per linked image in the layers of `st`: its file's status, where it was found when away from +/// Per linked image or placed document of `st`, wherever it is stored: its file's status, where it was found when away from /// its path, and whether the image shows its preview (each file probed once). pub(crate) fn statuses(st: &crate::DocState) -> BTreeMap<NodeId, (Status, Option<String>, bool)> { let mut out = BTreeMap::new(); @@ -1595,6 +2054,9 @@ pub(crate) fn statuses(st: &crate::DocState) -> BTreeMap<NodeId, (Status, Option /// The format of the file image `im` of `d` shows: its link's extension, else its pixels' type. fn format_label(d: &Document, im: &ImageObject) -> &'static str { + if im.link.is_some() && d.images.get(&im.key).is_some_and(ImageBlob::is_separated) { + return "DCS"; + } im.link .as_ref() .and_then(|l| fileio::format_for_name(l.name()).or_else(|| fileio::readable_format_for_name(l.name()))) @@ -1615,6 +2077,60 @@ fn status_rank(status: &str) -> usize { ["missing", "modified", "ok", "embedded"].iter().position(|s| *s == status).unwrap_or(4) } +/// The DCS images in the layers of `d` that are transparent (themselves, or a group or layer that +/// holds them) or overlap an object that is, as Show DCS Transparency Interactions marks them. +fn dcs_transparency(d: &Document) -> BTreeSet<NodeId> { + /// Each visible DCS image's id, bounds and whether it is transparent, and the bounds of each + /// other visible object with its own transparency; bounds are cut to `clip`, the bounds of the + /// clipping paths of the clip groups and layers holding the object. + fn walk(d: &Document, n: &Node, held: bool, clip: Option<Rect>, images: &mut Vec<(NodeId, Rect, bool)>, see_through: &mut Vec<Rect>) { + if !n.visible { + return; + } + let own = n.shows_own_transparency(); + // The part of the object that shows through `clip`; none when it is clipped away. + let shown = n.geometric_bounds().and_then(|b| match clip { + Some(c) => Some(c.intersect(b)).filter(|i| i.area() > 0.0), + None => Some(b), + }); + match &n.kind { + NodeKind::Image(im) if d.images.get(&im.key).is_some_and(ImageBlob::is_separated) => { + if let Some(b) = shown { + images.push((n.id, b, held || own)); + // A transparent DCS image is an object with its own transparency for the + // others it overlaps. + if own { + see_through.push(b); + } + } + } + _ if own => see_through.extend(shown), + _ => {} + } + let Some(children) = n.children() else { return }; + // A clip group's or clipping layer's first child clips the others. + let clip = match &n.kind { + NodeKind::Group { clip: true, .. } | NodeKind::Layer { clip: true, .. } => match children.first().and_then(|c| c.geometric_bounds()) { + Some(c) => Some(clip.map_or(c, |o| o.intersect(c))), + None => clip, + }, + _ => clip, + }; + for c in children { + walk(d, c, held || own, clip, images, see_through); + } + } + let (mut images, mut see_through) = (vec![], vec![]); + for l in &d.layers { + walk(d, l, false, None, &mut images, &mut see_through); + } + images + .into_iter() + .filter(|(_, b, transparent)| *transparent || see_through.iter().any(|t| t.intersect(*b).area() > 0.0)) + .map(|(id, ..)| id) + .collect() +} + fn list(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "links.list"; let st = s.doc()?; @@ -1622,18 +2138,22 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> { if !matches!(show, "all" | "missing" | "modified" | "embedded") { return Err(bad(C, format!("show `{show}`: all, missing, modified or embedded"))); } + let interactions = if switch_or(p, "dcsTransparency", false, C)? { dcs_transparency(&st.doc) } else { BTreeSet::new() }; let statuses = statuses(st); - let mut objects = vec![]; - st.doc.walk(|n| { - if matches!(n.kind, NodeKind::Image(_) | NodeKind::PlacedDocument(_)) { - objects.push(n); + // The layer tree's objects, top first as the Layers panel lists them, then the others in the + // order they are stored (opacity-mask art, symbols, graph designs, patterns), each once. + let (mut objects, mut nested) = (vec![], vec![]); + let mut seen = std::collections::HashSet::new(); + st.doc.visit_stored(|n, place| { + if matches!(n.kind, NodeKind::Image(_) | NodeKind::PlacedDocument(_)) && n.id.0 != 0 && seen.insert(n.id) { + if place.in_layers() { objects.push((n, place)) } else { nested.push((n, place)) } } }); - // Top first, as the Layers panel lists them. objects.reverse(); + objects.extend(nested); let mut counts: BTreeMap<&str, usize> = BTreeMap::new(); let mut rows = vec![]; - for n in objects { + for (n, place) in objects { let (status, found, preview) = match statuses.get(&n.id) { Some((s, f, p)) => (s.as_str(), f.as_deref(), *p), None => ("embedded", None, false), @@ -1663,18 +2183,25 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> { o.insert("linked".into(), json!(link.is_some())); o.insert("status".into(), json!(status)); } + let doc_path = LinkBase::of(st).doc; if let Some(l) = link { - row["path"] = json!(l.path); + note_path(&mut row, "path", &l.path, doc_path); if let Some(page) = l.page { row["page"] = json!(page); } } if let Some(f) = found { - row["found"] = json!(f); + note_path(&mut row, "found", f, doc_path); } if preview { row["preview"] = json!(true); } + if let Some(owner) = owner_json(&st.doc, place) { + row["owner"] = owner; + } + if interactions.contains(&n.id) { + row["dcsTransparency"] = json!(true); + } rows.push(row); } let text = |r: &Value, k: &str| r[k].as_str().unwrap_or_default().to_lowercase(); @@ -1692,15 +2219,21 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> { fn go_to(s: &mut Session, p: &Value) -> Result<Value> { let st = s.doc()?; let id = linked_param(st, p, "links.goTo")?; + // An object in mask art or a definition has no place of its own on the canvas: the selection + // is cleared, and the reply names what holds it. + if let Some(owner) = st.doc.stored_node(id).and_then(|(_, place)| owner_json(&st.doc, place)) { + s.select(|_, sel| sel.set([]))?; + return Ok(json!({ "id": id.0, "onCanvas": false, "owner": owner })); + } let b = st.doc.node(id).and_then(Node::geometric_bounds).unwrap_or_default(); s.select(|_, sel| sel.set([id]))?; - Ok(json!({ "id": id.0, "bounds": [b.x0, b.y0, b.x1, b.y1] })) + Ok(json!({ "id": id.0, "bounds": [b.x0, b.y0, b.x1, b.y1], "onCanvas": true })) } fn embed(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "links.embed"; let st = s.doc()?; - let kind = |id: &NodeId| st.doc.node(*id).map(|n| &n.kind); + let kind = |id: &NodeId| stored(&st.doc, *id).map(|n| &n.kind); let linked = |id: &NodeId| match kind(id) { Some(NodeKind::Image(im)) => im.link.is_some(), Some(NodeKind::PlacedDocument(_)) => true, @@ -1713,6 +2246,14 @@ fn embed(s: &mut Session, p: &Value) -> Result<Value> { if ids.is_empty() { return Err(bad(C, "select the linked images or placed documents, or pass ids")); } + // A DCS file's plates print from its file. + let separated = |id: &NodeId| match kind(id) { + Some(NodeKind::Image(im)) => st.doc.images.get(&im.key).is_some_and(ImageBlob::is_separated), + _ => false, + }; + if let Some(id) = ids.iter().find(|id| separated(id)) { + return Err(bad(C, format!("object {}: {}", id.0, super::place::dcs::LINK_ONLY))); + } // Placed documents become editable copies of their art: those whose file can be read. let (mut documents, mut missing) = (vec![], vec![]); for id in ids.iter().copied() { @@ -1731,6 +2272,10 @@ fn embed(s: &mut Session, p: &Value) -> Result<Value> { } match probe(&g, LinkBase::of(st)) { (Status::Ok | Status::Modified, Some(mut f)) => match read_image(&mut f, &g.link, &mut image_reads) { + // One showing its preview is a DCS file only its file tells. + Ok((_, img)) if img.blob.is_separated() => { + return Err(bad(C, format!("object {}: {}", g.ids.first().map_or(0, |id| id.0), super::place::dcs::LINK_ONLY))); + } Ok(read) => { done.extend(&g.ids); reads.push((g.ids, read)); @@ -1746,7 +2291,7 @@ fn embed(s: &mut Session, p: &Value) -> Result<Value> { install(d, &ids, read, Some(Preserve::Bounds), None)?; } for id in &done { - if let Some(Node { kind: NodeKind::Image(im), .. }) = d.node_mut(*id) { + if let Some(Node { kind: NodeKind::Image(im), .. }) = d.stored_node_mut(*id) { im.link = None; } } @@ -1774,7 +2319,7 @@ fn unembed(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "links.unembed"; let st = s.doc()?; let id = image_param(st, p, C)?; - let n = st.doc.node(id).ok_or(crate::EngineError::NoNode(id))?; + let n = stored(&st.doc, id).ok_or(crate::EngineError::NoNode(id))?; let im = image_of(&st.doc, id).ok_or_else(|| bad(C, format!("object {} is not an image", id.0)))?; if im.link.is_some() { return Err(bad(C, format!("image {} is linked already", id.0))); @@ -1797,7 +2342,7 @@ fn unembed(s: &mut Session, p: &Value) -> Result<Value> { }; let path = absolute_path(&if fileio::extension(path).is_empty() { format!("{path}.{ext}") } else { path.to_string() }); // Read before writing: pixels that can't be read leave no file behind. - let img = linked_image(&bytes)?; + let img = linked_image(&bytes, Some(&path))?; write_file(&path, &bytes)?; let read = (link_info(&path, &bytes), img); s.edit("Unembed", |d, _| install(d, &[id], read, Some(Preserve::Bounds), None))?; @@ -1811,13 +2356,17 @@ fn placement_json(o: PlacementOptions) -> Value { /// Link Info's fields of the linked file `l` (of object `id` of `st`) into `out`. fn file_fields(st: &crate::DocState, id: NodeId, l: &LinkInfo, out: &mut Value) { + // Whether the path is shown is judged for the caller asking, before the opener's roots apply. + let shown = path_shown(&l.path, LinkBase::of(st).doc); // A confined caller reads within its own roots; anyone else within what the caller that // opened the document may read (never wider than the caller asking now). let roots = crate::file_access::current().or_else(|| st.opened_by.clone()); - crate::file_access::confine(roots.as_ref(), || file_fields_here(st, id, l, out)); + crate::file_access::confine(roots.as_ref(), || file_fields_here(st, id, l, shown, out)); } -fn file_fields_here(st: &crate::DocState, id: NodeId, l: &LinkInfo, out: &mut Value) { +/// [`file_fields`]; without `shown`, the link's path (`path`, `link`) and folder (`location`) +/// and the size and date the document keeps of its file are left out. +fn file_fields_here(st: &crate::DocState, id: NodeId, l: &LinkInfo, shown: bool, out: &mut Value) { let base = LinkBase::of(st); let status = groups(&st.doc, Some(&[id])).first().map_or(Status::Missing, |g| probe(g, base).0); let doc_path = base.doc; @@ -1825,13 +2374,20 @@ fn file_fields_here(st: &crate::DocState, id: NodeId, l: &LinkInfo, out: &mut Va let stamp = path.as_deref().and_then(file_stamp); out["status"] = json!(status.as_str()); note_refused(out, l, doc_path); - out["path"] = json!(l.path); + if shown { + out["path"] = json!(l.path); + out["location"] = json!(l.folder()); + } else if let Some(o) = out.as_object_mut() { + for k in ["path", "link", "location"] { + o.remove(k); + } + } out["fileName"] = json!(l.name()); - out["location"] = json!(l.folder()); + let kept = |v: Option<u64>| v.filter(|_| shown); for (k, v) in [ ("page", l.page.map(u64::from)), - ("fileSize", stamp.map(|s| s.0).or(l.size)), - ("modified", stamp.and_then(|s| s.1).or(l.modified)), + ("fileSize", stamp.map(|s| s.0).or(kept(l.size))), + ("modified", stamp.and_then(|s| s.1).or(kept(l.modified))), ("created", path.as_deref().and_then(file_created)), ] { if let Some(v) = v { @@ -1849,7 +2405,7 @@ fn scale_rotation(xf: Affine, (px, py): (f64, f64)) -> (Value, Value) { /// Link Info of placed document `id`. fn placed_info(st: &crate::DocState, id: NodeId) -> Result<Value> { - let n = st.doc.node(id).ok_or(crate::EngineError::NoNode(id))?; + let n = stored(&st.doc, id).ok_or(crate::EngineError::NoNode(id))?; let NodeKind::PlacedDocument(pl) = &n.kind else { return Err(bad("links.info", format!("object {} is not a placed document", id.0))) }; let size = n.geometric_bounds().unwrap_or_default(); let (scale, rotation) = scale_rotation(pl.xf, (1.0, 1.0)); @@ -1929,7 +2485,7 @@ fn placement_options(s: &mut Session, p: &Value) -> Result<Value> { }; s.edit("Placement Options", |d, _| { for id in &ids { - if let Some(o) = d.node_mut(*id).and_then(placement_mut) { + if let Some(o) = d.stored_node_mut(*id).and_then(placement_mut) { set(o); } } diff --git a/crates/engine/src/cmd/live.rs b/crates/engine/src/cmd/live.rs index 464f241159..618865cede 100644 --- a/crates/engine/src/cmd/live.rs +++ b/crates/engine/src/cmd/live.rs @@ -21,7 +21,7 @@ use super::expand::gradient_sampler; use super::pathops::Beside; use super::{ CommandSpec, EngineError, Result, Session, always, bad, check_numbers, cmd, color_param, f64_or, f64_req, finite_numbers, has_doc, has_multi, - has_selection, id_param, named_ids, number_or, ok, str_param, switch_or, text_param, + has_selection, named_ids, number_or, object_param, ok, str_param, switch_or, text_param, }; mod blend; diff --git a/crates/engine/src/cmd/live/blend.rs b/crates/engine/src/cmd/live/blend.rs index 7d7c21227a..a208d527fa 100644 --- a/crates/engine/src/cmd/live/blend.rs +++ b/crates/engine/src/cmd/live/blend.rs @@ -1,5 +1,7 @@ use std::collections::BTreeSet; +use vectorcraft_doc::live::BlendSpineMode; + use super::common::{ DEFAULT_DISTANCE, DEFAULT_STEPS, ease_param, fix_ids, ids_json, is_blend, orientation_param, percent_param, roots_param, selected_of, spacing_param, starts_param, wrap, @@ -61,6 +63,19 @@ fn extend_spine(spec: &mut BlendSpec, old: &[Arc<Node>], old_spec: &BlendSpec, k spec.spine = Some(path); } +/// Does `p` set easing (`easingType` or `ramp`)? Easing needs a spine. +fn gives_easing(p: &Value) -> bool { + ["easingType", "ramp"].iter().any(|key| p.get(*key).is_some_and(|v| !v.is_null())) +} + +/// The Create Spine mode `p` gives as `key`, or `current` when it is omitted or null. +fn spine_mode_param(p: &Value, cmd: &str, key: &str, current: BlendSpineMode) -> Result<BlendSpineMode> { + match p.get(key).filter(|v| !v.is_null()) { + None => Ok(current), + Some(v) => v.as_str().and_then(BlendSpineMode::from_id).ok_or_else(|| bad(cmd, format!("`{key}` must be one of auto, always, never"))), + } +} + pub(super) fn blend_make(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "object.blend.make"; let roots = roots_param(s, p)?; @@ -69,16 +84,22 @@ pub(super) fn blend_make(s: &mut Session, p: &Value) -> Result<Value> { } let starts = starts_param(p, &roots)?; let base = first_blend(&s.doc()?.doc, &roots); + let defaults = s.prefs.blend_options.unwrap_or_default(); + // Create Spine applies to a new blend; one taking more keys keeps whether it has a spine. + let create_spine = spine_mode_param(p, C, "createSpine", defaults.create_spine)?; let cur = match base.as_ref().map(|n| &n.kind) { - Some(NodeKind::Blend { spec, .. }) => BlendDefaults { spacing: spec.spacing, orientation: spec.orientation }, - _ => s.prefs.blend_options.unwrap_or_default(), + Some(NodeKind::Blend { spec, .. }) => BlendDefaults { spacing: spec.spacing, orientation: spec.orientation, ..defaults }, + _ => defaults, }; let spacing = spacing_param(p, C, cur.spacing)?; let orientation = orientation_param(p, cur.orientation); - let (ease0, color0) = match base.as_ref().map(|n| &n.kind) { - Some(NodeKind::Blend { spec, .. }) => (spec.ease, spec.color_shift), - _ => Default::default(), + let (ease0, color0, no_spine) = match base.as_ref().map(|n| &n.kind) { + Some(NodeKind::Blend { spec, .. }) => (spec.ease, spec.color_shift, spec.no_spine), + _ => (Default::default(), 0.0, !create_spine.creates_spine()), }; + if no_spine && gives_easing(p) { + return Err(bad(C, "the blend has no spine")); + } let ease = ease_param(p, C, ease0)?; let color_shift = percent_param(p, C, "colorShift", color0, -100.0)?; let id = s.edit("Make Blend", |d, sel| { @@ -91,7 +112,7 @@ pub(super) fn blend_make(s: &mut Session, p: &Value) -> Result<Value> { n.knockout = vectorcraft_doc::Knockout::On; n }); - let mut spec = BlendSpec { spacing, orientation, ease, color_shift, starts, ..Default::default() }; + let mut spec = BlendSpec { spacing, orientation, ease, color_shift, starts, no_spine, ..Default::default() }; if let NodeKind::Blend { children: old, spec: old_spec } = &n.kind { extend_spine(&mut spec, old, old_spec, &children); } @@ -303,7 +324,11 @@ pub(super) fn spine_remove_anchor(s: &mut Session, p: &Value) -> Result<Value> { if anchors.contains(&index) { return Err(bad(C, "a key object sits on that point")); } - if sp.anchors.len() <= 2 { + // A closed spine pinned open keeps a copy of its first point at its end (#6809), so the + // points left must be two apart, not only two in number. + let mut rest = sp.anchors.iter().enumerate().filter(|(i, _)| *i != index).map(|(_, a)| a.p); + let first = rest.next(); + if sp.anchors.len() <= 2 || first.is_none_or(|f| rest.all(|q| q.distance(f) < 0.01)) { return Err(bad(C, "a spine keeps at least two points")); } sp.anchors.remove(index); @@ -346,9 +371,12 @@ pub(super) fn blend_options(s: &mut Session, p: &Value) -> Result<Value> { // Nothing to set them on: the options new blends start with (easing is per blend). let d = s.prefs.blend_options.unwrap_or_default(); let spacing = spacing_param(p, C, d.spacing)?; - s.prefs.blend_options = Some(BlendDefaults { spacing, orientation: orientation_param(p, d.orientation) }); + s.prefs.blend_options = Some(BlendDefaults { spacing, orientation: orientation_param(p, d.orientation), ..d }); return Ok(json!({ "defaults": true })); }; + if gives_easing(p) && any_without_spine(s) { + return Err(bad(C, "the blend has no spine")); + } let spacing = spacing_param(p, C, cur.spacing)?; let orientation = orientation_param(p, cur.orientation); let ease = ease_param(p, C, cur.ease)?; @@ -361,6 +389,39 @@ pub(super) fn blend_options(s: &mut Session, p: &Value) -> Result<Value> { }) } +pub(super) fn blend_set_easing(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "object.blend.setEasing"; + let id = match crate::cmd::object_param(p, "id", C)? { + Some(id) => id, + None => *selected_of(s, is_blend).first().ok_or_else(|| bad(C, "select a blend or give `id`"))?, + }; + let doc = &s.doc()?.doc; + let Some(NodeKind::Blend { children, spec }) = doc.node(id).map(|n| &n.kind) else { return Err(bad(C, "not a blend")) }; + if !doc.is_editable(id) { + return Err(bad(C, "the object is hidden or locked")); + } + let ease = ease_param(p, C, spec.ease)?; + let color_shift = percent_param(p, C, "colorShift", spec.color_shift, -100.0)?; + // Easing moves the steps along a spine, so it needs one with a length to run along. + let easing = ["easingType", "ramp"].iter().any(|key| p.get(*key).is_some_and(|v| !v.is_null())); + let spined = spec.eases_along_spine() + && live::blend_spine(children, spec).and_then(|(path, _)| Spine::new(&path)).is_some_and(|sp| sp.length().is_finite() && sp.length() > 0.0); + if easing && !spined { + return Err(bad(C, "the blend has no spine")); + } + let changed = ease != spec.ease || color_shift != spec.color_shift; + if changed { + s.edit("Blend Options", |d, _| { + if let Some(NodeKind::Blend { spec, .. }) = d.node_mut(id).map(|n| &mut n.kind) { + spec.ease = ease; + spec.color_shift = color_shift; + } + Ok(()) + })?; + } + Ok(json!({ "id": id.0, "easingType": ease.kind.id(), "ramp": ease.ramp * 100.0, "colorShift": color_shift, "changed": changed })) +} + /// Spacing and orientation as `object.blend.options` takes them; the step count and distance /// not in use show their defaults. fn blend_options_json(spacing: BlendSpacing, orientation: BlendOrientation) -> Value { @@ -384,6 +445,7 @@ pub(super) fn blend_info(s: &mut Session, _: &Value) -> Result<Value> { v["colorShift"] = json!(spec.color_shift); v["starts"] = json!((0..keys.len()).map(|i| spec.start(i)).collect::<Vec<_>>()); v["keys"] = json!(keys.iter().map(|k| k.0).collect::<Vec<_>>()); + v["hasSpine"] = json!(!spec.no_spine); if let Some(NodeKind::Blend { children, .. }) = s.doc()?.doc.node(id).map(|n| &n.kind) && let Some((path, anchors)) = live::blend_spine(children, &spec) && let Some(sp) = path.subpaths.first() @@ -403,6 +465,19 @@ pub(super) fn blend_info(s: &mut Session, _: &Value) -> Result<Value> { }) } +/// The Blend panel's Create Spine: with `mode`, sets whether new blends get a spine; without, reads +/// it. A tool setting kept with the preferences, not an undo step; blends already made keep theirs. +pub(super) fn blend_create_spine(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "object.blend.createSpine"; + let mut d = s.prefs.blend_options.unwrap_or_default(); + let mode = spine_mode_param(p, C, "mode", d.create_spine)?; + if mode != d.create_spine { + d.create_spine = mode; + s.prefs.blend_options = Some(d); + } + Ok(json!({ "mode": mode.id() })) +} + pub(super) fn blend_expand(s: &mut Session, _: &Value) -> Result<Value> { let blends = selected_of(s, is_blend); let ids = s.edit("Expand Blend", |d, sel| { @@ -507,6 +582,8 @@ pub(super) fn blend_replace_spine(s: &mut Session, _: &Value) -> Result<Value> { let spine = d.node(path).and_then(|n| n.path_data().cloned()).ok_or(EngineError::NoNode(path))?; d.remove(path)?; if let Some(NodeKind::Blend { children, spec }) = d.node_mut(b).map(|n| &mut n.kind) { + // A blend made without a spine gets this one. + spec.no_spine = false; spec.spine = Some(spine); spec.key_anchors.clear(); keys_to_spine(children, spec); @@ -517,7 +594,16 @@ pub(super) fn blend_replace_spine(s: &mut Session, _: &Value) -> Result<Value> { ok() } +/// Is any selected blend one made without a spine? +fn any_without_spine(s: &Session) -> bool { + let Ok(st) = s.doc() else { return false }; + selected_of(s, is_blend).iter().any(|b| matches!(st.doc.node(*b).map(|n| &n.kind), Some(NodeKind::Blend { spec, .. }) if spec.no_spine)) +} + pub(super) fn blend_reverse_spine(s: &mut Session, _: &Value) -> Result<Value> { + if any_without_spine(s) { + return Err(bad("object.blend.reverseSpine", "the blend has no spine")); + } edit_blends(s, "Reverse Spine", |children, spec| { if spec.spine.is_some() && pin(children, spec) { // The keys keep their anchors, which now count from the other end. diff --git a/crates/engine/src/cmd/live/commands.rs b/crates/engine/src/cmd/live/commands.rs index b69b4e869d..692ce9e563 100644 --- a/crates/engine/src/cmd/live/commands.rs +++ b/crates/engine/src/cmd/live/commands.rs @@ -1,6 +1,6 @@ use super::blend::{ - blend_expand, blend_info, blend_make, blend_options, blend_release, blend_replace_spine, blend_reverse_spine, blend_reverse_stack, - spine_add_anchor, spine_convert_anchor, spine_move_anchor, spine_remove_anchor, spine_reshape_segment, + blend_create_spine, blend_expand, blend_info, blend_make, blend_options, blend_release, blend_replace_spine, blend_reverse_spine, + blend_reverse_stack, blend_set_easing, spine_add_anchor, spine_convert_anchor, spine_move_anchor, spine_remove_anchor, spine_reshape_segment, }; use super::common::{has_blend, has_envelope, has_mesh}; use super::envelope::{ @@ -18,7 +18,7 @@ pub fn specs() -> Vec<CommandSpec> { "Make", ["Object", "Blend"], Some("Cmd+Alt+B"), - "{ids?, steps?: n | distance?: pt | smooth?: bool, orientation?: page|path (default: the Blend Options set with nothing selected, else smooth colour and page), starts?: [anchor index | null, …] (per object of `ids`, else of the selection in paint order: the anchor of its first subpath the blend starts from; an open path's last anchor runs it the other way), spacing?: smooth|steps|distance (with value), value?: n, easingType?: easeIn|easeOut|easeInOut|easeOutIn, ramp?: pct (0..100), colorShift?: pct (-100..100; 0: even)} blend the selected objects (paint order) into a live blend; a blend among them takes the others in as more key objects (keeping its options, name and transparency) instead of nesting → {id}", + "{ids?, steps?: n | distance?: pt | smooth?: bool, orientation?: page|path (default: the Blend Options set with nothing selected, else smooth colour and page), starts?: [anchor index | null, …] (per object of `ids`, else of the selection in paint order: the anchor of its first subpath the blend starts from; an open path's last anchor runs it the other way), spacing?: smooth|steps|distance (with value), value?: n, easingType?: easeIn|easeOut|easeInOut|easeOutIn, ramp?: pct (0..100), colorShift?: pct (-100..100; 0: even), createSpine?: auto|always|never (default: the mode object.blend.createSpine sets; never: a blend without a spine, which takes no easing)} blend the selected objects (paint order) into a live blend; a blend among them takes the others in as more key objects (keeping its options, name, transparency and whether it has a spine) instead of nesting → {id}", has_doc, blend_make ), @@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> { "Release", ["Object", "Blend"], Some("Cmd+Alt+Shift+B"), - "{} release the selected blends: the key objects come back and the spine stays as a path with no fill or stroke, below them; a blend with a name, opacity, blend mode, isolation, opacity mask or appearance of its own comes back as a group keeping them (and its knockout) → {ids (the keys), spines: [ids], groups: [ids]}", + "{} release the selected blends: the key objects come back and the spine (if the blend has one) stays as a path with no fill or stroke, below them; a blend with a name, opacity, blend mode, isolation, opacity mask or appearance of its own comes back as a group keeping them (and its knockout) → {ids (the keys), spines: [ids], groups: [ids]}", has_blend, blend_release ), @@ -40,6 +40,24 @@ pub fn specs() -> Vec<CommandSpec> { always, blend_options ), + cmd!( + "object.blend.createSpine", + "Create Spine", + [], + None, + "{mode?: auto|always|never} the Blend panel's Create Spine: whether new blends get a spine (auto and always: the straight lines between the key centers, as before; never: no spine to show, edit, reverse or release, and no easing, until Replace Spine gives one); with no `mode`, reads it; blends already made keep theirs (a tool setting kept with the preferences, not an undo step) → {mode}", + always, + blend_create_spine + ), + cmd!( + "object.blend.setEasing", + "Blend Easing", + [], + None, + "{id? (default: the first selected blend), easingType?: easeIn|easeOut|easeInOut|easeOutIn, ramp?: pct (0..100), colorShift?: pct (-100..100)} set one blend's easing and color shift, as the blend widgets on the canvas do; omitted ones keep their value. easingType and ramp need a blend whose steps follow a spine (a replaced or edited spine, or Align to Path); a blend made without a spine takes them once Replace Spine has given it one; out of range, a hidden or locked blend and a blend with no spine are errors. A value that changes nothing records no undo step → {id, easingType, ramp, colorShift, changed}", + has_doc, + blend_set_easing + ), cmd!( "object.blend.expand", "Expand", @@ -54,7 +72,7 @@ pub fn specs() -> Vec<CommandSpec> { "Replace Spine", ["Object", "Blend"], None, - "{} use the selected path as the spine of the selected blend (the path is consumed)", + "{} use the selected path as the spine of the selected blend (the path is consumed); a blend made without a spine gets this one", has_blend, blend_replace_spine ), @@ -63,7 +81,7 @@ pub fn specs() -> Vec<CommandSpec> { "Reverse Spine", ["Object", "Blend"], None, - "{} reverse the order of the key objects along the spine", + "{} reverse the order of the key objects along the spine; an error when a selected blend has no spine", has_blend, blend_reverse_spine ), @@ -72,7 +90,7 @@ pub fn specs() -> Vec<CommandSpec> { "Blend Info", [], None, - "{} the options of the first selected blend, else those new blends start with → {target: blend|defaults, id?, spacing: smooth|steps|distance, steps, distance, orientation: page|path, easingType?: easeIn|easeOut|easeInOut|easeOutIn, ramp?: pct, colorShift?: pct, keys?: [ids], starts?: [anchor|null], spine?: {anchors: [{x, y, in: [x, y], out: [x, y]}], closed, keyAnchors: [anchor each key sits on] | null (keys spread evenly: a spine from Replace Spine), explicit: false for the straight lines between the key centres}}", + "{} the options of the first selected blend, else those new blends start with → {target: blend|defaults, id?, spacing: smooth|steps|distance, steps, distance, orientation: page|path, easingType?: easeIn|easeOut|easeInOut|easeOutIn, ramp?: pct, colorShift?: pct, keys?: [ids], starts?: [anchor|null], hasSpine?: false for a blend made without a spine (no `spine` then), spine?: {anchors: [{x, y, in: [x, y], out: [x, y]}], closed, keyAnchors: [anchor each key sits on] | null (keys spread evenly: a spine from Replace Spine), explicit: false for the straight lines between the key centres}}", always, blend_info ), @@ -136,7 +154,7 @@ pub fn specs() -> Vec<CommandSpec> { "Make with Warp…", ["Object", "Envelope Distort"], Some("Cmd+Alt+Shift+W"), - "{ids?, style?: arc|arcLower|arcUpper|arch|bulge|shellLower|shellUpper|flag|wave|fish|rise|fisheye|inflate|squeeze|twist (arc), bend?: % -100..100 (50), h?: horizontal distortion % -100..100 (0), v?: vertical distortion % (0), horizontal?: bool (true) | orientation?: horizontal|vertical, horizontalDistortion?: as h, verticalDistortion?: as v} envelope the selected objects with a warp (Envelope Options from object.envelope.options with nothing selected; type maps from its glyph outline bounds) → {id}", + "{ids?, style?: arc|arcLower|arcUpper|arch|bulge|shellLower|shellUpper|flag|wave|fish|rise|fisheye|inflate|squeeze|twist (arc), bend?: % -100..100 (50), h?: horizontal distortion % -100..100 (0), v?: vertical distortion % (0), horizontal?: bool (true) | orientation?: horizontal|vertical, horizontalDistortion?: as h, verticalDistortion?: as v, version?: 0|1 (1: each style bends the bounds as one Bézier patch; 0: VectorCraft's earlier map)} envelope the selected objects with a warp (Envelope Options from object.envelope.options with nothing selected; type maps from its glyph outline bounds) → {id}", has_selection, env_make_warp ), @@ -154,7 +172,7 @@ pub fn specs() -> Vec<CommandSpec> { "Make with Top Object", ["Object", "Envelope Distort"], Some("Cmd+Alt+C"), - "{ids?} the topmost selected path becomes the envelope of the others: its outline splits into four sides at its corners, and each piece of a side takes a share of the content in proportion to its control polygon's length (type maps from its glyph outline bounds) → {id}", + "{ids?} the topmost selected path becomes the envelope of the others: its outline splits into four sides at its corners, and each piece of a side takes a share of the content in proportion to its control polygon's length, and a side whose pieces are all one curve split at anchors follows that curve's parameter (type maps from its glyph outline bounds) → {id}", has_multi, env_make_top ), @@ -163,7 +181,7 @@ pub fn specs() -> Vec<CommandSpec> { "Reset with Warp…", ["Object", "Envelope Distort"], None, - "{style?, bend?, h?, v?, horizontal? | orientation? (as makeWithWarp; unset: the envelope's current warp, else arc 50 %), horizontalDistortion?: as h, verticalDistortion?: as v} make the selected envelopes warp envelopes, keeping their content", + "{style?, bend?, h?, v?, horizontal? | orientation? (as makeWithWarp; unset: the envelope's current warp, else arc 50 %), horizontalDistortion?: as h, verticalDistortion?: as v, version?: as makeWithWarp (unset: a warp envelope's own, else 1)} make the selected envelopes warp envelopes, keeping their content", has_envelope, env_reset_warp ), @@ -181,7 +199,7 @@ pub fn specs() -> Vec<CommandSpec> { "Envelope Info", [], None, - "{} the selected envelope's settings, or with none selected the defaults new envelopes get → {id: n|null, type: warp|mesh|topObject, style, bend, h, v, horizontal, rows, cols, fidelity, antiAlias, preserveShape: clippingMask|transparency, distortAppearance, distortLinearGradients, distortPatternFills, boundsMargin?: [top, bottom, left, right] (shares of the content's height and width, reported only when not zero: with distortAppearance, how far the box the content maps from reaches past its geometric bounds), editing}", + "{} the selected envelope's settings, or with none selected the defaults new envelopes get → {id: n|null, type: warp|mesh|topObject, style, bend, h, v, horizontal, version (a warp's map: 1, each style as one Bézier patch; 0, the earlier map), rows, cols, fidelity, antiAlias, preserveShape: clippingMask|transparency, distortAppearance, distortLinearGradients, distortPatternFills, boundsMargin?: [top, bottom, left, right] (shares of the content's height and width, reported only when not zero: with distortAppearance, how far the box the content maps from reaches past its geometric bounds), editing}", has_doc, env_info ), @@ -199,7 +217,7 @@ pub fn specs() -> Vec<CommandSpec> { "Envelope Options…", ["Object", "Envelope Distort"], None, - "{fidelity?: 0..100, antiAlias?: bool, preserveShape?: clippingMask|transparency, distortAppearance?: bool, distortLinearGradients?: bool, distortPatternFills?: bool (the last two work with distortAppearance; on an envelope with boundsMargin, distortAppearance also switches the content between the box with the margins and its geometric box), style?, bend?, h?, v?, horizontal? (warp envelopes), horizontalDistortion?: as h, verticalDistortion?: as v, orientation?: horizontal|vertical} set the selected envelopes' options; with no envelope selected, the options new envelopes get (see object.envelope.info)", + "{fidelity?: 0..100, antiAlias?: bool, preserveShape?: clippingMask|transparency, distortAppearance?: bool, distortLinearGradients?: bool, distortPatternFills?: bool (the last two work with distortAppearance; on an envelope with boundsMargin, distortAppearance also switches the content between the box with the margins and its geometric box), style?, bend?, h?, v?, horizontal? (warp envelopes), horizontalDistortion?: as h, verticalDistortion?: as v, orientation?: horizontal|vertical, version?: 0|1 (warp envelopes' map, as makeWithWarp)} set the selected envelopes' options; with no envelope selected, the options new envelopes get (see object.envelope.info)", has_doc, env_options ), @@ -226,7 +244,7 @@ pub fn specs() -> Vec<CommandSpec> { "Move Envelope Mesh Point", [], None, - "{id, index, x, y, handle?: 0 right|1 left|2 down|3 up} move a point of a mesh envelope (its handles follow), or with `handle` place that handle end at (x, y); object.mesh.movePoint, addLine and deletePoint edit mesh envelopes too", + "{id, index, x, y, handle?: 0 right|1 left|2 down|3 up} move a point of a mesh or warp envelope (its handles follow), or with `handle` place that handle end at (x, y); a warp's points are those of its grid (4×4 patches, or 8×8 or 16×16 where 4×4 draws more than 0.1% of its diagonal away from the warp), and its first edit makes it a mesh envelope on that grid in the same undo step (a warp no such grid follows is refused: Reset with Mesh first); object.mesh.movePoint, movePoints, addLine and deletePoint edit mesh and warp envelopes too", has_doc, env_set_mesh_point ), @@ -245,7 +263,7 @@ pub fn specs() -> Vec<CommandSpec> { "Set Mesh Point Color", [], None, - "{id, index | points: [index…] | items: [{id, index | points}…], color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1} colour and/or opacity of gradient mesh points (one undo step; an index out of range changes nothing)", + "{id, index | points: [index…] | items: [{id, index | points}…], color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1} colour and/or opacity of gradient mesh points (one undo step; an index out of range changes nothing, and so does a call that changes no point, with no undo step)", has_doc, mesh_set_color ), @@ -254,7 +272,7 @@ pub fn specs() -> Vec<CommandSpec> { "Move Mesh Point", [], None, - "{id, index, x, y, handle?: 0 right|1 left|2 down|3 up} move a point of a gradient mesh or mesh envelope (its handles follow), or with `handle` place that handle end at (x, y)", + "{id, index, x, y, handle?: 0 right|1 left|2 down|3 up} move a point of a gradient mesh or a mesh or warp envelope (its handles follow; a warp becomes a mesh envelope, see object.envelope.setMeshPoint), or with `handle` place that handle end at (x, y)", has_doc, mesh_move_point ), @@ -263,7 +281,7 @@ pub fn specs() -> Vec<CommandSpec> { "Move Mesh Points", [], None, - "{id, points: [index…] | items: [{id, index | points}…], dx, dy} move points of gradient meshes or mesh envelopes by (dx, dy), their handles with them (one undo step; an index out of range changes nothing)", + "{id, points: [index…] | items: [{id, index | points}…], dx, dy} move points of gradient meshes or mesh or warp envelopes by (dx, dy), their handles with them (warps become mesh envelopes, see object.envelope.setMeshPoint; one undo step; an index out of range changes nothing, and so does a call that moves no point, with no undo step)", has_doc, mesh_move_points ), @@ -272,7 +290,7 @@ pub fn specs() -> Vec<CommandSpec> { "Add Mesh Line", [], None, - "{id, x, y, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), tolerance?: pt (0)} add a row and a column through (x, y) to a gradient mesh (new point in `color`) or a mesh envelope; a point outside within `tolerance` of the edge adds them through the nearest point of the edge → {index}", + "{id, x, y, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), tolerance?: pt (0)} add a row and a column through (x, y), inside or on the edge, to a gradient mesh (new point in `color`) or a mesh or warp envelope (a warp becomes a mesh envelope, see object.envelope.setMeshPoint); a point outside within `tolerance` of the edge adds them through the nearest point of the edge; at a point that is already a mesh point it adds no line, and records no undo step unless `color` changes a gradient mesh's point (an envelope's points have no color) → {index}", has_doc, mesh_add_line ), @@ -281,7 +299,7 @@ pub fn specs() -> Vec<CommandSpec> { "Delete Mesh Point", [], None, - "{id, index} delete the mesh lines through a point of a gradient mesh or mesh envelope", + "{id, index} delete the mesh lines through a point of a gradient mesh or a mesh or warp envelope (a warp becomes a mesh envelope, see object.envelope.setMeshPoint)", has_doc, mesh_delete_point ), diff --git a/crates/engine/src/cmd/live/envelope.rs b/crates/engine/src/cmd/live/envelope.rs index 1aceb49b54..5357ea51c0 100644 --- a/crates/engine/src/cmd/live/envelope.rs +++ b/crates/engine/src/cmd/live/envelope.rs @@ -1,9 +1,9 @@ use super::super::object::choice; use super::common::{fix_ids, ids_json, is_envelope, roots_param, selected_of, wrap}; -use super::mesh::{handle_param, index_param, whole}; +use super::mesh::{envelope_edit_grid, handle_param, index_param, mesh_envelope, warp_point_stays, whole}; use super::{ Affine, Appearance, Arc, Beside, Color, Document, EngineError, EnvelopeKind, EnvelopeMap, EnvelopeOptions, Node, NodeId, NodeKind, Paint, - PathData, Point, PreserveShape, Result, Session, Value, bad, check_numbers, f64_or, f64_req, id_param, json, live, ok, switch_or, text_param, + PathData, Point, PreserveShape, Result, Session, Value, bad, check_numbers, f64_or, f64_req, json, live, object_param, ok, switch_or, text_param, }; // ---------- Envelope ---------- @@ -13,9 +13,14 @@ const WARP_NUMBERS: &[&str] = &["bend", "h", "v", "horizontalDistortion", "verti fn warp_kind(p: &Value, cmd: &str, cur: Option<&EnvelopeKind>) -> Result<EnvelopeKind> { check_numbers(p, WARP_NUMBERS, cmd)?; - let (mut style, mut bend, mut h, mut v, mut horizontal) = ("arc".to_string(), 50.0, 0.0, 0.0, true); - if let Some(EnvelopeKind::Warp { style: s0, bend: b0, h: h0, v: v0, horizontal: z0 }) = cur { - (style, bend, h, v, horizontal) = (s0.clone(), *b0, *h0, *v0, *z0); + // A new warp takes its style's Bézier net; an edited one keeps the map it has unless `version` + // names one. + let (mut style, mut bend, mut h, mut v, mut horizontal, mut version) = ("arc".to_string(), 50.0, 0.0, 0.0, true, live::WARP_NET); + if let Some(EnvelopeKind::Warp { style: s0, bend: b0, h: h0, v: v0, horizontal: z0, version: n0 }) = cur { + (style, bend, h, v, horizontal, version) = (s0.clone(), *b0, *h0, *v0, *z0, *n0); + } + if let Some(n) = p.get("version") { + version = live::warp_version(n).ok_or_else(|| bad(cmd, format!("`version` must be 0 or {}", live::WARP_NET)))?; } if let Some(s) = text_param(p, "style", cmd)? { let s = s.strip_prefix("warp.").unwrap_or(s); @@ -32,7 +37,7 @@ fn warp_kind(p: &Value, cmd: &str, cur: Option<&EnvelopeKind>) -> Result<Envelop Some(o) => o == "horizontal", None => given, }; - Ok(EnvelopeKind::Warp { style, bend, h, v, horizontal }) + Ok(EnvelopeKind::Warp { style, bend, h, v, horizontal, version }) } /// The options and fidelity new envelopes get (Envelope Options with no envelope selected). @@ -74,8 +79,7 @@ fn mesh_kind(map: &EnvelopeMap, maintain: bool, rows: u32, cols: u32) -> Envelop return EnvelopeKind::Mesh { rows, cols, points: map.grid(rows, cols), handles: vec![] }; } // The surface's points with handles along it: the grid lines keep the current shape. - let m = map.surface_mesh(rows, cols, Color::BLACK); - EnvelopeKind::Mesh { rows, cols, points: m.points.iter().map(|q| q.p).collect(), handles: m.points.iter().map(|q| q.handles).collect() } + mesh_envelope(&map.surface_mesh(rows, cols, Color::BLACK)) } pub(super) fn env_make_mesh(s: &mut Session, p: &Value) -> Result<Value> { @@ -206,8 +210,8 @@ pub(super) fn env_info(s: &mut Session, _: &Value) -> Result<Value> { return Ok(envelope_options_json(json!({ "id": null }), &options, fidelity)); }; let v = match &**kind { - EnvelopeKind::Warp { style, bend, h, v, horizontal } => { - json!({"type": "warp", "style": style, "bend": bend, "h": h, "v": v, "horizontal": horizontal}) + EnvelopeKind::Warp { style, bend, h, v, horizontal, version } => { + json!({"type": "warp", "style": style, "bend": bend, "h": h, "v": v, "horizontal": horizontal, "version": version}) } EnvelopeKind::Mesh { rows, cols, .. } => json!({"type": "mesh", "rows": rows, "cols": cols}), EnvelopeKind::TopObject { .. } => json!({"type": "topObject"}), @@ -419,11 +423,24 @@ pub(super) fn env_edit_contents(s: &mut Session, p: &Value) -> Result<Value> { pub(super) fn env_set_mesh_point(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "object.envelope.setMeshPoint"; - let id = id_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?; let index = index_param(p, "index", C)?; let q = Point::new(f64_req(p, "x", C)?, f64_req(p, "y", C)?); let handle = handle_param(p, C)?; + // A warp whose point or handle stays where it is stays a warp. + if warp_point_stays(&s.doc()?.doc, id, index, handle, q, C)? { + return ok(); + } s.edit("Move Envelope Point", |d, _| { + // A warp's first edited point makes it a mesh envelope on its grid, in the same step. + if let Some(n) = d.node(id) + && matches!(&n.kind, NodeKind::Envelope { kind, .. } if matches!(**kind, EnvelopeKind::Warp { .. })) + { + let grid = envelope_edit_grid(n, C).ok_or_else(|| bad(C, "not a mesh envelope point"))??; + if let Some(NodeKind::Envelope { kind, .. }) = d.node_mut(id).map(|n| &mut n.kind) { + **kind = mesh_envelope(&grid); + } + } let Some(NodeKind::Envelope { kind, .. }) = d.node_mut(id).map(|n| &mut n.kind) else { return Err(bad(C, "not a mesh envelope point")); }; diff --git a/crates/engine/src/cmd/live/mesh.rs b/crates/engine/src/cmd/live/mesh.rs index 70c2d9f348..97b6160718 100644 --- a/crates/engine/src/cmd/live/mesh.rs +++ b/crates/engine/src/cmd/live/mesh.rs @@ -4,7 +4,7 @@ use super::common::{fix_ids, ids_json, is_mesh, replace_with, roots_param, selec use super::envelope::{outline_of, rows_cols}; use super::{ Color, Document, EngineError, EnvelopeKind, GradientMesh, MeshAppearance, Node, NodeId, NodeKind, Paint, Point, Result, Session, Value, bad, - check_numbers, color_param, f64_or, f64_req, finite_numbers, gradient_sampler, id_param, json, live, ok, str_param, + check_numbers, color_param, f64_or, f64_req, finite_numbers, gradient_sampler, json, live, object_param, ok, str_param, }; // ---------- Gradient mesh ---------- @@ -115,31 +115,94 @@ fn image_mesh(d: &Document, im: &vectorcraft_doc::ImageObject, rows: u32, cols: /// Run `f` on the gradient mesh `p.id` (one undo step `label`); with `envelopes`, a mesh /// envelope's grid too (see [`edit_grid`]). fn with_mesh<T>(s: &mut Session, p: &Value, cmd: &str, label: &str, envelopes: bool, f: impl FnOnce(&mut GradientMesh) -> Result<T>) -> Result<T> { - let id = id_param(p, "id").ok_or_else(|| bad(cmd, "missing `id`"))?; + let id = object_param(p, "id", cmd)?.ok_or_else(|| bad(cmd, "missing `id`"))?; s.edit(label, move |d, _| edit_grid(d, id, cmd, envelopes, f)) } -/// Run `f` on the gradient mesh `id` of `d`; with `envelopes`, a mesh envelope's grid too (its -/// points and handles are written back: editing fills in the handles). -fn edit_grid<T>(d: &mut Document, id: NodeId, cmd: &str, envelopes: bool, f: impl FnOnce(&mut GradientMesh) -> Result<T>) -> Result<T> { - match d.node_mut(id).map(|n| &mut n.kind) { - Some(NodeKind::Mesh(m)) => f(m), - Some(NodeKind::Envelope { kind, .. }) if envelopes && matches!(**kind, EnvelopeKind::Mesh { .. }) => { - let EnvelopeKind::Mesh { rows, cols, points, handles } = &mut **kind else { - return Err(bad(cmd, "not a gradient mesh or mesh envelope")); - }; - let mut m = live::envelope_grid(*rows, *cols, points, handles).ok_or_else(|| bad(cmd, "the envelope's mesh is malformed"))?; - let r = f(&mut m)?; - (*rows, *cols) = (m.rows, m.cols); - *points = m.points.iter().map(|q| q.p).collect(); - *handles = m.points.iter().map(|q| q.handles).collect(); - Ok(r) +/// The grid an edit of envelope `n`'s points starts from: a mesh envelope's own grid, or a warp's +/// grid ([`live::warp_grid`]), which the edit turns into a mesh envelope. `None` for other nodes. +pub(super) fn envelope_edit_grid(n: &Node, cmd: &str) -> Option<Result<GradientMesh>> { + let NodeKind::Envelope { kind, .. } = &n.kind else { return None }; + match &**kind { + EnvelopeKind::Mesh { rows, cols, points, handles } => { + Some(live::envelope_grid(*rows, *cols, points, handles).ok_or_else(|| bad(cmd, "the envelope's mesh is malformed"))) } - Some(_) => Err(bad(cmd, if envelopes { "not a gradient mesh or mesh envelope" } else { "not a gradient mesh" })), + EnvelopeKind::Warp { .. } => { + Some(live::warp_grid(n).ok_or_else(|| bad(cmd, "this warp's points can't be edited: use Reset with Mesh first"))) + } + EnvelopeKind::TopObject { .. } => None, + } +} + +/// The mesh envelope kind of grid `m`, with its points' handles. +pub(super) fn mesh_envelope(m: &GradientMesh) -> EnvelopeKind { + EnvelopeKind::Mesh { + rows: m.rows, + cols: m.cols, + points: m.points.iter().map(|q| q.p).collect(), + handles: m.points.iter().map(|q| q.handles).collect(), + } +} + +/// Does placing point `index` of warp envelope `id` of `d`, or that point's `handle` end, at `q` +/// leave it where it is? Such a placement is no edit. `false` for other objects and for an index +/// out of range, whose edits run as before. +pub(super) fn warp_point_stays(d: &Document, id: NodeId, index: usize, handle: Option<usize>, q: Point, cmd: &str) -> Result<bool> { + let Some(n) = d.node(id).filter(|n| matches!(&n.kind, NodeKind::Envelope { kind, .. } if matches!(**kind, EnvelopeKind::Warp { .. }))) else { + return Ok(false); + }; + let grid = envelope_grid_to_edit(n, cmd, true)?; + Ok(grid.points.get(index).is_some_and(|pt| match handle { + // The caller sends a handle's end as point plus handle; `q - p` can round away from it. + Some(h) => pt.handles.get(h).is_some_and(|v| pt.p + *v == q), + None => pt.p == q, + })) +} + +/// The grid of envelope `n` that [`edit_grid`] edits (only `envelopes`), or the error it fails with. +fn envelope_grid_to_edit(n: &Node, cmd: &str, envelopes: bool) -> Result<GradientMesh> { + match envelope_edit_grid(n, cmd).filter(|_| envelopes) { + Some(grid) => grid, + None => Err(bad(cmd, if envelopes { "not a gradient mesh or mesh envelope" } else { "not a gradient mesh" })), + } +} + +/// The grid of mesh `id` of `d` that [`edit_grid`] edits, as it is now. +fn grid_to_edit(d: &Document, id: NodeId, cmd: &str, envelopes: bool) -> Result<GradientMesh> { + match d.node(id) { + Some(Node { kind: NodeKind::Mesh(m), .. }) => Ok(m.clone()), + Some(n) => envelope_grid_to_edit(n, cmd, envelopes), None => Err(EngineError::NoNode(id)), } } +/// Run `f` on the gradient mesh `id` of `d`; with `envelopes`, a warp or mesh envelope's grid too +/// (see [`edit_node`]). +fn edit_grid<T>(d: &mut Document, id: NodeId, cmd: &str, envelopes: bool, f: impl FnOnce(&mut GradientMesh) -> Result<T>) -> Result<T> { + edit_node(d.node_mut(id).ok_or(EngineError::NoNode(id))?, cmd, envelopes, f) +} + +/// [`edit_grid`] on a node: with `envelopes`, a warp or mesh envelope's grid +/// ([`envelope_edit_grid`]) is edited too, and its points and handles are written back as a mesh +/// envelope (editing fills in the handles, and makes a warp a mesh envelope). +fn edit_node<T>(n: &mut Node, cmd: &str, envelopes: bool, f: impl FnOnce(&mut GradientMesh) -> Result<T>) -> Result<T> { + if let NodeKind::Mesh(m) = &mut n.kind { + return f(m); + } + let start = envelope_grid_to_edit(n, cmd, envelopes)?; + let mut m = start.clone(); + let r = f(&mut m)?; + // A warp stays a warp when the edit changed nothing. + let warp = matches!(&n.kind, NodeKind::Envelope { kind, .. } if matches!(**kind, EnvelopeKind::Warp { .. })); + if warp && m == start { + return Ok(r); + } + if let NodeKind::Envelope { kind, .. } = &mut n.kind { + **kind = mesh_envelope(&m); + } + Ok(r) +} + /// Most mesh points one command names, over all its meshes. const MAX_POINTS: usize = 1 << 20; @@ -147,7 +210,7 @@ const MAX_POINTS: usize = 1 << 20; /// points}…]}`. Each mesh comes once, with its points in order and without repeats. fn point_items(p: &Value, cmd: &str) -> Result<Vec<(NodeId, BTreeSet<usize>)>> { let one = |q: &Value| -> Result<(NodeId, BTreeSet<usize>)> { - let id = id_param(q, "id").ok_or_else(|| bad(cmd, "missing `id`"))?; + let id = object_param(q, "id", cmd)?.ok_or_else(|| bad(cmd, "missing `id`"))?; let points = match q.get("points") { None | Some(Value::Null) => BTreeSet::from([index_param(q, "index", cmd)?]), Some(Value::Array(v)) if v.len() <= MAX_POINTS => v @@ -174,7 +237,8 @@ fn point_items(p: &Value, cmd: &str) -> Result<Vec<(NodeId, BTreeSet<usize>)>> { } /// Run `f` on each mesh point `items` names, as one undo step `label` (an index out of range -/// fails it, changing nothing); with `envelopes`, on mesh envelopes' points too. +/// fails it, changing nothing); with `envelopes`, on warp and mesh envelopes' points too. When `f` +/// changes no point, nothing changes and no undo step is recorded. fn with_points( s: &mut Session, items: &[(NodeId, BTreeSet<usize>)], @@ -183,6 +247,20 @@ fn with_points( envelopes: bool, mut f: impl FnMut(&mut live::MeshPoint) -> Result<()>, ) -> Result<()> { + let doc = &s.doc()?.doc; + let mut changes = false; + for (id, points) in items { + let mut m = grid_to_edit(doc, *id, cmd, envelopes)?; + for i in points { + let q = m.points.get_mut(*i).ok_or_else(|| bad(cmd, "index out of range"))?; + let before = q.clone(); + f(q)?; + changes |= *q != before; + } + } + if !changes { + return Ok(()); + } s.edit(label, |d, _| { for (id, points) in items { edit_grid(d, *id, cmd, envelopes, |m| { @@ -251,6 +329,10 @@ pub(super) fn mesh_move_point(s: &mut Session, p: &Value) -> Result<Value> { let index = index_param(p, "index", C)?; let q = Point::new(f64_req(p, "x", C)?, f64_req(p, "y", C)?); let handle = handle_param(p, C)?; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?; + if warp_point_stays(&s.doc()?.doc, id, index, handle, q, C)? { + return ok(); + } with_mesh(s, p, C, "Move Mesh Point", true, |m| { let pt = m.points.get_mut(index).ok_or_else(|| bad(C, "index out of range"))?; match handle { @@ -281,12 +363,41 @@ pub(super) fn mesh_add_line(s: &mut Session, p: &Value) -> Result<Value> { check_numbers(p, &["tolerance"], C)?; let tol = f64_or(p, "tolerance", 0.0).max(0.0); let color = color_param(p, "color", C)?.map(|c| crate::cmd::paint::new_color(s, p, c)); - let index = with_mesh(s, p, C, "Add Mesh Line", true, |m| { + let add = move |m: &mut GradientMesh| { let i = m.add_lines_at(q, tol).ok_or_else(|| bad(C, "point is outside the mesh"))?; if let Some(c) = color { m.points[i].color = c; } Ok(i) + }; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?; + if s.script_running() { + return Err(EngineError::Busy); + } + // The lines are added to a copy of the object. A point that is already a mesh point adds none: + // when its color stays too, nothing changes and no undo step is recorded. The grid is compared, + // not the node: a mesh envelope stored without handles takes them in any edit, a warp becomes + // a mesh envelope, and neither keeps colors, so only their points and handles count. + let orig = s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?.clone(); + let colored = matches!(orig.kind, NodeKind::Mesh(_)); + let mut node = orig.clone(); + let (i, same) = edit_node(&mut node, C, true, |m| { + let before = m.clone(); + let i = add(m)?; + let shape = |g: &GradientMesh| (g.rows, g.cols, g.points.iter().map(|q| (q.p, q.handles)).collect::<Vec<_>>()); + Ok((i, if colored { *m == before } else { shape(m) == shape(&before) })) + })?; + if same { + return Ok(json!({ "index": i })); + } + let index = s.edit("Add Mesh Line", move |d, _| { + let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?; + // Settling typed values before the edit may have changed the object: add the lines again. + if n.kind != orig.kind { + return edit_node(n, C, true, add); + } + n.kind = node.kind; + Ok(i) })?; Ok(json!({ "index": index })) } diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index 8ea016db65..1ab0e0b670 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -115,7 +115,7 @@ pub fn specs() -> Vec<CommandSpec> { "Rasterize…", ["Object"], None, - "{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline)} replace the selection with an embedded image (PNG; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; an image larger than 64 Mpx or 32,768 px a side is refused; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}", + "{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline)} replace the selection with an embedded image (PNG; grayscale makes a gray PNG, and bitmap a 1-bit TIFF or, where it has transparency, a black-and-white gray PNG with alpha; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; an image larger than 64 Mpx or 32,768 px a side is refused; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}", has_selection, rasterize ), @@ -729,7 +729,9 @@ fn cmyk_raster( /// The image Object › Rasterize makes of some art, before it goes in a document /// ([`rasterize_art`]). pub(crate) struct Rasterized { - /// A PNG, or a CMYK image of the art's inks ([`cmyk_raster`]). + /// A PNG (greyscale for the Grayscale colour model), a 1-bit TIFF or greyscale PNG for Bitmap + /// ([`vectorcraft_render::Rendered::to_bilevel`]), or a CMYK image of the art's inks + /// ([`cmyk_raster`]). blob: vectorcraft_doc::ImageBlob, /// A CMYK image's transparency, a greyscale PNG: it becomes the image's opacity mask. alpha: Option<Vec<u8>>, @@ -769,7 +771,8 @@ impl Rasterized { /// Object › Rasterize's image of `nodes` (drawn also where hidden) with the params `p` of command /// `cmd`, each defaulting to `doc`'s raster effects settings: over the bounds of what the art draws /// ([`vectorcraft_render::drawn_bounds`]) and the room around them, in whole pixels. With `inks`, -/// a CMYK document's colour model makes a CMYK image ([`cmyk_raster`]); otherwise images are PNGs. +/// a CMYK document's colour model makes a CMYK image ([`cmyk_raster`]); otherwise images are PNGs, +/// greyscale for the Grayscale and Bitmap colour models (an opaque Bitmap image is a 1-bit TIFF). pub(crate) fn rasterize_art(doc: &vectorcraft_doc::Document, nodes: Vec<Node>, p: &Value, cmd: &str, inks: bool) -> Result<Rasterized> { check_numbers(p, &["ppi"], cmd)?; let ppi = f64_or(p, "ppi", doc.raster_effects_ppi); @@ -836,10 +839,17 @@ pub(crate) fn rasterize_art(doc: &vectorcraft_doc::Document, nodes: Vec<Node>, p let tmp = isolated_doc(doc, nodes); let opts = raster.render_options(RasterFormat::Png); let (img, warning) = render_pixels(&tmp, region, scale, &opts, look.color_model)?; - let (blob, alpha) = if inks && doc.color_mode == vectorcraft_doc::ColorMode::Cmyk && look.color_model == RasterColorModel::Document { - cmyk_raster(&tmp, region, scale, &opts, &img)? - } else { - (vectorcraft_doc::ImageBlob::new("image/png", img.to_png().map_err(EngineError::Other)?), None) + let png = + |bytes: std::result::Result<Vec<u8>, String>| bytes.map(|b| vectorcraft_doc::ImageBlob::new("image/png", b)).map_err(EngineError::Other); + let (blob, alpha) = match look.color_model { + RasterColorModel::Document if inks && doc.color_mode == vectorcraft_doc::ColorMode::Cmyk => cmyk_raster(&tmp, region, scale, &opts, &img)?, + RasterColorModel::Document => (png(img.to_png())?, None), + // Grayscale images, as the colour models say (#6969). + RasterColorModel::Grayscale => (png(img.to_gray_png())?, None), + RasterColorModel::Bitmap => { + let (mime, bytes) = img.to_bilevel(ppi).map_err(EngineError::Other)?; + (vectorcraft_doc::ImageBlob::new(mime, bytes), None) + } }; let xf = Affine::translate(region.origin().to_vec2()) * Affine::scale(1.0 / scale); Ok(Rasterized { blob, alpha, width: img.width, height: img.height, xf, clip, warning }) @@ -871,7 +881,7 @@ fn rasterize(s: &mut Session, p: &Value) -> Result<Value> { Ok(out) } -fn has_image(s: &Session) -> std::result::Result<(), String> { +pub(crate) fn has_image(s: &Session) -> std::result::Result<(), String> { has_selection(s)?; let st = s.active().ok_or("no document open")?; if st.selection.objects.iter().any(|id| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Image(_)))) { @@ -1043,6 +1053,11 @@ fn crop_image(s: &mut Session, p: &Value) -> Result<Value> { bare.blend = Default::default(); bare.appearance = Appearance::default().into(); bare.visible = true; + // The image's own pixels are cut, not the masked ones a color mask shows: the mask is made + // again for the cut pixels after the edit. + if let Some(e) = bare.extras_if_any() { + e.color_mask = None; + } let tmp = isolated_doc(&st.doc, vec![bare]); let region = Rect::new(r.x0, r.y0, r.x0 + (r.width() * scale).round().max(1.0) / scale, r.y0 + (r.height() * scale).round().max(1.0) / scale); let (png, w, h, warning) = @@ -1306,13 +1321,16 @@ fn convert_to_artboards(s: &mut Session, _: &Value) -> Result<Value> { let symbols = d.symbol_boxes(); let boxes: Vec<(NodeId, Rect)> = roots.iter().filter_map(|id| Some((*id, d.node(*id)?.geometric_bounds_with(&symbols)?))).collect(); let mut converted = vec![]; + // The highest artboard id the document has, kept up to date as artboards are added. + let mut top = d.artboards.iter().map(|a| a.id).max(); for (id, b) in boxes { if b.width() <= 0.0 || b.height() <= 0.0 { continue; } // Named one past the highest artboard id the document has, whatever id it is given. - let number = d.artboards.iter().map(|a| a.id).max().map_or(1, |m| m.saturating_add(1)); - let aid = d.next_artboard_id(); + let number = top.map_or(1, |m| m.saturating_add(1)); + let aid = d.next_artboard_id_above(top); + top = top.max(Some(aid)); d.artboards.push(vectorcraft_doc::Artboard { id: aid, name: format!("Artboard {number}"), diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 20dc187ab5..2a8d074617 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -1,13 +1,24 @@ //! File → New: the settings `file.new` takes, the New Document presets (generated in code, by //! category), the user's saved presets and the recently used sizes (both kept in the //! preferences), and the artboard grid layout shared with Rearrange All Artboards. +//! +//! New Document profiles: each built-in category has a profile, a native document in the +//! `New Document Profiles` folder next to the preferences ([`Session::attach_new_doc_profiles`]). +//! `file.new` starts a document of that category with the profile's swatches, graphic styles, +//! brushes, symbols, character and paragraph styles, rulers, document setup and print settings +//! ([`DocSettings::document_from_profile`]). The grid stays that of Preferences › Guides & Grid, +//! which applies to every open document. A category without a profile file starts with the +//! defaults, and a profile that can't be read leaves them in place and is reported in `file.new`'s +//! result. + +use std::sync::Arc; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; -use vectorcraft_doc::{Artboard, Background, ColorMode, Document, Unit}; +use vectorcraft_doc::{Artboard, Background, ColorMode, Document, LayerColor, Node, Unit}; use vectorcraft_geom::{Point, Rect}; -use super::{CommandSpec, Result, Session, always, bad, clock_date, cmd, date_param, str_param}; +use super::{CommandSpec, Result, Session, always, bad, clock_date, cmd, date_param, str_param, switch_or}; pub fn specs() -> Vec<CommandSpec> { vec![ @@ -16,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> { "New Document Presets", [], None, - "{category?: \"Recent\"|\"Saved\"|\"Mobile\"|\"Web\"|\"Print\"|\"Film & Video\"|\"Art & Illustration\"|\"Branding\"|\"Social\"} the New Document presets by category (Recent: the last sizes used; Saved: the user's presets) → {categories: [{name, presets: [{name, size: \"1920 × 1080 px\", width: pt, height: pt, units, orientation, artboards, artboardLayout: {layout, columns, spacing, rightToLeft}, bleed, backgroundContents, colorMode, rasterEffectsPpi, previewMode}]}]}; file.new {preset: name} starts from one", + "{category?: \"Recent\"|\"Saved\"|\"Mobile\"|\"Web\"|\"Print\"|\"Film & Video\"|\"Art & Illustration\"|\"Branding\"|\"Social\"} the New Document presets by category (Recent: the last sizes used; Saved: the user's presets) → {categories: [{name, presets: [{name, size: \"1920 × 1080 px\", width: pt, height: pt, units, orientation, artboards, artboardLayout: {layout, columns, spacing, rightToLeft}, bleed, backgroundContents, colorMode, rasterEffectsPpi, previewMode, alignNewObjectsToPixelGrid (on in the Mobile and Web presets)}]}]}; file.new {preset: name} starts from one", always, list ), @@ -38,6 +49,33 @@ pub fn specs() -> Vec<CommandSpec> { |s| if s.prefs.new_doc_presets.is_empty() { Err("no saved presets".into()) } else { Ok(()) }, delete ), + cmd!( + query "file.newProfiles", + "New Document Profiles", + [], + None, + "{} the New Document profiles, one per built-in category of file.newPresets: native documents in the New Document Profiles folder next to the preferences, whose swatches, swatch groups, graphic styles, brushes, symbols, patterns, character and paragraph styles, composite fonts, SVG filters, graph designs, ruler origin and mode, transparency grid, document setup (other than bleed, background and Align New Objects to Pixel Grid), assigned color profiles, Document Raster Effects Settings (other than the resolution) and print settings a new document of that category starts with → {profiles: [{name, customized?: a profile file exists (else the shipped profile, today's defaults, applies), path?; both left out for a request that may not read the folder}], folder?: the folder (none in runs without preferences and on the web)}", + always, + list_profiles + ), + cmd!( + "file.newProfiles.edit", + "Edit Profile", + [], + None, + "{name: a category of file.newPresets} open the category's New Document profile as a document to edit (File › Save keeps the changes for the next file.new); a category without a profile file gets the shipped profile written first; under automation roots it needs write and read access to the file, and an error names the file by its file name outside the read roots → document.open's result", + always, + edit_profile + ), + cmd!( + "file.newProfiles.reset", + "Reset Profile", + [], + None, + "{name: a category of file.newPresets} delete the category's profile file, so the shipped profile (today's defaults) applies again; an open copy of it stays open; under automation roots it needs write access to the file, and an error names the file by its file name outside the read roots → {name, reset: whether a file was deleted}", + always, + reset_profile + ), ] } @@ -144,6 +182,15 @@ pub struct DocSettings { #[serde(deserialize_with = "de_ppi")] pub raster_effects_ppi: f64, pub preview_mode: PreviewMode, + /// Align New Objects to Pixel Grid ([`vectorcraft_doc::DocSetup::align_new_objects_to_pixel_grid`]): + /// on in the Mobile and Web presets, off in the others and in a saved or Recent preset from + /// before it. + pub align_new_objects_to_pixel_grid: bool, + /// The New Document profile the document starts from (a built-in category's name): the + /// category of a built-in preset, kept by the saved and Recent presets made from it; `None`: + /// the defaults. + #[serde(skip_serializing_if = "Option::is_none")] + pub profile: Option<String>, } impl Default for DocSettings { @@ -163,6 +210,8 @@ impl Default for DocSettings { color_mode: ColorMode::Rgb, raster_effects_ppi: 72.0, preview_mode: PreviewMode::Default, + align_new_objects_to_pixel_grid: false, + profile: None, } } } @@ -211,6 +260,8 @@ impl DocSettings { "colorMode": color_mode_id(self.color_mode), "rasterEffectsPpi": self.raster_effects_ppi, "previewMode": self.preview_mode.id(), + "alignNewObjectsToPixelGrid": self.align_new_objects_to_pixel_grid, + "profile": self.profile, }) } @@ -235,8 +286,8 @@ impl DocSettings { if let Some(h) = length("height", self.units)? { self.height = h; } - if !(self.width > 0.0 && self.height > 0.0) || self.width > MAX_SIDE || self.height > MAX_SIDE { - return Err(bad(cmd, "width/height must be positive and within the canvas")); + if !side_in_range(self.width) || !side_in_range(self.height) { + return Err(side_error(cmd, self.units)); } match p.get("orientation").and_then(Value::as_str) { None => {} @@ -273,6 +324,12 @@ impl DocSettings { if let Some(m) = p.get("previewMode").filter(|v| !v.is_null()) { self.preview_mode = m.as_str().and_then(PreviewMode::parse).ok_or_else(|| bad(cmd, "previewMode must be default, pixel or overprint"))?; } + self.align_new_objects_to_pixel_grid = switch_or(p, "alignNewObjectsToPixelGrid", self.align_new_objects_to_pixel_grid, cmd)?; + match p.get("profile") { + None => {} + Some(Value::Null) => self.profile = None, + Some(v) => self.profile = Some(profile_name(v, cmd)?.to_string()), + } let extent = self.boards().iter().fold(Rect::ZERO, |a, r| a.union(*r)); if extent.width().max(extent.height()) + self.bleed.iter().fold(0.0f64, |a, b| a.max(*b)) * 2.0 > crate::MAX_COORD { return Err(bad(cmd, "the artboards don't fit on the canvas: fewer artboards, less spacing or a smaller size")); @@ -330,6 +387,7 @@ impl DocSettings { d.raster_effects_ppi = self.raster_effects_ppi; d.setup.bleed = self.bleed; d.setup.background = self.background; + d.setup.align_new_objects_to_pixel_grid = self.align_new_objects_to_pixel_grid; d.artboards = self .boards() .into_iter() @@ -349,10 +407,126 @@ impl DocSettings { .collect(); d } + + /// The new document started from New Document profile `profile`: [`Self::document`] with the + /// profile's swatches, swatch groups, graphic styles, brushes, symbols, patterns and the images + /// they use, character and paragraph styles, composite fonts, SVG filters, graph designs, ruler + /// origin and mode, transparency grid, document setup (bleed, background and Align New Objects + /// to Pixel Grid stay these settings'), assigned color profiles, raster effects settings (the + /// resolution stays these settings') and print settings, in these settings' color mode (the + /// profile's colors converted as Document Color Mode converts them). The profile's art, + /// layers and artboards are left out: the document has one empty layer. + pub fn document_from_profile(&self, mut profile: Document) -> Document { + if profile.color_mode != self.color_mode { + super::colormgmt::set_color_mode(&mut profile, self.color_mode, true, None, super::colormgmt::Grays::Profile); + } + let profile_next_id = profile.peek_next_id(); + let mut d = self.document(); + d.swatches = profile.swatches; + d.swatch_groups = profile.swatch_groups; + d.graphic_styles = profile.graphic_styles; + d.char_styles = profile.char_styles; + d.para_styles = profile.para_styles; + d.composite_fonts = profile.composite_fonts; + d.symbols = profile.symbols; + d.graph_designs = profile.graph_designs; + d.patterns = profile.patterns; + d.images = profile.images; + d.svg_filters = profile.svg_filters; + d.spot_use_lab = profile.spot_use_lab; + d.ruler_origin = profile.ruler_origin; + d.rulers = profile.rulers; + d.artboard_ruler_origins = profile.artboard_ruler_origins.into_iter().filter(|(id, _)| d.artboards.iter().any(|a| a.id == *id)).collect(); + d.transparency_grid = profile.transparency_grid; + d.print_setup = profile.print_setup; + d.color_profiles = profile.color_profiles; + // The resolution stays the preset's (raster_effects_ppi); the other raster effects settings + // are the profile's. + d.raster_effects = profile.raster_effects; + let setup = std::mem::replace(&mut d.setup, profile.setup); + d.setup.bleed = setup.bleed; + d.setup.background = setup.background; + d.setup.align_new_objects_to_pixel_grid = setup.align_new_objects_to_pixel_grid; + if let Some(brushes) = profile.unknown.get("brushes") { + d.unknown.insert("brushes".into(), brushes.clone()); + } + // Symbol, pattern and graph design art keeps the profile's ids, which a damaged file can + // have above its counter: the counter goes past all of them, as it does for a loaded + // document's layers, before the new layer takes an id. + d.raise_next_id(profile_next_id); + d.layers = d + .symbols + .iter() + .map(|s| s.art.clone()) + .chain(d.graph_designs.iter().map(|g| g.art.clone())) + .chain(d.patterns.iter().flat_map(|p| p.art.iter().cloned())) + .collect(); + d.fix_next_id(); + let layer = d.alloc_id(); + d.layers = vec![Arc::new(Node::layer(layer, "Layer 1", LayerColor::Preset(0)))]; + // Images only the profile's art used stay behind: an image is kept when an object of the new + // document names it in its `key`, as a native save keeps only the images its objects name. + let images = std::mem::take(&mut d.images); + if !images.is_empty() { + d.images = match serde_json::to_value(&d) { + Ok(v) => { + let used = image_keys(&v); + images.into_iter().filter(|(k, _)| used.contains(k.as_str())).collect() + } + Err(_) => images, + }; + } + d + } } -/// Largest artboard side `file.new` accepts, points. -const MAX_SIDE: f64 = 16383.0 * 10.0; +/// The string values of every `key` member at any depth of `v`, which name the images a document's +/// objects use, collected in one pass. +fn image_keys(v: &Value) -> std::collections::HashSet<&str> { + let mut keys = std::collections::HashSet::new(); + let mut stack = vec![v]; + while let Some(v) = stack.pop() { + match v { + Value::Object(m) => { + for (k, v) in m { + match v.as_str() { + Some(s) if k == "key" => { + keys.insert(s); + } + _ => stack.push(v), + } + } + } + Value::Array(a) => stack.extend(a), + _ => {} + } + } + keys +} + +/// Largest artboard side `file.new` and `artboard.new` accept, points: the span of the canvas +/// ([`crate::MAX_COORD`] from the origin) less the largest bleed on both sides, 3,999,856 pt. +pub(crate) const MAX_SIDE: f64 = crate::MAX_COORD - 2.0 * vectorcraft_doc::setup::MAX_BLEED; + +/// Is `side` an artboard side `file.new` and `artboard.new` accept: more than 0 and at most [`MAX_SIDE`]? +pub(crate) fn side_in_range(side: f64) -> bool { + side > 0.0 && side <= MAX_SIDE +} + +/// The error of an artboard side outside [`side_in_range`]: the limit in points, and in `units` as +/// well when they aren't points, rounded down to the decimals [`Unit::number`] shows so the value +/// shown is one the commands take. +pub(crate) fn side_error(cmd: &str, units: Unit) -> crate::EngineError { + let limit = match units { + Unit::Points => format!("{MAX_SIDE} pt"), + u => { + let step = if matches!(u, Unit::Pixels | Unit::Picas | Unit::Q | Unit::Ha) { 1e3 } else { 1e4 }; + let shown = (u.from_pt(MAX_SIDE) * step).floor() / step; + format!("{MAX_SIDE} pt ({} {})", u.number(u.to_pt(shown)), u.suffix()) + } + }; + bad(cmd, format!("width and height must be more than 0 and at most {limit}")) +} /// Largest artboard spacing, points. const MAX_SPACING: f64 = 1.0e5; @@ -543,6 +717,10 @@ pub const CATEGORIES: &[Category] = &[ ), ]; +/// The built-in categories whose presets start with Align New Objects to Pixel Grid on +/// (<https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/pixel-preview-mode-for-web-graphics.html>). +const PIXEL_ALIGNED_CATEGORIES: [&str; 2] = ["Mobile", "Web"]; + /// The category tabs in order: Recent, Saved, then the built-in categories. pub fn category_names() -> impl Iterator<Item = &'static str> { ["Recent", "Saved"].into_iter().chain(CATEGORIES.iter().map(|c| c.0)) @@ -551,7 +729,8 @@ pub fn category_names() -> impl Iterator<Item = &'static str> { /// The built-in presets of one category: screen sizes in pixels, the others in `general` /// (Preferences ▸ Units ▸ General). fn builtin(c: &Category, general: Unit) -> impl Iterator<Item = DocSettings> + '_ { - let (_, color_mode, ppi, presets) = *c; + let (category, color_mode, ppi, presets) = *c; + let align = PIXEL_ALIGNED_CATEGORIES.contains(&category); presets.iter().map(move |&(name, w, h, units)| DocSettings { name: name.into(), width: units.to_pt(w), @@ -559,6 +738,8 @@ fn builtin(c: &Category, general: Unit) -> impl Iterator<Item = DocSettings> + ' units: if units == Unit::Pixels { units } else { general }, color_mode, raster_effects_ppi: ppi, + align_new_objects_to_pixel_grid: align, + profile: Some(category.into()), ..DocSettings::default() }) } @@ -609,7 +790,18 @@ pub(crate) fn file_new(s: &mut Session, p: &Value) -> Result<Value> { if size != Some(sorted(&settings)) { settings.name = "Custom".into(); } - let mut d = settings.document(); + let (profile, profile_error) = match settings.profile.as_deref() { + Some(name) => match s.read_profile(name) { + Ok(p) => (p, None), + Err(e) => (None, Some(e)), + }, + None => (None, None), + }; + let applied = profile.is_some(); + let (mut d, links_from, warnings) = match profile { + Some(p) => (settings.document_from_profile(p.doc), Some(p.file), p.warnings), + None => (settings.document(), None, vec![]), + }; d.grid = s.prefs.grid(); d.title = match str_param(p, "name").or(str_param(p, "title")).map(str::trim).filter(|t| !t.is_empty()) { // New Document offers the next untitled name: taking it uses it up. @@ -619,13 +811,26 @@ pub(crate) fn file_new(s: &mut Session, p: &Value) -> Result<Value> { }; d.metadata.created = clock_date(s, "created", date_param(p, "created", C)?); let i = s.add_document(d, None); + // The profile's links keep their relative paths, which name places from the profile's file, as + // a new document from a history state keeps its source's. + s.doc_mut()?.links_from = links_from; // Overprint Preview is the engine's (the UI turns Pixel Preview on from `previewMode`). Both // are views of the whole app, so Default leaves them as they are. if settings.preview_mode == PreviewMode::Overprint { s.execute("view.overprintPreview", &json!({ "on": true }))?; } remember(s, &settings); - Ok(json!({ "index": i, "previewMode": settings.preview_mode.id() })) + let mut out = json!({ "index": i, "previewMode": settings.preview_mode.id() }); + if applied { + out["profile"] = json!(settings.profile); + } + if !warnings.is_empty() { + out["warnings"] = json!(warnings); + } + if let Some(e) = profile_error { + out["profileError"] = json!({ "profile": settings.profile, "reason": e }); + } + Ok(out) } /// Put `settings` first in Recent (one entry per size and units). @@ -679,3 +884,161 @@ fn delete(s: &mut Session, p: &Value) -> Result<Value> { let i = saved.iter().position(|q| q.name.eq_ignore_ascii_case(name)).ok_or_else(|| bad(C, format!("no saved preset called `{name}`")))?; Ok(json!({ "deleted": saved.remove(i).name })) } + +/// The largest New Document profile file `file.new` reads, bytes (VectorCraft's own limit); a +/// larger one is reported and the document starts with the defaults. +pub const MAX_PROFILE_BYTES: u64 = 64 << 20; + +/// `file.new`'s reason for a profile when the request being served may not read the profiles +/// folder: the folder's path is left out. +const PROFILE_DENIED: &str = "the request may not read the New Document profiles folder"; + +/// A profile's file as [`Session::read_profile`] read it. +struct ReadProfile { + doc: Document, + /// The file's path, which its links' relative paths name places from. + file: String, + /// A warning for each color profile the file carries that can't be used. + warnings: Vec<String>, +} + +/// The New Document profiles' names: the built-in categories, in tab order. +pub fn profile_names() -> impl Iterator<Item = &'static str> { + CATEGORIES.iter().map(|c| c.0) +} + +/// The profile `v` names (a built-in category, any case). +fn profile_name(v: &Value, cmd: &str) -> Result<&'static str> { + let name = v.as_str().map(str::trim).unwrap_or_default(); + profile_names().find(|c| c.eq_ignore_ascii_case(name)).ok_or_else(|| { + let shown = v.as_str().map_or_else(|| v.to_string(), str::to_string); + bad(cmd, format!("no New Document profile called `{shown}` ({})", profile_names().collect::<Vec<_>>().join(", "))) + }) +} + +impl Session { + /// Keep the New Document profiles in the folder `dir` (`New Document Profiles` next to the + /// preferences). The folder is made when a profile is first edited. + pub fn attach_new_doc_profiles(&mut self, dir: std::path::PathBuf) { + self.new_doc_profile_dir = Some(dir); + } + + /// The New Document profiles' folder ([`Session::attach_new_doc_profiles`]); none on the web. + pub fn new_doc_profile_dir(&self) -> Option<&std::path::Path> { + self.new_doc_profile_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32")) + } + + /// The file of profile `name`, whether or not it exists. + fn profile_path(&self, name: &str) -> Option<std::path::PathBuf> { + Some(self.new_doc_profile_dir()?.join(format!("{name}.{}", vectorcraft_format::EXTENSION))) + } + + /// Whether profile `name` has a file, which `file.newProfiles.reset` deletes. + pub fn new_doc_profile_customized(&self, name: &str) -> bool { + self.profile_path(name).is_some_and(|p| p.is_file()) + } + + /// Profile `name`'s document, its file's path and a warning for each color profile the file + /// carries that can't be used: `None` when it has no file (the shipped profile, the defaults), + /// the reason when the request being served may not read it, or its file can't be read, is + /// larger than [`MAX_PROFILE_BYTES`] or isn't a native document VectorCraft reads. + fn read_profile(&self, name: &str) -> std::result::Result<Option<ReadProfile>, String> { + let Some(path) = self.profile_path(name) else { return Ok(None) }; + let file = path.to_string_lossy().to_string(); + // Checked before the file is looked for, so a request that may not read the folder learns + // nothing of its files, nor where the folder is. + let denied = |_| PROFILE_DENIED.to_string(); + crate::file_access::check_read(&file).map_err(denied)?; + if std::fs::symlink_metadata(&path).is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound) { + return Ok(None); + } + crate::file_access::check_read(&file).map_err(denied)?; + let bytes = crate::store::read_capped(&path, MAX_PROFILE_BYTES)?; + // The color profiles the file carries are installed where missing, as opening it installs + // them, so the new document's assigned profiles draw and are saved with it. + let (mut doc, _, warnings) = super::fileio::native_file(&bytes).map_err(|e| e.to_string())?; + // Linked images in its symbols, patterns and brushes are read from their files, as placing + // a document reads them. + super::links::resolve(&mut doc, super::links::LinkBase::file(Some(&file)), false, false); + Ok(Some(ReadProfile { doc, file, warnings })) + } +} + +/// The shipped profile of category `name`: the defaults, as a document of the category's first +/// preset. +fn shipped_profile(s: &Session, name: &str) -> Document { + let first = CATEGORIES.iter().find(|c| c.0 == name).and_then(|c| builtin(c, s.default_units()).next()); + let mut d = first.unwrap_or_default().document(); + d.title = name.to_string(); + d +} + +/// `path` when the request being served may read it. +fn shown(path: &std::path::Path) -> Option<String> { + let path = path.to_string_lossy().to_string(); + crate::file_access::check_read(&path).is_ok().then_some(path) +} + +fn list_profiles(s: &mut Session, _: &Value) -> Result<Value> { + let profiles: Vec<Value> = profile_names() + .map(|name| { + let mut v = json!({ "name": name }); + match s.profile_path(name) { + // A request that may not read the folder learns nothing of its files. + Some(path) => { + if let Some(p) = shown(&path) { + v["customized"] = json!(path.is_file()); + v["path"] = json!(p); + } + } + None => v["customized"] = json!(false), + } + v + }) + .collect(); + Ok(json!({ "profiles": profiles, "folder": s.new_doc_profile_dir().and_then(shown) })) +} + +/// `msg`, an error about the profile file at `path`, as the request being served may see it: the +/// file named whole inside the read roots, else by its file name. +fn profile_error(msg: String, path: &str) -> super::EngineError { + super::fileio::naming_in_error(super::EngineError::Other(msg), path) +} + +/// The file of profile `name` for `cmd` to change, checked against the request's write access. +fn writable_profile(s: &Session, name: &str, cmd: &str) -> Result<std::path::PathBuf> { + let path = s.profile_path(name).ok_or_else(|| bad(cmd, "New Document profiles need the preferences folder, which this run doesn't have"))?; + let file = path.to_string_lossy(); + crate::file_access::check_write(&file).map_err(|e| profile_error(e, &file))?; + Ok(path) +} + +fn edit_profile(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "file.newProfiles.edit"; + let name = profile_name(p.get("name").unwrap_or(&Value::Null), C)?; + let file = writable_profile(s, name, C)?; + let path = file.to_string_lossy().to_string(); + // document.open reads it next: a profile it can't open is not written either. + crate::file_access::check_read(&path).map_err(|e| profile_error(e, &path))?; + if !file.exists() { + let bytes = vectorcraft_format::save(&shipped_profile(s, name), false); + file.parent() + .map_or(Ok(()), std::fs::create_dir_all) + .and_then(|()| std::fs::write(&file, bytes)) + .map_err(|e| profile_error(format!("{path}: {e}"), &path))?; + } + s.execute("document.open", &json!({ "path": path })) +} + +fn reset_profile(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "file.newProfiles.reset"; + let name = profile_name(p.get("name").unwrap_or(&Value::Null), C)?; + let file = writable_profile(s, name, C)?; + let path = file.to_string_lossy().to_string(); + let reset = match std::fs::remove_file(&file) { + Ok(()) => true, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => false, + Err(e) => return Err(profile_error(format!("{path}: {e}"), &path)), + }; + Ok(json!({ "name": name, "reset": reset })) +} diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 64157a20fa..5eee2d3fce 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -37,7 +37,8 @@ pub(crate) use bounds::{bounds_rewrite, object_bounds_transform}; pub use commands::specs; pub(super) use compound::{as_clipping_path, make_clipping_path, release_clip}; pub(crate) use pixelgrid::{ - can_align, keep_aligned_in, keep_compound_aligned, keep_pixel_aligned, refresh as refresh_pixel_aligned, resnap, snap_if_aligned, + align_new_object, can_align, keep_aligned_in, keep_compound_aligned, keep_pixel_aligned, refresh as refresh_pixel_aligned, resnap, + snap_if_aligned, }; pub(super) use shape::recut; pub(crate) use transform::{apply_transform, preview_copies, scaling, transform_node, transform_patterns, transforms_objects}; diff --git a/crates/engine/src/cmd/object/arrange.rs b/crates/engine/src/cmd/object/arrange.rs index ff5b950d03..e460712376 100644 --- a/crates/engine/src/cmd/object/arrange.rs +++ b/crates/engine/src/cmd/object/arrange.rs @@ -169,28 +169,47 @@ pub(super) fn lock(s: &mut Session, _: &Value) -> Result<Value> { ok() } -/// The selected objects ([`selected_roots`]) that Lock › Selection and Hide › Selection change: in -/// isolation mode, only those inside the isolated object, where a path of the isolated compound -/// path is an object of its own. +/// The selected objects ([`selected_roots`]) and ruler guides that Lock › Selection and Hide › +/// Selection change: in isolation mode, only the objects inside the isolated object, where a path +/// of the isolated compound path is an object of its own. A guide counts while it can be edited +/// (it and its layer shown and unlocked, and Lock Guides off). fn selected_lock_hide_roots(s: &Session) -> Result<Vec<NodeId>> { - match crate::cmd::ordinary_isolation(s.doc()?) { + let st = s.doc()?; + match crate::cmd::ordinary_isolation(st) { Some(root) => crate::cmd::edit::selected_roots_inside(s, root, false), - None => selected_roots(s), + None => { + let mut ids = selected_roots(s)?; + if !s.guides_locked() { + let d = &st.doc; + ids.extend(st.selection.guides.iter().copied().filter(|id| d.ruler_guide(*id).is_some_and(|g| d.guide_editable(&g)))); + } + Ok(ids) + } } } +/// The objects and ruler guides in `d` that `f` picks (layers never). fn collect_flag(d: &Document, f: impl Fn(&Node) -> bool) -> Vec<NodeId> { let mut v = vec![]; d.walk(|n| { - if !n.is_layer() && !n.is_ruler_guide() && f(n) { + if !n.is_layer() && f(n) { v.push(n.id) } }); v } +/// Select what Unlock All or Show All changed (`ids`): the objects, and the ruler guides among +/// them as guides (a guide that still can't be edited is then dropped from the selection). +fn select_changed(d: &Document, sel: &mut vectorcraft_doc::Selection, ids: &[NodeId]) { + let guides: std::collections::HashSet<NodeId> = d.ruler_guides().into_iter().filter_map(|g| g.id).collect(); + let (on_guides, objects): (Vec<NodeId>, Vec<NodeId>) = ids.iter().copied().partition(|id| guides.contains(id)); + sel.set(objects); + sel.guides = on_guides; +} + /// The objects that `f` picks for `object.unlockAll` and `object.showAll` (`cmd`): in the whole -/// document, inside the isolated object in isolation mode, or with `scope: "group"` inside the +/// document (its ruler guides included), inside the isolated object in isolation mode, or with `scope: "group"` inside the /// groups that hold the selected objects (in isolation mode, only the objects of those groups /// that are inside the isolated object). A selected group is the group that holds its own /// members, and the objects of a group inside another such group are taken once. With @@ -253,7 +272,7 @@ pub(super) fn unlock_all(s: &mut Session, p: &Value) -> Result<Value> { n.locked = false; } } - sel.set(ids.iter().copied()); + select_changed(d, sel, &ids); Ok(()) })?; Ok(json!({ "count": ids.len() })) @@ -292,7 +311,7 @@ pub(super) fn show_all(s: &mut Session, p: &Value) -> Result<Value> { n.visible = true; } } - sel.set(ids.iter().copied()); + select_changed(d, sel, &ids); Ok(()) })?; Ok(json!({ "count": ids.len() })) diff --git a/crates/engine/src/cmd/object/bounds.rs b/crates/engine/src/cmd/object/bounds.rs index 3dc1c37dad..0a427e3ea0 100644 --- a/crates/engine/src/cmd/object/bounds.rs +++ b/crates/engine/src/cmd/object/bounds.rs @@ -133,16 +133,16 @@ fn bounds_transform(s: &Session, p: &Value, ids: Vec<NodeId>, least: f64, anchor // the objects differ, the members of groups and the objects in symbols' art included, and with // strokes that scale, when the sizes are out of proportion. The objects are then measured one // by one ([`Spans::measure`]), and the scales solved for. Objects with geometry effects, - // objects with a butt-capped stroke along a segment at a slant, whose margins change with the - // segment's direction, and type measured by its glyphs, are measured as drawn after each scale - // tried instead ([`refit_drawn`]). + // objects with a stroke that stops at the corners of a segment at a slant (butt caps, bevel and + // miter joins), whose margins change with the segment's direction, and type measured by its + // glyphs, are measured as drawn after each scale tried instead ([`refit_drawn`]). let to_local = frame.to_doc().inverse(); let drawn = || { by_glyphs || ids .iter() .filter_map(|id| d.node(*id)) - .any(|n| effects::preview::draws_geometry(&symbols, n) || n.has_slanted_butt_stroke(&symbols, to_local)) + .any(|n| effects::preview::draws_geometry(&symbols, n) || n.has_slanted_stroke_corners(&symbols, to_local)) }; // Without Use Preview Bounds the box has no margins (`v`, `vs` and `g` are one box, glyph ink // included), so the scales above are exact and nothing is refitted. diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index eb019a88e9..21d6530e53 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -7,7 +7,7 @@ use super::props::set_props; use super::shape::{expand_shape, set_live_shape}; use super::transform::{move_cmd, nudge, reflect, rotate, scale, shear, transform, transform_again}; use super::{CommandSpec, cmd, has_doc, has_multi, has_selection, has_selection_or_guides}; -use crate::cmd::has_selected_member; +use crate::cmd::has_selected_member_or_guide; pub fn specs() -> Vec<CommandSpec> { vec![ @@ -52,7 +52,7 @@ pub fn specs() -> Vec<CommandSpec> { "Reflect…", ["Object", "Transform"], None, - "{ids?: [id…] (selected first; default: the selection), axis: \"vertical\"|\"horizontal\"|deg, origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.", + "{ids?: [id…] (selected first; default: the selection), axis: \"vertical\"|\"horizontal\"|deg (the mirror line, counter-clockwise from horizontal; 0: horizontal; omitted: vertical), origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.", has_selection, reflect ), @@ -151,8 +151,8 @@ pub fn specs() -> Vec<CommandSpec> { "Selection", ["Object", "Lock"], Some("Cmd+2"), - "{ids?: [id…] (selected first; default: the selection; in isolation mode, only those inside the isolated object)}", - has_selected_member, + "{ids?: [id…] (selected first; default: the selection, selected ruler guides included; in isolation mode, only the objects inside the isolated object)}", + has_selected_member_or_guide, lock ), cmd!( @@ -160,7 +160,7 @@ pub fn specs() -> Vec<CommandSpec> { "Unlock All", ["Object"], Some("Cmd+Alt+2"), - "{scope?: \"document\"|\"group\" (default document, which in isolation mode is the isolated object; group: only the objects inside the groups that hold the selected objects, a selected group holding its own; the in-window menu item chosen with Shift+Alt)} unlock the locked objects and select them → {count}", + "{scope?: \"document\"|\"group\" (default document, which in isolation mode is the isolated object; group: only the objects inside the groups that hold the selected objects, a selected group holding its own; the in-window menu item chosen with Shift+Alt)} unlock the locked objects and select them; document scope outside isolation mode also unlocks ruler guides locked on their own → {count}", has_doc, unlock_all ), @@ -169,8 +169,8 @@ pub fn specs() -> Vec<CommandSpec> { "Selection", ["Object", "Hide"], Some("Cmd+3"), - "{ids?: [id…] (selected first; default: the selection; in isolation mode, only those inside the isolated object)}", - has_selected_member, + "{ids?: [id…] (selected first; default: the selection, selected ruler guides included; in isolation mode, only the objects inside the isolated object)}", + has_selected_member_or_guide, hide ), cmd!( @@ -178,7 +178,7 @@ pub fn specs() -> Vec<CommandSpec> { "Show All", ["Object"], Some("Cmd+Alt+3"), - "{scope?: \"document\"|\"group\" (default document, which in isolation mode is the isolated object; group: only the objects inside the groups that hold the selected objects, a selected group holding its own; the in-window menu item chosen with Shift+Alt)} show the hidden objects and select them → {count}", + "{scope?: \"document\"|\"group\" (default document, which in isolation mode is the isolated object; group: only the objects inside the groups that hold the selected objects, a selected group holding its own; the in-window menu item chosen with Shift+Alt)} show the hidden objects and select them; document scope outside isolation mode also shows ruler guides hidden on their own → {count}", has_doc, show_all ), diff --git a/crates/engine/src/cmd/object/pixelgrid.rs b/crates/engine/src/cmd/object/pixelgrid.rs index 6441fda0c3..64d47ca0a9 100644 --- a/crates/engine/src/cmd/object/pixelgrid.rs +++ b/crates/engine/src/cmd/object/pixelgrid.rs @@ -22,6 +22,16 @@ pub(crate) fn can_align(n: &Node) -> bool { matches!(n.kind, NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. }) } +/// For an object being drawn into `d`: when the document's Align New Objects to Pixel Grid is on +/// and [`can_align`] accepts `n`, turn `n`'s pixel-aligned property on. The edit that adds it snaps +/// it to the pixel grid ([`refresh`]). Pasted, duplicated, placed and imported objects do not come +/// through here. +pub(crate) fn align_new_object(d: &Document, n: &mut Node) { + if d.setup.align_new_objects_to_pixel_grid && can_align(n) { + n.extras_mut().pixel_aligned = true; + } +} + /// `object.setPixelAligned`: turn the pixel-aligned property of the objects given (or the selected /// objects) on or off. Turning it on snaps them to the pixel grid at once. Every object must be /// one [`can_align`] accepts, else nothing changes. When every object already has the value, the diff --git a/crates/engine/src/cmd/objects_on_path.rs b/crates/engine/src/cmd/objects_on_path.rs index 1a36a4e29f..7dc8aec1c9 100644 --- a/crates/engine/src/cmd/objects_on_path.rs +++ b/crates/engine/src/cmd/objects_on_path.rs @@ -9,6 +9,11 @@ //! from the tool's options (Objects on Path Tool Options). `object.objectsOnPath.options` sets the //! group's Pivot, Rotate and Space (the distance between the objects along the path, and where the //! first one attaches), and `object.objectsOnPath.expand` makes it a plain group. +//! `object.objectsOnPath.selectMember` chooses one object of a selected group (its Select/Move +//! widget), and `object.objectsOnPath.moveMember` moves one object to another's place along the +//! path, the objects between it and that place each moving one place toward where it was; hidden +//! and locked objects keep their places. `object.objectsOnPath.detach` takes one object out of its +//! group, just above it, and the others move up the path. //! //! After every edit, [`refresh`] puts the objects of each Objects on Path group that changed back //! on its path: editing the path moves them, an object moved on its own goes back to its place, @@ -17,9 +22,10 @@ //! //! Behavior: <https://helpx.adobe.com/illustrator/using/objects-on-path.html> (the tool and //! Object › Objects on Path › Attach; the order on the path, the attachment point, the distribution, -//! the objects squared to the path; Pivot and Rotate; path edits realign the objects; Expand). +//! the objects squared to the path; Pivot and Rotate; path edits realign the objects; Detach and +//! the objects that move up the path after it; Expand). -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::sync::Arc; use serde_json::{Value, json}; @@ -28,7 +34,7 @@ use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; use vectorcraft_geom::Rect; use super::edit::{roots_of, selected_roots}; -use super::{CommandSpec, EngineError, Result, Session, bad, check_numbers, checked_id, checked_ids_param, cmd, has_selection}; +use super::{CommandSpec, EngineError, Result, Session, bad, check_numbers, checked_id, checked_ids_param, cmd, has_doc, has_selection}; /// The id of the Objects on Path tool. pub const TOOL: &str = "objectsOnPath"; @@ -53,6 +59,33 @@ pub fn specs() -> Vec<CommandSpec> { has_objects_on_path, options ), + cmd!( + "object.objectsOnPath.selectMember", + "Select Object on Path", + [], + None, + "{member: id of an object of an Objects on Path group} select the group alone with that object chosen, as a click on the object's Select/Move widget does; any other selection change clears the choice → {group, member}", + has_doc, + select_member + ), + cmd!( + "object.objectsOnPath.moveMember", + "Move Object on Path", + [], + None, + "{member: id of an object of an Objects on Path group, target: id of another object of the same group, group?: the group's id (when given, it must be the group of both); neither object nor the group may be hidden or locked} move the object to the target's place along the path; the objects between them each move one place toward where it was, except hidden and locked objects, which keep their places. Only the order along the path changes: Space, the start, Pivot, Rotate and the order in the Layers panel stay. A target that is the object itself changes nothing → {group, member, index}", + has_doc, + move_member + ), + cmd!( + "object.objectsOnPath.detach", + "Detach Object from Path", + [], + None, + "{member?: id of an object of an Objects on Path group (default: the object chosen with the selected group's Select/Move widget); neither the object nor the group may be hidden or locked} take one object off the path, out of its group and just above the group in the Layers panel, where it stays as drawn and is selected alone. The group's other objects move up the path in their order: with Auto Space they spread evenly again, and a Space value and the start are kept. The group and its path stay, even with one object or none left → {group, member}", + has_doc, + detach + ), cmd!( "object.objectsOnPath.expand", "Expand", @@ -296,6 +329,112 @@ fn options(s: &mut Session, p: &Value) -> Result<Value> { Ok(json!({ "ids": groups.iter().map(|g| g.0).collect::<Vec<_>>() })) } +// ---------- Select/Move ---------- + +/// The Objects on Path group whose object `key` of `p` names, checked: an object listed in the +/// group's record (not its path), in a group that is not hidden or locked. +fn member_param(s: &Session, p: &Value, key: &str, cmd: &str) -> Result<(NodeId, NodeId)> { + let v = p.get(key).filter(|v| !v.is_null()).ok_or_else(|| bad(cmd, format!("missing `{key}`")))?; + let id = checked_id(s, v, cmd)?; + let d = &s.doc()?.doc; + let not_on_path = || bad(cmd, format!("`{key}` must name an object attached to the path of an Objects on Path group")); + let g = + d.ancestry(id).unwrap_or_default().into_iter().rev().nth(1).filter(|g| d.node(*g).is_some_and(is_objects_on_path)).ok_or_else(not_on_path)?; + let listed = d.node(g).and_then(|n| n.extras().objects_on_path.as_deref()).is_some_and(|rec| rec.members.iter().any(|m| m.id == id)); + if !listed { + return Err(not_on_path()); + } + if !d.is_editable(g) { + return Err(bad(cmd, "the Objects on Path group is hidden or locked")); + } + if !d.is_editable(id) { + return Err(bad(cmd, format!("`{key}` names an object that is hidden or locked"))); + } + Ok((g, id)) +} + +fn select_member(s: &mut Session, p: &Value) -> Result<Value> { + let (g, member) = member_param(s, p, "member", "object.objectsOnPath.selectMember")?; + s.select(|_, sel| sel.set_on_path_member(g, member))?; + Ok(json!({ "group": g.0, "member": member.0 })) +} + +fn move_member(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "object.objectsOnPath.moveMember"; + let (g, member) = member_param(s, p, "member", C)?; + let (target_group, target) = member_param(s, p, "target", C)?; + if target_group != g { + return Err(bad(C, "`target` must be an object of the same Objects on Path group as `member`")); + } + if let Some(v) = p.get("group").filter(|v| !v.is_null()) + && checked_id(s, v, C)? != g + { + return Err(bad(C, "`group` must be the Objects on Path group of `member` and `target`")); + } + let at = |s: &Session| -> Result<usize> { + let rec = s.doc()?.doc.node(g).and_then(|n| n.extras().objects_on_path.as_deref().cloned()).ok_or(EngineError::NoNode(g))?; + rec.members.iter().position(|m| m.id == member).ok_or(EngineError::NoNode(member)) + }; + // Onto its own place: nothing changes, and no undo step is recorded. + if target == member { + return Ok(json!({ "group": g.0, "member": member.0, "index": at(s)? })); + } + // Hidden and locked objects between them keep their places. + let index = s.edit("Move Object on Path", |d, _| { + let mut rec = d.node(g).and_then(|n| n.extras().objects_on_path.as_deref().cloned()).ok_or(EngineError::NoNode(g))?; + let fixed: HashSet<NodeId> = { + let editable = d.editable(); + rec.members.iter().map(|m| m.id).filter(|&id| !editable(id)).collect() + }; + let index = rec.move_member(member, target, |id| fixed.contains(&id)).ok_or(EngineError::NoNode(member))?; + let n = d.node_mut(g).ok_or(EngineError::NoNode(g))?; + n.extras_mut().objects_on_path = Some(Box::new(rec)); + Ok(index) + })?; + Ok(json!({ "group": g.0, "member": member.0, "index": index })) +} + +// ---------- Detach ---------- + +/// The object chosen with the Select/Move widget of the one selected Objects on Path group. +fn chosen_member(s: &Session) -> Option<NodeId> { + let st = s.active()?; + match st.selection.objects[..] { + [_] => st.selection.on_path_member, + _ => None, + } +} + +fn detach(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "object.objectsOnPath.detach"; + const CHOOSE: &str = "choose the object to detach with its Select/Move widget"; + let (g, member) = if p.get("member").is_none_or(Value::is_null) { + let chosen = chosen_member(s).ok_or_else(|| bad(C, CHOOSE))?; + let found = member_param(s, &json!({ "member": chosen.0 }), "member", C)?; + if s.active().is_none_or(|st| st.selection.objects[..] != [found.0]) { + return Err(bad(C, CHOOSE)); + } + found + } else { + member_param(s, p, "member", C)? + }; + // The object goes just above the group, in the group's parent, and keeps where it is drawn. + // When the group is itself an object on another group's path, the object goes above that + // group instead (and so on outward), so it does not join that path. The refresh after the edit + // removes it from the group's record and moves the others up the path. + s.edit("Detach Object from Path", |d, sel| { + let mut above = g; + while let Some(p) = d.parent_of(above).filter(|p| d.node(*p).is_some_and(is_objects_on_path)) { + above = p; + } + let (parent, index, _) = d.position(above).ok_or(EngineError::NoNode(above))?; + d.move_node(member, parent, index + 1)?; + sel.set([member]); + Ok(()) + })?; + Ok(json!({ "group": g.0, "member": member.0 })) +} + // ---------- Expand ---------- fn expand(s: &mut Session, p: &Value) -> Result<Value> { diff --git a/crates/engine/src/cmd/package.rs b/crates/engine/src/cmd/package.rs index ee6d7e3c89..8d6f53d55b 100644 --- a/crates/engine/src/cmd/package.rs +++ b/crates/engine/src/cmd/package.rs @@ -12,7 +12,7 @@ use vectorcraft_doc::{Document, LinkInfo}; use serde_json::{Value, json}; -use super::fileio::{create_dir, write_file}; +use super::fileio::{create_dir, document_path, shown_link, shown_path, write_file}; use super::links::LinkBase; use super::{CommandSpec, Result, Session, bad, cmd, has_doc, switch_or, text_param, unique_name}; @@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> { "Package", [], None, - "{folder?, name?: (default: \"<document> Folder\"), copyLinks?: true, linksFolder?: true (the linked files go in Links/, else next to the document), relink?: true (the packaged document links to the copies), copyFonts?: true (the fonts its type uses go in Fonts/; fonts whose licence doesn't allow embedding are left out), report?: true (<document> Report.txt)} copy the saved document as it is now into folder/name as <document>.vectorcraft with its linked files and fonts; the open document doesn't change → {folder, files: [paths relative to folder/name], links, fonts (counts copied), missingLinks: [file names not found], skippedFonts: [{font, reason}], warnings: [nested files copied unchanged or cycles/depth stopped]}; no folder → the same with {name: \"<name>.zip\", dataBase64} (a zip of the files in <name>/) instead of folder", + "{folder?, name?: (default: \"<document> Folder\"), copyLinks?: true, linksFolder?: true (the linked files go in Links/, else next to the document), relink?: true (the packaged document links to the copies), copyFonts?: true (the fonts its type uses go in Fonts/; fonts whose licence doesn't allow embedding are left out), report?: true (<document> Report.txt)} copy the saved document as it is now into folder/name as <document>.vectorcraft with its linked files and fonts; the open document doesn't change → {folder, files: [paths relative to folder/name], links, fonts (counts copied), missingLinks: [file names not found], skippedFonts: [{font, reason}], warnings: [nested files copied unchanged or cycles/depth stopped]}; no folder → the same with {name: \"<name>.zip\", dataBase64} (a zip of the files in <name>/) instead of folder. The warnings and the report name a file outside the automation read roots by its file name", has_doc, package )] @@ -178,8 +178,10 @@ impl<'a> Collector<'a> { /// Warns when a file that placed `.ai` file `source` links (`name`) was copied as `copy`: the /// copy of `source` finds it only by its name, beside it. + /// `path` is the link's path as the warning names it. fn renamed(&mut self, lines: &mut Vec<String>, source: &str, path: &str, name: &str, copy: &str) { if Path::new(copy).file_name().and_then(std::ffi::OsStr::to_str) != Some(name) { + let source = shown_path(source); let message = format!( "{path}: copied as {copy}; the copy of {source} looks for it as {name} and shows the file of that name, if any, else its preview" ); @@ -207,11 +209,13 @@ impl<'a> Collector<'a> { let section = self.sections.len(); self.sections.push(vec![]); let mut lines = vec![]; - // The packaged document's sections read as before; a placed document's name its file. + // The packaged document's sections read as before; a placed document's name its file. The + // report and the warnings name a file outside a confined request's read roots by its name. + let shown_source = shown_path(source); let heading = |lines: &mut Vec<String>, title: &str| { lines.push(title.into()); if depth > 0 { - lines.push(format!("Document: {source}")); + lines.push(format!("Document: {shown_source}")); } }; // A file's saved path is only meaningful inside its own document. @@ -243,17 +247,21 @@ impl<'a> Collector<'a> { heading(&mut lines, "LINKED FILES"); for file in linked_files(doc) { let found_path = file.found_path.as_deref().unwrap_or(&file.path); + // The stored path, whole when the place it names (read from this document's folder) is + // inside the read roots. A file found elsewhere does not show a stored path outside them. + let resolved = document_path(&file.path, Some(source)).ok(); + let shown = shown_link(&file.path, resolved.as_deref()).into_owned(); if let Some(ancestor) = self.visiting.get(found_path).cloned() { // The ancestor is already included (possibly the root document). A // cyclic reference cannot have a final content hash until both files // have been written, so leave its size/hash unspecified, not stale. - self.warn(&mut lines, format!("{}: circular placed-document link to {ancestor}; stopped following the cycle", file.path)); + self.warn(&mut lines, format!("{shown}: circular placed-document link to {ancestor}; stopped following the cycle")); local.insert(file.path.clone(), Copied { name: ancestor, size: None, hash: None }); continue; } if let Some(existing) = self.copies.get(found_path).cloned() { if by_name { - self.renamed(&mut lines, source, &file.path, &file.name, &existing.name); + self.renamed(&mut lines, source, &shown, &file.name, &existing.name); } // Another document may place other pages of a PDF copied already. if self.opts.copy_fonts @@ -265,8 +273,8 @@ impl<'a> Collector<'a> { continue; } let Some(mut bytes) = file.bytes else { - lines.push(format!("{}: not found ({}), not copied", file.name, file.path)); - self.missing.push(if depth == 0 { file.name.clone() } else { format!("{} ({source})", file.name) }); + lines.push(format!("{}: not found ({shown}), not copied", file.name)); + self.missing.push(if depth == 0 { file.name.clone() } else { format!("{} ({shown_source})", file.name) }); continue; }; if self.copies.len() >= 10_000 { @@ -277,7 +285,7 @@ impl<'a> Collector<'a> { let unique = free_name(&name, if self.opts.links_folder { &mut self.link_names } else { &mut self.taken }); let destination_file = format!("{dir}{unique}"); if by_name { - self.renamed(&mut lines, source, &file.path, &file.name, &destination_file); + self.renamed(&mut lines, source, &shown, &file.name, &destination_file); } // A placed PDF or .ai file is copied as it is, as an image is; the files a .ai file // read from its editing data links are copied beside it. @@ -285,7 +293,7 @@ impl<'a> Collector<'a> { let placed_file = pages.is_some(); if placed_file && let Some(mut art) = super::place::document::editing_data(&file.name, &bytes) { if depth >= vectorcraft_doc::placed_document::MAX_DEPTH { - self.warn(&mut lines, format!("{}: nesting limit reached; copied unchanged without collecting its own links", file.path)); + self.warn(&mut lines, format!("{shown}: nesting limit reached; copied unchanged without collecting its own links")); } else { self.collect(&mut art, found_path, &destination_file, depth + 1, true, None)?; } @@ -296,7 +304,7 @@ impl<'a> Collector<'a> { } if placed_file && super::place::document::is_native(&file.name, &bytes) { if depth >= vectorcraft_doc::placed_document::MAX_DEPTH { - self.warn(&mut lines, format!("{}: nesting limit reached; copied unchanged without collecting its own links", file.path)); + self.warn(&mut lines, format!("{shown}: nesting limit reached; copied unchanged without collecting its own links")); } else { match vectorcraft_format::load_file(&bytes) { Ok(saved) => { @@ -320,8 +328,7 @@ impl<'a> Collector<'a> { Err(e) => self.warn( &mut lines, format!( - "{}: could not rewrite linked document ({e}); copied unchanged, its own links were not relinked", - file.path + "{shown}: could not rewrite linked document ({e}); copied unchanged, its own links were not relinked" ), ), } @@ -329,7 +336,7 @@ impl<'a> Collector<'a> { } Err(e) => self.warn( &mut lines, - format!("{}: unreadable linked document ({e}); copied unchanged, its own links were not collected", file.path), + format!("{shown}: unreadable linked document ({e}); copied unchanged, its own links were not collected"), ), } } @@ -337,7 +344,7 @@ impl<'a> Collector<'a> { let copy = Copied { name: destination_file.clone(), size: Some(bytes.len() as u64), hash: Some(hash_bytes(&bytes)) }; self.copies.insert(found_path.to_string(), copy.clone()); local.insert(file.path.clone(), copy); - lines.push(format!("{} → {destination_file}", file.path)); + lines.push(format!("{shown} → {destination_file}")); self.entries.push((destination_file, bytes)); } lines.push(String::new()); @@ -518,7 +525,7 @@ fn collect_and_write(package: Package, write: &mut dyn FnMut(&str, &[u8]) -> Res // The report. if let Some(info) = info { let report_name = free_name(&format!("{stem} Report.txt"), &mut taken); - let mut text = format!("Package: {doc_name}\nFrom: {doc_path}\n\n"); + let mut text = format!("Package: {doc_name}\nFrom: {}\n\n", shown_path(&doc_path)); lines.iter().for_each(|l| text.push_str(&format!("{l}\n"))); text.push_str(&info); entries.push((report_name, text.into_bytes())); diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 93c4cbf2c7..85d11ea7ec 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -4,9 +4,9 @@ use std::borrow::Cow; use serde_json::{Value, json}; use vectorcraft_color::{BlendMode, Color, GradientPaint, Paint}; -use vectorcraft_doc::{Appearance, CharStyle, Document, Node, NodeId, NodeKind}; +use vectorcraft_doc::{Appearance, CharStyle, Document, GraySource, Node, NodeId, NodeKind}; -use super::appearance::{ItemTarget, appearance_targets, edit_items, edit_items_then, item_target}; +use super::appearance::{ItemTarget, edit_items, edit_items_then, item_target, row_targets}; use super::gradient::{item_paint_bounds, place_paint, place_run_paint, run_paint_mut, run_stroke_weight, unplaced}; use super::{ Affine, CommandSpec, Result, Session, always, bad, bool_or, check_numbers, check_switches, cmd, color_value, has_doc, leaf_targets, ok, @@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> { "Fill", [], None, - "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector), method?: classic|perceptual (as paint.editGradient; default classic), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial and conic; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic), dither?: bool (linear, radial and conic fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial or conic `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid colour recolours only the gradient mesh point last clicked with the Mesh tool or Direct Selection; while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern) → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}", + "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid colour recolours only the gradient mesh point last clicked with the Mesh tool or Direct Selection; while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern) → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}", has_doc, |s, p| set_paint(s, p, true) ), @@ -73,7 +73,7 @@ pub fn specs() -> Vec<CommandSpec> { "Transparency", ["Window", "Transparency"], None, - "{ids?|id?, opacity?: 0..100, blend?: name, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, item?: appearance item index|null, 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)} for `ids`, the selection, or the object whose opacity mask is being edited; opacity and blend go to the targeted fill/stroke item (omitted: the Appearance panel's active item, else the objects; a gradient mesh point last clicked with the Mesh tool or Direct Selection takes the opacity itself). With an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, opacity and blend change that object for this instance only (isolate, knockout, knockoutShape, aligned and target are refused). On a path directly in a graph series, the graph also stores the opacity and blend mode of the object and of the topmost visible fill and stroke (exceptions: docs/mcp.md)", + "{ids?|id?, opacity?: 0..100, blend?: name, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, item?: appearance item index|null, 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)} for `ids`, the selection, or the object whose opacity mask is being edited; opacity and blend go to the targeted fill/stroke item (omitted: the Appearance panel's active item, else the objects; a gradient mesh point last clicked with the Mesh tool or Direct Selection takes the opacity itself). With an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, opacity and blend change that object for this instance only (isolate, knockout, knockoutShape, aligned and target are refused). On a path directly in a graph series (for a fill or stroke item, a series group's id stands for those paths), the graph also stores the opacity and blend mode of the object and of the topmost visible fill and stroke (exceptions: docs/mcp.md)", has_doc, transparency ), @@ -641,7 +641,7 @@ fn paint_new_art(s: &mut Session, paint: &Paint, fill: bool) { } } -/// Does `p` ask for `span: "selection"` (#2127)? Only a linear, radial or conic gradient the targets +/// Does `p` ask for `span: "selection"` (#2127)? Only a linear, radial, conic or diamond gradient the targets /// would each fit to their own bounds can span them: one with its own vector (`start`/`end`), /// a freeform one or a gradient swatch already has its placement. fn spans_targets(p: &Value, paint: &Paint) -> std::result::Result<bool, String> { @@ -656,7 +656,7 @@ fn spans_targets(p: &Value, paint: &Paint) -> std::result::Result<bool, String> return Err("span: \"selection\" places a `gradient`, not a swatch".into()); } if g.gradient.kind == vectorcraft_color::GradientKind::Freeform || g.freeform.is_some() { - return Err("span: \"selection\" places a linear, radial or conic gradient, not a freeform one".into()); + return Err("span: \"selection\" places a linear, radial, conic or diamond gradient, not a freeform one".into()); } if g.geom.is_some() { return Err( @@ -690,7 +690,9 @@ fn placed_across(d: &Document, ids: &[NodeId], paint: Paint, p: &Value, fill: bo /// The images among `ids` that a fill of `paint` colorizes: grayscale and 1-bit images, for a solid /// color (or none on a colorized image, which takes the color off). The color may be black, white, /// a process color or a spot color; on an image with an alpha channel, only a spot color, black or -/// white, and other colors are an error. +/// white, and other colors are an error. A colorized image that shows a preview that isn't +/// grayscale, such as a missing link's placeholder, takes a solid color as its new colorize paint; +/// while its paint is one an alpha channel allows, a process color is an error there too. fn colorized_images(d: &Document, ids: &[NodeId], paint: &Paint) -> std::result::Result<Vec<NodeId>, String> { let mut out = vec![]; for id in ids { @@ -701,7 +703,22 @@ fn colorized_images(d: &Document, ids: &[NodeId], paint: &Paint) -> std::result: out.push(*id); continue; } - let Some(gray) = d.image_blob(im).and_then(|b| b.gray_source()) else { continue }; + // The Fill proxy shows such an image's colorize paint. Its pixels are not known until the + // file is relinked: a process color replaces only a process color, which the image's + // pixels already accepted, so a relink can't bring back an alpha channel under one. + if matches!(paint, Paint::Solid { .. }) + && let Some(old) = n.extras().colorize.as_deref() + && d.image_blob(im).is_some_and(|b| !b.takes_colorize()) + { + if !colorizes_transparency(d, paint) && colorizes_transparency(d, old) { + return Err(PROCESS_ON_TRANSPARENCY.into()); + } + out.push(*id); + continue; + } + // A color-masked image is colorized as it shows: its masked pixels, which have an alpha + // channel. + let Some(gray) = d.image_blob(&d.shown_image(n, im)).and_then(|b| b.gray_source()) else { continue }; match paint { // Without a color, `none` goes to the image's fill item. Paint::None => continue, @@ -718,7 +735,8 @@ fn colorized_images(d: &Document, ids: &[NodeId], paint: &Paint) -> std::result: } /// The message for a process color on a grayscale image with an alpha channel. -const PROCESS_ON_TRANSPARENCY: &str = "a process color can't colorize a grayscale image with transparency: use a spot color, black or white"; +pub(super) const PROCESS_ON_TRANSPARENCY: &str = + "a process color can't colorize a grayscale image with transparency: use a spot color, black or white"; /// Can `paint` colorize a grayscale image with an alpha channel: a color linked to a spot swatch /// of `d`, black or white? @@ -737,11 +755,7 @@ pub(super) fn check_colorized(d: &Document) -> std::result::Result<(), String> { let mut refused = false; let mut visit = |n: &Node| { vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| { - if let (NodeKind::Image(im), Some(paint)) = (&m.kind, m.extras().colorize.as_deref()) - && !refused - && !colorizes_transparency(d, paint) - && d.image_blob(im).and_then(|b| b.gray_source()).is_some_and(|g| g.alpha) - { + if !refused && gray_colorized_with_process(d, m).is_some_and(|g| g.alpha) { refused = true; } }) @@ -761,6 +775,19 @@ pub(super) fn check_colorized_kept(was_ok: bool, d: &Document) -> std::result::R if was_ok { check_colorized(d) } else { Ok(()) } } +/// Is `n` an image colorized with a color that [`colorizes_transparency`] refuses? When its pixels +/// are grayscale or 1-bit, they can't have an alpha channel. +pub(super) fn colorized_with_process(d: &Document, n: &Node) -> bool { + matches!(n.kind, NodeKind::Image(_)) && n.extras().colorize.as_deref().is_some_and(|paint| !colorizes_transparency(d, paint)) +} + +/// How the pixels `n` shows are gray, when `n` is a grayscale or 1-bit image colorized with a +/// color that [`colorizes_transparency`] refuses ([`colorized_with_process`]). +pub(super) fn gray_colorized_with_process(d: &Document, n: &Node) -> Option<GraySource> { + let NodeKind::Image(im) = &n.kind else { return None }; + if colorized_with_process(d, n) { d.image_blob(&d.shown_image(n, im)).and_then(|b| b.gray_source()) } else { None } +} + /// Is `e` the refusal of [`check_colorized`]? pub(super) fn is_colorize_refusal(e: &EngineError) -> bool { e.to_string().contains(PROCESS_ON_TRANSPARENCY) @@ -1035,7 +1062,7 @@ fn transparency(s: &mut Session, p: &Value) -> Result<Value> { return s.execute("object.setProps", &Value::Object(q)); }; // Opacity and blend belong to the targeted fill/stroke; isolate/knockout/knockoutShape stay object-level. - let item_ids = if editing_mask { ids } else { appearance_targets(s, p)? }; + let item_ids = if editing_mask { ids } else { row_targets(s, p)? }; if explicit { let d = &s.doc()?.doc; if !item_ids.iter().any(|id| d.node(*id).is_some_and(|n| index < n.appearance.items.len())) { diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index b8bdd24d05..5910435a75 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -67,7 +67,7 @@ pub fn specs() -> Vec<CommandSpec> { "Character / Paragraph", [], None, - "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tenth of an em each, pushOutFirst does so only when moving the character before them to the next line would leave the line more than an em short, and pushOutOnly, the default, moves it unless Burasagari hangs an overflowing comma or full stop; no effect with kinsoku \"none\"), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings, as text.setRangeStyle: a tate-chu-yoko block moves up or down, right or left, and on a vertical path toward or away from the path's start, to its left or right), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference, as text.setRangeStyle: the height of the font that the size measures), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\" (line breaking, Every-line by default), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text, and graph labels keep the character and paragraph attributes for every label of their kind when the graph is drawn again, the graph still setting each label's alignment)", + "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"yakumonoHankaku\"|\"gyomatsuYakumonoHankaku\"|\"gyomatsuYakumonoZenkaku\"|\"yakumonoZenkaku\"|\"lineEndHalf\" (Mojikumi Set: Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tenth of an em each, pushOutFirst does so only when moving the character before them to the next line would leave the line more than an em short, and pushOutOnly, the default, moves it unless Burasagari hangs an overflowing comma or full stop; no effect with kinsoku \"none\"), bunriKinshi?: bool (Paragraph panel menu › Bunri-Kinshi: a line never breaks inside an inseparable pair, two em dashes, two horizontal ellipses, two two-dot leaders or the two halves of a vertical kana repeat mark, and justification adds no space inside one; kept but without effect with kinsoku \"none\"; off by default), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings, as text.setRangeStyle: a tate-chu-yoko block moves up or down, right or left, and on a vertical path toward or away from the path's start, to its left or right), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options, as text.setRangeStyle: space before and after each character in reading order), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference, as text.setRangeStyle: the height of the font that the size measures), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), koreanLineBreakAnywhere?: bool (Paragraph panel menu › Korean Line Break Anywhere: a line may break between any two Hangul syllables; off, a word with Hangul in it breaks only at its spaces and punctuation, or where it is wider than the line; new type: false, paragraphs saved before the option: true), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\" (line breaking, Every-line by default), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text, and graph labels keep the character and paragraph attributes for every label of their kind when the graph is drawn again, the graph still setting each label's alignment; a number or switch given as another type fails the call, and a null value leaves its attribute as it is, so a call with only null values fails with nothing to change; a call that gives the values the text already has records no undo step). Or {paragraphIndents: [{id, start: byte where the paragraph starts, leftIndent?, firstLineIndent?: pt -1296..1296}…]} alone (Tabs panel indent markers over paragraphs with indents of their own): each entry sets one paragraph of a type object, at least one indent each, at most 100000 entries; every entry is checked before anything changes, and an unknown key, a value out of range, an object that is not type, a byte where no paragraph starts or two entries for one paragraph with other values fail the call; all of it is one edit, a threaded story flowing again once, and when no paragraph's indents change nothing is recorded → {ids}", has_doc, set_format ), @@ -122,7 +122,7 @@ pub(crate) fn boards_and_art_noted(s: &mut Session, p: &Value, cmd: &str) -> Res /// Add `selectedArtboards` to the running command's journal entry when `p` names no artboard, so a /// replay acts on the artboards the Artboard tool had selected. An action leaves it out /// (`REPLAY_ONLY`) and keeps an `index` or `indices` the call gave. -fn note_artboards(s: &mut Session, p: &Value, indices: &[usize]) { +pub(crate) fn note_artboards(s: &mut Session, p: &Value, indices: &[usize]) { if p.get("index").is_none() && p.get("indices").is_none() { s.note_journal("selectedArtboards", json!(indices)); } @@ -130,7 +130,7 @@ fn note_artboards(s: &mut Session, p: &Value, indices: &[usize]) { /// The artboards `cmd` acts on: `index` or `indices`, else `selectedArtboards` (a replay of the /// journal), else those the Artboard tool has selected, else its active one. -fn named_or_selected(s: &Session, p: &Value, cmd: &str) -> Result<Vec<usize>> { +pub(crate) fn named_or_selected(s: &Session, p: &Value, cmd: &str) -> Result<Vec<usize>> { let t = s.tool_options_of("artboard"); let d = &s.doc()?.doc; if p.get("index").is_some() || p.get("indices").is_some() { @@ -467,6 +467,9 @@ fn list_level_param(p: &Value, cmd: &str) -> Result<Option<u8>> { fn set_format(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "text.setFormat"; + if p.get("paragraphIndents").is_some() { + return set_paragraph_indents(s, p); + } let ids = super::typecmd::text_targets(s, p, C)?; check_switches( p, @@ -482,6 +485,29 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> { "hyphenate", "hyphenateCapitalized", "romanHangingPunctuation", + "koreanLineBreakAnywhere", + "bunriKinshi", + ], + C, + )?; + // Each value that `num` reads below must be a number or null. + super::check_numbers( + p, + &[ + "baselineShift", + "hScale", + "vScale", + "rotation", + "leftIndent", + "rightIndent", + "firstLineIndent", + "spaceBefore", + "spaceAfter", + "wordsLongerThan", + "afterFirst", + "beforeLast", + "hyphenLimit", + "hyphenationZone", ], C, )?; @@ -535,6 +561,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> { "mojikumi", "kinsoku", "kinsokuType", + "bunriKinshi", "direction", "leadingModel", "charAlign", @@ -544,6 +571,8 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> { "tateChuYoko", "tcyUpDown", "tcyLeftRight", + "akiLeft", + "akiRight", "standardVerticalRoman", "noBreak", "digits", @@ -552,10 +581,12 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> { "fontAxes", "burasagari", "romanHangingPunctuation", + "koreanLineBreakAnywhere", "kashida", "composer", ]; - if !keys.iter().any(|k| p.get(*k).is_some()) { + // A null value leaves its attribute as it is, as an omitted one does. + if !keys.iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) { return Err(bad(C, "nothing to change")); } // The anti-aliasing method belongs to the whole type object; each frame keeps its own method. @@ -584,16 +615,27 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> { let font_height_reference = super::textedit::font_height_reference_param(p, C)?; let tcy_up_down = super::textedit::tcy_offset_param(p, "tcyUpDown", C)?; let tcy_left_right = super::textedit::tcy_offset_param(p, "tcyLeftRight", C)?; + let aki_left = super::textedit::aki_param(p, "akiLeft", C)?; + let aki_right = super::textedit::aki_param(p, "akiRight", C)?; let mojikumi = match p.get("mojikumi") { - None => None, + None | Some(Value::Null) => None, Some(v) => Some(match v.as_str() { Some("none") => vectorcraft_doc::Mojikumi::None, Some("lineEndHalf") => vectorcraft_doc::Mojikumi::LineEndHalf, - _ => return Err(bad(C, "`mojikumi` must be \"none\" or \"lineEndHalf\"")), + Some("yakumonoHankaku") => vectorcraft_doc::Mojikumi::YakumonoHankaku, + Some("gyomatsuYakumonoHankaku") => vectorcraft_doc::Mojikumi::GyomatsuYakumonoHankaku, + Some("gyomatsuYakumonoZenkaku") => vectorcraft_doc::Mojikumi::GyomatsuYakumonoZenkaku, + Some("yakumonoZenkaku") => vectorcraft_doc::Mojikumi::YakumonoZenkaku, + _ => { + return Err(bad( + C, + "`mojikumi` must be \"none\", \"yakumonoHankaku\", \"gyomatsuYakumonoHankaku\", \"gyomatsuYakumonoZenkaku\", \"yakumonoZenkaku\" or \"lineEndHalf\"", + )); + } }), }; let kinsoku = match p.get("kinsoku") { - None => None, + None | Some(Value::Null) => None, Some(v) => Some(match v.as_str() { Some("none") => vectorcraft_doc::Kinsoku::None, Some("hard") => vectorcraft_doc::Kinsoku::Hard, @@ -602,7 +644,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> { }), }; let kinsoku_type = match p.get("kinsokuType") { - None => None, + None | Some(Value::Null) => None, Some(v) => Some(match v.as_str() { Some("pushInFirst") => vectorcraft_doc::KinsokuShoriType::PushInFirst, Some("pushOutFirst") => vectorcraft_doc::KinsokuShoriType::PushOutFirst, @@ -611,7 +653,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> { }), }; let direction = match p.get("direction") { - None => None, + None | Some(Value::Null) => None, Some(v) => Some(match v.as_str() { Some("auto") => None, Some("leftToRight") => Some(vectorcraft_doc::ParaDirection::LeftToRight), @@ -620,7 +662,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> { }), }; let leading_model = match p.get("leadingModel") { - None => None, + None | Some(Value::Null) => None, Some(v) => Some(match v.as_str() { Some("romanBaseline") => vectorcraft_doc::LeadingModel::RomanBaseline, Some("emBoxTop") => vectorcraft_doc::LeadingModel::EmBoxTop, @@ -628,7 +670,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> { }), }; let burasagari = match p.get("burasagari") { - None => None, + None | Some(Value::Null) => None, Some(v) => Some(match v.as_str() { Some("none") => vectorcraft_doc::Burasagari::None, Some("standard") => vectorcraft_doc::Burasagari::Standard, @@ -637,7 +679,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> { }), }; let kashida = match p.get("kashida") { - None => None, + None | Some(Value::Null) => None, Some(v) => Some(match v.as_str() { Some("none") => vectorcraft_doc::text::Kashida::None, Some("short") => vectorcraft_doc::text::Kashida::Short, @@ -668,7 +710,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> { let spacing = |k: &str| spacing_param(p, k, C); let (word_spacing, letter_spacing, glyph_scaling) = (spacing("wordSpacing")?, spacing("letterSpacing")?, spacing("glyphScaling")?); let single_word = match p.get("singleWordJustification") { - None => None, + None | Some(Value::Null) => None, Some(v) => Some(match v.as_str() { Some("fullJustify") => SingleWordJustify::FullJustify, Some("alignLeft") => SingleWordJustify::AlignLeft, @@ -678,7 +720,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> { }), }; let auto_leading = match p.get("autoLeading") { - None => None, + None | Some(Value::Null) => None, Some(v) => Some(v.as_f64().filter(|v| v.is_finite()).ok_or_else(|| bad(C, "`autoLeading` must be a number"))?), }; // A paragraph whose Minimum, Desired and Maximum would no longer be in order. @@ -744,6 +786,12 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> { if let Some(v) = tcy.1 { st.tcy_left_right = v; } + if let Some(v) = aki_left { + st.aki_left = v; + } + if let Some(v) = aki_right { + st.aki_right = v; + } if let Some(v) = flag("standardVerticalRoman") { st.standard_vertical_roman = v; } @@ -785,12 +833,20 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> { l.level = list_level.unwrap_or(l.level); } }; - s.edit("Character", |d, _| { + // The change is made on a copy first: a call whose values are the ones the text already has + // records no edit, undo step or revision. Only the type objects and graph label styles the call + // changes are compared, not the whole document. + super::variablecmds::settle_typing(s)?; + let mut doc = (*s.doc()?.doc).clone(); + let mut changed = false; + { + let d = &mut doc; // The paragraph change, for the graph labels to keep. let mut para_change = None; let out_of_order_error = |name: &str| bad(C, format!("`{name}`: Minimum must not exceed Desired, nor Desired Maximum")); for id in &ids { let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { continue }; + let before = t.clone(); let baseline_shift = num("baselineShift").map(|v| super::typecmd::local_type_value(t, v, (-1296.0, 1296.0), false, C)).transpose()?; let h_scale = num("hScale").map(|v| super::typecmd::local_type_value(t, v, (1.0, 10000.0), true, C)).transpose()?; let local = |v: Option<f64>| v.map(|v| super::typecmd::local_type_value(t, v, (-1296.0, 1296.0), false, C)).transpose(); @@ -867,6 +923,9 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> { if let Some(v) = kinsoku_type { para.kinsoku_type = v; } + if let Some(v) = flag("bunriKinshi") { + para.bunri_kinshi = v; + } if let Some(v) = direction { para.direction = v; } @@ -879,6 +938,9 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> { if let Some(v) = flag("romanHangingPunctuation") { para.roman_hanging = v; } + if let Some(v) = flag("koreanLineBreakAnywhere") { + para.korean_line_break_anywhere = v; + } if let Some(v) = kashida { para.kashida = v; } @@ -891,16 +953,17 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> { return Err(out_of_order_error(name)); } super::typecmd::refresh_bounds(t); + changed |= *t != before; para_change = Some(paras); } // Graph labels keep a change made to all of their text through the graph being drawn again. if range.is_none() { let shift = num("baselineShift").map(|v| v.clamp(-1296.0, 1296.0)); let scale = num("hScale").map(|v| v.clamp(1.0, 10000.0)); - super::graph::capture_label_styles(d, &ids, &|st| chars(st, shift, scale, (tcy_up_down, tcy_left_right))); + changed |= super::graph::capture_label_styles(d, &ids, &|st| chars(st, shift, scale, (tcy_up_down, tcy_left_right))); if let Some(paras) = para_change { // The kept attributes are checked too: they may differ from the labels'. - super::graph::capture_label_paragraphs(d, &ids, &|para| { + changed |= super::graph::capture_label_paragraphs(d, &ids, &|para| { let mut out_of_order = None; paras(para, &mut out_of_order); out_of_order.map_or(Ok(()), |name| Err(out_of_order_error(name))) @@ -910,14 +973,20 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> { if let Some(v) = anti_alias { for id in &ids { if let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) { + changed |= t.anti_alias != v; t.anti_alias = v; } } // Graph labels keep the method through the graph being drawn again. - super::graph::capture_label_anti_alias(d, &ids, v); + changed |= super::graph::capture_label_anti_alias(d, &ids, v); } - Ok(()) - })?; + } + if changed { + s.edit("Character", |d, _| { + *d = doc; + Ok(()) + })?; + } let mut result = json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }); if let Some(kerning) = p.get("kerning") { result["kerning"] = kerning.clone(); @@ -925,6 +994,126 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> { Ok(result) } +/// The most entries `paragraphIndents` takes in one `text.setFormat` call. +pub(crate) const MAX_PARAGRAPH_INDENTS: usize = 100_000; + +/// The indents one `paragraphIndents` entry gives its paragraph. +#[derive(Clone, Copy, Debug, PartialEq)] +struct ParagraphIndent { + left: Option<f64>, + first_line: Option<f64>, +} + +/// A type object that `paragraphIndents` names: the bytes where its paragraphs start and the +/// indents its entries give them, by paragraph index. +struct IndentedFrame { + id: NodeId, + starts: Vec<usize>, + changes: Vec<(usize, ParagraphIndent)>, +} + +/// `text.setFormat` with `paragraphIndents`: each entry names one paragraph of a type object, by +/// the object and the byte where the paragraph starts, and sets its left and first-line indents. +/// Every entry is checked against the document before anything changes. Each type object's +/// paragraph styles are rebuilt once and the whole change is one edit, so a threaded story flows +/// again once however many of its paragraphs change. When no entry changes its paragraph, nothing +/// is edited. +fn set_paragraph_indents(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "text.setFormat"; + const KEY: &str = "paragraphIndents"; + if let Some(other) = p.as_object().and_then(|o| o.keys().find(|k| *k != KEY)) { + return Err(bad(C, format!("`{KEY}` takes no `{other}` beside it"))); + } + let entries = p.get(KEY).and_then(Value::as_array).ok_or_else(|| bad(C, format!("`{KEY}` must be a list")))?; + if entries.is_empty() { + return Err(bad(C, format!("`{KEY}` is empty"))); + } + if entries.len() > MAX_PARAGRAPH_INDENTS { + return Err(bad(C, format!("`{KEY}` takes at most {MAX_PARAGRAPH_INDENTS} entries (got {})", entries.len()))); + } + let d = &s.doc()?.doc; + // The type objects in the order they first appear. + let mut frames: Vec<IndentedFrame> = vec![]; + let mut frame_at: std::collections::HashMap<NodeId, usize> = std::collections::HashMap::new(); + let mut given: std::collections::HashMap<(NodeId, usize), ParagraphIndent> = std::collections::HashMap::new(); + for (n, e) in entries.iter().enumerate() { + let e = e.as_object().ok_or_else(|| bad(C, format!("`{KEY}` entry {n} must be an object")))?; + if let Some(k) = e.keys().find(|k| !["id", "start", "leftIndent", "firstLineIndent"].contains(&k.as_str())) { + return Err(bad(C, format!("`{KEY}` entry {n}: unknown key `{k}`"))); + } + let indent = |k: &str| -> Result<Option<f64>> { + match e.get(k) { + None => Ok(None), + Some(v) => match v.as_f64() { + Some(x) if x.is_finite() && x.abs() <= MAX_PARA => Ok(Some(x)), + _ => Err(bad(C, format!("`{KEY}` entry {n}: `{k}` must be a number from -{MAX_PARA} to {MAX_PARA} pt"))), + }, + } + }; + let change = ParagraphIndent { left: indent("leftIndent")?, first_line: indent("firstLineIndent")? }; + if change.left.is_none() && change.first_line.is_none() { + return Err(bad(C, format!("`{KEY}` entry {n} sets neither `leftIndent` nor `firstLineIndent`"))); + } + let id = NodeId(e.get("id").and_then(Value::as_u64).ok_or_else(|| bad(C, format!("`{KEY}` entry {n}: `id` must be an object id")))?); + let start = index(e.get("start").and_then(Value::as_u64).ok_or_else(|| bad(C, format!("`{KEY}` entry {n}: `start` must be a byte offset")))?); + let k = match frame_at.get(&id) { + Some(k) => *k, + None => { + let Some(NodeKind::Text(t)) = d.node(id).map(|n| &n.kind) else { + return Err(bad(C, format!("`{KEY}` entry {n}: {} is not a type object", id.0))); + }; + let plain = t.plain_text(); + let mut starts = vec![0]; + starts.extend(plain.bytes().enumerate().filter_map(|(i, c)| (c == b'\n').then_some(i + 1))); + frames.push(IndentedFrame { id, starts, changes: vec![] }); + frame_at.insert(id, frames.len() - 1); + frames.len() - 1 + } + }; + let Some(IndentedFrame { starts, changes, .. }) = frames.get_mut(k) else { continue }; + let para = starts.binary_search(&start).map_err(|_| bad(C, format!("`{KEY}` entry {n}: no paragraph of {} starts at byte {start}", id.0)))?; + match given.insert((id, para), change) { + None => changes.push((para, change)), + Some(was) if was == change => {} + Some(_) => { + return Err(bad( + C, + format!("`{KEY}` entry {n} gives the paragraph at byte {start} of {} other indents than an entry before it", id.0), + )); + } + } + } + let ids = json!({ "ids": frames.iter().map(|f| f.id.0).collect::<Vec<_>>() }); + // Only the type objects with a paragraph whose indents change are edited. + let differs = |t: &vectorcraft_doc::TextObject, i: usize, c: &ParagraphIndent| { + let para = t.para_at(i); + c.left.is_some_and(|v| v != para.left_indent) || c.first_line.is_some_and(|v| v != para.first_line_indent) + }; + frames.retain(|f| match d.node(f.id).map(|n| &n.kind) { + Some(NodeKind::Text(t)) => f.changes.iter().any(|(i, c)| differs(t, *i, c)), + _ => false, + }); + if frames.is_empty() { + return Ok(ids); + } + s.edit("Character", |d, _| { + for f in &frames { + let Some(NodeKind::Text(t)) = d.node_mut(f.id).map(|n| &mut n.kind) else { continue }; + let mut styles = t.paragraph_styles(); + for (i, c) in &f.changes { + if let Some(para) = styles.get_mut(*i) { + para.left_indent = c.left.unwrap_or(para.left_indent); + para.first_line_indent = c.first_line.unwrap_or(para.first_line_indent); + } + } + t.set_paragraph_styles(styles); + super::typecmd::refresh_bounds(t); + } + Ok(()) + })?; + Ok(ids) +} + /// The part of a story paragraph in one frame, as [`convert_list_to_text`] reads it: the frame, /// the frame's paragraph, its bytes there, its list, the marker the frame's layout draws for it /// and the numbered paragraphs the frame counts before it at each list level. diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs index 4b8ae5d2be..ddbaec22a2 100644 --- a/crates/engine/src/cmd/params.rs +++ b/crates/engine/src/cmd/params.rs @@ -15,8 +15,8 @@ //! commands a command runs, the steps of a `command.batch` or an `action.batch` included: a //! misspelled `widht` no longer runs the command with its default. So are the `params` of an //! effect (#1592): `effect.apply` and -//! `effect.setParams` answer a key the effect doesn't take, or a value of another type than its -//! default, with a parameter error ([`check_effect_params`]). +//! `effect.setParams` answer a key the effect doesn't take, or a value of another type than the +//! effect reads, with a parameter error ([`check_effect_params`]). //! //! A command with a parameter schema (`CommandSpec::schema`) is also checked against the schema //! before it runs ([`crate::schemas::check`]): the schema refuses a value of the wrong type or out @@ -263,15 +263,15 @@ pub(crate) fn unknown(id: &str, key: &str, keys: &[&str]) -> crate::EngineError } /// `params` of built-in effect `effect`, as command `id` was given them (#1592): only keys the -/// effect takes (those of its dialog defaults and of its params description), each of its -/// default's type, a `color` the effect can draw ([`check_effect_color`]) and a Levels or Curves -/// `channel` the effect has ([`check_effect_channel`]). Numbers out of range pass: the effect -/// clamps them when it draws. An effect plug-in resolves its own against its manifest, and an -/// unknown effect is the command's to report. +/// effect takes (those of its dialog defaults and of its params description), each of the type +/// the effect reads ([`check_effect_types`]), a `color` the effect can draw ([`check_effect_color`]) +/// and a Levels or Curves `channel` the effect has ([`check_effect_channel`]). Numbers out of range +/// pass: the effect clamps them when it draws. An installed effect plug-in's are checked against its +/// manifest, and an unknown effect is the command's to report. pub fn check_effect_params(id: &str, effect: &str, params: &Value) -> Result<()> { let Value::Object(given) = params else { return Ok(()) }; if effect.starts_with(vectorcraft_plugins::effect::PREFIX) { - return Ok(()); + return check_effect_types(id, effect, params); } let Some(info) = vectorcraft_render::effects::effect_info(effect) else { return Ok(()) }; let defaults = info.defaults.as_object(); @@ -282,18 +282,10 @@ pub fn check_effect_params(id: &str, effect: &str, params: &Value) -> Result<()> keys.push(key); } } - for (key, v) in given { - if !keys.contains(&key.as_str()) { - return Err(unknown(id, key, &keys)); - } - match defaults.and_then(|d| d.get(key)) { - Some(Value::Number(_)) if !v.is_number() => return Err(bad(id, format!("`{key}` must be a number"))), - Some(Value::Bool(_)) if !v.is_boolean() => return Err(bad(id, format!("`{key}` must be true or false"))), - // (A colour is also taken as `[r, g, b]` or as a colour object.) - Some(Value::String(_)) if v.is_number() || v.is_boolean() => return Err(bad(id, format!("`{key}` must be a string"))), - _ => {} - } + if let Some(key) = given.keys().find(|k| !keys.contains(&k.as_str())) { + return Err(unknown(id, key, &keys)); } + check_effect_types(id, effect, params)?; // An SVG filter's XML is one drawable <filter> element. if effect == vectorcraft_render::effects::SVG_FILTER && let Some(xml) = given.get("xml") @@ -317,10 +309,71 @@ pub fn check_effect_params(id: &str, effect: &str, params: &Value) -> Result<()> if effect == vectorcraft_render::effects::SVG_FILTER && given.contains_key("name") && !given.contains_key("xml") { return Err(bad(id, "an SVG filter is named by its id: give `xml` with `name`")); } + // A Warp's map is one this build draws: 0, the earlier map, or its style's Bézier net. + let newest = vectorcraft_render::effects::WARP_NET; + if effect.starts_with("warp.") + && let Some(v) = given.get("version") + && vectorcraft_render::effects::warp_version(v).is_none() + { + return Err(bad(id, format!("`version` must be 0 or {newest}"))); + } check_effect_color(id, effect, params)?; check_effect_channel(id, effect, params) } +/// The type of the values in `params` of effect `effect`, as command `id` was given them: a key +/// the effect has a dialog default for takes a value of its default's type, a key only the +/// effect's params description names takes the type the effect reads ([`undefaulted_type`]), and +/// an installed effect plug-in's take the types its manifest gives them. The `style` of Crop Marks +/// is `roman` or `japanese`. A number given as text (`"10 pt"`), `true` for a number, `1` for a +/// switch and `null` for either are refused. +fn check_effect_types(id: &str, effect: &str, params: &Value) -> Result<()> { + let Value::Object(given) = params else { return Ok(()) }; + if effect.starts_with(vectorcraft_plugins::effect::PREFIX) { + return match vectorcraft_plugins::effect::installed(effect) { + Some(plugin) => plugin.manifest().resolve_params(params).map(drop).map_err(|why| bad(id, why.to_string())), + None => Ok(()), + }; + } + let Some(info) = vectorcraft_render::effects::effect_info(effect) else { return Ok(()) }; + for (key, v) in given { + let want = info.defaults.get(key).cloned().or_else(|| undefaulted_type(effect, key)); + match want { + Some(Value::Number(_)) if !v.is_number() => return Err(bad(id, format!("`{key}` must be a number"))), + Some(Value::Bool(_)) if !v.is_boolean() => return Err(bad(id, format!("`{key}` must be true or false"))), + // (A colour is also taken as `[r, g, b]` or as a colour object.) + Some(Value::String(_)) if v.is_number() || v.is_boolean() => return Err(bad(id, format!("`{key}` must be a string"))), + _ => {} + } + } + // Crop Marks draw one of two styles. + if effect == vectorcraft_render::effects::CROP_MARKS + && let Some(style) = given.get("style") + && style.as_str().and_then(vectorcraft_doc::marks::MarkStyle::parse).is_none() + { + return Err(bad(id, "`style` must be roman or japanese")); + } + Ok(()) +} + +/// A value of the type effect `effect` reads for `key`, a parameter its params description names +/// without a dialog default: the earlier 3D Perspective and light (`perspective`, `lightAzimuth`, +/// `lightElevation`) and Scribble `variation` are numbers, an Outline Stroke's `width` is a number +/// and a Gaussian Blur's `linear` is true or false. A Glass or Texturizer `textureImage`, an SVG +/// filter's `name` and `xml`, a Warp's `version` and the `style` of Crop Marks have checks of their +/// own; they aren't listed. +pub(crate) fn undefaulted_type(effect: &str, key: &str) -> Option<Value> { + use vectorcraft_render::effects; + let number = || Some(Value::from(0.0)); + match key { + "perspective" | "lightAzimuth" | "lightElevation" if effects::is_three_d(effect) => number(), + "variation" if effect == "stylize.scribble" => number(), + "width" if effect == "path.outlineStroke" => number(), + "linear" if effect == "blur.gaussian" => Some(Value::Bool(false)), + _ => None, + } +} + /// Can an effect read `v` as its `color`: a string [`Color::from_hex`] reads (`#rrggbb`, `#rgb`, /// `#rrggbbaa`, black, white, red, green, blue), `[r, g, b]` whose first three entries are numbers /// (read on a 0..1 scale) or a color object (`{"model": "rgb", "r": …}`)? The effect draws its @@ -720,9 +773,7 @@ fn check_export_options(id: &str, params: &Value) -> Result<()> { NO_SAVE_FORMAT } "document.export" | "document.exportSelection" | "document.serialize" => { - // `richBlack` is Appearance of Black's setting for a raster export, and `params` an - // exporter plug-in's own. - keys.extend(["includeArtboardFill", "selectedOnly", "richBlack", "params"]); + keys.extend(super::fileio::EXPORT_PARAMS); keys.extend(FORMATS.iter().filter(|f| f.write).flat_map(|f| f.options).map(|o| o.name)); NO_FORMAT } diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index 91da35e51b..2dee458930 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -12,7 +12,7 @@ use super::draw2::usize_opt; use super::pathops::Beside; use super::{ CommandSpec, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, f64_req, finite_numbers, has_anchors, has_doc, has_selected_path, - has_selection, id_param, ids_param, index, number_or, ok, str_param, switch_or, targets, + has_selection, ids_param, index, number_or, object_param, ok, str_param, switch_or, targets, }; use crate::EngineError; @@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> { "Close Path", [], None, - "{id, subpath?: usize (the open subpath to close, 0 included; default: the last open one), in?: [x,y] (handle into the first anchor, placed as path.setHandle places it: a smooth first anchor keeps its outgoing handle in line at its own length, a corner keeps it where it is), out?: [x,y] (the first anchor's outgoing handle, placed after `in`; the anchor becomes a corner), independent?: bool (`in` makes the first anchor a corner and leaves its outgoing handle)}", + "{id, subpath?: usize (the open subpath to close, 0 included; default: the last open one), at?: [x,y] (move the first anchor there, its handles with it, before `in` and `out` are placed), in?: [x,y] (handle into the first anchor, placed as path.setHandle places it: a smooth first anchor keeps its outgoing handle in line at its own length, a corner keeps it where it is), out?: [x,y] (the first anchor's outgoing handle, placed after `in`; the anchor becomes a corner), independent?: bool (`in` makes the first anchor a corner and leaves its outgoing handle)}", has_doc, close ), @@ -168,7 +168,7 @@ pub(super) fn path_mut(d: &mut vectorcraft_doc::Document, id: NodeId) -> Result< } fn append_anchor(s: &mut Session, p: &Value) -> Result<Value> { - let id = id_param(p, "id").ok_or_else(|| bad("path.appendAnchor", "missing id"))?; + let id = object_param(p, "id", "path.appendAnchor")?.ok_or_else(|| bad("path.appendAnchor", "missing id"))?; let a = anchor_from_json(p, "path.appendAnchor")?; let subpath = p.get("subpath").and_then(Value::as_u64).map(|u| u as usize); s.edit("Pen", |d, sel| { @@ -205,13 +205,15 @@ fn append_anchor(s: &mut Session, p: &Value) -> Result<Value> { /// Close the active open subpath of `id`, optionally setting the handles of the first anchor. The /// incoming handle moves as Move Direction Handle moves it: the outgoing handle turns with it only /// on a smooth anchor, so the first segment of a path that starts at a corner keeps its shape. +/// `at` first moves the anchor, its handles with it (the Pen's closing drag with Space held). fn close(s: &mut Session, p: &Value) -> Result<Value> { - let id = id_param(p, "id").ok_or_else(|| bad("path.close", "missing id"))?; + let id = object_param(p, "id", "path.close")?.ok_or_else(|| bad("path.close", "missing id"))?; let subpath = p.get("subpath").and_then(Value::as_u64).map(|u| u as usize); let handle = |key: &str| match p.get(key).filter(|h| !h.is_null()) { None => Ok(None), Some(h) => finite_numbers(h).map(|[x, y]| Some(Point::new(x, y))).ok_or_else(|| bad("path.close", format!("`{key}` must be [x, y]"))), }; + let at = handle("at")?; let h_in = handle("in")?; let h_out = handle("out")?; let independent = switch_or(p, "independent", false, "path.close")?; @@ -223,6 +225,9 @@ fn close(s: &mut Session, p: &Value) -> Result<Value> { }; sp.closed = true; if let Some(first) = sp.anchors.first_mut() { + if let Some(to) = at { + first.translate(to - first.p); + } if let Some(h) = h_in { first.set_handle(false, h, independent); } @@ -303,7 +308,7 @@ pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_ge } fn set_handle(s: &mut Session, p: &Value) -> Result<Value> { - let id = id_param(p, "id").ok_or_else(|| bad("path.setHandle", "missing id"))?; + let id = object_param(p, "id", "path.setHandle")?.ok_or_else(|| bad("path.setHandle", "missing id"))?; let si = usize_opt(p, "subpath", "path.setHandle")?.unwrap_or(0); let ai = p.get("anchor").and_then(Value::as_u64).map(index).ok_or_else(|| bad("path.setHandle", "missing anchor"))?; let out = str_param(p, "which") != Some("in"); @@ -321,7 +326,7 @@ fn set_handle(s: &mut Session, p: &Value) -> Result<Value> { /// `path.moveAnchor`: one anchor to (x, y), its handles keeping their offsets (the Anchor Point /// tool's Shift-drag). fn move_anchor(s: &mut Session, p: &Value) -> Result<Value> { - let id = id_param(p, "id").ok_or_else(|| bad("path.moveAnchor", "missing id"))?; + let id = object_param(p, "id", "path.moveAnchor")?.ok_or_else(|| bad("path.moveAnchor", "missing id"))?; let si = usize_opt(p, "subpath", "path.moveAnchor")?.unwrap_or(0); let ai = p.get("anchor").and_then(Value::as_u64).map(index).ok_or_else(|| bad("path.moveAnchor", "missing anchor"))?; let pos = Point::new(f64_req(p, "x", "path.moveAnchor")?, f64_req(p, "y", "path.moveAnchor")?); @@ -341,7 +346,7 @@ fn move_anchor(s: &mut Session, p: &Value) -> Result<Value> { } fn set_anchors(s: &mut Session, p: &Value) -> Result<Value> { - let id = id_param(p, "id").ok_or_else(|| bad("path.setAnchors", "missing id"))?; + let id = object_param(p, "id", "path.setAnchors")?.ok_or_else(|| bad("path.setAnchors", "missing id"))?; let subs = p.get("subpaths").and_then(Value::as_array).ok_or_else(|| bad("path.setAnchors", "missing subpaths"))?; let data = PathData::new( subs.iter() @@ -476,6 +481,12 @@ fn join_point(sp: &mut SubPath, ai: usize, smooth: bool) { } } +#[cfg(test)] +thread_local! { + /// Anchors that [`merge_coincident`] moved to a lower index of their vector on this thread. + static ANCHOR_MOVES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; +} + /// Merge each run of `picked` neighbours of `sp` that lie on one another into one anchor, which /// keeps the first one's incoming handle and the last one's outgoing handle. Returns how many /// anchors went. @@ -496,23 +507,68 @@ fn merge_coincident(sp: &mut SubPath, picked: impl Fn(usize) -> bool, join_kind: join_point(sp, 0, smooth); } } - // Back to front, so the indices `picked` knows stay true for the anchors still to visit. - for i in (1..sp.anchors.len()).rev() { + // Back to front, so the indices `picked` knows stay true for the anchors still to visit. A + // merged anchor is only marked here; the marked anchors are removed in one pass at the end. + let closed = sp.closed; + let anchors = &mut sp.anchors; + let len = anchors.len(); + let mut gone = vec![false; len]; + // The anchor after `i` that is still on the path, and the last one still on it. + let mut next = None; + let mut last = len.saturating_sub(1); + for i in (1..len).rev() { if picked(i - 1) && picked(i) - && let Some([a, b]) = sp.anchors.get_mut(i - 1..=i) + && let Some([a, b]) = anchors.get_mut(i - 1..=i) && same(a, b) { a.h_out = b.h_out; - sp.anchors.remove(i); - if let Some(smooth) = join_kind { - join_point(sp, i - 1, smooth); + if let Some(slot) = gone.get_mut(i) { + *slot = true; } + if next.is_none() { + last = i - 1; + } + if let Some(smooth) = join_kind { + // The neighbors the anchor has on the path as it now stands, as `join_point` sees them. + let prev = if i > 1 { Some(i - 2) } else { closed.then_some(last) }; + let after = next.or(closed.then_some(0)); + join_point_between(anchors, i - 1, prev, after, smooth); + } + } else { + next = Some(i); } } + #[cfg(test)] + if let Some(first) = gone.iter().position(|&g| g) { + // `retain` moves each anchor it keeps after the first one it drops. + let dropped = gone.iter().filter(|&&g| g).count(); + ANCHOR_MOVES.set(ANCHOR_MOVES.get() + (len - first - dropped)); + } + if gone.contains(&true) { + let mut k = 0; + anchors.retain(|_| { + let keep = !gone.get(k).copied().unwrap_or(false); + k += 1; + keep + }); + } before - sp.anchors.len() } +/// [`join_point`] on anchor `ai` of `anchors` with its neighbors given by index. +fn join_point_between(anchors: &mut [Anchor], ai: usize, prev: Option<usize>, next: Option<usize>, smooth: bool) { + let at = |j: Option<usize>| j.and_then(|j| anchors.get(j)).map(|a| a.p); + let (prev, next) = (at(prev), at(next)); + if let Some(a) = anchors.get_mut(ai) { + if smooth { + a.smooth_between(prev, next); + } else { + a.retract(); + } + } +} + /// Close subpath `si` of path `id`, merging coincident endpoints if present. fn close_subpath_in_node(d: &mut Document, id: NodeId, si: usize, join_kind: Option<bool>) -> Result<()> { let path = path_mut(d, id)?; @@ -746,8 +802,19 @@ pub(super) fn join(s: &mut Session, p: &Value) -> Result<Value> { let mut merged = vec![]; for (id, picked) in &st.selection.anchors { let Some(mut path) = st.doc.node(*id).and_then(|n| n.path_data()).cloned() else { continue }; - let n: usize = - path.subpaths.iter_mut().enumerate().map(|(si, sp)| merge_coincident(sp, |ai| picked.contains(&(si, ai)), join_kind)).sum(); + // One flag per anchor; references past the end of a subpath or to a missing one pick nothing. + let mut masks: Vec<Vec<bool>> = path.subpaths.iter().map(|sp| vec![false; sp.anchors.len()]).collect(); + for &(si, ai) in picked { + if let Some(flag) = masks.get_mut(si).and_then(|m| m.get_mut(ai)) { + *flag = true; + } + } + let n: usize = path + .subpaths + .iter_mut() + .zip(&masks) + .map(|(sp, mask)| merge_coincident(sp, |ai| mask.get(ai).copied().unwrap_or(false), join_kind)) + .sum(); if n > 0 { merged.push((*id, path)); } @@ -1271,7 +1338,7 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result<Value> { .into_iter() .enumerate() .flat_map(|(si, sp)| { - let cuts = refs.iter().filter_map(|&(s, seg)| (s == si).then_some(seg)).collect(); + let cuts = subpath_refs(refs, si).collect(); without_segments(sp, &cuts) }) .filter(|s| s.anchors.len() >= 2) @@ -1283,7 +1350,7 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result<Value> { .into_iter() .enumerate() .flat_map(|(si, sp)| { - let gone = set.iter().filter_map(|&(s, ai)| (s == si).then_some(ai)).collect(); + let gone = subpath_refs(set, si).collect(); without_anchors(sp, &gone) }) .filter(|s| s.anchors.len() >= 2) @@ -1309,6 +1376,12 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result<Value> { ok() } +/// The anchor or segment indexes in `refs` that belong to subpath `si`, in index order. +/// `refs` is ordered by subpath first, so this reads only that subpath's entries. +pub(super) fn subpath_refs(refs: &BTreeSet<(usize, usize)>, si: usize) -> impl Iterator<Item = usize> + '_ { + refs.range((si, 0)..=(si, usize::MAX)).map(|&(_, i)| i) +} + /// Retain path `id` from `d` without copying its geometry before deletion takes its subpaths. /// The shared snapshot supplies the original path classification and, only if needed, gradient /// bounds after the working node's geometry has moved. Returns `NoNode` for a missing/non-path ID. @@ -1562,7 +1635,7 @@ fn renumber_after_insert(sel: &mut Selection, id: NodeId, si: usize, added: usiz } fn reshape(s: &mut Session, p: &Value) -> Result<Value> { - let id = id_param(p, "id").ok_or_else(|| bad("path.reshape", "missing id"))?; + let id = object_param(p, "id", "path.reshape")?.ok_or_else(|| bad("path.reshape", "missing id"))?; let at = Point::new(f64_req(p, "x", "path.reshape")?, f64_req(p, "y", "path.reshape")?); check_numbers(p, &["dx", "dy", "tol", "radius"], "path.reshape")?; let delta = Vec2::new(f64_or(p, "dx", 0.0), f64_or(p, "dy", 0.0)); @@ -1684,7 +1757,7 @@ fn reshape(s: &mut Session, p: &Value) -> Result<Value> { } fn insert_anchor(s: &mut Session, p: &Value) -> Result<Value> { - let id = id_param(p, "id").ok_or_else(|| bad("path.insertAnchor", "missing id"))?; + let id = object_param(p, "id", "path.insertAnchor")?.ok_or_else(|| bad("path.insertAnchor", "missing id"))?; let si = usize_opt(p, "subpath", "path.insertAnchor")?.unwrap_or(0); let seg = p.get("segment").and_then(Value::as_u64).map(index).ok_or_else(|| bad("path.insertAnchor", "missing segment"))?; let t = number_or(p, "t", 0.5, "path.insertAnchor")?.clamp(0.0, 1.0); @@ -1717,7 +1790,7 @@ fn cut_at_anchors(s: &mut Session, _: &Value) -> Result<Value> { let Some(pd) = st.doc.node(*id).and_then(|n| n.path_data()) else { continue }; let (mut subs, mut starts) = (vec![], vec![]); for (si, sp) in pd.subpaths.iter().enumerate() { - let at: BTreeSet<usize> = set.iter().filter(|(s, _)| *s == si).map(|(_, a)| *a).collect(); + let at: BTreeSet<usize> = subpath_refs(set, si).collect(); let pieces = sp.cut_at(&at); // The pieces that start at a cut: every piece of an opened closed subpath, all but the // first of an open one. @@ -1758,3 +1831,140 @@ fn cut_at_anchors(s: &mut Session, _: &Value) -> Result<Value> { })?; Ok(super::draw2::ids_json(&ids)) } + +#[cfg(test)] +mod tests { + use super::*; + + /// `merge_coincident` removing each merged anchor from the vector straight away, kept as the + /// reference the one-pass version must match. + fn merge_coincident_by_removal(sp: &mut SubPath, picked: impl Fn(usize) -> bool, join_kind: Option<bool>) -> usize { + let same = |a: &Anchor, b: &Anchor| a.p.distance(b.p) < 1e-6; + let before = sp.anchors.len(); + if sp.closed + && before > 2 + && picked(0) + && picked(before - 1) + && let [first, .., last] = sp.anchors.as_mut_slice() + && same(first, last) + { + first.h_in = last.h_in; + sp.anchors.pop(); + if let Some(smooth) = join_kind { + join_point(sp, 0, smooth); + } + } + for i in (1..sp.anchors.len()).rev() { + if picked(i - 1) + && picked(i) + && let Some([a, b]) = sp.anchors.get_mut(i - 1..=i) + && same(a, b) + { + a.h_out = b.h_out; + sp.anchors.remove(i); + if let Some(smooth) = join_kind { + join_point(sp, i - 1, smooth); + } + } + } + before - sp.anchors.len() + } + + /// Every field of every anchor, bit for bit. + fn bits(sp: &SubPath) -> (Vec<[u64; 6]>, Vec<AnchorKind>, bool) { + let b = |p: Point| [p.x.to_bits(), p.y.to_bits()]; + let fields = sp.anchors.iter().map(|a| [b(a.p), b(a.h_in), b(a.h_out)].concat().try_into().unwrap()).collect(); + (fields, sp.anchors.iter().map(|a| a.kind).collect(), sp.closed) + } + + /// A small linear congruential generator, so the cases are the same on every run. + struct Lcg(u64); + impl Lcg { + fn below(&mut self, n: u64) -> u64 { + self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (self.0 >> 33) % n + } + } + + fn same_as_removal(sp: &SubPath, picked: &dyn Fn(usize) -> bool, join_kind: Option<bool>) { + let (mut ours, mut theirs) = (sp.clone(), sp.clone()); + let n = merge_coincident(&mut ours, picked, join_kind); + let m = merge_coincident_by_removal(&mut theirs, picked, join_kind); + assert_eq!(n, m, "{sp:?} {join_kind:?}"); + assert_eq!(bits(&ours), bits(&theirs), "{sp:?} {join_kind:?}"); + } + + /// Short paths with points on, near and just past the merge distance, selections with stale + /// indices, every anchor kind and every join kind give the same anchors, bit for bit, as + /// removing each merged anchor straight away. + #[test] + fn merging_coincident_anchors_matches_removing_them_one_by_one() { + let spots = [(0.0, 0.0), (0.0, 0.0), (0.0, 0.0), (5e-7, 0.0), (0.0, 1.5e-6), (10.0, 0.0), (5.0, 5.0), (10.0, 0.0)]; + let mut rng = Lcg(7); + for _ in 0..30_000 { + let n = rng.below(9) as usize; + let anchors = (0..n) + .map(|_| { + let (x, y) = spots[rng.below(spots.len() as u64) as usize]; + let p = Point::new(x, y); + let handle = |rng: &mut Lcg| match rng.below(3) { + 0 => p, + _ => p + Vec2::new(rng.below(7) as f64 - 3.0, rng.below(7) as f64 - 3.0), + }; + let (h_in, h_out) = (handle(&mut rng), handle(&mut rng)); + let kind = if rng.below(2) == 0 { AnchorKind::Corner } else { AnchorKind::Smooth }; + Anchor { p, h_in, h_out, kind } + }) + .collect(); + let sp = SubPath::new(anchors, rng.below(2) == 0); + let picks: Vec<bool> = (0..n + 2).map(|_| rng.below(4) != 0).collect(); + let join_kind = [None, Some(false), Some(true)][rng.below(3) as usize]; + same_as_removal(&sp, &|i| picks.get(i).copied().unwrap_or(false), join_kind); + } + } + + /// A smooth join of three anchors on one another takes the outgoing handle the middle anchor + /// was given when it joined the right one: an already smooth left anchor keeps that handle. + #[test] + fn a_smooth_join_of_three_anchors_keeps_the_handle_the_middle_one_got() { + let o = Point::ZERO; + let left = Anchor { p: o, h_in: Point::new(-2.0, 0.0), h_out: o, kind: AnchorKind::Smooth }; + let right = Anchor { p: o, h_in: o, h_out: Point::new(0.0, 5.0), kind: AnchorKind::Corner }; + let mut sp = SubPath::new(vec![left, Anchor::corner(o), right, Anchor::corner(Point::new(10.0, 0.0))], false); + assert_eq!(merge_coincident(&mut sp, |i| i < 3, Some(true)), 2); + let a = sp.anchors[0]; + assert_eq!((a.h_in, a.h_out, a.kind), (Point::new(-2.0, 0.0), Point::new(10.0 / 3.0, 0.0), AnchorKind::Smooth)); + assert_eq!(sp.anchors.len(), 2); + } + + /// One long run of selected anchors on one another, open or closed, becomes one anchor. + #[test] + fn a_long_run_of_anchors_on_one_another_becomes_one() { + for closed in [false, true] { + for join_kind in [None, Some(false), Some(true)] { + let anchors = (0..50_000).map(|i| Anchor::smooth(Point::ZERO, Point::new(1.0, i as f64))).collect(); + let sp = SubPath::new(anchors, closed); + same_as_removal(&sp, &|_| true, join_kind); + let mut ours = sp.clone(); + assert_eq!(merge_coincident(&mut ours, |_| true, join_kind), 49_999); + assert_eq!((ours.anchors.len(), ours.closed), (1, closed)); + } + } + } + + /// A long selected run at the start of a path followed by as many anchors that stay: each + /// anchor after the run moves once, not once per merged anchor. + #[test] + fn a_long_run_before_many_other_anchors_merges_in_one_pass() { + let run = 300_000; + let anchors = (0..run).map(|_| Anchor::corner(Point::ZERO)).chain((1..=run).map(|i| Anchor::corner(Point::new(i as f64, 1.0)))).collect(); + let mut sp = SubPath::new(anchors, false); + ANCHOR_MOVES.set(0); + assert_eq!(merge_coincident(&mut sp, |i| i < run, Some(false)), run - 1); + assert_eq!(ANCHOR_MOVES.get(), run); + assert_eq!(sp.anchors.len(), run + 1); + assert_eq!(sp.anchors[0].p, Point::ZERO); + assert_eq!(sp.anchors[1].p, Point::new(1.0, 1.0)); + assert_eq!(sp.anchors[run].p, Point::new(run as f64, 1.0)); + } +} diff --git a/crates/engine/src/cmd/pathops.rs b/crates/engine/src/cmd/pathops.rs index 5b9e25d354..b4ce273dad 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -896,7 +896,7 @@ pub(crate) fn outlined_stroke( }; let art = d.reid(&art); let mut art = with_transparency(d, art, st.opacity, st.blend); - let raster: Vec<_> = st.effects.iter().filter(|e| !vectorcraft_render::effects::is_geometry(&e.id)).cloned().collect(); + let raster = vectorcraft_render::effects::without_geometry(&st.effects); if !raster.is_empty() { if !art.appearance.effects.is_empty() { art = Node::group(d.alloc_id(), vec![Arc::new(art)]); @@ -946,7 +946,7 @@ pub(crate) fn outlined_stroke( /// geometry effects leave nothing to paint, an empty group takes the path's place. /// `None` when `l` has no stroke to outline. pub(crate) fn outline_strokes(d: &mut Document, brushes: &[vectorcraft_brush::Brush], l: &Node) -> Option<Node> { - use vectorcraft_render::effects::{GeomContext, apply_geometry_with, has_geometry, has_transform_art, is_geometry, reshape}; + use vectorcraft_render::effects::{GeomContext, apply_geometry_carrying, has_geometry, has_transform_art, reshape, without_geometry}; if !l.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(st) if outlinable(st))) { return None; } @@ -975,7 +975,7 @@ pub(crate) fn outline_strokes(d: &mut Document, brushes: &[vectorcraft_brush::Br parts.push(styled_copy(d, l, std::mem::take(&mut fills))); } let mut plain = moved; - plain.effects_mut().retain(|e| !is_geometry(&e.id)); + *plain.effects_mut() = without_geometry(plain.effects()); parts.push(styled_copy(d, &shape, vec![plain])); } AppearanceItem::Stroke(st) if outlinable(st) => { @@ -983,11 +983,16 @@ pub(crate) fn outline_strokes(d: &mut Document, brushes: &[vectorcraft_brush::Br parts.push(styled_copy(d, l, std::mem::take(&mut fills))); } let mut plain = st.clone(); - plain.effects.retain(|e| !is_geometry(&e.id)); let stroked = match path.bounds() { - Some(b) if has_geometry(&st.effects) => apply_geometry_with(&st.effects, &path, b, &ctx.item(item)), + Some(b) if has_geometry(&st.effects) => { + let (stroked, carry) = apply_geometry_carrying(&st.effects, &path, b, &ctx.item(item)); + // Its raster effects follow only the Transform effects that moved it. + carry.hide_skipped(&mut plain.effects); + stroked + } _ => path.clone(), }; + plain.effects = without_geometry(&plain.effects); parts.extend(outlined_stroke(d, brushes, &stroked, rule, &plain)); } _ => {} @@ -1228,7 +1233,7 @@ fn simplify(s: &mut Session, p: &Value) -> Result<Value> { Some(l) => po::simplify_level_tolerance(l), None => given_tolerance.unwrap_or(1.0), }; - let opts = po::SimplifyOptions { tolerance: tolerance.clamp(1e-4, 1e4), corner_angle_deg: corner_angle, straight_lines, smooth: 0.0 }; + let opts = po::SimplifyOptions { tolerance: tolerance.clamp(1e-4, 1e4), corner_angle_deg: corner_angle, straight_lines, ..Default::default() }; // A path with segments direct-selected simplifies only their runs, and keeps those runs (and the // other anchors it had selected) direct-selected. let roots = selected_roots(s)?; diff --git a/crates/engine/src/cmd/patterncmds.rs b/crates/engine/src/cmd/patterncmds.rs index 4075676ca6..2800e8e674 100644 --- a/crates/engine/src/cmd/patterncmds.rs +++ b/crates/engine/src/cmd/patterncmds.rs @@ -14,6 +14,7 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_color::Paint; use vectorcraft_doc::pattern::{self, Overlap, PATTERN_EDIT_LAYER, PatternDef, PatternEdit, RepeatKind, RepeatSpec, TileType, pattern_paint}; +use vectorcraft_doc::swatches::PaintFn; use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Selection}; use vectorcraft_geom::{Point, Rect}; @@ -54,7 +55,15 @@ pub fn specs() -> Vec<CommandSpec> { in_pattern_edit, pattern_done ), - cmd!("object.pattern.cancel", "Cancel", [], None, "{} leave pattern editing mode, discarding changes", in_pattern_edit, pattern_cancel), + cmd!( + "object.pattern.cancel", + "Cancel", + [], + None, + "{} leave pattern editing mode, discarding changes; a pattern made for this edit is removed with its swatches, and every paint of it, new art's fill and stroke included, becomes none", + in_pattern_edit, + pattern_cancel + ), cmd!( "object.pattern.saveCopy", "Save a Copy", @@ -78,7 +87,7 @@ pub fn specs() -> Vec<CommandSpec> { "Delete Pattern", [], None, - "{name} delete a pattern swatch (objects painted with it lose that paint)", + "{name} delete a pattern and its swatches; every paint of it, new art's fill and stroke included, becomes none → {unpainted: the number of document paints cleared}", has_doc, pattern_delete ), @@ -403,26 +412,96 @@ pub(crate) fn finish_edit(d: &mut Document, sel: &mut Selection) -> Result<Strin Ok(pe.pattern) } +/// Leave pattern editing mode, discarding the changes (`object.pattern.cancel`). An existing +/// pattern gets its definition back, its name included when Pattern Options renamed it while it was +/// edited and no other pattern, swatch or color group has taken that name since. A new pattern is +/// removed with its swatches, and every paint of it left in the document and in the fill, stroke +/// and appearance new art takes becomes no paint ([`forget_pattern`]). fn pattern_cancel(s: &mut Session, _: &Value) -> Result<Value> { - s.edit("Cancel Pattern Editing", |d, sel| { + let changed = s.edit("Cancel Pattern Editing", |d, sel| { let (pe, _) = leave_edit(d, sel)?; match pe.original { - Some(orig) => { + Some(mut orig) => { + if orig.name != pe.pattern && (d.pattern(&orig.name).is_some() || swatch_name_clash(d, &pe.pattern, &orig.name)) { + orig.name = pe.pattern.clone(); + } + let back = (orig.name != pe.pattern).then(|| orig.name.clone()); if let Some(def) = d.pattern_mut(&pe.pattern) { *def = orig; } + if let Some(old) = &back { + rename_pattern_uses(d, &pe.pattern, old); + } + Ok(back.map(|old| (pe.pattern, Some(old)))) } None => { - d.patterns.retain(|p| p.name != pe.pattern); - d.swatches.retain(|sw| !matches!(&sw.paint, Paint::Pattern { pattern, .. } if *pattern == pe.pattern)); + forget_pattern(d, &pe.pattern); + Ok(Some((pe.pattern, None))) } } - Ok(()) })?; after_edit_mode(s, None)?; + if let Some((name, to)) = changed { + map_new_art_paints(s, &mut pattern_paints(&name, to.as_deref()))?; + } ok() } +/// A [`PaintFn`] that puts a paint of pattern `to` in place of each paint of pattern `name`, with +/// its placement kept, or no paint for `to` `None`. +fn pattern_paints<'a>(name: &'a str, to: Option<&'a str>) -> impl FnMut(&Paint) -> Option<Paint> + 'a { + move |p| match p { + Paint::Pattern { pattern, xf } if pattern == name => Some(match to { + Some(n) => Paint::Pattern { pattern: n.to_string(), xf: *xf }, + None => Paint::None, + }), + _ => None, + } +} + +/// Remove pattern `name` from `d`: its definition and every swatch, grouped or not, whose paint is +/// the pattern. Every paint of the pattern left anywhere in the document (the art, opacity masks, +/// type, symbol definitions, graph designs, graphs' stored series and label paints, other patterns' +/// tiles, graphic and character styles and the art of brushes) becomes no paint. Returns the number of such paints. +fn forget_pattern(d: &mut Document, name: &str) -> usize { + d.patterns.retain(|p| p.name != name); + let is_it = |sw: &vectorcraft_color::Swatch| matches!(&sw.paint, Paint::Pattern { pattern, .. } if pattern == name); + d.swatches.retain(|sw| !is_it(sw)); + for g in &mut d.swatch_groups { + g.swatches.retain(|sw| !is_it(sw)); + } + super::swatch::map_all_paints(d, &mut pattern_paints(name, None)) +} + +/// Apply `f` to the fill and stroke new art takes and to the paints of its template appearance. A +/// change is recorded with the step just made, so Undo and Redo put these paints back with the +/// document. +fn map_new_art_paints(s: &mut Session, f: &mut PaintFn) -> Result<()> { + let start = super::colormgmt::new_art_colors_before(s)?; + let old = s.paint.clone(); + let pd = &mut s.paint; + let template = pd.appearance.iter_mut().flat_map(|a| a.items.iter_mut()).map(|it| match it { + vectorcraft_doc::AppearanceItem::Fill(f) => &mut f.paint, + vectorcraft_doc::AppearanceItem::Stroke(s) => &mut s.paint, + }); + for p in [&mut pd.fill, &mut pd.stroke].into_iter().chain(template) { + if let Some(q) = f(p) { + *p = q; + } + } + if s.paint != old { + super::colormgmt::record_new_art_colors(s, start)?; + // The step takes the paints the command finally leaves, after the selection's appearance + // is inherited. + let st = s.doc()?; + if st.interaction.is_none() { + let uid = st.uid; + s.batch_paint_docs.push(uid); + } + } + Ok(()) +} + fn pattern_save_copy(s: &mut Session, p: &Value) -> Result<Value> { let wanted = text_param(p, "name", "object.pattern.saveCopy")?.map(str::trim).filter(|n| !n.is_empty()).map(str::to_string); let name = s.edit("Save a Copy", |d, _| { @@ -524,6 +603,9 @@ fn pattern_options(s: &mut Session, p: &Value) -> Result<Value> { } Ok(()) })?; + if let Some(nn) = &new_name { + map_new_art_paints(s, &mut pattern_paints(&name, Some(nn)))?; + } Ok(json!({ "name": out_name })) } @@ -552,47 +634,19 @@ fn swatch_name_clash(d: &Document, old: &str, new: &str) -> bool { } /// Rename a pattern in swatches, paints and the edit record. Of the swatches named `old`, only the -/// pattern's own take the new name. +/// pattern's own take the new name. The paints are renamed wherever [`forget_pattern`] clears them. fn rename_pattern_uses(d: &mut Document, old: &str, new: &str) { - let fix = |p: &mut Paint| { - if let Paint::Pattern { pattern, .. } = p - && pattern == old - { - *pattern = new.to_string(); - } - }; - for sw in d.swatches.iter_mut().chain(d.swatch_groups.iter_mut().flat_map(|g| g.swatches.iter_mut())) { + for sw in d.swatches_iter_mut() { if sw.name == old && pattern_name(&sw.paint).is_some_and(|p| p == old) { sw.name = new.to_string(); } - fix(&mut sw.paint); } if let Some(pe) = &mut d.pattern_edit && pe.pattern == old { pe.pattern = new.to_string(); } - let ids = nodes_using(d, Some(old)); - for id in ids { - if let Some(n) = d.node_mut(id) { - for it in n.appearance.items.iter_mut() { - match it { - vectorcraft_doc::AppearanceItem::Fill(f) => fix(&mut f.paint), - vectorcraft_doc::AppearanceItem::Stroke(s) => fix(&mut s.paint), - } - } - } - } -} - -fn nodes_using(d: &Document, name: Option<&str>) -> Vec<NodeId> { - let mut ids = vec![]; - d.walk(|n| { - if pattern::uses_pattern(n, name) { - ids.push(n.id); - } - }); - ids + super::swatch::map_all_paints(d, &mut pattern_paints(old, Some(new))); } fn pattern_delete(s: &mut Session, p: &Value) -> Result<Value> { @@ -604,29 +658,8 @@ fn pattern_delete(s: &mut Session, p: &Value) -> Result<Value> { if editing(s).is_some_and(|e| e.pattern == name) { return Err(bad(C, "finish editing the pattern first")); } - let n = s.edit("Delete Pattern", |d, _| { - d.patterns.retain(|p| p.name != name); - let is_it = |sw: &vectorcraft_color::Swatch| matches!(&sw.paint, Paint::Pattern { pattern, .. } if *pattern == name); - d.swatches.retain(|sw| !is_it(sw)); - for g in &mut d.swatch_groups { - g.swatches.retain(|sw| !is_it(sw)); - } - let ids = nodes_using(d, Some(&name)); - for id in &ids { - if let Some(n) = d.node_mut(*id) { - for it in n.appearance.items.iter_mut() { - let p = match it { - vectorcraft_doc::AppearanceItem::Fill(f) => &mut f.paint, - vectorcraft_doc::AppearanceItem::Stroke(s) => &mut s.paint, - }; - if matches!(p, Paint::Pattern { pattern, .. } if *pattern == name) { - *p = Paint::None; - } - } - } - } - Ok(ids.len()) - })?; + let n = s.edit("Delete Pattern", |d, _| Ok(forget_pattern(d, &name)))?; + map_new_art_paints(s, &mut pattern_paints(&name, None))?; Ok(json!({ "unpainted": n })) } diff --git a/crates/engine/src/cmd/patternlib.rs b/crates/engine/src/cmd/patternlib.rs index 011dfc131c..f69e4b889e 100644 --- a/crates/engine/src/cmd/patternlib.rs +++ b/crates/engine/src/cmd/patternlib.rs @@ -23,8 +23,11 @@ pub struct BuiltinPatternLibrary { } /// The built-in pattern libraries (Window → Swatch Libraries → Patterns), in menu order. -pub const PATTERN_LIBRARIES: &[BuiltinPatternLibrary] = - &[BuiltinPatternLibrary { id: "geometric-patterns", name: "Geometric Patterns", make: geometric_patterns }]; +pub const PATTERN_LIBRARIES: &[BuiltinPatternLibrary] = &[ + BuiltinPatternLibrary { id: "geometric-patterns", name: "Geometric Patterns", make: geometric_patterns }, + BuiltinPatternLibrary { id: "grit-textures", name: "Grit Textures", make: grit_textures }, + BuiltinPatternLibrary { id: "optical-effects", name: "Optical Effects", make: optical_effects }, +]; /// The library category of the built-in pattern libraries. pub const CATEGORY: &str = "patterns"; @@ -154,6 +157,262 @@ fn geometric_patterns(d: &mut Document) { add(d, "Zigzag", 10.0, 8.0, TileType::Grid, vec![polygon(&[(0.0, 5.0), (5.0, 1.0), (10.0, 5.0), (10.0, 7.0), (5.0, 3.0), (0.0, 7.0)])]); } +/// SplitMix64, a small generator with a fixed seed per pattern, so a grit pattern draws the same +/// marks every time it is made. +struct SplitMix64(u64); + +impl SplitMix64 { + fn next(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } + + /// A number from `lo` up to, but not including, `hi`. + fn range(&mut self, lo: f64, hi: f64) -> f64 { + lo + (self.next() >> 11) as f64 / (1u64 << 53) as f64 * (hi - lo) + } +} + +/// A round dot of radius `r` at (`x`, `y`). +fn dot(x: f64, y: f64, r: f64) -> PathData { + shapes::ellipse(Rect::new(x - r, y - r, x + r, y + r)) +} + +/// An irregular fleck of four to seven corners about (`x`, `y`), at most `r` from it. +fn fleck(rng: &mut SplitMix64, x: f64, y: f64, r: f64) -> PathData { + use std::f64::consts::TAU; + let n = 4 + (rng.next() % 4) as usize; + let turn = rng.range(0.0, TAU); + let points: Vec<(f64, f64)> = (0..n) + .map(|k| { + let a = turn + TAU * (k as f64 + rng.range(-0.3, 0.3)) / n as f64; + let reach = r * rng.range(0.55, 1.0); + (x + reach * a.cos(), y + reach * a.sin()) + }) + .collect(); + polygon(&points) +} + +/// A thin straight scratch `len` long and `width` wide, centered on (`x`, `y`) at a random angle. +fn scratch(rng: &mut SplitMix64, x: f64, y: f64, len: f64, width: f64) -> PathData { + let (s, c) = rng.range(0.0, std::f64::consts::PI).sin_cos(); + let (hx, hy, wx, wy) = (c * len / 2.0, s * len / 2.0, -s * width / 2.0, c * width / 2.0); + polygon(&[(x - hx - wx, y - hy - wy), (x + hx - wx, y + hy - wy), (x + hx + wx, y + hy + wy), (x - hx + wx, y - hy + wy)]) +} + +/// A grit pattern of `count` marks scattered over a square grid tile of side `size`, drawn from +/// `seed` (`mark` draws one at a point). A mark that reaches past an edge is kept whole: the tiling +/// draws the part outside the tile on the next tile, so the tiles join without a seam. +fn grit(d: &mut Document, name: &str, size: f64, seed: u64, count: usize, mark: impl Fn(&mut SplitMix64, f64, f64) -> PathData) { + let mut rng = SplitMix64(seed); + let marks = (0..count) + .map(|_| { + let (x, y) = (rng.range(0.0, size), rng.range(0.0, size)); + mark(&mut rng, x, y) + }) + .collect(); + add(d, name, size, size, TileType::Grid, marks); +} + +/// Grit Textures: seamless black grain, grit, sand, speckle, stipple, scratch and fleck textures on +/// a clear background, each drawn from its own fixed seed. +fn grit_textures(d: &mut Document) { + grit(d, "Fine Grain", 24.0, 1, 320, |rng, x, y| dot(x, y, rng.range(0.15, 0.35))); + grit(d, "Coarse Grit", 30.0, 2, 150, |rng, x, y| { + let r = rng.range(0.45, 1.1); + fleck(rng, x, y, r) + }); + grit(d, "Sand", 24.0, 3, 280, |rng, x, y| { + let r = rng.range(0.2, 0.45); + fleck(rng, x, y, r) + }); + grit(d, "Speckle", 30.0, 4, 90, |rng, x, y| dot(x, y, rng.range(0.3, 0.9))); + // Stipple: one dot in each cell of a 12 × 12 grid, moved a little off the cell's center. + let mut rng = SplitMix64(5); + let (size, cells) = (24.0, 12); + let step = size / f64::from(cells); + let dots = (0..cells) + .flat_map(|row| (0..cells).map(move |col| (col, row))) + .map(|(col, row)| { + let x = (f64::from(col) + 0.5) * step + rng.range(-0.3, 0.3) * step; + let y = (f64::from(row) + 0.5) * step + rng.range(-0.3, 0.3) * step; + dot(x, y, rng.range(0.3, 0.45)) + }) + .collect(); + add(d, "Stipple", size, size, TileType::Grid, dots); + grit(d, "Scratches", 36.0, 6, 45, |rng, x, y| { + let (len, width) = (rng.range(2.0, 7.0), rng.range(0.15, 0.35)); + scratch(rng, x, y, len, width) + }); + grit(d, "Sparse Flecks", 36.0, 7, 32, |rng, x, y| { + let r = rng.range(0.35, 0.8); + fleck(rng, x, y, r) + }); + grit(d, "Dense Flecks", 18.0, 8, 220, |rng, x, y| { + let r = rng.range(0.2, 0.5); + fleck(rng, x, y, r) + }); +} + +/// `n` + 1 points of the curve `(t, f(t))` for `t` from `t0` to `t1`, evenly spaced. +fn curve(t0: f64, t1: f64, n: u32, f: impl Fn(f64) -> f64) -> Vec<(f64, f64)> { + (0..=n) + .map(|i| { + let t = t0 + (t1 - t0) * f64::from(i) / f64::from(n); + (t, f(t)) + }) + .collect() +} + +/// The closed band between two curves drawn from the same side to the same side: `upper` forward, +/// then `lower` back. +fn band(upper: &[(f64, f64)], lower: &[(f64, f64)]) -> PathData { + let points: Vec<(f64, f64)> = upper.iter().chain(lower.iter().rev()).copied().collect(); + polygon(&points) +} + +/// 72 corners of the circle of radius `r` about (`cx`, `cy`), turning the other way with `reverse`. +fn circle(cx: f64, cy: f64, r: f64, reverse: bool) -> SubPath { + const CORNERS: u32 = 72; + let turn = if reverse { -std::f64::consts::TAU } else { std::f64::consts::TAU }; + let points: Vec<Point> = (0..CORNERS) + .map(|i| { + let a = turn * f64::from(i) / f64::from(CORNERS); + Point::new(cx + r * a.cos(), cy + r * a.sin()) + }) + .collect(); + SubPath::polyline(&points, true) +} + +/// The ring from radius `inner` to `outer` about (`cx`, `cy`): the outer circle and the inner one +/// turning the other way, so the middle stays clear under either fill rule. An `inner` of 0 gives +/// a disk. +fn ring(cx: f64, cy: f64, inner: f64, outer: f64) -> PathData { + let mut subpaths = vec![circle(cx, cy, outer, false)]; + if inner > 0.0 { + subpaths.push(circle(cx, cy, inner, true)); + } + PathData::new(subpaths) +} + +/// A lens `2 × l` long and `2 × h` high about (`cx`, `cy`), lying along x: two half sine waves that +/// meet at its tips, turning the other way with `reverse`. +fn lens(cx: f64, cy: f64, l: f64, h: f64, reverse: bool) -> SubPath { + const STEPS: u32 = 32; + let at = |i: u32, side: f64| { + let t = f64::from(i) / f64::from(STEPS); + Point::new(cx - l + 2.0 * l * t, cy + side * h * (std::f64::consts::PI * t).sin()) + }; + let mut points: Vec<Point> = (0..=STEPS).map(|i| at(i, -1.0)).chain((1..STEPS).rev().map(|i| at(i, 1.0))).collect(); + if reverse { + points.reverse(); + } + SubPath::polyline(&points, true) +} + +/// Optical Effects: black waves, rings, warped checks, pinched stripes, chevrons and lenses on a +/// clear background. Each tile is one period of its design, so a band that leaves one edge comes +/// back at the same place on the opposite edge. Art that reaches past an edge is kept whole: the +/// tiling draws the part outside the tile on the next tile. +fn optical_effects(d: &mut Document) { + use std::f64::consts::TAU; + // Three bands 5 pt wide, 12 pt apart, each one sine wave across the tile. + let bands = (0..3u32) + .map(|k| { + let mid = move |x: f64| 6.0 + 12.0 * f64::from(k) + 3.0 * (TAU * x / 36.0).sin(); + band(&curve(0.0, 36.0, 48, |x| mid(x) - 2.5), &curve(0.0, 36.0, 48, |x| mid(x) + 2.5)) + }) + .collect(); + add(d, "Sine Bands", 36.0, 36.0, TileType::Grid, bands); + // Nine thin waves 4 pt apart, two waves across the tile, each a ninth of a wave on from the one + // above it, so the ninth leads into the first wave of the next tile down. + let lines = (0..9u32) + .map(|k| { + let (y, phase) = (2.0 + 4.0 * f64::from(k), TAU * f64::from(k) / 9.0); + let mid = move |x: f64| y + 2.5 * (TAU * x / 18.0 + phase).sin(); + band(&curve(0.0, 36.0, 72, |x| mid(x) - 0.6), &curve(0.0, 36.0, 72, |x| mid(x) + 0.6)) + }) + .collect(); + add(d, "Ripple Lines", 36.0, 36.0, TileType::Grid, lines); + // Thin rings 3 pt apart about the center and rings 3.3 pt apart about a point 4 pt to its + // right. The two sets cross, and the outer rings reach into the next tile across. + let rings = (1..=7u32) + .map(|k| (24.0, 3.0 * f64::from(k))) + .chain((1..=7u32).map(|k| (28.0, 3.3 * f64::from(k)))) + .map(|(cx, r)| ring(cx, 24.0, r - 0.6, r + 0.6)) + .collect(); + add(d, "Interference Rings", 48.0, 48.0, TileType::Grid, rings); + // Rings 2 pt and 1 pt wide by turns about the tile's corner and about its center, the center's + // starting with the narrower one. The corner's rings are the same rings at all four corners. + let mut rings = vec![]; + for (c, first) in [(0.0, 0), (20.0, 1)] { + let mut r = 0.0; + for k in 0..5 { + let width = if (k + first) % 2 == 0 { 2.0 } else { 1.0 }; + rings.push(ring(c, c, r, r + width)); + r += width + 1.2; + } + } + add(d, "Offset Rings", 40.0, 40.0, TileType::Grid, rings); + // An 8 × 8 checkerboard of 4 pt cells whose columns are bent by a sine wave down the tile and + // whose rows by one across it, each edge drawn through five points. + let warp = |x: f64, y: f64| (x + 2.0 * (TAU * y / 32.0).sin(), y + 2.0 * (TAU * x / 32.0).sin()); + let cells = (0..8u32) + .flat_map(|row| (0..8u32).map(move |col| (col, row))) + .filter(|(col, row)| (col + row) % 2 == 0) + .map(|(col, row)| { + let (x, y) = (4.0 * f64::from(col), 4.0 * f64::from(row)); + let corners = [(x, y), (x + 4.0, y), (x + 4.0, y + 4.0), (x, y + 4.0), (x, y)]; + let points: Vec<(f64, f64)> = corners + .windows(2) + .flat_map(|e| { + let (a, b) = (e[0], e[1]); + (0..4u32).map(move |i| { + let t = f64::from(i) / 4.0; + warp(a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t) + }) + }) + .collect(); + polygon(&points) + }) + .collect(); + add(d, "Warped Checks", 32.0, 32.0, TileType::Grid, cells); + // Six upright stripes 6 pt apart that widen from 0.8 pt to 5.6 pt and narrow again down the tile, + // each a sixth of a wave on from the one to its left. + let stripes = (0..6u32) + .map(|k| { + let (x, phase) = (3.0 + 6.0 * f64::from(k), TAU * f64::from(k) / 6.0); + let half = move |y: f64| 1.6 + 1.2 * (TAU * y / 36.0 + phase).cos(); + let side = |s: f64| -> Vec<(f64, f64)> { curve(0.0, 36.0, 48, |y| x + s * half(y)).into_iter().map(|(y, at)| (at, y)).collect() }; + band(&side(-1.0), &side(1.0)) + }) + .collect(); + add(d, "Pinched Stripes", 36.0, 36.0, TileType::Grid, stripes); + // Four zigzag bands 8 pt apart, two zigzags across the tile; the bend and the width of the bands + // rise and fall from band to band. + let chevrons = [(0.0, 3.0, 4.0), (8.0, 4.5, 2.5), (16.0, 3.0, 1.0), (24.0, 1.5, 2.5)] + .into_iter() + .map(|(y, bend, width)| { + let upper: Vec<(f64, f64)> = (0..=4u32).map(|i| (8.0 * f64::from(i), if i % 2 == 1 { y + bend } else { y })).collect(); + let lower: Vec<(f64, f64)> = upper.iter().map(|&(x, y)| (x, y + width)).collect(); + band(&upper, &lower) + }) + .collect(); + add(d, "Chevron Pulse", 32.0, 32.0, TileType::Grid, chevrons); + // Five nested lens outlines 1.5 pt wide about the center, 14 pt to 78 pt long. The longer ones + // reach across the side edges and cross the next tiles' lenses. + let lenses = (0..5u32) + .map(|k| { + let (l, h) = (7.0 + 8.0 * f64::from(k), 4.0 + 4.0 * f64::from(k)); + PathData::new(vec![lens(24.0, 24.0, l, h, false), lens(24.0, 24.0, l - 1.5, h - 1.5, true)]) + }) + .collect(); + add(d, "Radiating Lenses", 48.0, 48.0, TileType::Grid, lenses); +} + #[cfg(test)] mod tests { use super::*; @@ -168,4 +427,157 @@ mod tests { assert_eq!(existing_pattern(&d, &lib, "Dots").as_deref(), expected, "{other}"); } } + + fn grit_doc() -> Document { + let mut d = Document::new(100.0, 100.0); + grit_textures(&mut d); + d + } + + #[test] + fn grit_textures_draw_the_same_marks_every_time() { + let (a, b) = (grit_doc(), grit_doc()); + assert_eq!(a.patterns.len(), 8); + assert_eq!(a.patterns, b.patterns); + } + + /// Every grit tile is 18 to 36 pt with at most 600 marks, each with an area, touching the tile + /// and near it. Marks reach past the edges, and the tiling draws a tile's art on the next tile + /// across each edge a mark crosses. No mark is another mark moved by a whole tile, which the tiling would draw + /// twice in one place. + #[test] + fn grit_tiles_join_without_a_seam() { + let mut crossing = 0; + for p in &grit_doc().patterns { + let (w, h) = (p.width(), p.height()); + assert!((18.0..=36.0).contains(&w) && w == h && p.tile.x0 == 0.0 && p.tile.y0 == 0.0, "{}", p.name); + assert!(!p.art.is_empty() && p.art.len() <= 600, "{}: {} marks", p.name, p.art.len()); + let bounds: Vec<Rect> = p + .art + .iter() + .map(|n| match &n.kind { + vectorcraft_doc::NodeKind::Path { path, .. } => path.bounds().unwrap_or_else(|| panic!("{}: an empty mark", p.name)), + _ => panic!("{}: a mark that is not a path", p.name), + }) + .collect(); + let near = |a: &Rect, b: Rect| { + (a.x0 - b.x0).abs() < 1e-9 && (a.y0 - b.y0).abs() < 1e-9 && (a.x1 - b.x1).abs() < 1e-9 && (a.y1 - b.y1).abs() < 1e-9 + }; + let band = p.tile.inflate(w / 4.0, h / 4.0); + for b in &bounds { + assert!(b.width() > 0.0 && b.height() > 0.0, "{}: {b:?}", p.name); + assert!(b.x1 > 0.0 && b.y1 > 0.0 && b.x0 < w && b.y0 < h, "{}: {b:?} does not touch the tile", p.name); + assert!(b.x0 >= band.x0 && b.y0 >= band.y0 && b.x1 <= band.x1 && b.y1 <= band.y1, "{}: {b:?} is too far out", p.name); + // The tile past each edge the mark crosses draws this tile's art. + let (dx, dy) = (f64::from(i8::from(b.x1 > w) - i8::from(b.x0 < 0.0)), f64::from(i8::from(b.y1 > h) - i8::from(b.y0 < 0.0))); + for (x, y) in [(dx, 0.0), (0.0, dy), (dx, dy)] { + let next = p.tile + kurbo::Vec2::new(x * w, y * h); + assert!(p.offsets_covering(next).contains(&kurbo::Vec2::ZERO), "{}: {b:?} is cut off at {next:?}", p.name); + } + crossing += usize::from(dx != 0.0 || dy != 0.0); + for (dx, dy) in [(w, 0.0), (-w, 0.0), (0.0, h), (0.0, -h), (w, h), (w, -h), (-w, h), (-w, -h)] { + let moved = *b + kurbo::Vec2::new(dx, dy); + assert!(!bounds.iter().any(|o| near(o, moved)), "{}: {b:?} is drawn twice by the tiling", p.name); + } + } + } + assert!(crossing > 0, "no mark reaches past an edge"); + } + + const OPTICAL: [&str; 8] = + ["Sine Bands", "Ripple Lines", "Interference Rings", "Offset Rings", "Warped Checks", "Pinched Stripes", "Chevron Pulse", "Radiating Lenses"]; + + fn optical_doc() -> Document { + let mut d = Document::new(100.0, 100.0); + optical_effects(&mut d); + d + } + + /// The paths of pattern `p`'s art, each with its fill rule. + fn paths(p: &PatternDef) -> Vec<(&PathData, vectorcraft_geom::FillRule)> { + p.art + .iter() + .map(|n| match &n.kind { + vectorcraft_doc::NodeKind::Path { path, rule, .. } => (path, *rule), + _ => panic!("{}: art that is not a path", p.name), + }) + .collect() + } + + #[test] + fn optical_effects_is_a_pattern_library_of_eight_bounded_tiles() { + let b = PATTERN_LIBRARIES.iter().find(|b| b.id == "optical-effects").expect("Optical Effects is listed"); + assert_eq!(b.name, "Optical Effects"); + let names: Vec<String> = library_doc(b.id).unwrap().patterns.iter().map(|p| p.name.clone()).collect(); + assert_eq!(names, OPTICAL); + // Made twice, the art is the same. + let (a, again) = (optical_doc(), optical_doc()); + assert_eq!(a.patterns, again.patterns); + for p in &a.patterns { + let (w, h) = (p.width(), p.height()); + assert!((32.0..=48.0).contains(&w) && w == h && p.tile.x0 == 0.0 && p.tile.y0 == 0.0, "{}", p.name); + assert_eq!(p.tile_type, TileType::Grid, "{}", p.name); + let paths = paths(p); + let segments: usize = paths.iter().flat_map(|(path, _)| &path.subpaths).map(SubPath::segment_count).sum(); + assert!(!paths.is_empty() && paths.len() <= 600 && segments <= 20_000, "{}: {} paths, {segments} segments", p.name, paths.len()); + for (path, _) in &paths { + let b = path.bounds().unwrap_or_else(|| panic!("{}: an empty path", p.name)); + assert!([b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()) && b.width() > 0.0 && b.height() > 0.0, "{}: {b:?}", p.name); + assert!(b.x1 > 0.0 && b.y1 > 0.0 && b.x0 < w && b.y0 < h, "{}: {b:?} does not touch the tile", p.name); + } + } + } + + /// Just either side of a tile's right and bottom edges, the tiling paints the same points: a band + /// cut off at an edge, or one that comes back at another height or width, paints one side only. + /// No path is another moved by a whole tile, which the tiling would draw twice in one place. + #[test] + fn optical_tiles_join_without_a_seam() { + const SAMPLES: u32 = 400; + const STEP: f64 = 1e-4; + for p in &optical_doc().patterns { + let (w, h) = (p.width(), p.height()); + let shapes: Vec<(BezPathFill, Rect)> = + paths(p).into_iter().map(|(path, rule)| ((path.to_bezpath(), rule), path.bounds().unwrap_or(Rect::ZERO))).collect(); + let paints = |q: Point| { + let near = Rect::new(q.x - STEP, q.y - STEP, q.x + STEP, q.y + STEP); + p.offsets_covering(near).into_iter().any(|o| { + let at = q - o; + shapes.iter().any(|((bp, rule), b)| { + let inside = b.x0 <= at.x && at.x <= b.x1 && b.y0 <= at.y && at.y <= b.y1; + let turns = if inside { kurbo::Shape::winding(bp, at) } else { 0 }; + match rule { + vectorcraft_geom::FillRule::EvenOdd => turns % 2 != 0, + vectorcraft_geom::FillRule::NonZero => turns != 0, + } + }) + }) + }; + let (mut differ, mut painted) = (0, 0); + for i in 0..SAMPLES { + let t = (f64::from(i) + 0.37) / f64::from(SAMPLES); + let (right, bottom) = (Point::new(w, t * h), Point::new(t * w, h)); + let (dx, dy) = (kurbo::Vec2::new(STEP, 0.0), kurbo::Vec2::new(0.0, STEP)); + for (a, b) in [(right - dx, right + dx), (bottom - dy, bottom + dy)] { + let (pa, pb) = (paints(a), paints(b)); + differ += usize::from(pa != pb); + painted += usize::from(pa); + } + } + assert!(differ <= 2, "{}: {differ} of {} points across the edges differ", p.name, 2 * SAMPLES); + assert!(painted > 0, "{}: nothing crosses an edge", p.name); + let bounds: Vec<Rect> = shapes.iter().map(|(_, b)| *b).collect(); + let same = |a: &Rect, b: Rect| { + (a.x0 - b.x0).abs() < 1e-9 && (a.y0 - b.y0).abs() < 1e-9 && (a.x1 - b.x1).abs() < 1e-9 && (a.y1 - b.y1).abs() < 1e-9 + }; + for b in &bounds { + for (dx, dy) in [(w, 0.0), (-w, 0.0), (0.0, h), (0.0, -h), (w, h), (w, -h), (-w, h), (-w, -h)] { + let moved = *b + kurbo::Vec2::new(dx, dy); + assert!(!bounds.iter().any(|o| same(o, moved)), "{}: {b:?} is drawn twice by the tiling", p.name); + } + } + } + } + + type BezPathFill = (vectorcraft_geom::BezPath, vectorcraft_geom::FillRule); } diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index a59e7267e0..20f19ef803 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -5,12 +5,14 @@ //! the file declares ([`fileio::ppi`]; 72 ppi when it declares none), linked to its file with //! `link` ([`super::links`]). //! - An SVG becomes one group of its art; so does a DXF drawing, read with the DXF options -//! (`dxf`, [`fileio::dxfimport`]). -//! - An EMF or WMF picture becomes one group, clipped to its frame (`crop: "crop"`) or bounded by -//! its art (`crop: "bounding"`). +//! (`dxf`, [`fileio::dxfimport`]), and an HP-GL plot file (`vectorcraft_cad::hpgl`). +//! - An EMF, WMF or PICT picture becomes one group, clipped to its frame (`crop: "crop"`) or +//! bounded by its art (`crop: "bounding"`). //! - An EPS file (or a PostScript .ai) becomes one group, clipped to its bounding box or bounded by //! its art: the document an EPS file of ours carries, else what its PostScript draws, else its //! preview ([`fileio::load`]). +//! - A DCS file, an EPS file with one program per printing plate, becomes one linked image of its +//! plates ([`dcs`]); it is never embedded. //! - A PDF/.ai/.ait page or a native document's artboard becomes one group, clipped to the page //! (`crop: "crop"`; a PDF page's `art`, `trim`, `bleed` or `media` box too) or bounded by its art //! (`crop: "bounding"`). With Link, a PDF/.ai/.ait page placed from a file becomes a placed @@ -32,6 +34,7 @@ //! `place` tool) with several files, which emits one `file.place` per click or drag. pub(crate) mod adopt; +pub(crate) mod dcs; mod doc; pub(crate) mod document; pub(crate) mod docx; @@ -55,6 +58,9 @@ use crate::{EngineError, MAX_COORD}; const PLACE: &str = "file.place"; const QUEUE: &str = "file.place.queue"; +/// The error of a file read apart from the session while another document is active, or after the +/// document it was read for closed ([`Session::place_read`], [`Session::place_queue_read`]). +const NOT_ACTIVE: &str = "the document it was prepared for is no longer active"; /// The most files one `file.place.queue` loads. const MAX_QUEUE: usize = 100; /// The longest thumbnail side `thumbnail` may ask for (px). @@ -69,7 +75,7 @@ pub fn specs() -> Vec<CommandSpec> { "Place…", ["File"], Some("Cmd+Shift+P"), - "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set), platform?: \"windows\" (Windows-1252) | \"mac\" (Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at)} → {ids, name, format, linked, width, height, warnings}. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, PDF/.ai, EMF/WMF (clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", + "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set), platform?: \"windows\" (Windows-1252) | \"mac\" (Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file placed in a clip group, which the Links commands take}. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", has_doc, place ), @@ -78,7 +84,7 @@ pub fn specs() -> Vec<CommandSpec> { "Placed File Info", [], None, - "{path | name | dataBase64 (a file's path, or its name with its bytes), page?, crop?, password?, thumbnail?: px, link?: bool, dxf?: {…} (both as file.place)} what file.place would place, without placing it → {name, format, width, height (pt at 100%), pixelWidth?, pixelHeight?, ppi?: [x, y], colorMode?: RGB|Grayscale|CMYK (raster images), warnings, thumbnailBase64?: PNG of at most `thumbnail` (≤ 512) px on its longer side}", + "{path | name | dataBase64 (a file's path, or its name with its bytes), page?, crop?, password?, thumbnail?: px, link?: bool, dxf?: {…} (both as file.place)} what file.place would place, without placing it → {name, format, width, height (pt at 100%), pixelWidth?, pixelHeight?, ppi?: [x, y], colorMode?: RGB|Grayscale|CMYK (raster images), plates?: [ink names] (a DCS file), warnings, thumbnailBase64?: PNG of at most `thumbnail` (≤ 512) px on its longer side}", always, info ), @@ -87,7 +93,7 @@ pub fn specs() -> Vec<CommandSpec> { "Image Info", [], None, - "{id?} an image object (default: the one selected) → {id, name, linked, link, colorMode: RGB|Grayscale|CMYK, pixelWidth, pixelHeight, ppi: [x, y] at its placed size, width, height}", + "{id?} an image object (default: the one selected) → {id, name, linked, link (the linked file's path; null when embedded, or when automation read roots are in force and the file is outside them), colorMode: RGB|Grayscale|CMYK, pixelWidth, pixelHeight, ppi: [x, y] at its placed size, width, height}", has_doc, image_info ), @@ -114,6 +120,8 @@ enum Art { /// A VectorCraft document or a PDF/.ai page placed linked: the file read, the link, and /// whether the art's bounds (not the artboard or page) are shown. Document(document::Source, LinkInfo, bool), + /// A DCS file: one linked image of its plates, clipped by its clipping path ([`dcs`]). + Dcs(Box<dcs::DcsArt>), Vector { /// The loaded document: the source of the art's resources. src: Box<Document>, @@ -205,6 +213,15 @@ fn load(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool) -> Result<Loa )); } let crop = opts.crop != CropTo::Bounding; + // A DCS file stays linked to its file, which its plates print from; its parameters are checked + // as an EPS file's are. + if dcs::is_dcs(&src.bytes) { + let path = src.path.filter(|_| bool_or(p, "link", true)).map(fileio::absolute_path).ok_or_else(|| bad(cmd, dcs::LINK_ONLY))?; + let a = dcs::read(&src.bytes, Some(&path)).map_err(|e| bad(cmd, format!("{name}: {e}")))?; + let link = super::links::link_info(&path, &src.bytes); + let (natural, warnings) = (a.page, a.warnings.clone()); + return Ok(Loaded { name, format, art: Art::Dcs(Box::new(a)), natural, warnings, link: Some(link), board: None }); + } // A VectorCraft document: placed linked from its file, else as an editable copy. if matches!(format.id, "vectorcraft" | "template") { let page = page as u32; @@ -264,7 +281,7 @@ fn load(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool) -> Result<Loa let board = doc.artboards.first().map(|a| a.rect).filter(|_| anchored); let layers = std::mem::take(&mut doc.layers); let symbols = doc.symbol_boxes(); - let (nodes, clip) = if matches!(format.id, "svg" | "svgz" | "dxf") { + let (nodes, clip) = if matches!(format.id, "svg" | "svgz" | "dxf" | "hpgl") { // An SVG with `crop: "crop"` asked for is framed and clipped by its viewBox (its artboard), // as a PDF by its page: art drawn on a shared canvas keeps its place and scale (#788). By // default, as Illustrator places one, it is its art's bounds. @@ -408,6 +425,21 @@ fn build(d: &mut Document, l: Loaded, link: Option<LinkInfo>) -> Node { }; Node::new(d.alloc_id(), NodeKind::Image(Box::new(im))) } + Art::Dcs(a) => { + let a = *a; + super::links::store_image(d, &a.img.key, a.img.blob, link.is_some()); + dcs::add_spot_swatches(d, &a.spots); + let im = + ImageObject { key: a.img.key, width: a.img.width, height: a.img.height, xf: a.xf, link, placement: Default::default(), pixels: None }; + let image = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im))); + match a.clip { + Some(c) => { + let children = vec![Arc::new(d.reid(&c)), Arc::new(image)]; + Node::new(d.alloc_id(), NodeKind::Group { children, clip: true }) + } + None => image, + } + } Art::Text(t) => Node::new(d.alloc_id(), NodeKind::Text(Box::new(text::area_text(t, l.natural, &d.setup)))), Art::Document(s, link, bounding) => document::node(d, &s, link, bounding), Art::Vector { src, mut nodes, clip } => { @@ -474,11 +506,13 @@ fn fit(natural: Rect, r: Rect) -> Affine { Affine::translate(r.center().to_vec2()) * Affine::scale(k) * Affine::translate(-natural.center().to_vec2()) } -/// What `file.place` takes from the session before it reads the file: the params, the object -/// Replace swaps and the artboard under `at`, which a DXF drawing is laid out on -/// ([`Session::prepare_place`]). [`PlaceJob::read`] reads and decodes the file without the session, -/// on any thread. +/// What `file.place` takes from the session before it reads the file: the document it places into, +/// the params, the object Replace swaps and the artboard under `at`, which a DXF drawing is laid +/// out on ([`Session::prepare_place`]). [`PlaceJob::read`] reads and decodes the file without the +/// session, on any thread. pub struct PlaceJob { + /// The document it was prepared in (`DocState::uid`). + doc: u64, params: Value, old: Option<NodeId>, /// The object Replace swaps as it was when Place started. @@ -506,9 +540,13 @@ impl PlaceJob { pub fn read(self) -> Result<PlaceRead> { let mut loaded = load(&self.params, PLACE, self.target, true)?; let linked = loaded.link.is_some() && bool_or(&self.params, "link", true); - if let Art::Image(img) = &mut loaded.art { - let unread = super::links::kept_unread(&img.blob.bytes); - img.blob = super::links::readable_and_kept(img.blob.clone(), unread, linked)?; + match &mut loaded.art { + Art::Image(img) => { + let unread = super::links::kept_unread(&img.blob.bytes); + img.blob = super::links::readable_and_kept(img.blob.clone(), unread, linked)?; + } + Art::Dcs(a) => a.img.blob = super::links::readable(a.img.blob.clone(), false, true)?, + _ => {} } Ok(PlaceRead { job: self, loaded }) } @@ -527,10 +565,14 @@ impl Session { /// Run `file.place` with the params of `read` as a command (checked and journaled as any /// other) that places the file `read` holds instead of reading it again → `file.place`'s - /// reply. The object Replace swaps must still be in the document as it was when Place started; - /// when the selection changed meanwhile, `select.set` selects that object again first, so a - /// replay of the journal replaces the same object. + /// reply. The document Place started in must be the active one, and the object Replace swaps + /// must still be in it as it was when Place started; when the selection changed meanwhile, + /// `select.set` selects that object again first, so a replay of the journal replaces the same + /// object. pub fn place_read(&mut self, read: PlaceRead) -> Result<Value> { + if self.doc()?.uid != read.job.doc { + return Err(bad(PLACE, NOT_ACTIVE)); + } let params = read.job.params.clone(); if let Some(old) = read.job.old { let st = self.doc()?; @@ -582,7 +624,7 @@ fn prepare(s: &Session, p: &Value) -> Result<PlaceJob> { (true, _) => return Err(bad(PLACE, "replace: select the one object to replace")), }; let replaced = old.and_then(|id| st.doc.node(id)).cloned(); - Ok(PlaceJob { params: p.clone(), old, replaced, target: board_at(&st.doc, at) }) + Ok(PlaceJob { doc: st.uid, params: p.clone(), old, replaced, target: board_at(&st.doc, at) }) } /// Place the file `read` holds in the active document. @@ -628,7 +670,11 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> { let below = st.current_layer().or_else(|| parent.and_then(|p| st.doc.layer_of(p))); let link = loaded.link.take().filter(|_| bool_or(p, "link", true)); let linked = link.is_some(); - let (name, format, warnings) = (loaded.name.clone(), loaded.format.id, std::mem::take(&mut loaded.warnings)); + let (name, format, mut warnings) = (loaded.name.clone(), loaded.format.id, std::mem::take(&mut loaded.warnings)); + let dcs_clipped = matches!(&loaded.art, Art::Dcs(a) if a.clip.is_some()); + if let Art::Dcs(a) = &loaded.art { + warnings.extend(dcs::swatch_notes(&st.doc, &a.spots)); + } let (id, size) = s.edit("Place", |d, sel| { let node = transformed(build(d, loaded, link), m); let size = node.geometric_bounds_with(&d.symbol_boxes()).unwrap_or_default(); @@ -650,9 +696,18 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> { } Ok((id, size)) })?; - Ok( - json!({ "ids": [id.0], "name": name, "format": format, "linked": linked, "width": size.width(), "height": size.height(), "warnings": warnings }), - ) + let mut out = json!({ "ids": [id.0], "name": name, "format": format, "linked": linked, "width": size.width(), "height": size.height(), "warnings": warnings }); + // A DCS file clipped by its clipping path: its image, which the Links commands take. + if dcs_clipped { + let image = s.doc()?.doc.node(id).and_then(|n| match &n.kind { + NodeKind::Group { children, clip: true } => children.get(1).filter(|c| matches!(c.kind, NodeKind::Image(_))).map(|c| c.id), + _ => None, + }); + if let Some(image) = image { + out["image"] = json!(image.0); + } + } + Ok(out) } /// The artboard under `at` (its edges included, [`Document::artboard_holding`]), else the first. @@ -709,6 +764,8 @@ fn queued_files(p: &Value) -> Result<Vec<Value>> { /// ([`Session::prepare_place_queue`]). [`QueueJob::read`] reads them without the session, on any /// thread. pub struct QueueJob { + /// The document it was prepared in (`DocState::uid`). + doc: u64, params: Value, files: Vec<Value>, } @@ -716,6 +773,8 @@ pub struct QueueJob { /// The files [`QueueJob::read`] read, which [`Session::place_queue_read`] loads the place cursor /// with. pub struct QueueRead { + /// The document the files were read for (`DocState::uid`). + doc: u64, params: Value, entries: Vec<Value>, files: Vec<Value>, @@ -730,13 +789,13 @@ impl QueueJob { /// Read every file for its size and thumbnail, as `file.place.queue` does, without the session. pub fn read(self) -> Result<QueueRead> { - read_queue(self.params, self.files) + read_queue(self.doc, self.params, self.files) } } -/// Read each of `queued`, the files of `file.place.queue` with params `p`, for its size and -/// thumbnail. -fn read_queue(p: Value, queued: Vec<Value>) -> Result<QueueRead> { +/// Read each of `queued`, the files of `file.place.queue` with params `p` for the document `doc`, +/// for its size and thumbnail. +fn read_queue(doc: u64, p: Value, queued: Vec<Value>) -> Result<QueueRead> { let thumbnail = p.get("thumbnail").and_then(Value::as_f64); let (mut entries, mut files, mut skipped) = (vec![], vec![], vec![]); for mut q in queued { @@ -750,10 +809,14 @@ fn read_queue(p: Value, queued: Vec<Value>) -> Result<QueueRead> { // so that drawing it does not decode the file again. let checked = load(&q, QUEUE, None, false).and_then(|mut l| { let linked = l.link.is_some() && bool_or(&q, "link", true); - if let Art::Image(img) = &mut l.art { - let unread = super::links::kept_unread(&img.blob.bytes); - let check = if thumbnail.is_some() { super::links::readable_and_kept } else { super::links::readable }; - img.blob = check(img.blob.clone(), unread, linked)?; + match &mut l.art { + Art::Image(img) => { + let unread = super::links::kept_unread(&img.blob.bytes); + let check = if thumbnail.is_some() { super::links::readable_and_kept } else { super::links::readable }; + img.blob = check(img.blob.clone(), unread, linked)?; + } + Art::Dcs(a) => a.img.blob = super::links::readable(a.img.blob.clone(), false, true)?, + _ => {} } Ok(l) }); @@ -773,7 +836,7 @@ fn read_queue(p: Value, queued: Vec<Value>) -> Result<QueueRead> { } } } - Ok(QueueRead { params: p, entries, files, skipped }) + Ok(QueueRead { doc, params: p, entries, files, skipped }) } impl Session { @@ -784,12 +847,17 @@ impl Session { has_doc(self).map_err(|why| EngineError::Disabled(QUEUE.into(), why))?; check_switches(params, &["link", "template"], QUEUE)?; check_numbers(params, &["thumbnail"], QUEUE)?; - Ok(QueueJob { params: params.clone(), files: queued_files(params)? }) + let files = queued_files(params)?; + Ok(QueueJob { doc: self.doc()?.uid, params: params.clone(), files }) } /// Run `file.place.queue` with the params of `read` as a command that loads the place cursor - /// with the files `read` holds instead of reading them again → `file.place.queue`'s reply. + /// with the files `read` holds instead of reading them again → `file.place.queue`'s reply. The + /// document the files were read for must be the active one. pub fn place_queue_read(&mut self, read: QueueRead) -> Result<Value> { + if self.doc()?.uid != read.doc { + return Err(bad(QUEUE, NOT_ACTIVE)); + } let params = read.params.clone(); self.queue_hand_off = Some(read); let r = self.execute(QUEUE, ¶ms); @@ -871,6 +939,15 @@ pub fn read_info(p: &Value) -> Result<Value> { out["ppi"] = json!([x, y]); out["colorMode"] = json!(color_mode(&img.blob.bytes)); } + if let Art::Dcs(a) = &l.art { + let (x, y) = a.img.ppi.unwrap_or((72.0, 72.0)); + out["pixelWidth"] = json!(a.img.width); + out["pixelHeight"] = json!(a.img.height); + out["ppi"] = json!([x, y]); + out["colorMode"] = json!("CMYK"); + let plates: Vec<String> = a.img.blob.separated().map(|s| s.plates.iter().map(|p| p.name.clone()).collect()).unwrap_or_default(); + out["plates"] = json!(plates); + } if let Some(px) = p.get("thumbnail").and_then(Value::as_f64) { out["thumbnailBase64"] = json!(thumbnail_png(l, px)?); } @@ -885,17 +962,20 @@ pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result<Value> { (None, [id]) => *id, _ => return Err(bad(C, "select one image or pass id")), }; - let n = st.doc.node(id).ok_or(EngineError::NoNode(id))?; + // An image in opacity-mask art or a definition's art is found by its id too (`links.list`). + let n = st.doc.stored_node(id).map(|(n, _)| &**n).ok_or(EngineError::NoNode(id))?; let NodeKind::Image(im) = &n.kind else { return Err(bad(C, format!("object {} is not an image", id.0))) }; // Effective resolution: 72 pt per inch over the points one pixel spans along each axis. let [a, b, c, d, ..] = im.xf.as_coeffs(); let ppi = |x: f64, y: f64| Some(x.hypot(y)).filter(|l| *l > 1e-12).map_or(0.0, |l| 72.0 / l); let size = n.geometric_bounds().unwrap_or_default(); + // A linked file outside the read roots of the caller asking now is left unnamed, as in Link Info. + let doc_path = super::links::LinkBase::of(st).doc; Ok(json!({ "id": id.0, "name": n.display_name(), "linked": im.link.is_some(), - "link": im.link.as_ref().map(|l| &l.path), + "link": im.link.as_ref().map(|l| &l.path).filter(|path| super::links::path_shown(path, doc_path)), "colorMode": st.doc.images.get(&im.key).map_or("RGB", |b| color_mode(&b.bytes)), "pixelWidth": im.width, "pixelHeight": im.height, diff --git a/crates/engine/src/cmd/place/adopt.rs b/crates/engine/src/cmd/place/adopt.rs index fb0622632e..9cd28b7e25 100644 --- a/crates/engine/src/cmd/place/adopt.rs +++ b/crates/engine/src/cmd/place/adopt.rs @@ -10,7 +10,7 @@ use std::sync::Arc; use vectorcraft_brush::{Brush, BrushKind}; use vectorcraft_color::Paint; -use vectorcraft_doc::{AppearanceItem, Document, Node, NodeKind}; +use vectorcraft_doc::{AppearanceItem, Document, Node, NodeKind, PatternDef, Symbol}; use super::unique_name; @@ -78,6 +78,12 @@ fn refs(n: &mut Node, f: &mut impl FnMut(Ref)) { NodeKind::SymbolInstance { symbol, .. } => f(Ref::Symbol(symbol)), _ => {} } + // A color-masked image's masked pixels come along, and the key they were made from + // follows the image's. + if let Some(cm) = n.extras_if_any().and_then(|e| e.color_mask.as_deref_mut()) { + f(Ref::Image(&mut cm.key)); + f(Ref::Image(&mut cm.from)); + } }); } @@ -112,11 +118,12 @@ impl Used { type Renames = BTreeMap<String, (Option<String>, bool)>; /// Names in `dst` for the `used` definitions of `src` (`def`): the same name when `dst` has none -/// (copied) or an equal one (shared), else a free variant (`taken`, copied). -fn names<T: PartialEq>( +/// (copied) or one that is the `same` (shared), else a free variant (`taken`, copied). +fn names<T>( used: &[String], def: impl Fn(&str) -> Option<T>, existing: impl Fn(&str) -> Option<T>, + same: impl Fn(&T, &T) -> bool, taken: impl Fn(&str) -> bool, ) -> Renames { let mut out = Renames::new(); @@ -124,7 +131,7 @@ fn names<T: PartialEq>( let Some(d) = def(name) else { continue }; let entry = match existing(name) { None => (Some(name.clone()), true), - Some(e) if e == d => (Some(name.clone()), false), + Some(e) if same(&e, &d) => (Some(name.clone()), false), Some(_) => { (Some(unique_name(name, |c| taken(c) || used.iter().any(|u| u == c) || out.values().any(|(n, _)| n.as_deref() == Some(c)))), true) } @@ -134,6 +141,65 @@ fn names<T: PartialEq>( out } +/// `n` as `dst` would copy it in ([`Document::reid`]), with the ids a document of its own gives it: +/// art copied in once, which differs from the file's only in its ids, compares equal to the file's. +fn canon(dst: &Document, n: &Node) -> Node { + let mut own = Document::new(0.0, 0.0); + // Pixels the art carries take a key `dst` doesn't use for other pixels, as they do in `dst`. + let mut keys = vec![]; + vectorcraft_doc::swatches::walk_with_masks(n, &mut |c| { + if let NodeKind::Image(im) = &c.kind + && im.pixels.is_some() + { + keys.push(im.key.clone()); + } + }); + for (k, blob) in &dst.images { + if keys.iter().any(|key| k == key || k.strip_prefix(key.as_str()).is_some_and(|rest| rest.starts_with('-'))) { + own.images.insert(k.clone(), blob.clone()); + } + } + own.reid(n) +} + +/// Do symbols `a` and `b` draw the same, whatever ids their art has ([`canon`])? +fn same_symbol(dst: &Document, a: &Symbol, b: &Symbol) -> bool { + let own = |s: &Symbol| Symbol { art: Arc::new(canon(dst, &s.art)), ..s.clone() }; + own(a) == own(b) +} + +/// Do patterns `a` and `b` draw the same, whatever ids their art has ([`canon`])? +fn same_pattern(dst: &Document, a: &PatternDef, b: &PatternDef) -> bool { + let bare = |p: &PatternDef| PatternDef { art: vec![], ..p.clone() }; + bare(a) == bare(b) && a.art.len() == b.art.len() && a.art.iter().zip(&b.art).all(|(x, y)| canon(dst, x) == canon(dst, y)) +} + +/// Does art `a` use a resource that `m` (images, symbols, patterns, brushes, swatches) gives +/// another name, or a swatch whose link `m` drops? +fn uses_moved(a: &Node, m: [&Renames; 5]) -> bool { + let moved = |map: &Renames, k: &str| map.get(k).is_some_and(|(new, _)| new.as_deref() != Some(k)); + let (mut a, mut any) = (a.clone(), false); + refs(&mut a, &mut |r| { + any |= match r { + Ref::Image(k) => moved(m[0], k), + Ref::Symbol(k) => moved(m[1], k), + Ref::Pattern(k) => moved(m[2], k), + Ref::Brush(k) => moved(m[3], k), + Ref::Swatch(link) => link.as_deref().is_some_and(|k| moved(m[4], k)), + } + }); + any +} + +/// Copy each of `shared` in `map` under a free name, as [`names`] does for a definition `dst` +/// holds differently. +fn unshare(map: &mut Renames, shared: &[String], used: &[String], taken: impl Fn(&str) -> bool) { + for name in shared { + let free = unique_name(name, |c| taken(c) || used.iter().any(|u| u == c) || map.values().any(|(n, _)| n.as_deref() == Some(c))); + map.insert(name.clone(), (Some(free), true)); + } +} + /// The renamed resources whose definitions are copied: (name in `src`, name in `dst`). fn copies(m: &Renames) -> Vec<(&str, &str)> { m.iter().filter(|(_, (_, copy))| *copy).filter_map(|(old, (new, _))| Some((old.as_str(), new.as_deref()?))).collect() @@ -188,14 +254,17 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) { } } - let images = names(&used.images, |k| src.images.get(k), |k| dst.images.get(k), |c| dst.images.contains_key(c)); - let symbols = names( + let images = names(&used.images, |k| src.images.get(k), |k| dst.images.get(k), |a, b| a == b, |c| dst.images.contains_key(c)); + // Symbol and pattern art copied in takes ids of `dst`, so their art is compared by what it + // draws: placing the same file again shares what the first placement brought. + let mut symbols = names( &used.symbols, |n| src.symbols.iter().find(|s| s.name == n), |n| dst.symbols.iter().find(|s| s.name == n), + |a, b| same_symbol(dst, a, b), |c| dst.symbols.iter().any(|s| s.name == c), ); - let patterns = names(&used.patterns, |n| src.pattern(n), |n| dst.pattern(n), |c| dst.pattern(c).is_some()); + let mut patterns = names(&used.patterns, |n| src.pattern(n), |n| dst.pattern(n), |a, b| same_pattern(dst, a, b), |c| dst.pattern(c).is_some()); // A swatch the document defines differently isn't renamed (that would add look-alike swatches): // the colours linked to it keep their look, unlinked. let swatches: Renames = used @@ -230,12 +299,33 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) { any }; let mut dst_brushes = vectorcraft_brush::library(dst); - let brushes = names( + let mut brushes = names( &used.brushes, |n| src_brushes.iter().find(|b| b.name == n).map(|b| (b, moves_art(b))), |n| dst_brushes.iter().find(|b| b.name == n).map(|b| (b, false)), + |a, b| a == b, |c| dst_brushes.iter().any(|b| b.name == c), ); + // Likewise a symbol, pattern or brush whose art uses a resource that moves isn't the + // document's of that name: it is copied under a free name, which can move what uses it in turn. + loop { + let maps = [&images, &symbols, &patterns, &brushes, &swatches]; + let shared = |map: &Renames| map.iter().filter(|(_, (_, copy))| !*copy).map(|(k, _)| k.clone()).collect::<Vec<_>>(); + let sym: Vec<String> = + shared(&symbols).into_iter().filter(|n| src.symbols.iter().any(|s| s.name == *n && uses_moved(&s.art, maps))).collect(); + let pat: Vec<String> = + shared(&patterns).into_iter().filter(|n| src.pattern(n).is_some_and(|p| p.art.iter().any(|a| uses_moved(a, maps)))).collect(); + let bru: Vec<String> = shared(&brushes) + .into_iter() + .filter(|n| src_brushes.iter().find(|b| b.name == *n).is_some_and(|b| brush_art(&mut b.clone()).into_iter().any(|a| uses_moved(a, maps)))) + .collect(); + if sym.is_empty() && pat.is_empty() && bru.is_empty() { + break; + } + unshare(&mut symbols, &sym, &used.symbols, |c| dst.symbols.iter().any(|s| s.name == c)); + unshare(&mut patterns, &pat, &used.patterns, |c| dst.pattern(c).is_some()); + unshare(&mut brushes, &bru, &used.brushes, |c| dst_brushes.iter().any(|b| b.name == c)); + } let mut rename = |r: Ref| { let (map, k) = match r { @@ -266,6 +356,8 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) { if let Some(mut def) = src.symbols.iter().find(|s| s.name == old).cloned() { def.name = new.to_string(); refs(Arc::make_mut(&mut def.art), &mut rename); + // The art takes ids of `dst`: those of `src` may name objects of `dst` already. + def.art = Arc::new(dst.reid(&def.art)); dst.symbols.push(def); } } @@ -274,6 +366,7 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) { def.name = new.to_string(); for a in &mut def.art { refs(Arc::make_mut(a), &mut rename); + *a = Arc::new(dst.reid(a)); } dst.patterns.push(def); } diff --git a/crates/engine/src/cmd/place/dcs.rs b/crates/engine/src/cmd/place/dcs.rs new file mode 100644 index 0000000000..69a397c5d1 --- /dev/null +++ b/crates/engine/src/cmd/place/dcs.rs @@ -0,0 +1,181 @@ +//! DCS files (`file.place` with Link): an EPS file with one program per printing plate +//! ([`vectorcraft_eps::dcs`]). It is placed as one linked image whose plates are kept with its +//! pixels ([`vectorcraft_doc::separated`]): the screen and composite output show the plates mixed +//! into CMYK, and print separations put each plate on its own ink. Its spot plates become spot +//! swatches, and the clipping path its composite is drawn through clips it. A DCS file can't be +//! opened or embedded (Embed, Place without Link): the image stays linked to its file, which the +//! Links commands read again ([`raster`]). + +use vectorcraft_color::swatch::Swatch; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::separated::PlateFile; +use vectorcraft_doc::{Document, ImageBlob, Node, NodeKind}; +use vectorcraft_geom::{Affine, Rect}; + +use super::super::fileio::{self, RasterImage}; +use super::super::{EngineError, Result}; + +/// The largest plate file read (bytes). +const MAX_PLATE_FILE: u64 = 1 << 30; + +/// What refuses to open or embed a DCS file. +pub(crate) const LINK_ONLY: &str = "DCS files can only be placed linked: use File › Place with Link on"; + +/// A DCS file read for placing. +pub(crate) struct DcsArt { + pub img: RasterImage, + /// The image's pixels onto the file's page (its bounding box, top-left at the origin). + pub xf: Affine, + pub page: Rect, + /// The clipping path the composite is drawn through, on the page. + pub clip: Option<Node>, + /// The spot plates' inks and their process equivalents. + pub spots: Vec<(String, [f32; 4])>, + pub warnings: Vec<String>, +} + +/// Is `bytes` a DCS file (an EPS file naming its plates)? +pub(crate) fn is_dcs(bytes: &[u8]) -> bool { + vectorcraft_eps::dcs::read(bytes).is_some() +} + +/// The most bytes read from the start of a file to look at its DCS header. +pub(crate) const HEAD_BYTES: usize = 1 << 20; + +/// Does the header of the PostScript in file `head` (the first bytes of a file `size` bytes long, +/// at most [`HEAD_BYTES`]) name DCS plates? `None` when `head` can't tell: that PostScript doesn't +/// start within it (a binary EPS header that puts it further on), or its header goes on past it. A +/// `head` that holds the whole file is read as [`is_dcs`] reads it, and a binary EPS header whose +/// PostScript or TIFF preview ends past `size` names none, as [`is_dcs`] finds for the whole file. +pub(crate) fn head_is_dcs(head: &[u8], size: u64) -> Option<bool> { + const DOS_MAGIC: [u8; 4] = [0xC5, 0xD0, 0xD3, 0xC6]; + if head.len() < HEAD_BYTES || head.len() as u64 >= size { + return Some(is_dcs(head)); + } + let (ps, whole) = if head.starts_with(&DOS_MAGIC) { + let word = |at: usize| head.get(at..at + 4).and_then(|b| <[u8; 4]>::try_from(b).ok()).map(|b| u32::from_le_bytes(b) as usize); + let fits = |at: usize| Some((word(at)? as u64).checked_add(word(at + 4)? as u64).is_some_and(|end| end <= size)); + if !fits(4)? || (word(24)? != 0 && !fits(20)?) { + return Some(false); + } + let (start, len) = (word(4)?, word(8)?); + let ps = head.get(start..).filter(|ps| !ps.is_empty())?; + (ps.get(..len).unwrap_or(ps), start.checked_add(len).is_some_and(|end| end <= head.len())) + } else { + (head, false) + }; + if is_dcs(ps) { + return Some(true); + } + (whole || header_ended(ps)).then_some(false) +} + +/// Does `ps`, the start of some PostScript, hold all of the header [`vectorcraft_eps::dcs::read`] +/// looks at (up to `%%EndComments`, a line that isn't a comment, or its 10,000th line)? Its last +/// line may be cut off, so it doesn't count. +fn header_ended(ps: &[u8]) -> bool { + let mut lines = ps.split(|b| matches!(b, b'\n' | b'\r')).filter(|l| !l.is_empty()).peekable(); + let mut n = 0; + while let Some(line) = lines.next() { + if lines.peek().is_none() { + return false; + } + n += 1; + if line.starts_with(b"%%EndComments") || !line.starts_with(b"%") || n >= 10_000 { + return true; + } + } + false +} + +/// DCS file `bytes`, read from `path` (when there is one: plate files of their own are found in its +/// folder), with every plate. +pub(crate) fn read(bytes: &[u8], path: Option<&str>) -> Result<DcsArt> { + let dcs = vectorcraft_eps::dcs::read(bytes).ok_or_else(|| EngineError::Other("not a DCS file".into()))?; + let mut files = vec![]; + let mut file = |name: &str| plate_file(path, name, &mut files); + let p = vectorcraft_eps::dcs::place(bytes, &dcs, &mut file).map_err(EngineError::Other)?; + // The clipping path in the image's pixel space, where the Links commands put it again; the + // image keeps it, so they know a clip group of that path as the file's. + let to_pixels = (p.xf.determinant().abs() > 1e-12).then(|| p.xf.inverse()); + let clip = match (&p.clip, to_pixels) { + (Some(Node { kind: NodeKind::Path { path, .. }, .. }), Some(inv)) => Some(path.transformed(inv)), + _ => None, + }; + let blob = ImageBlob::separated_tiff_clipped(&p.separated, p.ppi, &files, clip.as_ref()) + .ok_or_else(|| EngineError::Other("the plates can't be kept".into()))?; + let img = RasterImage { key: blob.content_key(), blob, width: p.separated.width, height: p.separated.height, ppi: p.ppi, clip }; + let spots = p.separated.spots().map(|s| (s.name.clone(), s.cmyk)).collect(); + Ok(DcsArt { img, xf: p.xf, page: p.page, clip: p.clip, spots, warnings: p.warnings }) +} + +/// A linked file's image, as the Links commands read it again: a DCS file's plates +/// ([`read`]), else the image file ([`fileio::raster_image`]). +pub(crate) fn raster(bytes: &[u8], path: Option<&str>) -> Result<RasterImage> { + if is_dcs(bytes) { read(bytes, path).map(|a| a.img) } else { fileio::raster_image(bytes) } +} + +/// The path of the plate file a DCS file at `main` names `name`: the file of that name (its last +/// component, of any system's path) in `main`'s folder, with that name. +fn plate_path(main: Option<&str>, name: &str) -> std::result::Result<(String, String), String> { + let base = name.rsplit(['/', '\\', ':']).next().unwrap_or(name); + let folder = main.map(std::path::Path::new).and_then(std::path::Path::parent); + let Some(folder) = folder.filter(|_| !base.is_empty()) else { + return Err(format!("`{name}` is a file of its own, which can only be found next to the DCS file's path")); + }; + Ok((folder.join(base).to_string_lossy().into_owned(), base.to_string())) +} + +/// The path of the plate file named `name` that the DCS file at `main` (a path as a link keeps +/// it) was read with ([`plate_path`]); `None` when `main` has no folder. +pub(crate) fn plate_file_path(main: &str, name: &str) -> Option<String> { + plate_path(Some(main), name).ok().map(|(path, _)| path) +} + +/// The plate file a DCS file at `main` names `name` ([`plate_path`]), noted in `files` as it is now. +fn plate_file(main: Option<&str>, name: &str, files: &mut Vec<PlateFile>) -> std::result::Result<Vec<u8>, String> { + let (path, base) = plate_path(main, name)?; + match fileio::file_stamp(&path) { + None => Err(format!("`{base}` is not in the DCS file's folder")), + Some((size, _)) if size > MAX_PLATE_FILE => Err(format!("`{base}` is larger than {} MB", MAX_PLATE_FILE >> 20)), + Some((size, modified)) => { + let bytes = fileio::read_file(&path).map_err(|e| e.to_string())?; + files.push(PlateFile { name: base, size, modified: modified.unwrap_or(0) }); + Ok(bytes) + } + } +} + +/// Whether one of `files`, the plate files of their own a separated image was read from +/// ([`ImageBlob::plate_files`]), next to the DCS file at `main`, is gone or changed since. +pub(crate) fn plate_files_changed(files: &[PlateFile], main: &str) -> bool { + files.iter().any(|f| { + let stamp = plate_path(Some(main), &f.name).ok().and_then(|(path, _)| fileio::file_stamp(&path)); + stamp.is_none_or(|(size, modified)| size != f.size || modified.unwrap_or(0) != f.modified) + }) +} + +/// Add `spots` to `d` as spot swatches, each whose name no swatch has, in its process equivalent. +pub(crate) fn add_spot_swatches(d: &mut Document, spots: &[(String, [f32; 4])]) { + for (name, [c, m, y, k]) in spots { + if d.swatch(name).is_none() { + d.swatches.push(Swatch { name: name.clone(), paint: Paint::solid(Color::cmyk(*c, *m, *y, *k)), global: true, spot: true }); + } + } +} + +/// A warning for each of `spots` whose name a swatch of `d` already has that isn't a spot color in +/// the same process equivalent: the document's swatch stays, and the plate prints by it. +pub(crate) fn swatch_notes(d: &Document, spots: &[(String, [f32; 4])]) -> Vec<String> { + let mut out = vec![]; + for (name, cmyk) in spots { + let Some(sw) = d.swatch(name) else { continue }; + let same = sw.spot + && matches!(sw.paint.color(), Some(Color::Cmyk { c, m, y, k }) if [c, m, y, k].iter().zip(cmyk).all(|(a, b)| (a - b).abs() < 0.005)); + if !same { + let how = if sw.spot { "a different color" } else { "a process color, so the plate prints as process inks" }; + out.push(format!("the document's swatch `{name}` is kept: it is {how}")); + } + } + out +} diff --git a/crates/engine/src/cmd/place/document.rs b/crates/engine/src/cmd/place/document.rs index 9f58e4851d..8e4afaa295 100644 --- a/crates/engine/src/cmd/place/document.rs +++ b/crates/engine/src/cmd/place/document.rs @@ -378,8 +378,10 @@ pub(crate) fn full_documents(d: &Document) -> (Cow<'_, Document>, Vec<String>) { /// Placed document `id` of `d` replaced by an editable copy of its art, as placing its file /// without Link gives (its resources joining `d`, renamed where `d` uses a name for something /// else), keeping the object's id, place, name and transparency: Break Link and Object › Expand. +/// A placed document in opacity-mask art or in the art of a symbol, graph design or pattern is +/// replaced where it is stored. pub(crate) fn expand(d: &mut Document, id: NodeId, cmd: &str) -> Result<()> { - let n = d.node(id).cloned().ok_or(EngineError::NoNode(id))?; + let n = d.stored_node(id).map(|(n, _)| Node::clone(n)).ok_or(EngineError::NoNode(id))?; let NodeKind::PlacedDocument(p) = &n.kind else { return Err(bad(cmd, format!("object {} is not a placed document", id.0))) }; let blob = d.images.get(&p.key).ok_or_else(|| bad(cmd, format!("object {} has lost its file's contents: relink it", id.0)))?; let bytes = vectorcraft_doc::placed_document::full_bytes(p, blob) @@ -395,6 +397,10 @@ pub(crate) fn expand(d: &mut Document, id: NodeId, cmd: &str) -> Result<()> { let art = super::transformed(Node::new(d.alloc_id(), NodeKind::Group { children, clip: a.clip.is_some() }), m); let mut out = n.clone(); out.kind = art.kind; + if d.node(id).is_none() { + *d.stored_node_mut(id).ok_or(EngineError::NoNode(id))? = out; + return Ok(()); + } let (par, index, _) = d.position(id).ok_or(EngineError::NoNode(id))?; d.remove(id)?; d.insert(par, index, out)?; diff --git a/crates/engine/src/cmd/place/text.rs b/crates/engine/src/cmd/place/text.rs index ab5562b5f9..25f5f36dbd 100644 --- a/crates/engine/src/cmd/place/text.rs +++ b/crates/engine/src/cmd/place/text.rs @@ -108,7 +108,7 @@ pub(in crate::cmd) fn windows_1252(b: u8) -> char { } /// Byte `b` of Mac Roman. -pub(super) fn mac_roman(b: u8) -> char { +pub(in crate::cmd) fn mac_roman(b: u8) -> char { const HIGH: [char; 128] = [ 'Ä', 'Å', 'Ç', 'É', 'Ñ', 'Ö', 'Ü', 'á', 'à', 'â', 'ä', 'ã', 'å', 'ç', 'é', 'è', // 'ê', 'ë', 'í', 'ì', 'î', 'ï', 'ñ', 'ó', 'ò', 'ô', 'ö', 'õ', 'ú', 'ù', 'û', 'ü', // diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index e8e57301e8..3fa082bdb0 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -52,7 +52,7 @@ use vectorcraft_plugins::{Budget, Command, Kind, Plugin, effect, export, objects use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, cmd, has_doc, ids_param, str_param, switch_or}; -use vectorcraft_plugins::permissions::{self, Grant, Permission}; +use vectorcraft_plugins::permissions::{self, Grant, GrantToken, Permission}; /// What a plug-in error looks like to the user. A run the caller cancelled changed nothing. fn err(e: vectorcraft_plugins::Error) -> EngineError { @@ -62,13 +62,28 @@ fn err(e: vectorcraft_plugins::Error) -> EngineError { } } +/// Under automation read roots, a reply names a file or folder outside them by its name alone. +fn shown_file(path: &str) -> String { + super::fileio::shown_path(path).into_owned() +} + +/// A plug-in turned off for the next launch, or the one a launch stopped at, as a reply shows it: a +/// file outside the automation read roots is named by its file name. +fn shown_item(item: &safe_mode::Item) -> Value { + let mut v = item.to_json(); + if let Some(file) = item.file.as_deref() { + v["file"] = json!(shown_file(file)); + } + v +} + /// JSON description of an installed plug-in. pub fn describe(p: &Plugin) -> Value { let m = p.manifest(); let mut v = json!({ "id": m.id, "name": m.name, "version": m.version, "kind": m.kind.name(), "author": m.author, "description": m.description, "params": m.params_doc(), "paramsSchema": serde_json::to_value(m).ok().and_then(|v| v.get("params").cloned()), - "size": p.size(), "source": p.source(), + "size": p.size(), "source": p.source().map(shown_file), "permissions": permissions::names(&m.permissions()), "hash": p.hash(), "api": m.api, }); match m.kind { @@ -657,13 +672,53 @@ fn takes_over(s: &Session, plugin: &Plugin) -> bool { } } +#[cfg(test)] +thread_local! { + /// Tests: runs once in the next `plugin.install` on this thread after its checks and before it + /// installs, as another session changing the plug-ins in between would. + pub(crate) static BEFORE_INSTALL: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) }; + /// Tests: runs once in the next `plugin.install` on this thread right after it reads the grant + /// held for the id. + pub(crate) static AFTER_GRANT_READ: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) }; + /// Tests: runs once in the next `plugin.install` on this thread after it installs and before it + /// writes the store. + pub(crate) static BEFORE_STORE: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) }; + /// Tests: runs once on this thread when [`hold_plugin_changes`] finds the lock held and waits. + pub(crate) static WHILE_WAITING: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) }; +} + +/// Held by `plugin.install` from its first read of the grant until the store holds what it +/// installed, and throughout by `plugin.remove`, by loads of the stored plug-ins +/// ([`Session::load_stored_plugins`]) and by loads of a plug-ins folder: these run one after the +/// other across sessions. +static PLUGIN_CHANGES: Mutex<()> = Mutex::new(()); + +/// Takes [`PLUGIN_CHANGES`], waiting while another session holds it. +pub(crate) fn hold_plugin_changes() -> std::sync::MutexGuard<'static, ()> { + match PLUGIN_CHANGES.try_lock() { + Ok(held) => held, + Err(std::sync::TryLockError::Poisoned(e)) => e.into_inner(), + Err(std::sync::TryLockError::WouldBlock) => { + #[cfg(test)] + if let Some(waiting) = WHILE_WAITING.take() { + waiting(); + } + PLUGIN_CHANGES.lock().unwrap_or_else(|e| e.into_inner()) + } + } +} + /// `plugin.install`: loads and checks the module, refuses `grant` and `allowHeavy` that neither an /// [`InstallApproval`] for this module nor the session allows, one that asks for a heavy budget /// unless `allowHeavy` says a person agreed, one that lists permissions no person has granted this /// very module unless `grant` lists them all, one that would take another module's place -/// ([`takes_over`]) unless `replace` is true, and one whose SHA-256 isn't the `hash` given; records -/// the grant with the module's hash, keeps it for the next start and installs it → its -/// `plugin.list` entry. A module that lists no permissions ends any grant held for its id. +/// ([`takes_over`]) unless `replace` is true, and one whose SHA-256 isn't the `hash` given. It then +/// checks the plug-in installed under the id and its grant again while it records the grant with +/// the module's hash and installs it ([`registry::install_checked`]), and only then keeps both for +/// the next start → its `plugin.list` entry. A refused install changes neither the plug-in store +/// nor the plug-ins and grants of the process. A module that lists no permissions ends any grant +/// held for its id. A `plugin.remove` in another session waits until the install has written the +/// store. fn install(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "plugin.install"; // One use: spent whatever this install does. @@ -681,21 +736,36 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> { { return Err(bad(C, "the module doesn't have the SHA-256 `hash` gives: nothing was installed")); } - if replace == Some(false) && registry::get(plugin.id()).is_some() { - return Err(bad(C, format!("a plug-in with id {:?} is already installed", plugin.id()))); + // A removal in another session waits until the store holds what this install wrote. + let _held = hold_plugin_changes(); + // The grant the checks below count on, the approval included. The install checks it again, + // with the plug-in installed under the id, before anything is stored: another session may + // change either in between. + let seen_grant = registry::granted(plugin.id()); + #[cfg(test)] + if let Some(between) = AFTER_GRANT_READ.take() { + between(); } - // Another module under the id gets the settings and cache kept for it: whoever installs it asks - // the user first. - if replace != Some(true) && takes_over(s, &plugin) { + let installed_already = || bad(C, format!("a plug-in with id {:?} is already installed", plugin.id())); + let taken_over = || { let name = permissions::display_text(&plugin.manifest().name, permissions::MAX_SHOWN_NAME); - return Err(bad( + bad( C, format!( "“{name}” is another module than the plug-in with id {:?} and would get the settings and cache kept for it: install it with `replace: true` once the user agrees", plugin.id() ), - )); + ) + }; + if replace == Some(false) && registry::get(plugin.id()).is_some() { + return Err(installed_already()); } + // Another module under the id gets the settings and cache kept for it: whoever installs it asks + // the user first. + if replace != Some(true) && takes_over(s, &plugin) { + return Err(taken_over()); + } + let (installed_already, taken_over) = (installed_already(), taken_over()); // `grant` and `allowHeavy` say that a person agreed, and a request alone can't say that. let approval = approval.filter(|a| a.covers(&plugin)); if !s.plugin_grants_from_requests && ((grant.is_some() && approval.is_none()) || (allow_heavy && !approval.is_some_and(|a| a.heavy))) { @@ -729,56 +799,93 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> { // this very module already covers all of them. let m = plugin.manifest(); let wanted = m.permissions(); - if !s.plugin_approved(&plugin) && !grant.as_ref().is_some_and(|g| wanted.iter().all(|w| g.contains(w))) { + let needs_approval = || { let name = permissions::display_text(&m.name, permissions::MAX_SHOWN_NAME); let asked = permissions::names(&wanted).join(", "); - return Err(bad( + bad( C, format!( "“{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants" ), - )); + ) + }; + let granted_here = grant.as_ref().is_some_and(|g| wanted.iter().all(|w| g.contains(w))); + // Without a plug-in store, the grant read above approves the module or doesn't. + let approved = match s.plugin_dir { + None => !m.asks_permissions() || seen_grant.as_ref().is_some_and(|g| g.covers(&m.id, plugin.hash(), &wanted)), + Some(_) => s.plugin_approved(&plugin), + }; + if !approved && !granted_here { + return Err(needs_approval()); + } + let needs_approval = needs_approval(); + let (id, hash, asks) = (m.id.clone(), plugin.hash().to_string(), m.asks_permissions()); + let g = Grant { id: id.clone(), hash: hash.clone(), permissions: wanted }; + let update = if asks { registry::GrantUpdate::Record(GrantToken::after_engine_approval(g.clone())) } else { registry::GrantUpdate::Revoke }; + // Another module installed under the id since the checks above takes the place they found free, + // or held by these bytes. A grant that changed since no longer approves what they approved, + // unless `grant` approves this module by itself or the new grant covers it. + let check = |installed: Option<&Plugin>, held: Option<&Grant>| { + if let Some(installed) = installed { + match replace { + Some(false) => return Err(installed_already), + None if installed.hash() != hash => return Err(taken_over), + _ => {} + } + } + if asks && !granted_here && held != seen_grant.as_ref() && !held.is_some_and(|h| h.covers(&id, &hash, &g.permissions)) { + return Err(needs_approval); + } + Ok(()) + }; + #[cfg(test)] + if let Some(between) = BEFORE_INSTALL.take() { + between(); + } + // The plug-in gets the settings and cache kept for its id. A module without permissions takes + // the id over, so nothing the user approved for the id applies any more. + let installed = registry::install_checked(plugin, update, check, || s.attach_plugin_storage(&id), err)?; + #[cfg(test)] + if let Some(between) = BEFORE_STORE.take() { + between(); } // Installed plug-ins stay installed after a restart (#2541). The module is written first and its // grant only once it is there; when the grant can't be written, the store gets the module it - // held back. A failed write of that module is only logged, and the grant then doesn't cover - // the new module. A stored module that can't be read back isn't replaced by one that needs a - // grant. - let previous = s.stored_plugin_bytes(plugin.id()); - let mut stored = (previous.is_ok() || !m.asks_permissions()) && s.store_plugin(plugin.id(), &bytes); - if m.asks_permissions() { - let g = Grant { id: m.id.clone(), hash: plugin.hash().to_string(), permissions: wanted }; - registry::grant(g.clone()); - if stored && !s.store_grant(&m.id, Some(g)) { - s.put_back_plugin(plugin.id(), previous.ok().flatten().as_deref()); - stored = false; + // held back. A failed write of that module is only logged: the store then holds the new module, + // which the grant doesn't cover. A write that reports a failure may still have put the old + // module back, so the store is read again to tell which module it holds. A stored module that + // can't be read back isn't replaced by one that needs a grant. + let previous = s.stored_plugin_bytes(&id); + let mut stored = (previous.is_ok() || !asks) && s.store_plugin(&id, &bytes); + let holds_new = |s: &Session| s.stored_plugin_bytes(&id).is_ok_and(|held| held.as_deref() == Some(&bytes[..])); + if asks { + if stored && !s.store_grant(&id, Some(g)) { + stored = !s.put_back_plugin(&id, previous.ok().flatten().as_deref()) && holds_new(s); } } else { - // This module takes the id over, so nothing the user approved for the id applies any more. - registry::revoke(&m.id); // When the write failed, the old stored module stays in the folder and needs its grant at // the next launch. A grant that can't be removed still approves the old bytes, so the store // gets the module it held back. When that module can't be read or written back, or there - // was none, no module goes with the grant, and the grant stops counting for this session. A - // grants file that is too large or doesn't hold a list approves nothing, and the new module - // stays; one that can't be opened or read may approve the old bytes once it reads again. - if stored && !s.store_grant(&m.id, None) && s.holds_plugin_grant(&m.id) { - let back = previous.as_ref().is_ok_and(|held| s.put_back_plugin(plugin.id(), held.as_deref())); - stored = !back; + // was none, no module goes with the grant, and the grant stops counting for every session in + // the process attached to the folder. A grants file that is too large or doesn't hold a list + // approves nothing, and the new module stays; one that can't be opened or read may approve + // the old bytes once it reads again. + let writes = s.grant_writes(); + if stored && !s.store_grant(&id, None) && s.holds_plugin_grant(&id) { + let back = previous.as_ref().is_ok_and(|held| s.put_back_plugin(&id, held.as_deref())); + stored = !back && holds_new(s); if !back || matches!(previous, Ok(None)) { - s.ignore_stored_grant(&m.id); + s.ignore_stored_grant(&id, writes); } } } - // It gets the settings and cache kept for its id. - s.attach_plugin_storage(plugin.id()); // Installing a disabled plug-in again (an updated version) turns it on for the next launch too, // also when it is disabled by its stored file alone (it stopped a launch while loading). When // the new version could not replace the stored file, the old one stays disabled. - let file = s.stored_plugin_file(plugin.id()); + let file = s.stored_plugin_file(&id); let mut changed = false; if file.is_none() || stored { - changed = safe_mode::set_enabled(&safe_mode::Item::of(&plugin), true); + changed = safe_mode::set_enabled(&safe_mode::Item::of(&installed), true); if let Some(file) = file { changed |= safe_mode::set_enabled(&safe_mode::Item::file(file), true); } @@ -786,7 +893,7 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> { if changed { s.store_disabled_plugins(); } - let mut v = describe_installed(®istry::install(plugin)); + let mut v = describe_installed(&installed); if !unknown.is_empty() { v["unknownCommands"] = json!(unknown); } @@ -885,7 +992,9 @@ fn load_folder(s: &Session, folder: &str) -> Value { None if crate::file_access::current().is_none() => Ok(()), None => Err(format!("automation path rejected: {} isn't valid text", f.display())), }; - match registry::load_folder_where(std::path::Path::new(folder), allow, s.plugin_approver()) { + // A `plugin.install` in another session finishes writing the store first. + let _held = hold_plugin_changes(); + match registry::load_folder_where(std::path::Path::new(folder), allow, s.plugin_folder_approver()) { Ok(r) => { for id in &r.loaded { s.attach_plugin_storage(id); @@ -928,9 +1037,46 @@ fn describe_installed(p: &Plugin) -> Value { v } +/// The folder load `report` as a reply shows it: under automation read roots, a folder outside them +/// is `null` and a failed file outside them is named by its file name, in the errors too. +fn shown_report(mut report: Value) -> Value { + let mut hidden: Vec<(String, String)> = vec![]; + if let Some(failed) = report.get_mut("failed").and_then(Value::as_array_mut) { + for row in failed { + let Some(file) = row.get("file").and_then(Value::as_str).map(str::to_string) else { continue }; + let shown = shown_file(&file); + if shown != file { + row["file"] = json!(shown); + hidden.push((file, shown)); + } + } + } + if let Some(folder) = report.get("folder").and_then(Value::as_str).map(str::to_string) { + let shown = shown_file(&folder); + if shown != folder { + report["folder"] = Value::Null; + hidden.push((folder, shown)); + } + } + // A failed file's path holds its folder's: the longer paths are put back first. + hidden.sort_by_key(|(path, _)| std::cmp::Reverse(path.len())); + let unnamed = |text: &str| hidden.iter().fold(text.to_string(), |t, (path, name)| t.replace(path.as_str(), name)); + if let Some(e) = report.get("error").and_then(Value::as_str).map(unnamed) { + report["error"] = json!(e); + } + if let Some(failed) = report.get_mut("failed").and_then(Value::as_array_mut) { + for row in failed { + if let Some(e) = row.get("error").and_then(Value::as_str).map(unnamed) { + row["error"] = json!(e); + } + } + } + report +} + fn list(_: &mut Session, _: &Value) -> Result<Value> { - let folder = FOLDER.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(|(_, _, r)| r.clone()); - let disabled: Vec<Value> = safe_mode::disabled().iter().map(safe_mode::Item::to_json).collect(); + let folder = FOLDER.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(|(_, _, r)| shown_report(r.clone())); + let disabled: Vec<Value> = safe_mode::disabled().iter().map(shown_item).collect(); Ok( json!({"plugins": registry::list().iter().map(|p| describe_installed(p)).collect::<Vec<_>>(), "folder": folder, "safeMode": safe_mode::active(), "disabled": disabled}), ) @@ -942,11 +1088,33 @@ fn safe_mode_state(_: &mut Session, _: &Value) -> Result<Value> { Ok(json!({ "active": safe_mode::active(), "source": safe_mode::source().map(safe_mode::Source::name), - "disabled": safe_mode::disabled().iter().map(safe_mode::Item::to_json).collect::<Vec<_>>(), - "pendingItem": safe_mode::previous().map(|i| i.to_json()), + "disabled": safe_mode::disabled().iter().map(shown_item).collect::<Vec<_>>(), + "pendingItem": safe_mode::previous().map(|i| shown_item(&i)), })) } +/// The file of a plug-in `plugin.safeMode` lists as `file`, or `plugin.list` as `source`: one they name +/// by its file name (outside the automation read roots) is found by that name, when no other listed +/// file has it. +fn listed_file(file: String) -> String { + let mut listed: Vec<String> = safe_mode::disabled() + .into_iter() + .chain(safe_mode::previous()) + .filter_map(|i| i.file) + .chain(registry::list().iter().filter_map(|p| p.source().map(str::to_string))) + .collect(); + listed.sort(); + listed.dedup(); + if listed.contains(&file) { + return file; + } + let mut named = listed.into_iter().filter(|f| shown_file(f) == file); + match (named.next(), named.next()) { + (Some(f), None) => f, + _ => file, + } +} + /// `plugin.setEnabled`: turns a plug-in on or off for the next launch, by `id` or by `file` (a /// plug-in that stopped a launch while loading may be known by its file alone). It neither loads /// nor unloads anything now, and uninstalls nothing. @@ -968,7 +1136,7 @@ fn set_enabled(s: &mut Session, p: &Value) -> Result<Value> { let stored = if enabled { s.stored_plugin_file(&id).map(safe_mode::Item::file) } else { None }; (registry::get(&id).map(|p| safe_mode::Item::of(&p)).unwrap_or(safe_mode::Item { id: Some(id), ..Default::default() }), stored) } - (None, Some(file)) => (safe_mode::Item::file(file), None), + (None, Some(file)) => (safe_mode::Item::file(listed_file(file)), None), (None, None) => return Err(bad(C, "give `id` or `file` (see plugin.safeMode)")), }; let items: Vec<&safe_mode::Item> = std::iter::once(&item).chain(stored.as_ref()).collect(); @@ -982,7 +1150,7 @@ fn set_enabled(s: &mut Session, p: &Value) -> Result<Value> { // Without a plug-in folder (a session confined to automation roots), or when the list there // can't take the change, the change stays in this process and goes with the next change that saves. let saved = !changed || s.store_disabled_plugins(); - Ok(json!({"changed": changed, "saved": saved, "disabled": safe_mode::disabled().iter().map(safe_mode::Item::to_json).collect::<Vec<_>>()})) + Ok(json!({"changed": changed, "saved": saved, "disabled": safe_mode::disabled().iter().map(shown_item).collect::<Vec<_>>()})) } fn info(_: &mut Session, p: &Value) -> Result<Value> { @@ -996,6 +1164,8 @@ fn info(_: &mut Session, p: &Value) -> Result<Value> { fn remove(s: &mut Session, p: &Value) -> Result<Value> { let id = str_param(p, "id").ok_or_else(|| bad("plugin.remove", "missing `id`"))?; + // An install in another session finishes its store writes first. + let _held = hold_plugin_changes(); let installed = registry::get(id).is_some(); // Settings and cache the store keeps for an id that isn't installed are deleted too. let stored = !installed && vectorcraft_plugins::manifest::valid_id(id) && s.has_plugin_storage(id); @@ -1051,7 +1221,7 @@ pub fn specs() -> Vec<CommandSpec> { "List Plug-ins", [], None, - "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}]} | null, safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", + "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}]} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", always, list ), @@ -1123,7 +1293,7 @@ pub fn specs() -> Vec<CommandSpec> { "Safe Mode", [], None, - "{} → {active: bool (no plug-in loads or runs: plugin.install, .run, .reload and exporters fail, live effects draw their object's geometry unchanged and the objects keep their effects), source: \"flag\" (started with --safe-mode) | \"startup\" (the user chose Safe Mode, or hasn't chosen yet, after a launch that stopped while a plug-in was loading) | null, disabled: [{id, file, name, label}] (turned off for the next launch; id is null for one known only by its file), pendingItem: {id, file, name, label} | null (the plug-in the last launch was loading when it stopped, until the user chooses; it may not be what stopped it)}. Safe Mode is chosen at launch, never by a command", + "{} → {active: bool (no plug-in loads or runs: plugin.install, .run, .reload and exporters fail, live effects draw their object's geometry unchanged and the objects keep their effects), source: \"flag\" (started with --safe-mode) | \"startup\" (the user chose Safe Mode, or hasn't chosen yet, after a launch that stopped while a plug-in was loading) | null, disabled: [{id, file, name, label}] (turned off for the next launch; id is null for one known only by its file; under automation read roots, a file outside them is named by its file name here and in pendingItem, and plugin.setEnabled takes that name), pendingItem: {id, file, name, label} | null (the plug-in the last launch was loading when it stopped, until the user chooses; it may not be what stopped it)}. Safe Mode is chosen at launch, never by a command", always, safe_mode_state ), @@ -1132,7 +1302,7 @@ pub fn specs() -> Vec<CommandSpec> { "Enable on Re-launch", [], None, - "{id | file: a plug-in as plugin.safeMode's disabled lists it, enabled: bool} turn a plug-in on or off for the next launch (Help › Safe Mode's Enable on Re-launch); nothing loads, unloads or is uninstalled now. Turning on by id also turns on the file the plug-in is stored in. Turning on one that isn't disabled is an error. plugin.install of a disabled plug-in turns it on → {changed, saved: false when the change isn't in the plug-in folder for the next launch (a session without one, or the list there can't be read or written or is full; it is saved with the next change that saves), disabled}", + "{id | file: a plug-in as plugin.safeMode's disabled lists it or as plugin.list's source (under automation read roots, a file outside them by the file name shown, when no other listed file has it), enabled: bool} turn a plug-in on or off for the next launch (Help › Safe Mode's Enable on Re-launch); nothing loads, unloads or is uninstalled now. Turning on by id also turns on the file the plug-in is stored in. Turning on one that isn't disabled is an error. plugin.install of a disabled plug-in turns it on → {changed, saved: false when the change isn't in the plug-in folder for the next launch (a session without one, or the list there can't be read or written or is full; it is saved with the next change that saves), disabled}", always, set_enabled ), diff --git a/crates/engine/src/cmd/plugin_call.rs b/crates/engine/src/cmd/plugin_call.rs index b151adcea2..71fbcc8540 100644 --- a/crates/engine/src/cmd/plugin_call.rs +++ b/crates/engine/src/cmd/plugin_call.rs @@ -102,7 +102,53 @@ const FILE_WORDS: &[&str] = &[ ]; /// Param keys that name a file or a folder. -const FILE_KEYS: &[&str] = &["path", "paths", "file", "files", "folder", "folders", "dir", "directory", "destinationFolder", "sourceFolder", "url"]; +const FILE_KEYS: &[&str] = + &["path", "paths", "file", "files", "folder", "folders", "dir", "directory", "destinationFolder", "sourceFolder", "url", "diffPath"]; + +/// The keys in [`FILE_KEYS`] that name a folder. +const FOLDER_KEYS: &[&str] = &["folder", "folders", "dir", "directory", "destinationFolder", "sourceFolder"]; + +/// What a param key that names a place on disk names there. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Location { + /// A file (or a list of files). + File, + /// A folder (or a list of folders). + Folder, +} + +/// What `key` names on disk when a command takes it ([`FILE_KEYS`]), or `None` when it never +/// names a file or a folder. +pub fn key_location(key: &str) -> Option<Location> { + if FOLDER_KEYS.contains(&key) { + Some(Location::Folder) + } else if FILE_KEYS.contains(&key) { + Some(Location::File) + } else { + None + } +} + +/// What `key` names on disk in command `spec`: [`key_location`], or `None` when [`NOT_FILES`] +/// names it for `spec` (it names part of the document there). +pub fn location_in(spec: &CommandSpec, key: &str) -> Option<Location> { + if NOT_FILES.contains(&(spec.id, key)) { None } else { key_location(key) } +} + +/// The param keys of `spec` that name a file or a folder, with what they name: the keys in +/// [`FILE_KEYS`] that its params description names ([`super::params::doc_keys`]), with those of the +/// commands its `…` entries name ([`super::params::takes_key`]), and its schema's params, less those +/// [`NOT_FILES`] names for it. Sorted, each key once. +pub fn location_keys(spec: &CommandSpec) -> Vec<(&'static str, Location)> { + let described = super::params::doc_keys(spec.params).map(|p| p.keys).unwrap_or_default(); + let in_schema = spec.schema.map(|s| s.params.iter().map(|p| p.name)).into_iter().flatten(); + let taken = FILE_KEYS.iter().copied().filter(|k| super::params::takes_key(spec.params, k)); + let mut keys: Vec<(&'static str, Location)> = + described.into_iter().chain(in_schema).chain(taken).filter_map(|k| Some((k, location_in(spec, k)?))).collect(); + keys.sort_unstable_by_key(|(k, _)| *k); + keys.dedup(); + keys +} /// Commands and the param key in [`FILE_KEYS`] that, in them, names part of the document (a path of /// its art, a setting, an attribute it stores or a result field), not a file. @@ -119,8 +165,14 @@ pub(crate) const NOT_FILES: &[(&str, &str)] = &[ ("attributes.set", "url"), ("svgInteractivity.info", "files"), ("addon.cleanup.rejoin", "paths"), + ("object.slice.options", "url"), + ("document.exportForScreens", "folders"), ]; +/// Commands and the keys from the top of their params down to a key in [`FILE_KEYS`] that, there, +/// names part of the document, not a file: a custom arrowhead's outline in `stroke.set`. +const NESTED_NOT_FILES: &[(&str, &[&str])] = &[("stroke.set", &["startArrow", "Custom", "path"]), ("stroke.set", &["endArrow", "Custom", "path"])]; + /// Is command id `id` one a plug-in may never call, from its id alone ([`DENIED_PREFIXES`], /// [`FILE_WORDS`])? fn denied_id(id: &str) -> bool { @@ -184,20 +236,32 @@ pub(crate) fn names_key(text: &str, key: &str) -> bool { /// Does `args`, the arguments of a call of command `id`, carry a key in [`FILE_KEYS`] at any depth /// (in objects and in arrays), such as an effect's `textureImage.path`? Only a key [`NOT_FILES`] -/// names for `id`, at the top level, isn't counted. The walk keeps its own stack, so deep -/// arguments can't overflow the thread's. +/// names for `id`, at the top level, and one at the end of a [`NESTED_NOT_FILES`] key list for +/// `id`, aren't counted. The walk keeps its own stack, so deep arguments can't overflow the +/// thread's. fn names_file(id: &str, args: &Value) -> bool { - let mut stack = vec![(args, true)]; - while let Some((v, top)) = stack.pop() { + // Each value, whether it is the params themselves, and the keys of a NESTED_NOT_FILES list + // still to follow below it. + let mut stack: Vec<(&Value, bool, Option<&[&str]>)> = vec![(args, true, None)]; + while let Some((v, top, trail)) = stack.pop() { match v { - Value::Array(a) => stack.extend(a.iter().map(|x| (x, false))), + Value::Array(a) => stack.extend(a.iter().map(|x| (x, false, None))), Value::Object(o) => { for (k, x) in o { let k = k.as_str(); - if FILE_KEYS.contains(&k) && !(top && NOT_FILES.contains(&(id, k))) { + let rest = if top { + NESTED_NOT_FILES + .iter() + .find(|(c, keys)| *c == id && keys.first() == Some(&k)) + .map(|(_, keys)| keys.get(1..).unwrap_or_default()) + } else { + trail.filter(|keys| keys.first() == Some(&k)).map(|keys| keys.get(1..).unwrap_or_default()) + }; + let document = (top && NOT_FILES.contains(&(id, k))) || rest.is_some_and(<[&str]>::is_empty); + if FILE_KEYS.contains(&k) && !document { return true; } - stack.push((x, false)); + stack.push((x, false, rest.filter(|keys| !keys.is_empty()))); } } _ => {} @@ -349,6 +413,7 @@ pub(crate) fn transaction(s: &mut Session, label: &str, f: impl FnOnce(&mut Sess st.interaction = None; } saved.restore(s); + s.sync_front_profiles(); Err(e) } } @@ -466,7 +531,8 @@ mod tests { } for (id, key) in NOT_FILES { let Some(spec) = crate::cmd::find_command(id) else { panic!("no command {id}") }; - assert!(names_key(spec.params, key), "{id} has no `{key}` param"); + let described = crate::cmd::params::doc_keys(spec.params).is_ok_and(|p| p.keys.contains(key)); + assert!(names_key(spec.params, key) || described, "{id} has no `{key}` param"); } let leaks: Vec<&str> = specs .iter() @@ -536,6 +602,16 @@ mod tests { assert!(!names_file("object.setLiveShape", &json!({"path": [[0, 0], [1, 1]]}))); assert!(names_file("object.setLiveShape", &json!({"options": {"path": "/tmp/x"}}))); assert!(names_file("object.move", &json!({"path": [[0, 0]]}))); + // A custom arrowhead's outline in stroke.set, only where stroke.set takes one. + let outline = json!({"subpaths": []}); + assert!(!names_file("stroke.set", &json!({"endArrow": {"Custom": {"name": "A", "path": outline}}}))); + assert!(!names_file("stroke.set", &json!({"startArrow": {"Custom": {"name": "A", "path": outline}}, "endArrow": "Triangle"}))); + assert!(names_file("stroke.set", &json!({"endArrow": {"Custom": {"name": "A", "path": outline, "file": "/tmp/x"}}}))); + assert!(names_file("stroke.set", &json!({"endArrow": {"Custom": {"path": {"path": "/tmp/x"}}}}))); + assert!(names_file("stroke.set", &json!({"endArrow": {"path": "/tmp/x"}}))); + assert!(names_file("stroke.set", &json!({"options": {"endArrow": {"Custom": {"path": "/tmp/x"}}}}))); + assert!(names_file("stroke.set", &json!({"endArrow": [{"Custom": {"path": "/tmp/x"}}]}))); + assert!(names_file("object.move", &json!({"endArrow": {"Custom": {"path": "/tmp/x"}}}))); // Deep nesting is walked without recursion. let mut deep = json!({"file": "/tmp/x"}); for _ in 0..10_000 { @@ -565,6 +641,40 @@ mod tests { read.unwrap(); } + /// [`location_keys`] names every key in [`FILE_KEYS`] that a command's params description or + /// schema names, in every way a description writes one (`path | name`, `folder? (…)`), less + /// those [`NOT_FILES`] names for it; folder keys name folders. No command a plug-in may call + /// has one. + #[test] + fn location_keys_come_from_the_command_catalog() { + let find = |id: &str| crate::cmd::find_command(id).unwrap_or_else(|| panic!("no command {id}")); + let keys = |id: &str| location_keys(find(id)); + assert!(keys("document.open").contains(&("path", Location::File)), "{:?}", keys("document.open")); + assert!(keys("document.compare").contains(&("diffPath", Location::File)), "{:?}", keys("document.compare")); + assert!(keys("addon.document.saveTimestampedCopy").contains(&("folder", Location::Folder))); + let relink = keys("links.relink"); + for k in [("path", Location::File), ("paths", Location::File), ("folder", Location::Folder)] { + assert!(relink.contains(&k), "{relink:?}"); + } + assert!(keys("action.batch").contains(&("destinationFolder", Location::Folder))); + for (id, key) in NOT_FILES { + assert!(!keys(id).iter().any(|(k, _)| k == key), "{id} `{key}` names a file"); + } + for spec in crate::cmd::command_specs() { + let found = location_keys(spec); + let described = crate::cmd::params::doc_keys(spec.params).map(|p| p.keys).unwrap_or_default(); + let in_schema = spec.schema.map(|s| s.params.iter().map(|p| p.name).collect::<Vec<_>>()).unwrap_or_default(); + for k in described.into_iter().chain(in_schema).filter(|k| FILE_KEYS.contains(k) && !NOT_FILES.contains(&(spec.id, *k))) { + assert!(found.iter().any(|(f, _)| *f == k), "{}: `{k}` is missing from {found:?}", spec.id); + } + assert!(found.iter().all(|(k, l)| (*l == Location::Folder) == FOLDER_KEYS.contains(k)), "{}: {found:?}", spec.id); + assert!(denied(spec).is_some() || found.is_empty(), "{} names {found:?} but a plug-in may call it", spec.id); + } + assert_eq!(key_location("url"), Some(Location::File)); + assert_eq!(key_location("sourceFolder"), Some(Location::Folder)); + assert_eq!(key_location("pathData"), None); + } + #[test] fn keys_are_found_as_whole_keys() { assert!(names_key("{path: a .wasm file}", "path")); diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 416a44adbc..ec1a95d373 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -32,6 +32,12 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.color.strokeToFill", "addon.color.swatchLegend", "addon.contour.set", + "addon.cutting.bridges", + "addon.cutting.weed", + "addon.image.applyColorMask", + "addon.image.colorMask", + "addon.image.removeBackground", + "addon.image.removeColorMask", "addon.pathtools.addPoints", "addon.pathtools.close", "addon.pathtools.corner", @@ -83,9 +89,12 @@ pub(super) const ALLOWED: &[&str] = &[ "appearance.showAllHidden", "appearance.targetContents", "appearance.transfer", + "artboard.align", "artboard.convertToArtboards", "artboard.delete", "artboard.deleteEmpty", + "artboard.distribute", + "artboard.distributeSpacing", "artboard.duplicate", "artboard.fitToArt", "artboard.fitToSelection", @@ -107,7 +116,9 @@ pub(super) const ALLOWED: &[&str] = &[ "brush.move", "brush.new", "brush.options", + "brush.placeArt", "brush.remove", + "brush.replaceArt", "brush.selectionArt", "brush.setCurrent", "brush.unused", @@ -147,6 +158,7 @@ pub(super) const ALLOWED: &[&str] = &[ "edit.colors.saturate", "edit.colors.toCMYK", "edit.colors.toGrayscale", + "edit.colors.toIndexed", "edit.colors.toRGB", "edit.duplicate", "edit.findNext", @@ -237,6 +249,7 @@ pub(super) const ALLOWED: &[&str] = &[ "object.blend.replaceSpine", "object.blend.reverseFrontToBack", "object.blend.reverseSpine", + "object.blend.setEasing", "object.blend.spine.addAnchor", "object.blend.spine.convertAnchor", "object.blend.spine.moveAnchor", @@ -302,8 +315,11 @@ pub(super) const ALLOWED: &[&str] = &[ "object.move", "object.nudge", "object.objectsOnPath.attach", + "object.objectsOnPath.detach", "object.objectsOnPath.expand", + "object.objectsOnPath.moveMember", "object.objectsOnPath.options", + "object.objectsOnPath.selectMember", "object.path.addAnchorPoints", "object.path.cleanUp", "object.path.divideObjectsBelow", @@ -461,13 +477,16 @@ pub(super) const ALLOWED: &[&str] = &[ "perspective.transform", "recolor.apply", "recolor.colors", + "recolor.pickTheme", "recolor.randomize", "recolor.reduce", + "recolor.weigh", "select.add", "select.all", "select.allOnArtboard", "select.anchors", "select.anchorsMany", + "select.byNote", "select.color", "select.font", "select.globalEdit", @@ -512,6 +531,7 @@ pub(super) const ALLOWED: &[&str] = &[ "select.same.textStrokeColor", "select.segments", "select.set", + "select.storedPath", "select.toggle", "select.update", "shape.arc", @@ -616,6 +636,8 @@ pub(super) const ALLOWED: &[&str] = &[ "text.thread.releaseSelection", "text.thread.remove", "text.touchType", + "threeD.addGraphic", + "threeD.mapGraphic", "transparency.disableOpacityMask", "transparency.editOpacityMask", "transparency.enableOpacityMask", @@ -641,6 +663,8 @@ pub(super) const ALLOWED: &[&str] = &[ "type.opticalMarginAlignment", "type.orientation.horizontal", "type.orientation.vertical", + "type.pathCenter.bottom", + "type.pathCenter.top", "type.pathOptions", "type.resetHorizontalScale", "type.resetTracking", @@ -675,8 +699,10 @@ pub(super) const DENIED: &[&str] = &[ "addon.pen.nextSegment", "effect.refreshDeferred", "graphicStyle.setOptions", + "object.blend.createSpine", "object.blend.options", "object.liquify", "object.pathfinder.options", + "stroke.arrowheads.edit", "type.compositeFonts.set", ]; diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index a92b4095a9..748e0a125a 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -156,6 +156,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[ p!("scrubNumericFields", "General", "Options", "Scrub Numeric Fields by Dragging", bool), p!("trackpadRotateView", "General", "Options", "Trackpad Gesture to Rotate View", bool), p!("holdToolKeys", "General", "Options", "Hold a Tool Shortcut to Use the Tool Temporarily", bool), + p!("boundingBoxWhileMovingAndDrawing", "General", "Options", "Show Bounding Box While Moving and Drawing", bool), // Selection & Anchor Display p!("selectionTolerance", "Selection & Anchor Display", "Selection", "Tolerance", num(1.0, 8.0, "px")), p!( @@ -211,6 +212,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[ p!("fontNamesInEnglish", "Type", "Options", "Show Font Names in English", bool), p!("autoSizeAreaType", "Type", "Options", "Auto Size New Area Type", bool), p!("fontPreview", "Type", "Options", "Enable in-menu font previews", bool), + p!("fontSamplesOnWhite", "Type", "Options", "Show samples on white", bool), p!("fontPreviewSize", "Type", "Options", "Font Preview Size", choice(&[("small", "Small"), ("medium", "Medium"), ("large", "Large")])), p!("recentFontsCount", "Type", "Options", "Number of Recent Fonts", int(1, 15)), p!("missingGlyphProtection", "Type", "Options", "Enable Missing Glyph Protection", bool), @@ -452,10 +454,10 @@ pub fn spec(key: &str) -> Option<&'static PrefSpec> { /// Preferences kept as one object with a command of their own instead of [`PREF_SPECS`] rows (they /// aren't in the Preferences dialog): the Eyedropper Options (`eyedropper.setOptions`), the /// Perspective Grid Options (`perspective.widget.options`), the Pathfinder Options -/// (`object.pathfinder.options`) and the Snap to Glyph options (`view.snapToGlyph.options`). -/// `prefs.get` and `prefs.set` take them by key (a partial object updates what it names) and -/// `prefs.reset` without a category resets them. -pub const PREF_GROUPS: &[&str] = &["eyedropper", "perspectiveWidget", "pathfinder", "glyphSnap"]; +/// (`object.pathfinder.options`), the Snap to Glyph options (`view.snapToGlyph.options`) and the +/// Pixel Snapping Options (`view.snapToPixel.options`). `prefs.get` and `prefs.set` take them by key +/// (a partial object updates what it names) and `prefs.reset` without a category resets them. +pub const PREF_GROUPS: &[&str] = &["eyedropper", "perspectiveWidget", "pathfinder", "glyphSnap", "pixelSnap"]; /// Validate a value for preference group `key` against `current`. fn validate_group(key: &str, current: &Value, v: &Value) -> std::result::Result<Value, String> { @@ -475,6 +477,10 @@ fn validate_group(key: &str, current: &Value, v: &Value) -> std::result::Result< let cur: vectorcraft_tools::GlyphSnap = serde_json::from_value(current.clone()).unwrap_or_default(); cur.merged(v).map(|o| json!(o)) } + "pixelSnap" => { + let cur: vectorcraft_tools::PixelSnap = serde_json::from_value(current.clone()).unwrap_or_default(); + cur.merged(v).map(|o| json!(o)) + } "perspectiveWidget" => { let mut merged = current.clone(); if let (Some(o), Some(p)) = (merged.as_object_mut(), v.as_object()) { @@ -687,6 +693,10 @@ impl Session { for e in self.prefs.keep_folders(&mut p) { log::warn!("{e}"); } + // Saved gradient presets get names no built-in preset or other saved one has. + for (old, new) in super::gradpresets::rename_clashing_presets(&mut p.gradient_presets) { + log::warn!("saved gradient preset {old} is listed as {new}: another preset has its name"); + } // The edit the active tool computes on another thread is applied first (the Preferences // dialog applies its settings here, outside a command). A failure to apply it was the // edit's own, and the preferences apply all the same. @@ -765,7 +775,7 @@ impl Session { pub fn specs() -> Vec<CommandSpec> { vec![ - cmd!(query "prefs.get", "Get Preferences", [], None, "{key?} → the value of one preference (or preference group: eyedropper), or {prefs: {…all…}}", always, get), + cmd!(query "prefs.get", "Get Preferences", [], None, "{key?} → the value of one preference (or preference group: eyedropper), or {prefs: {…all…}}; under automation read roots a folder preference outside them is null, and an export preset's folder outside them is left out", always, get), cmd!( query "prefs.set", "Set Preference", @@ -776,13 +786,13 @@ pub fn specs() -> Vec<CommandSpec> { set ), cmd!(query "prefs.reset", "Reset Preferences", [], None, "{category?} reset one category (or everything) to defaults", always, reset), - cmd!(query "prefs.list", "List Preferences", [], None, "{} → [{key, category, section, label, kind, value, …}] every preference", always, list), + cmd!(query "prefs.list", "List Preferences", [], None, "{} → [{key, category, section, label, kind, value, …}] every preference; under automation read roots a folder preference's value outside them is null", always, list), cmd!( query "prefs.export", "Export Preferences", [], None, - "{path?} write the preferences as a JSON file {format: \"vectorcraft-preferences\", version: 1, prefs: {key: value, …}}: every preference prefs.list lists and the eyedropper, perspectiveWidget, pathfinder and glyphSnap groups, without the folder preferences fontsFolder, pluginsFolder, recoveryFolder and templatesFolder and without saved presets; a file over 1 MB, which prefs.import would refuse, is an error and is not written → {path, count}; without path → {data: the file's text, count}", + "{path?} write the preferences as a JSON file {format: \"vectorcraft-preferences\", version: 1, prefs: {key: value, …}}: every preference prefs.list lists and the eyedropper, perspectiveWidget, pathfinder, glyphSnap and pixelSnap groups, without the folder preferences fontsFolder, pluginsFolder, recoveryFolder and templatesFolder and without saved presets; a file over 1 MB, which prefs.import would refuse, is an error and is not written → {path, count}; without path → {data: the file's text, count}", always, export ), @@ -882,8 +892,42 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> { Ok(json!({ "imported": values.len() })) } +/// The preferences that name a folder: the [`FOLDER_PREFS`] and the scratch disks. +const PATH_PREFS: [&str; 6] = ["fontsFolder", "pluginsFolder", "scratchPrimary", "scratchSecondary", "recoveryFolder", "templatesFolder"]; + +/// The scratch disk choices that are not folders. +const SCRATCH_CHOICES: [&str; 2] = ["Startup", "None"]; + +/// The preferences as `prefs.get`, `prefs.list`, `prefs.set` and `prefs.reset` show them to the +/// request being served. Under automation read roots, a folder preference ([`PATH_PREFS`]) outside +/// them is `null`, as `ui.inspect` leaves it out, and an export preset's `folder` outside them is +/// left out. An empty value (the default folder) and a scratch +/// disk choice ([`SCRATCH_CHOICES`]) are shown. Without roots the preferences are shown as they are. +fn shown_prefs(prefs: &Prefs) -> Value { + let mut all = prefs.to_json(); + if crate::file_access::current().is_none() { + return all; + } + // The app trims a folder before it uses it. + let hidden = |path: &str| !path.trim().is_empty() && crate::file_access::check_read(path.trim()).is_err(); + for key in PATH_PREFS { + let Some(path) = all[key].as_str() else { continue }; + if hidden(path) && !(key.starts_with("scratch") && SCRATCH_CHOICES.contains(&path.trim())) { + all[key] = Value::Null; + } + } + if let Some(presets) = all.get_mut("screenExportPresets").and_then(Value::as_array_mut) { + for settings in presets.iter_mut().filter_map(|p| p.get_mut("settings").and_then(Value::as_object_mut)) { + if settings.get("folder").and_then(Value::as_str).is_some_and(hidden) { + settings.remove("folder"); + } + } + } + all +} + fn get(s: &mut Session, p: &Value) -> Result<Value> { - let all = s.prefs.to_json(); + let all = shown_prefs(&s.prefs); match str_param(p, "key") { Some(k) if spec(k).is_some() || PREF_GROUPS.contains(&k) => Ok(all[k].clone()), Some(k) => Err(bad("prefs.get", format!("unknown preference `{k}`"))), @@ -911,7 +955,7 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> { if document_units && values.contains_key("unitsGeneral") && s.active().is_some() { s.set_document_units(s.default_units())?; } - let all = s.prefs.to_json(); + let all = shown_prefs(&s.prefs); Ok(Value::Object(values.keys().map(|k| (k.clone(), all[k.as_str()].clone())).collect())) } @@ -925,11 +969,11 @@ fn reset(s: &mut Session, p: &Value) -> Result<Value> { let mut next = s.prefs.clone(); next.reset(cat); s.apply_prefs(next); - Ok(json!({ "prefs": s.prefs.to_json() })) + Ok(json!({ "prefs": shown_prefs(&s.prefs) })) } fn list(s: &mut Session, _: &Value) -> Result<Value> { - let all = s.prefs.to_json(); + let all = shown_prefs(&s.prefs); Ok(Value::Array( PREF_SPECS .iter() diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index 9fe4665a5c..628facc1c3 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -112,6 +112,9 @@ fn preview(s: &mut Session, p: &Value) -> Result<Value> { super::printadvanced::flattener(C, &set, &s.prefs.flattener_presets)?; let mut pv = vectorcraft_pdf::preview(doc, &set).map_err(|e| pdf_error(C, e))?; pv.warnings.extend(type_warnings(doc, set.print_layers, &areas(&pv))); + // What the job loses comes first, then the notes on the options. + let settings = std::mem::take(&mut pv.setting_notes); + pv.warnings.extend(settings); let mut v = serde_json::to_value(pv).map_err(|e| EngineError::Other(e.to_string()))?; v["settings"] = to_json(&set)?; Ok(v) @@ -199,7 +202,9 @@ fn print(s: &mut Session, p: &Value) -> Result<Value> { let mut r = vectorcraft_pdf::print(printed, &PrintOptions { settings: set, for_printer: bool_or(p, "forPrinter", false), ..Default::default() }) .map_err(|e| pdf_error(PRINT, e))?; + // What the job loses comes first, then the notes on the options. r.warnings.extend(typed); + r.warnings.extend(r.setting_notes); return write_or_return(path, &r.bytes, json!({ "pages": r.pages, "format": "pdf", "warnings": r.warnings })); } let level = match p.get("level").filter(|v| !v.is_null()) { @@ -209,12 +214,13 @@ fn print(s: &mut Session, p: &Value) -> Result<Value> { } None => Level::default(), }; - let mut warnings = vec![]; + // What the job loses, then the notes on the options: a reply lists them in that order. + let (mut warnings, mut setting_notes) = (vec![], vec![]); if !bitmap && (tile_images || doc.layers.iter().any(|l| l.shows_transparency())) { warnings.push("transparency is flattened into opaque art and images (PostScript has none): see flattenerPreset".to_string()); } if !set.color.profile.trim().is_empty() && set.output.mode == vectorcraft_pdf::OutputMode::Composite { - warnings.push("the printer profile converts the colours of PDF output: PostScript prints the document's colours".to_string()); + setting_notes.push("the printer profile converts the colours of PDF output: PostScript prints the document's colours".to_string()); } let flatness = (!set.graphics.auto_flatness).then_some(set.graphics.flatness); let plan = vectorcraft_pdf::plan(prepared.as_ref().unwrap_or(doc), &PrintOptions { settings: set, postscript: true, ..Default::default() }) @@ -244,5 +250,11 @@ fn print(s: &mut Session, p: &Value) -> Result<Value> { } let areas: Vec<Rect> = plan.sheets.iter().filter_map(|sh| on_page(sh.area, sh.view * sh.place, sh.size)).collect(); warnings.extend(type_warnings(&full, which, &areas)); + for w in plan.setting_notes.iter().chain(&out.setting_notes) { + if !warnings.contains(w) && !setting_notes.contains(w) { + setting_notes.push(w.clone()); + } + } + warnings.extend(setting_notes); write_or_return(path, &out.bytes, json!({ "pages": plan.order.len(), "format": "postscript", "warnings": warnings })) } diff --git a/crates/engine/src/cmd/rasterfx.rs b/crates/engine/src/cmd/rasterfx.rs index 566a16dbfd..8f5f532c51 100644 --- a/crates/engine/src/cmd/rasterfx.rs +++ b/crates/engine/src/cmd/rasterfx.rs @@ -645,8 +645,8 @@ pub fn export_pdf(doc: &Document, opts: &vectorcraft_pdf::PdfOptions) -> std::re export_pdf_with_report(doc, opts).map(|r| r.bytes) } -/// Like [`export_pdf`], also returning the writer's warnings (options not applied yet, features -/// approximated or left out). +/// Like [`export_pdf`], also returning the writer's warnings (features approximated or left out) +/// and its notes on the options (options not applied yet). pub fn export_pdf_with_report( doc: &Document, opts: &vectorcraft_pdf::PdfOptions, diff --git a/crates/engine/src/cmd/recolor.rs b/crates/engine/src/cmd/recolor.rs index 74347caa04..8194f85547 100644 --- a/crates/engine/src/cmd/recolor.rs +++ b/crates/engine/src/cmd/recolor.rs @@ -7,10 +7,13 @@ use std::collections::{BTreeSet, HashMap}; use serde_json::{Value, json}; -use vectorcraft_color::recolor::{ColorKey, GlobalAdjust, Method, Preserve, Rng, RowMap, cluster, same_ink}; +use vectorcraft_color::recolor::{ + ColorKey, GlobalAdjust, Method, Preserve, Rng, RowMap, WeighUnit, cluster, row_shares, same_ink, weigh as weigh_rows, +}; use vectorcraft_color::{Color, Paint, Swatch}; use vectorcraft_doc::swatches::{node_colors, node_paints, override_paints}; use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use vectorcraft_geom::{Point, Rect}; use super::colorcmds::{NotChanged, Recolor, Scope, left_out}; use super::{CommandSpec, Result, Session, always, bad, checked_ids_param, cmd, color_value, has_doc, index, str_param, switch_or, text_param}; @@ -53,9 +56,895 @@ pub fn specs() -> Vec<CommandSpec> { always, randomize ), + cmd!( + query "recolor.pickTheme", + "Color Theme Picker", + [], + None, + "{picks: [{at: [x, y]} (a click: the object a Selection tool click there takes, with everything inside it) | {rect: [x0, y0, x1, y1]} (a marquee: every painted object it touches, and the part of each image inside it)] (1 to 256, in document points), colors?: 5 (1 to 64)} → {colors: [colour keys, the most used first], objects: the number of objects read} the colour palette of the art picked, for Recolor Artwork's Color Theme Picker: visible fills and strokes, gradient stops, text, mesh points, pattern tiles (with the patterns they use), the art of symbol instances (placed through their 9-slice guides), the colorize colour of an image it applies to and other images' pixels (at most 65,536 pixels of each pick of an image, spread evenly, and 1,048,576 pixels of at most 64 images in all; pixels less than half opaque and images that can't be decoded are left out). In a clip group, or under an opacity mask that clips, only what shows inside the clipping path or the mask art is read; a blend, envelope or repeat a marquee touches is read whole. The symbol instances read place at most 16,000,000 objects in all (an instance whose art would pass that is left out), and the pixels read inside clip groups are tested against at most 4,000,000 clipping-path elements in all (the picks of an image inside clip groups that would pass that are left out). Hidden or fully transparent objects and fill or stroke items are left out; locked objects are read. Each object read weighs the same, shared among its colours (an image's among its pixels; the vector art a symbol instance places counts as one object, each image it places on its own); similar colours merge (k-means in Lab) into at most `colors`, each shown by its most used colour in its own model. Picks that touch no art give no colours. Changes nothing", + has_doc, + pick_theme + ), + cmd!( + query "recolor.weigh", + "Prominent Colors", + [], + None, + "{map: rows [{from, to, …}] or {current: new} as recolor.apply, weights?: [numbers ≥ 0, one per row; an excluded row's is ignored, and at least one other must be above 0], ids?: as recolor.colors} → {map: the rows as given, each with its current colours (from) moved as below, shares: [one per row: its percent of the uses (recolor.colors' count) of the current colours of the rows that aren't excluded; 0 for an excluded row]} for Recolor Artwork's Prominent Colors (VectorCraft's own rule): without weights the rows stay as they are. With weights, current colours move one at a time between the rows that aren't excluded and have a new colour (to), while a move brings each row's share of the uses nearer its share of the weights, first the colour nearest in Lab to the first colour of the row it goes to compared with the row it leaves; a row's first colour stays in it, the tints of one global swatch in a row move together, a colour that another row with a new colour lists first stays where it is, the other rows with a new colour drop their entries for a colour that moves, and a use counts for the row recolor.apply recolors it with (rows with a new colour first, an exact colour before a hex one, the first row that lists it), else for the first other row that isn't excluded and lists it. The colours that can move are compared with the rows at most 50,000,000 times in all, and when they times the rows that aren't excluded pass that, none move. Changes nothing", + has_doc, + weigh + ), ] } +/// The pixels one read of an image by the Color Theme Picker takes, at most, the pixels all its +/// reads share, and the images one pick reads, at most. +const THEME_PIXELS: usize = 65_536; +const THEME_TOTAL_PIXELS: usize = 1 << 20; +const MAX_THEME_IMAGES: usize = 64; +/// The image reads one pick queues, at most. +const MAX_THEME_READS: usize = 4096; +/// The stroke segments the opacity masks one pick reads are outlined along, at most. +const MASK_OUTLINE_SEGMENTS: usize = 20_000; +/// The point-in-region tests the picks make to find whether outlines show through clip groups, +/// and the clipping-path elements the pixels of their images are tested against, at most. +const THEME_WORK: usize = 4_000_000; +/// The picks one `recolor.pickTheme` takes, and the colours it gives, at most. +const MAX_PICKS: usize = 256; +const MAX_THEME_COLORS: u64 = 64; +/// The objects the Color Theme Picker reads through, one inside another, at most. +const MAX_THEME_DEPTH: usize = 256; + +/// A pick of the Color Theme Picker: a click at a point or a marquee. +enum Pick { + At(Point), + Area(Rect), +} + +impl Pick { + /// `{at: [x, y]}` or `{rect: [x0, y0, x1, y1]}`, finite numbers. + fn param(v: &Value, cmd: &str) -> Result<Self> { + let numbers = |a: &Value, n: usize| -> Option<Vec<f64>> { + let a = a.as_array().filter(|a| a.len() == n)?; + a.iter().map(|x| x.as_f64().filter(|x| x.is_finite())).collect() + }; + match (v.get("at"), v.get("rect")) { + (Some(at), None) => { + numbers(at, 2).map(|p| Pick::At(Point::new(p[0], p[1]))).ok_or_else(|| bad(cmd, format!("`at` must be [x, y] (got {at})"))) + } + (None, Some(r)) => numbers(r, 4) + .map(|r| Pick::Area(Rect::new(r[0], r[1], r[2], r[3]).abs())) + .ok_or_else(|| bad(cmd, format!("`rect` must be [x0, y0, x1, y1] (got {r})"))), + _ => Err(bad(cmd, format!("each pick is {{at: [x, y]}} or {{rect: [x0, y0, x1, y1]}} (got {v})"))), + } + } +} + +/// A filled region: its outline and fill rule. +type Region = (vectorcraft_geom::BezPath, vectorcraft_geom::FillRule); + +/// An image the Color Theme Picker reads: its pixels, where it lies, the marquee it is read in +/// (`None`: all of it) and the region the clip groups around it show (`None`: unclipped). An +/// image its colorize paint applies to ([`vectorcraft_doc::ImageBlob::takes_colorize`]) gives that +/// paint's colours where a pixel read shows ink (opaque and darker than white). +#[derive(Clone)] +struct ImageRead<'a> { + blob: &'a vectorcraft_doc::ImageBlob, + xf: vectorcraft_geom::Affine, + size: (f64, f64), + area: Option<Rect>, + clip: Option<Vec<Region>>, + colorize: Option<Vec<Color>>, +} + +/// A pattern's colours, the image reads of its tiles, and the depth its tiles were read at when +/// [`MAX_THEME_DEPTH`] cut them short. +type PatternRead<'a> = (Vec<Color>, Vec<ImageRead<'a>>, Option<usize>); + +/// The colours the Color Theme Picker has read: each object weighs 1, shared among its colours. +struct Theme<'a> { + d: &'a Document, + boxes: vectorcraft_doc::SymbolBoxes<'a>, + samples: Vec<(Color, f32)>, + /// The images to read, each image decoded once for all its reads ([`Self::read_images`]), + /// and the images they read. + images: Vec<ImageRead<'a>>, + blobs: std::collections::HashSet<*const vectorcraft_doc::ImageBlob>, + /// What the clip groups being read show, in document space: the union of these regions + /// (none: nothing shows); `None` outside clip groups. + clip: Option<Vec<Region>>, + /// The colours of the patterns read so far (with the depth their tiles were read at when + /// [`MAX_THEME_DEPTH`] cut them short), and the patterns whose tiles are being read. + pattern_colors: HashMap<String, PatternRead<'a>>, + pattern_stack: Vec<String>, + /// Whether art was left out for passing [`MAX_THEME_DEPTH`]. + cut: bool, + /// The region tests [`Self::shows`] has made. + work: std::cell::Cell<usize>, + /// The objects the symbol instances read have placed, of [`vectorcraft_doc::MAX_SYMBOL_NODES`] + /// ([`vectorcraft_doc::charge_symbol_art`]). + symbol_nodes: u64, + /// The object isolated in isolation mode. + scope: Option<NodeId>, + /// The stroke segments opacity masks may still be outlined along ([`mask_regions`]). + mask_budget: usize, + objects: usize, +} + +/// The region both `a` and `b` (each a union of regions) cover, filled non-zero. +fn intersect_regions(a: &[Region], b: &[Region]) -> Vec<Region> { + let paths: Vec<vectorcraft_geom::PathData> = a.iter().chain(b).map(|(bp, _)| vectorcraft_geom::PathData::from_bezpath(bp)).collect(); + let inputs: Vec<(&vectorcraft_geom::PathData, vectorcraft_geom::FillRule)> = + paths.iter().zip(a.iter().chain(b)).map(|(p, (_, rule))| (p, *rule)).collect(); + let split = a.len(); + let both = vectorcraft_pathops::boolean_n(&inputs, |inside| inside.iter().any(|i| *i < split) && inside.iter().any(|i| *i >= split)); + if both.subpaths.is_empty() { vec![] } else { vec![(both.to_bezpath(), vectorcraft_geom::FillRule::NonZero)] } +} + +impl<'a> Theme<'a> { + fn new(d: &'a Document) -> Self { + Self { + d, + boxes: d.symbol_boxes(), + samples: vec![], + images: vec![], + blobs: std::collections::HashSet::new(), + clip: None, + pattern_colors: HashMap::new(), + cut: false, + pattern_stack: vec![], + work: std::cell::Cell::new(0), + symbol_nodes: 0, + scope: None, + mask_budget: MASK_OUTLINE_SEGMENTS, + objects: 0, + } + } + + fn add(&mut self, colors: Vec<Color>) { + if colors.is_empty() { + return; + } + let w = 1.0 / colors.len() as f32; + self.samples.extend(colors.into_iter().map(|c| (c, w))); + self.objects += 1; + } + + /// Read the images queued, each image's pixels decoded once, as colours: the pixels a read + /// gives that fall in one cell of 16 levels a channel merge into their average, weighted by how + /// many there are, and the cells of all the reads add up, so the images give at most 16³ + /// colours. Images that can't be decoded give none. The first [`MAX_THEME_IMAGES`] images + /// are read, and all the reads share [`THEME_TOTAL_PIXELS`] pixels (each read at least one, at + /// most [`THEME_PIXELS`]). The pixels read inside clip groups are tested against + /// [`THEME_WORK`] clipping-path elements in all; the reads of an image inside clip groups + /// that would pass it are left out. Gives the clipping-path elements tested. + fn read_images(&mut self) -> usize { + let reads = std::mem::take(&mut self.images); + // The reads of each image, in the order its first read came. + let mut by_image: Vec<(*const vectorcraft_doc::ImageBlob, Vec<&ImageRead>)> = vec![]; + for r in &reads { + let key: *const vectorcraft_doc::ImageBlob = r.blob; + match by_image.iter().position(|(k, _)| *k == key) { + Some(i) => by_image[i].1.push(r), + None if by_image.len() < MAX_THEME_IMAGES => by_image.push((key, vec![r])), + None => {} + } + } + let count: usize = by_image.iter().map(|(_, g)| g.len()).sum(); + let budget = (THEME_TOTAL_PIXELS / count.max(1)).clamp(1, THEME_PIXELS); + let mut pixels: HashMap<[u8; 3], ([f64; 3], f64)> = HashMap::new(); + // The clipping-path elements the pixels read have been tested against. + let tested = std::cell::Cell::new(0usize); + let elements = + |r: &ImageRead| r.clip.as_ref().map_or(0, |rs| rs.iter().map(|(bp, _)| bp.elements().len().max(1)).fold(0, usize::saturating_add)); + for (_, mut group) in by_image { + // Each pixel sampled for a read inside clip groups is tested against its clipping + // regions: the clipped reads of one image take at most `clipped` pixels each, so all + // of them keep within the work left, and the other reads take `budget`. When the work + // left can't test one pixel of each, the clipped reads are kept in order while their + // pixel fits, and the rest are left out. + let left = THEME_WORK.saturating_sub(tested.get()); + if group.iter().map(|r| elements(r)).fold(0, usize::saturating_add) > left { + let mut room = left; + group.retain(|r| { + let c = elements(r); + let fits = c <= room; + room = room.saturating_sub(if fits { c } else { 0 }); + fits + }); + } + let cost = group.iter().map(|r| elements(r)).fold(0, usize::saturating_add); + let clipped = left.checked_div(cost).map_or(budget, |w| budget.min(w)); + if group.is_empty() { + continue; + } + let keeps: Vec<Box<dyn Fn(f64, f64) -> bool + '_>> = group + .iter() + .map(|r| { + let (xf, (w, h), area, clip, cost, tested) = (r.xf, r.size, r.area, &r.clip, elements(r), &tested); + Box::new(move |u: f64, v: f64| { + let p = xf * Point::new(u * w, v * h); + area.is_none_or(|a| a.contains(p)) + && clip.as_ref().is_none_or(|rs| { + tested.set(tested.get().saturating_add(cost)); + rs.iter().any(|(bp, rule)| vectorcraft_geom::hit::fill_contains(bp, *rule, p)) + }) + }) as Box<dyn Fn(f64, f64) -> bool + '_> + }) + .collect(); + let picks: Vec<vectorcraft_doc::PixelPick> = group + .iter() + .zip(&keeps) + .map(|(r, keep)| { + use vectorcraft_geom::kurbo::Shape; + let (w, h) = r.size; + let inv = r.xf.inverse(); + // The box sampled: the marquee, cut to the clipping paths' bounds, so a small + // region a clip shows of a large image is still sampled densely. + let clip_box = r.clip.as_ref().map(|rs| rs.iter().map(|(bp, _)| bp.bounding_box()).reduce(|a, b| a.union(b)).unwrap_or_default()); + let region = match (r.area, clip_box) { + (Some(a), Some(c)) => Some(a.intersect(c)), + (a, c) => a.or(c), + }; + let box_uv = region.map(|a| { + let uv: Vec<Point> = + [(a.x0, a.y0), (a.x1, a.y0), (a.x0, a.y1), (a.x1, a.y1)].into_iter().map(|(x, y)| inv * Point::new(x, y)).collect(); + let low = |f: fn(&Point) -> f64| uv.iter().map(f).fold(f64::INFINITY, f64::min); + let high = |f: fn(&Point) -> f64| uv.iter().map(f).fold(f64::NEG_INFINITY, f64::max); + [low(|p| p.x) / w, low(|p| p.y) / h, high(|p| p.x) / w, high(|p| p.y) / h] + }); + (box_uv, if r.clip.is_some() { clipped } else { budget }, keep.as_ref()) + }) + .collect(); + let Some(each) = group[0].blob.sample_pixels(&picks) else { continue }; + for (px, read) in each.into_iter().zip(&group) { + if let Some(colors) = &read.colorize { + // Ink: an opaque pixel darker than white takes the colorize paint. + if !colors.is_empty() && px.iter().any(|p| p[3] >= 128 && p[..3].iter().any(|v| *v < 255)) { + let w = 1.0 / colors.len().max(1) as f32; + self.samples.extend(colors.iter().map(|c| (*c, w))); + self.objects += 1; + } + continue; + } + let mut cells: HashMap<[u8; 3], ([u64; 3], u64)> = HashMap::new(); + for [r, g, b, _] in px.into_iter().filter(|p| p[3] >= 128) { + let cell = cells.entry([r >> 4, g >> 4, b >> 4]).or_default(); + for (sum, v) in cell.0.iter_mut().zip([r, g, b]) { + *sum += u64::from(v); + } + cell.1 += 1; + } + let total: u64 = cells.values().map(|c| c.1).sum(); + if total == 0 { + continue; + } + for (key, (sum, n)) in cells { + let cell = pixels.entry(key).or_default(); + for (acc, s) in cell.0.iter_mut().zip(sum) { + *acc += s as f64 / total as f64; + } + cell.1 += n as f64 / total as f64; + } + self.objects += 1; + } + } + let mut cells: Vec<_> = pixels.into_iter().collect(); + // The same order on every run. + cells.sort_unstable_by_key(|c| c.0); + for (_, (sum, w)) in cells { + let [r, g, b] = sum.map(|s| (s / w).round().clamp(0.0, 255.0) as u8); + self.samples.push((Color::rgb8(r, g, b), w as f32)); + } + tested.get() + } + + /// Read `n` and everything visible inside it: each image (its part inside `area` when given, + /// and inside the clipping paths around it) and each other object with colours of its own + /// (that touches `area` when given, and shows inside the clipping paths around it). The art a + /// symbol instance shows (with a dynamic instance's own paints), placed where the instance + /// draws it, and the objects a blend, an envelope or a repeat draws elsewhere than they lie, + /// are read whole when the instance or the live object touches `area`. `depth` counts the + /// objects passed through: deeper art is left out. An enabled opacity mask that clips (and is + /// not inverted) shows the object only where its mask art is lighter than black + /// ([`mask_regions`]), as a clip group would. + fn read(&mut self, n: &Node, area: Option<Rect>, depth: usize) { + let Some(mask) = n.extras().mask.as_deref().filter(|m| !m.disabled && m.clip && !m.invert) else { + return self.read_unmasked(n, area, depth); + }; + let regions = mask_regions(&mask.art, &mut self.mask_budget); + let outer = self.clip.clone(); + self.clip = Some(match &outer { + None => regions, + Some(o) => intersect_regions(o, ®ions), + }); + self.read_unmasked(n, area, depth); + self.clip = outer; + } + + /// [`Self::read`] without `n`'s opacity mask. + fn read_unmasked(&mut self, n: &Node, area: Option<Rect>, depth: usize) { + if depth > MAX_THEME_DEPTH { + self.cut = true; + return; + } + // Hidden and fully transparent objects show nothing. + if !n.visible || n.opacity <= 0.0 || matches!(n.kind, NodeKind::Path { guide: true, .. }) { + return; + } + let touches = area.is_none_or(|r| self.touches(n, r)); + match &n.kind { + NodeKind::Image(im) => { + if !touches { + return; + } + // A document keeps its images' pixels in its image store. + let Some(blob) = self.d.images.get(&im.key) else { return }; + // An image with a colorize paint shows that paint's color, not its own pixels; + // other paints its appearance has (with effects that draw them) count as well. + let colorized = n.extras().colorize.is_some() && blob.takes_colorize(); + let own = if colorized || n.extras().colorize.is_none() { + self.own(n, true, depth) + } else { + // A colorize paint the image does not take (a linked image's preview) + // shows nothing. + let mut plain = n.clone(); + plain.extras_mut().colorize = None; + self.own(&plain, true, depth) + }; + let colorize = if colorized { + Some(own) + } else { + if self.shows(n, area) { + self.add(own); + } + None + }; + let size = (f64::from(im.width.max(1)), f64::from(im.height.max(1))); + self.queue_image(ImageRead { blob, xf: im.xf, size, area, clip: self.clip.clone(), colorize }); + return; + } + NodeKind::SymbolInstance { symbol, xf } => { + if touches + && self.shows(n, area) + && let Some(s) = self.d.symbols.iter().find(|s| s.name == *symbol) + { + // The art as the instance places it: through the symbol's 9-slice guides when + // it has them, else by the instance's transform. All the instances read share + // one limit on the objects they place, counted as the renderer counts them: an + // instance whose art would pass it shows nothing and is left out. + let dynamic = (!n.extras().symbol_overrides.is_empty()).then(|| vectorcraft_doc::symbol_overrides::dynamic_art(&s.art, n)); + let (d, art) = (self.d, dynamic.as_ref().unwrap_or(&s.art)); + let placed = match d.symbol_slice_map(symbol, *xf) { + Some(m) => vectorcraft_doc::charge_symbol_art(&mut self.symbol_nodes, m.most_placed(art, d), || { + let placed = d.place_symbol_art(symbol, art, *xf); + let n = placed.as_ref().map_or(0, |a| a.count_with_masks() as u64); + (placed, n) + }), + None => { + let count = art.count() as u64; + vectorcraft_doc::charge_symbol_art(&mut self.symbol_nodes, count, || (d.place_symbol_art(symbol, art, *xf), count)) + } + }; + let Some(Some(placed)) = placed else { return }; + // The instance's own paints; its overrides show in its art. + let own = self.own(n, false, depth); + self.add(own); + // The vector art counts as one object, each of its colours once, so an + // object the 9-slice guides cut into several copies does not count more. + // Each image placed is read on its own, as images are elsewhere. + let (samples, objects) = (self.samples.len(), self.objects); + self.read(&placed, None, depth + 1); + let added = self.samples.split_off(samples); + self.objects = objects; + let mut seen = std::collections::HashSet::new(); + let colors: Vec<Color> = added.into_iter().map(|(c, _)| c).filter(|c| seen.insert(ColorKey::of(c))).collect(); + self.add(colors); + } + return; + } + NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Repeat(_) => { + if touches && self.shows(n, area) { + let own = self.own(n, true, depth); + self.add(own); + // The copies are drawn elsewhere than the objects lie: the clipping paths + // around the live object, tested above, do not apply to the objects. + let clip = self.clip.take(); + for c in n.children().into_iter().flatten() { + self.read(c, None, depth + 1); + } + self.clip = clip; + } + return; + } + _ => {} + } + if touches && self.shows(n, area) { + let own = self.own(n, true, depth); + self.add(own); + } + // A compound path's members are its geometry: the compound paints them. + if matches!(n.kind, NodeKind::Compound { .. }) { + return; + } + // A clip group's clipping path paints whole, over the art it clips: it is read in the + // marquee as given and under the clip groups around it alone. + let clip_child = n.children().and_then(|c| c.first()).filter(|_| n.clips()); + if let Some(first) = clip_child { + self.read(first, area, depth + 1); + } + let inner = match area { + Some(r) => match vectorcraft_doc::hit::marquee_in(n, r) { + Some(inner) => Some(inner), + None => return, + }, + None => None, + }; + // A clip group shows its art where its clipping path's regions and the clip groups around + // it all show. + let outer = self.clip.clone(); + if n.clips() + && let Some(first) = n.children().and_then(|c| c.first()) + { + let regions: Vec<Region> = vectorcraft_doc::hit::clip_regions(first); + self.clip = Some(match &outer { + None => regions, + Some(o) => intersect_regions(o, ®ions), + }); + } + // A Shaper Group's original shapes, which the group keeps but does not show, are left out. + for (i, c) in n.children().into_iter().flatten().enumerate().skip(usize::from(clip_child.is_some())) { + if !vectorcraft_doc::hit::shaper_hides(n, i, self.scope) { + self.read(c, inner, depth + 1); + } + } + self.clip = outer; + } + + /// Does `n` show inside the region the clip groups around it show, in `area` when given? Its + /// box (cut to `area`) meets a region of it: the region's outline crosses the box, or a point + /// on a 9 × 9 grid over the part of the box inside the region's bounds lies in the region. + fn shows(&self, n: &Node, area: Option<Rect>) -> bool { + use vectorcraft_geom::kurbo::Shape; + let Some(regions) = &self.clip else { return true }; + let Some(b) = n.visual_bounds_with(&self.boxes) else { return false }; + let b = area.map_or(b, |r| b.intersect(r)); + let valid = |r: &Rect| r.width() >= 0.0 && r.height() >= 0.0; + if !valid(&b) { + return false; + } + // A path or compound path paints along its outline, and inside it where it has a visible + // fill: a point along the outline, or (filled) a point of a 9 × 9 grid over the part of the + // box inside a region's bounds that lies in both its fill and the region, must show. + let filled = has_fill(n); + let outline: Option<(Vec<&vectorcraft_geom::PathData>, vectorcraft_geom::FillRule)> = match &n.kind { + NodeKind::Path { path, rule, .. } => Some((vec![path], *rule)), + NodeKind::Compound { children, rule } => Some((children.iter().filter(|c| c.visible).filter_map(|c| c.path_data()).collect(), *rule)), + _ => None, + }; + if let Some((paths, own_rule)) = outline { + use vectorcraft_geom::ParamCurve; + use vectorcraft_geom::kurbo::ParamCurveArclen; + // The work all these tests do is bounded: past it, objects count as shown. + if self.work.get() > THEME_WORK { + return true; + } + let half = stroke_reach(n); + let cost: usize = regions.iter().map(|(bp, _)| bp.elements().len().max(1)).sum(); + let in_region = |p: Point| { + // Past the work allowed, the outline counts as shown. + if self.work.get() > THEME_WORK { + return true; + } + self.work.set(self.work.get() + cost); + regions.iter().any(|(bp, rule)| { + vectorcraft_geom::hit::fill_contains(bp, *rule, p) || half > 0.0 && vectorcraft_geom::hit::stroke_contains(bp, 0.0, half, p) + }) + }; + let mut fill = vectorcraft_geom::BezPath::new(); + for p in &paths { + fill.extend(p.to_bezpath().elements().iter().copied()); + } + // At most 4,096 points along the outline, shared among its segments by length, no + // farther apart than half the smallest region's width or height where that allows. + let step = regions + .iter() + .map(|(bp, _)| bp.bounding_box()) + .chain(area) + .map(|rb| rb.width().min(rb.height())) + .fold(f64::INFINITY, f64::min) + .max(0.01) + / 2.0; + // With a marquee, only the outline inside it (within the stroke's reach) counts. + let picked = area.map(|r| r.inflate(half, half)); + let segs: Vec<(vectorcraft_geom::PathSeg, f64)> = fill + .segments() + .take(4096) + .map(|s| { + let len = s.arclen(0.5); + (s, if len.is_finite() { len } else { 0.0 }) + }) + .collect(); + let total: f64 = segs.iter().map(|(_, l)| l).sum(); + let points = (total / step).ceil().clamp(64.0, 4096.0); + let along = segs.iter().any(|(seg, len)| { + let n = if total > 0.0 { (points * len / total).round().clamp(1.0, 4096.0) as u32 } else { 1 }; + (0..=n).any(|i| { + let p = seg.eval(f64::from(i) / f64::from(n)); + picked.is_none_or(|r| r.contains(p)) && in_region(p) + }) + }); + return along + || filled + && regions.iter().any(|(bp, _)| { + let g = b.intersect(bp.bounding_box()); + valid(&g) + && (0..81).any(|i| { + let p = Point::new(g.x0 + g.width() * f64::from(i % 9) / 8.0, g.y0 + g.height() * f64::from(i / 9) / 8.0); + in_region(p) && vectorcraft_geom::hit::fill_contains(&fill, own_rule, p) + }) + }); + } + regions.iter().any(|(bp, rule)| { + let g = b.intersect(bp.bounding_box()); + valid(&g) + && (vectorcraft_geom::hit::intersects_rect(&vectorcraft_geom::PathData::from_bezpath(bp), b) + || (0..81).any(|i| { + let p = Point::new(g.x0 + g.width() * f64::from(i % 9) / 8.0, g.y0 + g.height() * f64::from(i / 9) / 8.0); + vectorcraft_geom::hit::fill_contains(bp, *rule, p) + })) + }) + } + + /// Does the marquee `r` touch what `n` paints? A path or a compound path is touched where its + /// outline comes within half its widest visible stroke of `r` or, when it has a visible fill, + /// where `r`'s centre lies in that fill; any other object is touched by its box. + fn touches(&self, n: &Node, r: Rect) -> bool { + let boxed = n.visual_bounds_with(&self.boxes).is_some_and(|b| b.x0 <= r.x1 && r.x0 <= b.x1 && b.y0 <= r.y1 && r.y0 <= b.y1); + let filled = || has_fill(n); + let half = stroke_reach(n); + let near = r.inflate(half, half); + let crosses = |paths: &[&vectorcraft_geom::PathData], rule: vectorcraft_geom::FillRule| { + paths.iter().any(|p| vectorcraft_geom::hit::intersects_rect(p, near)) + || filled() && { + let mut bp = vectorcraft_geom::BezPath::new(); + for p in paths { + bp.extend(p.to_bezpath().elements().iter().copied()); + } + // A point on a 5 × 5 grid over the part of the marquee in the path's box lies + // in its fill. + use vectorcraft_geom::kurbo::Shape; + let g = r.intersect(bp.bounding_box()); + g.width() >= 0.0 + && g.height() >= 0.0 + && (0..25).any(|i| { + let p = Point::new(g.x0 + g.width() * f64::from(i % 5) / 4.0, g.y0 + g.height() * f64::from(i / 5) / 4.0); + vectorcraft_geom::hit::fill_contains(&bp, rule, p) + }) + } + }; + match &n.kind { + NodeKind::Path { path, rule, .. } => boxed && crosses(&[path], *rule), + NodeKind::Compound { children, rule } => { + let paths: Vec<&vectorcraft_geom::PathData> = children.iter().filter(|c| c.visible).filter_map(|c| c.path_data()).collect(); + boxed && crosses(&paths, *rule) + } + _ => boxed, + } + } +} + +/// The regions where opacity mask art `art` lets the masked object show: the regions +/// ([`vectorcraft_doc::hit::clip_regions`]) of its visible paths and compound paths filled lighter +/// than black (a solid color, a gradient with a stop lighter than black, or a pattern), the +/// outlines of the strokes lighter than black they have (dashes read as solid), the frames of its +/// images, the boxes of its type painted lighter than black, the boxes of art with effects (with +/// what the effects reach), and the regions of its clip groups and live objects whole. Black, +/// unfilled and unstroked paths without effects hide; how light the art is beyond that is not +/// read. Strokes are outlined along at most `budget` segments in all (it counts down); past that +/// a stroke counts by its box grown by half its width. +fn mask_regions(art: &Node, budget: &mut usize) -> Vec<Region> { + // Any color but black lets the masked art show. + fn light(p: &Paint) -> bool { + let lit = |c: &Color| c.to_rgba8(1.0)[..3].iter().any(|v| *v > 0); + match p { + Paint::None => false, + Paint::Solid { color, .. } => lit(color), + Paint::Gradient(g) => g.gradient.stops.iter().any(|s| lit(&s.color)), + _ => true, + } + } + fn walk(n: &Node, depth: usize, out: &mut Vec<Region>, budget: &mut usize) { + use vectorcraft_geom::kurbo::Shape; + // The mask art's root masks even when it is hidden. + // Guides draw nothing. + if depth > MAX_THEME_DEPTH || depth > 0 && (!n.visible || n.opacity <= 0.0) || matches!(n.kind, NodeKind::Path { guide: true, .. }) { + return; + } + // Art with effects can show light anywhere near it (a glow on black art): it counts + // whole, as a clipping path would. + let effects = !n.appearance.effects.is_empty() + || n.appearance.items.iter().any(|it| match it { + vectorcraft_doc::AppearanceItem::Fill(l) => l.visible && !l.effects.is_empty(), + vectorcraft_doc::AppearanceItem::Stroke(l) => l.visible && !l.effects.is_empty(), + }); + if effects { + if let Some(b) = n.visual_bounds() { + out.push((b.to_path(0.1), vectorcraft_geom::FillRule::NonZero)); + } + return; + } + let lit = n + .appearance + .items + .iter() + .any(|it| matches!(it, vectorcraft_doc::AppearanceItem::Fill(l) if l.visible && l.opacity > 0.0 && light(&l.paint))); + let stroke = n + .appearance + .items + .iter() + .filter_map(|it| match it { + vectorcraft_doc::AppearanceItem::Stroke(l) if l.visible && l.opacity > 0.0 && l.width > 0.0 && light(&l.paint) => Some(l.width / 2.0), + _ => None, + }) + .fold(None, |a: Option<f64>, w| Some(a.map_or(w, |a| a.max(w)))); + let boxed = |out: &mut Vec<Region>| { + if let Some(b) = n.geometric_bounds() { + out.push((b.to_path(0.1), vectorcraft_geom::FillRule::NonZero)); + } + }; + match &n.kind { + NodeKind::Path { .. } | NodeKind::Compound { .. } => { + if lit { + out.extend(vectorcraft_doc::hit::clip_regions(n)); + } + // A stroke shows the art along it: its outline with round ends and corners, a + // dashed stroke read as solid (the most it can show). + if let Some(half) = stroke { + let paths: Vec<&vectorcraft_geom::PathData> = match &n.kind { + NodeKind::Path { path, .. } => vec![path], + NodeKind::Compound { children, .. } => children.iter().filter_map(|c| c.path_data()).collect(), + _ => vec![], + }; + for p in paths { + // Past MASK_OUTLINE_SEGMENTS outlined segments, a stroke counts by its + // box grown by half its width. + let segments = p.to_bezpath().elements().len(); + if *budget < segments { + if let Some(b) = p.bounds().filter(|_| half.is_finite()) { + out.push((b.inflate(half, half).to_path(0.1), vectorcraft_geom::FillRule::NonZero)); + } + continue; + } + *budget -= segments; + let region = vectorcraft_pathops::outline_stroke( + p, + half * 2.0, + vectorcraft_pathops::Cap::Round, + vectorcraft_pathops::Join::Round, + 10.0, + ); + if !region.subpaths.is_empty() { + out.push((region.to_bezpath(), vectorcraft_geom::FillRule::NonZero)); + } + } + } + } + NodeKind::Image(_) => out.extend(vectorcraft_doc::hit::clip_regions(n)), + NodeKind::Text(t) => { + if lit || stroke.is_some() || t.runs.iter().any(|r| light(&r.style.fill) || r.style.stroke_width > 0.0 && light(&r.style.stroke)) { + boxed(out); + } + } + NodeKind::Group { clip: false, .. } | NodeKind::Layer { clip: false, .. } => { + // A Shaper Group's original shapes are kept but not drawn. + for (i, c) in n.children().into_iter().flatten().enumerate() { + if !vectorcraft_doc::hit::shaper_hides(n, i, None) { + walk(c, depth + 1, out, budget); + } + } + } + // Clip groups, live objects and placed documents count by the regions they clip to. + _ => out.extend(vectorcraft_doc::hit::clip_regions(n)), + } + } + let mut out = vec![]; + walk(art, 0, &mut out, budget); + out +} + +/// Does `n` have a fill item that paints: visible, not fully transparent and not None? +fn has_fill(n: &Node) -> bool { + n.appearance + .items + .iter() + .any(|it| matches!(it, vectorcraft_doc::AppearanceItem::Fill(l) if l.visible && l.opacity > 0.0 && !matches!(l.paint, Paint::None))) +} + +/// How far `n`'s widest painting stroke reaches from its path: half its width (0 without one). +fn stroke_reach(n: &Node) -> f64 { + let paints = |l: &vectorcraft_doc::StrokeLayer| l.visible && l.opacity > 0.0 && !matches!(l.paint, Paint::None) && l.width.is_finite(); + n.appearance + .items + .iter() + .filter_map(|it| match it { + vectorcraft_doc::AppearanceItem::Stroke(l) if paints(l) => Some(l.width.max(0.0) / 2.0), + _ => None, + }) + .fold(0.0, f64::max) +} + +/// The paints `m` shows: its visible fill items and its visible strokes wider than 0, its text's +/// fills and strokes wider than 0, and its colorize paint. +fn shown_paints(m: &Node) -> impl Iterator<Item = &Paint> { + let runs = match &m.kind { + NodeKind::Text(t) => t.runs.as_slice(), + _ => &[], + }; + let items = m.appearance.items.iter().filter_map(|it| match it { + vectorcraft_doc::AppearanceItem::Fill(l) if l.visible && l.opacity > 0.0 => Some(&l.paint), + vectorcraft_doc::AppearanceItem::Stroke(l) if l.visible && l.opacity > 0.0 && l.width > 0.0 => Some(&l.paint), + _ => None, + }); + let text = runs.iter().flat_map(|r| std::iter::once(&r.style.fill).chain((r.style.stroke_width > 0.0).then_some(&r.style.stroke))); + items.chain(text).chain(m.extras().colorize.as_deref()) +} + +/// Add the colours `m` shows itself to `out` (solid colours, gradient stops, its text's colours +/// and its mesh points; the paints a dynamic symbol instance keeps for objects of its art only +/// when `overrides` is set), and the names of the patterns it paints with to `patterns`, leaving +/// out names already there. +fn paint_colors_of(m: &Node, overrides: bool, out: &mut Vec<Color>, patterns: &mut Vec<String>) { + let kept = override_paints(m).filter(|_| overrides); + for p in shown_paints(m).chain(kept) { + match p { + Paint::Solid { color, .. } => out.push(*color), + Paint::Gradient(g) => out.extend(g.gradient.stops.iter().map(|s| s.color)), + Paint::Pattern { pattern, .. } if !patterns.contains(pattern) => patterns.push(pattern.clone()), + _ => {} + } + } + if let NodeKind::Mesh(mesh) = &m.kind { + out.extend(mesh.points.iter().map(|p| p.color)); + } +} + +impl<'a> Theme<'a> { + /// Queue image read `r`, within the limits of a pick: at most [`MAX_THEME_READS`] reads of + /// [`MAX_THEME_IMAGES`] images; nothing inside clip groups that show nothing. + fn queue_image(&mut self, r: ImageRead<'a>) { + if self.images.len() >= MAX_THEME_READS || r.clip.as_ref().is_some_and(Vec::is_empty) { + return; + } + let key: *const vectorcraft_doc::ImageBlob = r.blob; + if !self.blobs.contains(&key) { + if self.blobs.len() >= MAX_THEME_IMAGES { + return; + } + self.blobs.insert(key); + } + self.images.push(r); + } + + /// The colours `m` paints itself ([`paint_colors_of`]; a dynamic symbol instance's paints for + /// objects of its art only with `overrides`), and the colours its pattern tiles show, read as + /// document art is read (clip groups and symbols included; the tiles' images join this pick's + /// image reads). Each pattern's colours + /// are read once; a pattern whose tile uses itself, directly or through other patterns, adds + /// nothing more the second time. `depth` is `m`'s ([`Self::read`]): the tiles' art is read one + /// deeper, and a pattern whose tiles [`MAX_THEME_DEPTH`] cut short is read again when it is + /// used less deep. + fn own(&mut self, m: &Node, overrides: bool, depth: usize) -> Vec<Color> { + let mut out = vec![]; + let mut patterns: Vec<String> = vec![]; + paint_colors_of(m, overrides, &mut out, &mut patterns); + for name in patterns { + if let Some((colors, reads, cut)) = self.pattern_colors.get(&name).filter(|e| e.2.is_none_or(|at| depth >= at)) { + self.cut |= cut.is_some(); + out.extend(colors); + // The tiles' images count again for each use, within the pick's limits. + let reads = reads.clone(); + for r in reads { + self.queue_image(r); + } + continue; + } + if self.pattern_stack.contains(&name) || self.pattern_stack.len() >= MAX_THEME_DEPTH { + continue; + } + let Some(def) = self.d.pattern(&name) else { continue }; + let mut sub = Theme::new(self.d); + sub.pattern_stack = std::mem::take(&mut self.pattern_stack); + sub.pattern_stack.push(name.clone()); + sub.pattern_colors = std::mem::take(&mut self.pattern_colors); + // The tiles' images join this pick's image reads, within its limits. + sub.images = std::mem::take(&mut self.images); + sub.blobs = std::mem::take(&mut self.blobs); + // The tiles share this pick's limits on work too. + sub.work.set(self.work.get()); + sub.symbol_nodes = self.symbol_nodes; + sub.mask_budget = self.mask_budget; + let before = sub.images.len(); + for a in &def.art { + sub.read(a, None, depth + 1); + } + sub.pattern_stack.pop(); + self.pattern_stack = std::mem::take(&mut sub.pattern_stack); + self.pattern_colors = std::mem::take(&mut sub.pattern_colors); + let reads: Vec<ImageRead<'a>> = sub.images.get(before..).unwrap_or_default().to_vec(); + self.images = std::mem::take(&mut sub.images); + self.blobs = std::mem::take(&mut sub.blobs); + self.work.set(sub.work.get()); + self.symbol_nodes = sub.symbol_nodes; + self.mask_budget = sub.mask_budget; + self.cut |= sub.cut; + let colors: Vec<Color> = sub.samples.iter().map(|(c, _)| *c).collect(); + out.extend(&colors); + self.pattern_colors.insert(name, (colors, reads, sub.cut.then_some(depth))); + } + out + } +} + +fn pick_theme(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "recolor.pickTheme"; + let picks = match p.get("picks") { + Some(Value::Array(a)) if !a.is_empty() && a.len() <= MAX_PICKS => a.iter().map(|v| Pick::param(v, C)).collect::<Result<Vec<_>>>()?, + Some(Value::Array(a)) => return Err(bad(C, format!("`picks` must hold 1 to {MAX_PICKS} picks (got {})", a.len()))), + Some(v) => return Err(bad(C, format!("`picks` must be an array (got {v})"))), + None => return Err(bad(C, "missing `picks`")), + }; + let n = super::menucmds::whole_or(p, "colors", 5, C)?; + if !(1..=MAX_THEME_COLORS).contains(&n) { + return Err(bad(C, format!("`colors` must be between 1 and {MAX_THEME_COLORS} (got {n})"))); + } + let st = s.doc()?; + let d = &st.doc; + let mut theme = Theme::new(d); + theme.scope = st.isolation; + // In isolation mode: the isolated object, everything inside it and the containers around it. + let scope: Option<std::collections::HashSet<NodeId>> = st.isolation.and_then(|iso| d.node(iso)).map(|iso| { + let mut allowed = std::collections::HashSet::new(); + iso.walk(&mut |m| { + allowed.insert(m.id); + }); + let mut up = d.parent_of(iso.id); + while let Some(p) = up { + allowed.insert(p); + up = d.parent_of(p); + } + allowed + }); + for pick in picks { + match pick { + Pick::At(pt) => { + // In isolation mode only the isolated art (and the groups around it) can be hit; + // isolated Shaper Group originals are hittable then. + let opt = vectorcraft_doc::hit::HitOptions { scope: st.isolation, ..Default::default() }; + let hit = match &scope { + Some(allowed) => vectorcraft_doc::hit::hit_test_visible_skipping(d, pt, opt, &|id| !allowed.contains(&id)), + None => vectorcraft_doc::hit::hit_test_visible(d, pt, opt), + }; + if let Some(n) = hit.and_then(|h| d.node(h.top_object(st.isolation))) { + theme.read(n, None, 0); + } + } + Pick::Area(r) => match st.isolation.and_then(|iso| d.node(iso)) { + // In isolation mode a marquee reads the isolated art alone. + Some(iso) => theme.read(iso, Some(r), 0), + None => { + for l in &d.layers { + theme.read(l, Some(r), 0); + } + } + }, + } + } + theme.read_images(); + let colors = vectorcraft_color::recolor::theme_palette(&theme.samples, index(n)); + Ok(json!({"colors": colors.iter().map(key_str).collect::<Vec<_>>(), "objects": theme.objects})) +} + /// A colour the art uses: how often, and the global swatch it is linked to. struct Used { color: Color, @@ -184,6 +1073,181 @@ fn colors(s: &mut Session, p: &Value) -> Result<Value> { Ok(json!({ "colors": v })) } +/// `recolor.weigh`'s rows as given, each with `from` as a list (a `{current: new}` map gives a +/// row per entry). The rows have already been read by [`parse_rows`]. +fn given_rows(p: &Value) -> Vec<Value> { + match p.get("map") { + Some(Value::Array(rows)) => rows + .iter() + .map(|r| { + let mut r = r.clone(); + if let Some(f) = r.get("from").filter(|f| !f.is_array()).cloned() { + r["from"] = json!([f]); + } + r + }) + .collect(), + Some(Value::Object(m)) => m.iter().map(|(k, v)| json!({"from": [k], "to": v})).collect(), + _ => vec![], + } +} + +fn weigh(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "recolor.weigh"; + let rows = parse_rows(p, C)?; + let weights = match p.get("weights") { + None | Some(Value::Null) => None, + Some(Value::Array(a)) if a.len() == rows.len() => Some( + a.iter() + .map(|v| { + v.as_f64() + .filter(|x| x.is_finite() && *x >= 0.0) + .ok_or_else(|| bad(C, format!("each weight must be a number of 0 or more (got {v})"))) + }) + .collect::<Result<Vec<f64>>>()?, + ), + Some(v) => return Err(bad(C, format!("`weights` must be a list of {} numbers, one per row (got {v})", rows.len()))), + }; + let active: Vec<usize> = (0..rows.len()).filter(|&i| !rows[i].exclude).collect(); + if let Some(w) = &weights + && !active.is_empty() + && !active.iter().any(|&i| w[i] > 0.0) + { + return Err(bad(C, "at least one row that isn't excluded needs a weight above 0")); + } + let (ids, only) = scope_ids(s, p, C)?; + let st = s.doc()?; + let mut used: Vec<Option<Used>> = used_colors(&st.doc, &ids, only.as_ref()).into_iter().map(Some).collect(); + let mut by_key: HashMap<ColorKey, usize> = HashMap::new(); + let mut by_hex: HashMap<String, Vec<usize>> = HashMap::new(); + for (i, u) in used.iter().enumerate().filter_map(|(i, u)| Some((i, u.as_ref()?))) { + by_key.insert(ColorKey::of(&u.color), i); + by_hex.entry(u.color.to_hex()).or_default().push(i); + } + // Each current colour's uses and global swatch. A use counts where recolor.apply recolors it: + // rows with a new colour first, exact colours before hex colours, the first row that lists it; + // then the other rows that aren't excluded, in the same way. `owner` holds the row and entry that took each colour, + // and `shadows` the entries of rows with a new colour whose colours other entries took. + let mut owner: Vec<Option<(usize, usize)>> = vec![None; used.len()]; + let mut shadows: Vec<(usize, usize, Vec<usize>)> = vec![]; + let mut found: Vec<Vec<(usize, Option<String>)>> = rows.iter().map(|r| vec![(0, None); r.from.len()]).collect(); + for recolors in [true, false] { + for hex in [false, true] { + for (r, row) in rows.iter().enumerate().filter(|(_, r)| !r.exclude && r.new_color().is_some() == recolors) { + for (e, m) in row.from.iter().enumerate().filter(|(_, m)| matches!(m, Match::Hex(_)) == hex) { + let hits: Vec<usize> = match m { + Match::Key(k) => by_key.get(k).copied().into_iter().collect(), + Match::Hex(h) => by_hex.get(h).cloned().unwrap_or_default(), + }; + let (mut uses, mut link, mut took, mut taken) = (0, None, false, vec![]); + for i in hits { + match used[i].take() { + Some(u) => { + uses += u.count; + link = link.or(u.swatch); + took = true; + owner[i] = Some((r, e)); + } + None => taken.push(i), + } + } + found[r][e] = (uses, link); + if recolors && !took && !taken.is_empty() { + shadows.push((r, e, taken)); + } + } + } + } + } + // The units that move: in each row that isn't excluded, the colours linked to one global + // swatch go together, each other colour on its own, and the unit of the first colour stays. + let (mut units, mut members): (Vec<WeighUnit>, Vec<(usize, Vec<usize>)>) = (vec![], vec![]); + let mut unit_of: HashMap<(usize, usize), usize> = HashMap::new(); + for (n, &r) in active.iter().enumerate() { + let mut groups: Vec<(Option<&String>, Vec<usize>, usize)> = vec![]; + let mut by_link: HashMap<&String, usize> = HashMap::new(); + for (e, (uses, link)) in found[r].iter().enumerate() { + let g = match link { + Some(l) => *by_link.entry(l).or_insert_with(|| { + groups.push((Some(l), vec![], 0)); + groups.len() - 1 + }), + None => { + groups.push((None, vec![], 0)); + groups.len() - 1 + } + }; + groups[g].1.push(e); + groups[g].2 += uses; + } + for (k, (_, entries, uses)) in groups.into_iter().enumerate() { + for &e in &entries { + unit_of.insert((r, e), units.len()); + } + units.push(WeighUnit { color: rows[r].from[entries[0]].color(), uses: uses as f64, row: n, fixed: k == 0 }); + members.push((r, entries)); + } + } + // recolor.apply matches a colour to the first row with a new colour that lists it. A colour + // that another such row's first colour also lists stays where it is; another row's other + // entries for a colour that moves are dropped from that row below. + let owners = |taken: &[usize]| -> Vec<usize> { taken.iter().filter_map(|&i| unit_of.get(&owner[i]?).copied()).collect() }; + for (_, _, taken) in shadows.iter().filter(|(_, e, _)| *e == 0) { + for u in owners(taken) { + units[u].fixed = true; + } + } + if let Some(w) = &weights { + // Only rows with a new colour recolor what they hold, so only they give and take colours. + let movers: Vec<usize> = (0..active.len()).filter(|&n| rows[active[n]].new_color().is_some()).collect(); + let anchors: Vec<Color> = + movers.iter().map(|&n| rows[active[n]].from.first().map(Match::color).or(rows[active[n]].to).unwrap_or_default()).collect(); + let mut mover_of = vec![None; active.len()]; + for (m, &n) in movers.iter().enumerate() { + mover_of[n] = Some(m); + } + let at: Vec<Option<usize>> = units.iter().map(|u| mover_of[u.row]).collect(); + let sub: Vec<WeighUnit> = units.iter().zip(&at).filter_map(|(u, m)| Some(WeighUnit { row: (*m)?, ..*u })).collect(); + let to = weigh_rows(&sub, &anchors, &movers.iter().map(|&n| w[active[n]]).collect::<Vec<_>>()); + for ((u, _), m) in units.iter_mut().zip(&at).filter(|(_, m)| m.is_some()).zip(to) { + u.row = movers[m]; + } + } + let mut out = given_rows(p); + if weights.is_some() { + // Each row's colours: those that stayed, in their order, then those that came to it. + // A row's entry for a colour that moved to another row would take it back, so it goes. + let moved = |u: usize| active[units[u].row] != members[u].0; + let dropped: std::collections::HashSet<(usize, usize)> = + shadows.iter().filter(|(_, e, taken)| *e != 0 && owners(taken).into_iter().any(moved)).map(|(r, e, _)| (*r, *e)).collect(); + let old: Vec<Vec<Value>> = out.iter().map(|r| r["from"].as_array().cloned().unwrap_or_default()).collect(); + let mut stayed: Vec<Vec<usize>> = active.iter().map(|_| vec![]).collect(); + let mut came: Vec<Vec<Value>> = active.iter().map(|_| vec![]).collect(); + for (u, (r, entries)) in units.iter().zip(&members) { + let kept = entries.iter().copied().filter(|&e| !dropped.contains(&(*r, e))); + if active[u.row] == *r { + stayed[u.row].extend(kept); + } else { + came[u.row].extend(kept.filter_map(|e| old[*r].get(e).cloned())); + } + } + for (n, &r) in active.iter().enumerate() { + stayed[n].sort_unstable(); + let mut from: Vec<Value> = stayed[n].iter().filter_map(|&e| old[r].get(e).cloned()).collect(); + from.append(&mut came[n]); + if let Some(row) = out.get_mut(r) { + row["from"] = Value::Array(from); + } + } + } + let shares = row_shares(&units, active.len()); + let mut all = vec![0.0; rows.len()]; + for (n, &r) in active.iter().enumerate() { + all[r] = shares[n]; + } + Ok(json!({"map": out, "shares": all})) +} + /// The `method` parameter (`default` without one, or for null). A `method` that is not a string, /// such as `5`, names no method. fn method_param(p: &Value, cmd: &str, default: Method) -> Result<Method> { @@ -710,3 +1774,243 @@ fn randomize(_: &mut Session, p: &Value) -> Result<Value> { .collect(); Ok(json!({ "map": map })) } + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use vectorcraft_doc::{Appearance, ImageBlob, MAX_SYMBOL_NODES, PatternDef, Symbol}; + use vectorcraft_geom::{Affine, BezPath, FillRule, shapes}; + + use super::*; + + const RED: Color = Color::Rgb { r: 1.0, g: 0.0, b: 0.0 }; + const BLUE: Color = Color::Rgb { r: 0.0, g: 0.0, b: 1.0 }; + + /// A 10 pt square from (`x`, 0) painted `fill`. + fn square(d: &mut Document, x: f64, fill: Paint) -> Arc<Node> { + let p = shapes::rectangle(Rect::new(x, 0.0, x + 10.0, 10.0)); + Arc::new(Node::path(d.alloc_id(), p, Appearance::basic(fill, Paint::None, 0.0))) + } + + /// Symbol `name` whose art is a group of `art`, and an instance of it. + fn symbol(d: &mut Document, name: &str, art: Vec<Arc<Node>>) -> Arc<Node> { + let group = Node::group(d.alloc_id(), art); + d.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(group) }); + Arc::new(Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::IDENTITY })) + } + + fn has(t: &Theme, c: Color) -> bool { + t.samples.iter().any(|(s, _)| ColorKey::of(s) == ColorKey::of(&c)) + } + + /// The symbol instances read share one limit on the objects they place: with room for one + /// instance's art (a group and a square, 2 objects), the first instance is read and the + /// second, of another symbol, is left out. + #[test] + fn symbol_instances_share_one_limit_on_placed_objects() { + let mut d = Document::new(100.0, 100.0); + let red = square(&mut d, 0.0, Paint::solid(RED)); + let a = symbol(&mut d, "Red", vec![red]); + let blue = square(&mut d, 20.0, Paint::solid(BLUE)); + let b = symbol(&mut d, "Blue", vec![blue]); + let mut t = Theme::new(&d); + t.symbol_nodes = MAX_SYMBOL_NODES - 3; + t.read(&a, None, 0); + t.read(&b, None, 0); + assert!(has(&t, RED), "the first instance fits"); + assert!(!has(&t, BLUE), "the second does not"); + assert_eq!(t.symbol_nodes, MAX_SYMBOL_NODES - 1); + } + + /// An instance left out at the limit shows nothing, so its own paints are left out too. + #[test] + fn an_instance_past_the_limit_gives_none_of_its_own_paints() { + let mut d = Document::new(100.0, 100.0); + let red = square(&mut d, 0.0, Paint::solid(RED)); + let mut inst = (*symbol(&mut d, "Red", vec![red])).clone(); + inst.appearance = Appearance::basic(Paint::solid(BLUE), Paint::None, 0.0).into(); + let mut t = Theme::new(&d); + t.read(&inst, None, 0); + assert!(has(&t, BLUE), "the instance's own fill, with room for its art"); + let mut t = Theme::new(&d); + t.symbol_nodes = MAX_SYMBOL_NODES - 1; + t.read(&inst, None, 0); + assert!(t.samples.is_empty() && t.objects == 0, "nothing past the limit: {:?}", t.samples); + } + + /// An instance without 9-slice guides is counted as the renderer counts it, without the art of + /// its opacity masks: a square with a mask of 6 objects places 2. + #[test] + fn an_instance_is_counted_without_its_mask_art() { + let mut d = Document::new(100.0, 100.0); + let leaf = square(&mut d, 0.0, Paint::solid(BLUE)); + let mut mask = vectorcraft_doc::OpacityMask::new(Node::group(d.alloc_id(), vec![leaf; 5]), true); + mask.disabled = true; + let mut red = (*square(&mut d, 0.0, Paint::solid(RED))).clone(); + red.extras_mut().mask = Some(Box::new(mask)); + let inst = symbol(&mut d, "Masked", vec![Arc::new(red)]); + let mut t = Theme::new(&d); + t.symbol_nodes = MAX_SYMBOL_NODES - 3; + t.read(&inst, None, 0); + assert!(has(&t, RED)); + assert_eq!(t.symbol_nodes, MAX_SYMBOL_NODES - 1); + } + + /// Nested instances charge the limit at every level: a tree of four leaf instances (5 + /// objects) whose leaves place 2 objects each places 13 objects in all, and with 9 objects of + /// room it places the tree and two of its leaves. + #[test] + fn nested_symbol_instances_charge_every_level() { + let mut d = Document::new(100.0, 100.0); + let red = square(&mut d, 0.0, Paint::solid(RED)); + let leaf = symbol(&mut d, "Leaf", vec![red]); + let tree = symbol(&mut d, "Tree", vec![leaf; 4]); + let mut t = Theme::new(&d); + t.read(&tree, None, 0); + assert_eq!(t.symbol_nodes, 13); + let mut t = Theme::new(&d); + t.symbol_nodes = MAX_SYMBOL_NODES - 9; + t.read(&tree, None, 0); + assert_eq!(t.symbol_nodes, MAX_SYMBOL_NODES, "the tree and two leaves"); + assert!(has(&t, RED)); + } + + /// Patterns `P0` to `P{n}`: each tile a group holding a square filled with the next pattern, + /// the last a red square. Gives a square filled with `P0`. + fn pattern_chain(d: &mut Document, n: usize) -> Arc<Node> { + let fill = |i: usize| Paint::Pattern { pattern: format!("P{i}"), xf: Affine::IDENTITY }; + for i in 0..=n { + let inner = if i == n { square(d, 0.0, Paint::solid(RED)) } else { square(d, 0.0, fill(i + 1)) }; + let tile = Arc::new(Node::group(d.alloc_id(), vec![inner])); + d.patterns.push(PatternDef::new(&format!("P{i}"), vec![tile])); + } + square(d, 0.0, fill(0)) + } + + /// Pattern tiles are read one level deeper than the object their pattern fills, so a chain of + /// patterns shares one limit on depth with the art around it: the end of a chain of 50 is + /// read, the end of a chain of 200 (two levels for each tile) is not. + #[test] + fn pattern_tiles_share_one_depth_limit() { + let mut d = Document::new(100.0, 100.0); + let short = pattern_chain(&mut d, 50); + let mut t = Theme::new(&d); + t.read(&short, None, 0); + assert!(has(&t, RED), "a chain of 50"); + let mut d = Document::new(100.0, 100.0); + let long = pattern_chain(&mut d, 200); + let p100 = square(&mut d, 0.0, Paint::Pattern { pattern: "P100".into(), xf: Affine::IDENTITY }); + let mut t = Theme::new(&d); + t.read(&long, None, 0); + assert!(!has(&t, RED), "a chain of 200 passes {MAX_THEME_DEPTH} levels"); + // The patterns cut short there are read again when used less deep: from P100 the end is + // 100 patterns away. + t.read(&p100, None, 0); + assert!(has(&t, RED), "P100 read again at the top"); + } + + /// A pattern tile's symbol instances charge the same limit as the art around it. + #[test] + fn pattern_tiles_charge_the_symbol_limit() { + let mut d = Document::new(100.0, 100.0); + let red = square(&mut d, 0.0, Paint::solid(RED)); + let inst = symbol(&mut d, "Red", vec![red]); + d.patterns.push(PatternDef::new("Dots", vec![inst])); + let art = square(&mut d, 0.0, Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY }); + let mut t = Theme::new(&d); + t.read(&art, None, 0); + assert!(has(&t, RED)); + assert_eq!(t.symbol_nodes, 2, "the tile's instance placed a group and a square"); + let mut t = Theme::new(&d); + t.symbol_nodes = MAX_SYMBOL_NODES - 1; + t.read(&art, None, 0); + assert!(!has(&t, RED), "no room for the tile's instance"); + } + + /// A `size` px image of one color `rgba`. + fn blob(rgba: [u8; 4], size: u32) -> ImageBlob { + let mut png = Vec::new(); + image::RgbaImage::from_pixel(size, size, image::Rgba(rgba)).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + ImageBlob::png(png) + } + + /// A read of all of `blob`, placed at the origin 1 pt a pixel, inside a clipping path over + /// it of `elements` path elements. + fn clipped(blob: &ImageBlob, size: f64, elements: usize) -> ImageRead<'_> { + let mut bp = BezPath::new(); + bp.move_to((0.0, 0.0)); + let steps = elements.saturating_sub(4).max(1); + for i in 1..=steps { + bp.line_to((size * i as f64 / steps as f64, 0.0)); + } + bp.line_to((size, size)); + bp.line_to((0.0, size)); + bp.close_path(); + ImageRead { blob, xf: Affine::IDENTITY, size: (size, size), area: None, clip: Some(vec![(bp, FillRule::NonZero)]), colorize: None } + } + + /// The reads of one image inside clip groups share the work limit: three reads of a 64 px + /// image, each inside a clipping path of 3,000 elements, test at most [`THEME_WORK`] elements + /// in all and still read the image. + #[test] + fn reads_of_one_image_share_the_clip_work_limit() { + let d = Document::new(100.0, 100.0); + let red = blob([255, 0, 0, 255], 64); + let mut t = Theme::new(&d); + t.images = (0..3).map(|_| clipped(&red, 64.0, 3000)).collect(); + let tested = t.read_images(); + assert!(tested > 0 && tested <= THEME_WORK, "{tested} elements tested"); + assert!(has(&t, RED)); + } + + /// A read of an image outside clip groups keeps its own pixel budget when another read of the + /// same image inside a clip group gets only two pixels: the blue 8 px block in the corner of a + /// red 64 px image is still read. + #[test] + fn unclipped_reads_keep_their_budget_beside_clipped_reads() { + let d = Document::new(100.0, 100.0); + let red = blob([255, 0, 0, 255], 64); + let mut png = Vec::new(); + image::RgbaImage::from_fn(64, 64, |x, y| image::Rgba(if x >= 56 && y >= 56 { [0, 0, 255, 255] } else { [255, 0, 0, 255] })) + .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .unwrap(); + let corner = ImageBlob::png(png); + let mut t = Theme::new(&d); + let whole = ImageRead { clip: None, ..clipped(&corner, 64.0, 4) }; + // The red read leaves 6,400 elements of work; 3,200 elements a pixel leave two pixels. + t.images = vec![clipped(&red, 64.0, 3900), whole, clipped(&corner, 64.0, 3200)]; + let tested = t.read_images(); + assert!(tested <= THEME_WORK, "{tested} elements tested"); + assert!(has(&t, BLUE), "the read outside clip groups samples the whole image"); + } + + /// When the work left can't test a pixel of every clipped read of an image, the reads that fit + /// are still read: with 6,400 elements left, a read of a blue image inside a clipping path + /// of 5,000 elements is read beside one of 2,000 elements, which is left out. + #[test] + fn clipped_reads_that_fit_the_work_left_are_read() { + let d = Document::new(100.0, 100.0); + let (red, blue) = (blob([255, 0, 0, 255], 64), blob([0, 0, 255, 255], 64)); + let mut t = Theme::new(&d); + t.images = vec![clipped(&red, 64.0, 3900), clipped(&blue, 64.0, 5000), clipped(&blue, 64.0, 2000)]; + let tested = t.read_images(); + assert!(tested <= THEME_WORK, "{tested} elements tested"); + assert!(has(&t, BLUE), "the read that fits is read"); + } + + /// Past the work limit, the reads of an image inside clip groups are left out: a red image + /// inside a clipping path of 3,900 elements takes nearly all of it, and a blue image after it, + /// inside one of 100,000 elements, is not read. + #[test] + fn clipped_image_reads_past_the_work_limit_are_left_out() { + let d = Document::new(100.0, 100.0); + let (red, blue) = (blob([255, 0, 0, 255], 64), blob([0, 0, 255, 255], 64)); + let mut t = Theme::new(&d); + t.images = vec![clipped(&red, 64.0, 3900), clipped(&blue, 64.0, 100_000)]; + let tested = t.read_images(); + assert!(tested <= THEME_WORK, "{tested} elements tested"); + assert!(has(&t, RED)); + assert!(!has(&t, BLUE), "the blue image is past the limit"); + } +} diff --git a/crates/engine/src/cmd/recovery.rs b/crates/engine/src/cmd/recovery.rs index 4cf070c6ae..c1c7f789fe 100644 --- a/crates/engine/src/cmd/recovery.rs +++ b/crates/engine/src/cmd/recovery.rs @@ -17,7 +17,11 @@ //! store can, an announcement that lasts as long as the app ([`RecoveryStore::announce`]: the //! browser's Web Locks). Only areas nobody holds any more (their app is gone) are offered, and //! while their copies are restored or discarded the area is held, so two apps launched together -//! never both take it. +//! never both take it. An area's lock file or folder can be removed while its app runs, so each +//! recovery save and heartbeat checks that the lock still holds the area, and locks it again or +//! takes a new area. The copies it had in the old area stay there until it has written them again +//! in the new one, and an entry `<new area>/keeps-<old area>` ([`mark_left`]) tells other apps +//! that those copies belong to a running app, so none of them offers or discards them meanwhile. //! //! A heartbeat alone can't tell a gone app from one whose timers stopped (a background tab), so //! when unsure an area counts as held, and its app repairs what another app did meanwhile: each @@ -59,6 +63,9 @@ const BLOB_EXT: &str = ".blob"; /// The heartbeat entry of an area in a store without locks: when its app last said it runs (Unix /// seconds, as text). const BEAT: &str = "heartbeat"; +/// The start of an entry `<area>/keeps-<left area>`: the app holding `<area>` still keeps the copies +/// it left in `<left area>` ([`mark_left`]). +const KEEPS: &str = "keeps-"; /// The least time without a heartbeat after which an area's app counts as gone (seconds); else /// three Data Recovery intervals. const MIN_STALE: i64 = 180; @@ -90,6 +97,10 @@ pub trait RecoveryStore: Send + Sync { fn remove(&self, name: &str) -> std::result::Result<(), String>; /// Where the entries are, as the user knows it (a folder, "browser storage"). fn location(&self) -> String; + /// Is [`RecoveryStore::location`] a folder on this computer (default: no)? + fn in_folder(&self) -> bool { + false + } /// The areas in the store (default: those with entries). fn areas(&self) -> std::result::Result<Vec<String>, String> { let names = self.list()?; @@ -100,6 +111,12 @@ pub trait RecoveryStore: Send + Sync { fn lock(&self, _area: &str) -> std::result::Result<Lock, String> { Ok(Lock::Unsupported) } + /// Does `hold`, which [`RecoveryStore::lock`] gave for area `area`, still hold it? A lock on a + /// file or folder that was removed or replaced since holds nothing; when that can't be told now, + /// it does (default: it does). + fn still_held(&self, _area: &str, _hold: &(dyn std::any::Any + Send + Sync)) -> bool { + true + } /// Stores without locks: also hold area `area` in a way other apps can see that lasts exactly as /// long as this app runs, if the store has one (the browser's Web Locks) → it, until dropped. fn announce(&self, _area: &str) -> Option<Hold> { @@ -111,8 +128,13 @@ pub trait RecoveryStore: Send + Sync { fn announced(&self, _area: &str) -> Option<bool> { None } - /// Tidy away area `area` once it holds no copies and nobody holds it (its lock file and folder). + /// Tidy away area `area` once it holds no copies (its lock file and folder). The caller holds + /// the area until this returns. fn remove_area(&self, _area: &str) {} + /// Remove area `area`'s folder if it is empty, after [`RecoveryStore::remove_area`] and after the + /// caller let the area go. On some file systems a file that is open is removed only when it is + /// closed, so `remove_area` leaves the folder there while the area is held. + fn remove_empty_area(&self, _area: &str) {} /// The clock heartbeats are judged by (Unix seconds; `None`: none, so no area counts as gone). fn now(&self) -> Option<i64> { vectorcraft_doc::metadata::now_unix() @@ -261,7 +283,60 @@ impl FolderStore { builder.recursive(true); #[cfg(unix)] std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700); - builder.create(dir).map_err(|e| format!("{}: {e}", dir.display())) + builder.create(dir).map_err(|e| Self::folder_error(dir, &e, true)) + } + + /// The first folder on the way to `dir` (`dir` included), from the top down, that is not a + /// folder (`true`) or is missing (`false`). None when every one of them is a folder or one of + /// them can't be checked. + fn in_the_way(dir: &std::path::Path) -> Option<(&std::path::Path, bool)> { + let mut way: Vec<&std::path::Path> = dir.ancestors().filter(|p| !p.as_os_str().is_empty()).collect(); + way.reverse(); + for p in way { + match std::fs::metadata(p) { + Ok(m) if m.is_dir() => {} + Ok(_) => return Some((p, true)), + Err(m) if m.kind() == std::io::ErrorKind::NotFound => return Some((p, false)), + Err(_) => return None, + } + } + None + } + + /// The message for error `e` on folder `dir`, which was being made (`making`) or read. It + /// names the first folder on the way to `dir` that is not a folder, or is missing (when + /// `making`, the one that couldn't be made), and otherwise `dir`. + fn folder_error(dir: &std::path::Path, e: &std::io::Error, making: bool) -> String { + match Self::in_the_way(dir) { + Some((p, true)) => format!("{} is not a folder: {e}", p.display()), + Some((p, false)) if making => format!("couldn't make {}: {e}", p.display()), + Some((p, false)) if p != dir => format!("{} is missing", p.display()), + _ => format!("{}: {e}", dir.display()), + } + } + + /// The message for error `e` on file `f`. It names the first folder on the way to `f` that is + /// not a folder or is missing, and otherwise `f`. + fn file_error(f: &std::path::Path, e: &std::io::Error) -> String { + match f.parent().and_then(Self::in_the_way) { + Some((p, true)) => format!("{} is not a folder: {e}", p.display()), + Some((p, false)) => format!("{} is missing", p.display()), + None => format!("{}: {e}", f.display()), + } + } + + /// The outcome `r` of removing file `f`. A file that is not there counts as removed, unless a + /// file is on the way to it: Windows reports that as a missing file, and it is named as for a + /// listing. + pub(crate) fn removed(f: &std::path::Path, r: std::io::Result<()>) -> std::result::Result<(), String> { + match r { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => match f.parent().and_then(Self::in_the_way) { + Some((p, true)) => Err(format!("{} is not a folder: {e}", p.display())), + _ => Ok(()), + }, + Err(e) => Err(Self::file_error(f, &e)), + Ok(()) => Ok(()), + } } /// Refuse area folder `dir` unless it is a folder itself, not a link to one, and (on Unix) @@ -269,7 +344,7 @@ impl FolderStore { /// linked to a folder of its own in a shared recovery folder looked free, and claiming it /// wrote the copies through the link. fn own_area(dir: &std::path::Path) -> std::result::Result<(), String> { - let m = std::fs::symlink_metadata(dir).map_err(|e| format!("{}: {e}", dir.display()))?; + let m = std::fs::symlink_metadata(dir).map_err(|e| Self::folder_error(dir, &e, false))?; if !m.file_type().is_dir() { return Err(format!("{}: not a folder of its own", dir.display())); } @@ -281,11 +356,17 @@ impl FolderStore { } /// The plain names of the files (or, `dirs`, folders) in `dir`; none when it doesn't exist. + /// A file on the way to `dir` is an error: Windows reports such a folder as missing. fn names(dir: &std::path::Path, dirs: bool) -> std::result::Result<Vec<String>, String> { let entries = match std::fs::read_dir(dir) { Ok(e) => e, - Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(vec![]), - Err(e) => return Err(format!("{}: {e}", dir.display())), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + return match Self::in_the_way(dir) { + Some((p, true)) => Err(format!("{} is not a folder: {e}", p.display())), + _ => Ok(vec![]), + }; + } + Err(e) => return Err(Self::folder_error(dir, &e, false)), }; Ok(entries .filter_map(|e| e.ok()) @@ -295,6 +376,73 @@ impl FolderStore { .filter(|n| Self::plain(n)) .collect()) } + + /// Lock area folder `dir`, which was just made. Another app tidies an empty area away + /// (`tidy`) by removing its lock file and folder while it holds the lock. So when the folder + /// or the lock file is gone by now, or the lock taken is on a lock file the folder no longer + /// has, that app had the area: it is [`Lock::Busy`], and the caller tries another one. + pub(crate) fn lock_area(dir: &std::path::Path) -> std::result::Result<Lock, String> { + if let Err(e) = Self::own_area(dir) { + let gone = std::fs::symlink_metadata(dir).is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound); + return if gone { Ok(Lock::Busy) } else { Err(e) }; + } + let path = dir.join(LOCK_FILE); + match std::fs::OpenOptions::new().read(true).write(true).create(true).truncate(false).open(&path) { + Ok(file) => Self::take(file, &path), + Err(e) => Self::open_failed(e, &path), + } + } + + /// Opening lock file `path` failed with `e`. When the folder is gone by now, another app had the + /// area: it is [`Lock::Busy`]. So it is when the lock file is there but can't be opened: some + /// file systems keep a removed file that another app still has open until that app closes it, + /// and refuse to open it meanwhile. A lock file that can't be made is an error. + pub(crate) fn open_failed(e: std::io::Error, path: &std::path::Path) -> std::result::Result<Lock, String> { + match e.kind() { + std::io::ErrorKind::NotFound => Ok(Lock::Busy), + std::io::ErrorKind::PermissionDenied if std::fs::symlink_metadata(path).is_ok() => Ok(Lock::Busy), + _ => Err(Self::file_error(path, &e)), + } + } + + /// Lock `file`, opened as lock file `path`. The lock holds the area only while `path` still + /// names that file. + pub(crate) fn take(file: std::fs::File, path: &std::path::Path) -> std::result::Result<Lock, String> { + match file.try_lock() { + Ok(()) if Self::still_named(&file, path) => Ok(Lock::Held(Box::new(file))), + Ok(()) | Err(std::fs::TryLockError::WouldBlock) => Ok(Lock::Busy), + // The lock file was removed meanwhile, and locking it failed instead. + Err(std::fs::TryLockError::Error(_)) if !Self::still_named(&file, path) => Ok(Lock::Busy), + Err(std::fs::TryLockError::Error(e)) => Err(Self::file_error(path, &e)), + } + } + + /// Does `path` still name `file`? On Unix the two must be the same file (device and inode); on + /// Windows they must be the same file (volume serial number and file index); elsewhere `path` + /// must exist. When either file can't be read, it does not. + fn still_named(file: &std::fs::File, path: &std::path::Path) -> bool { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt as _; + match (file.metadata(), std::fs::symlink_metadata(path)) { + (Ok(a), Ok(b)) => a.dev() == b.dev() && a.ino() == b.ino(), + _ => false, + } + } + #[cfg(windows)] + { + let opened = file.try_clone().and_then(same_file::Handle::from_file); + match (opened, same_file::Handle::from_path(path)) { + (Ok(a), Ok(b)) => a == b, + _ => false, + } + } + #[cfg(not(any(unix, windows)))] + { + let _ = file; + std::fs::symlink_metadata(path).is_ok() + } + } } #[cfg(not(target_arch = "wasm32"))] @@ -313,10 +461,10 @@ impl RecoveryStore for FolderStore { if let Some(dir) = f.parent() { Self::own_area(dir)?; } - if !std::fs::symlink_metadata(&f).map_err(|e| format!("{}: {e}", f.display()))?.file_type().is_file() { + if !std::fs::symlink_metadata(&f).map_err(|e| Self::file_error(&f, &e))?.file_type().is_file() { return Err(format!("{}: not a plain file", f.display())); } - std::fs::read(&f).map_err(|e| format!("{}: {e}", f.display())) + std::fs::read(&f).map_err(|e| Self::file_error(&f, &e)) } fn write(&self, name: &str, bytes: &[u8]) -> std::result::Result<(), String> { let f = self.file(name)?; @@ -324,47 +472,51 @@ impl RecoveryStore for FolderStore { Self::create_area(dir)?; Self::own_area(dir)?; } - vectorcraft_format::write_atomic(&f, bytes).map_err(|e| format!("{}: {e}", f.display())) + vectorcraft_format::write_atomic(&f, bytes).map_err(|e| Self::file_error(&f, &e)) } fn remove(&self, name: &str) -> std::result::Result<(), String> { let f = self.file(name)?; - match std::fs::remove_file(&f) { - Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(format!("{}: {e}", f.display())), - _ => Ok(()), - } + Self::removed(&f, std::fs::remove_file(&f)) } fn location(&self) -> String { self.0.to_string_lossy().into_owned() } + fn in_folder(&self) -> bool { + true + } fn areas(&self) -> std::result::Result<Vec<String>, String> { Self::names(&self.0, true) } fn lock(&self, area: &str) -> std::result::Result<Lock, String> { let dir = self.area(area)?; Self::create_area(&dir)?; - Self::own_area(&dir)?; + Self::lock_area(&dir) + } + fn still_held(&self, area: &str, hold: &(dyn std::any::Any + Send + Sync)) -> bool { + let (Some(file), Ok(dir)) = (hold.downcast_ref::<std::fs::File>(), self.area(area)) else { return true }; let path = dir.join(LOCK_FILE); - let file = std::fs::OpenOptions::new() - .read(true) - .write(true) - .create(true) - .truncate(false) - .open(&path) - .map_err(|e| format!("{}: {e}", path.display()))?; - match file.try_lock() { - Ok(()) => Ok(Lock::Held(Box::new(file))), - Err(std::fs::TryLockError::WouldBlock) => Ok(Lock::Busy), - Err(std::fs::TryLockError::Error(e)) => Err(format!("{}: {e}", path.display())), + // Only a lock file or folder that is gone, or another one in its place, ends the hold. One + // that can't be read now (a network folder that doesn't answer) still counts as held. + match std::fs::symlink_metadata(&path) { + Ok(_) => Self::own_area(&dir).is_ok() && Self::still_named(file, &path), + Err(e) => e.kind() != std::io::ErrorKind::NotFound, } } fn remove_area(&self, area: &str) { // Best effort: whatever is left is tidied at a later launch. A folder that isn't empty - // (copies came back meanwhile) stays. + // (copies came back meanwhile) stays. The caller still holds the lock here. if let Ok(dir) = self.area(area) { let _ = std::fs::remove_file(dir.join(LOCK_FILE)); let _ = std::fs::remove_dir(&dir); } } + fn remove_empty_area(&self, area: &str) { + // Best effort, as above. An app that made the folder again meanwhile and has not locked it + // yet finds it gone and takes another area (`lock_area`); one that has keeps it. + if let Ok(dir) = self.area(area) { + let _ = std::fs::remove_dir(&dir); + } + } } /// The area this session keeps its copies in, while it holds it. @@ -391,6 +543,12 @@ pub struct Recovery { /// heartbeat it wrote there: that one doesn't make them look running, a newer one does (their /// app was only paused and came back). adopted: BTreeMap<String, i64>, + /// Copies in an area this session had to leave (`keep_hold`), by document uid, with their + /// store: each stays until its document has a copy in the new area, or needs none. They are + /// still this session's: never offered or discarded as a crash's here. + left: BTreeMap<u64, (Arc<dyn RecoveryStore>, String)>, + /// The `<own area>/keeps-<left area>` entries this session wrote in its area ([`mark_left`]). + marked: BTreeSet<String>, } impl Recovery { @@ -460,14 +618,120 @@ fn beating(store: &dyn RecoveryStore, area: &str, stale: i64, mine: Option<i64>) /// Refresh this session's hold on its area (the app does this every [`HEARTBEAT_EVERY`] seconds, /// so also on its first frame after its timers were paused): its heartbeat in a store without -/// locks, and its copies ([`repair`]) → the documents whose copies went missing (write them now). -/// Best effort: a missed beat only lets another app offer the copies once three intervals have -/// passed. +/// locks, and its copies ([`repair`]) → the documents whose copies went missing (write them now), +/// and those whose only copy is in an area the session left (`keep_hold`). Best effort: a missed +/// beat only lets another app offer the copies once three intervals have passed. pub fn heartbeat(s: &mut Session) -> Vec<u64> { + let mut lost = keep_hold(s); + // An entry that couldn't be written before, or that was removed since (by the user, a + // cleaner), is written now. + if let Some(own) = &s.recovery.own + && !s.recovery.marked.is_empty() + && let Ok(names) = own.store.list() + { + s.recovery.marked.retain(|n| names.contains(n)); + } + mark_left(s); if let Some(own) = s.recovery.own.as_ref().filter(|o| o.beats) { let _ = beat(own.store.as_ref(), &own.area); } - repair(s) + // A copy that was being written when the session left its area finished there. A document + // that gets no copy now (a complex one) keeps the copy it has. + lost.extend( + s.recovery + .left + .keys() + .filter(|&&uid| s.documents().iter().any(|d| d.uid == uid && d.recovery.is_none() && skip_reason(s, d).is_none())) + .copied(), + ); + lost.extend(repair(s)); + lost.sort_unstable(); + lost.dedup(); + lost +} + +/// Check that this session's lock still holds its area (stores with locks). The area's lock file, +/// or the whole area, can be removed while the app runs (by the user, a cleaner, another program), +/// and then another app can lock the area and offer or delete this session's copies as a crash's. +/// The area is locked again, made again first if it went (its copies are then written again). +/// When another app holds it now, the session takes a new area, and each copy left in the old one +/// stays until its document has a copy in the new one. → the documents whose copies must be +/// written again. +fn keep_hold(s: &mut Session) -> Vec<u64> { + drop_left_done(s); + let Some(own) = &mut s.recovery.own else { return vec![] }; + if own.beats || own.hold.as_deref().is_none_or(|h| own.store.still_held(&own.area, h)) { + return vec![]; + } + let (store, area) = (own.store.clone(), own.area.clone()); + // The lock held is on a file the area no longer has, so it holds nothing: it goes first (a + // removed file this app still has open can keep a new lock file from being made). + own.hold = None; + if let Ok(Lock::Held(h)) = store.lock(&area) { + own.hold = Some(h); + return repair(s); + } + let mut lost = vec![]; + for st in &mut s.docs { + if let Some(c) = st.recovery.take() { + s.recovery.left.insert(st.uid, (store.clone(), c.file)); + lost.push(st.uid); + } + } + s.recovery.own = None; + // Best effort: when no area can be taken now, the next recovery save says why. + let _ = claim(s, &store); + lost +} + +/// The copies left in an area this session left whose documents were saved, reverted or closed +/// since go. +fn drop_left_done(s: &mut Session) { + let done: Vec<u64> = s.recovery.left.keys().filter(|&&uid| !s.documents().iter().any(|d| d.uid == uid && d.is_dirty())).copied().collect(); + for uid in done { + drop_left(s, uid); + } +} + +/// Document `uid`'s copy in an area this session left goes. A copy that can't be removed now stays +/// this session's, and a later heartbeat removes it. +fn drop_left(s: &mut Session, uid: u64) { + let Some((store, file)) = s.recovery.left.get(&uid) else { return }; + let doc = store.remove(&format!("{file}{DOC_EXT}")); + let meta = store.remove(&format!("{file}{META_EXT}")); + if doc.is_ok() && meta.is_ok() { + s.recovery.left.remove(&uid); + mark_left(s); + } +} + +/// Record in this session's area each area it left that still holds copies of its documents: an +/// entry `<own area>/keeps-<left area>`, so another app leaves those copies alone while this one +/// runs ([`keeper`]). The entries of areas that hold none of its copies any more go. Best effort: +/// an entry not written or removed now is written or removed at the next heartbeat. +fn mark_left(s: &mut Session) { + let Some(own) = &s.recovery.own else { return }; + let (store, area) = (own.store.clone(), own.area.clone()); + let want: BTreeSet<String> = s + .recovery + .left + .values() + .filter(|(st, _)| st.location() == store.location()) + .filter_map(|(_, f)| f.split_once('/').map(|(a, _)| a)) + .filter(|a| *a != area) + .map(|a| format!("{area}/{KEEPS}{a}")) + .collect(); + let gone: Vec<String> = s.recovery.marked.difference(&want).cloned().collect(); + for n in gone { + if store.remove(&n).is_ok() { + s.recovery.marked.remove(&n); + } + } + for n in want { + if !s.recovery.marked.contains(&n) && store.write(&n, b"").is_ok() { + s.recovery.marked.insert(n); + } + } } /// Forget this session's copies that are missing from its area, so the next recovery save writes @@ -489,10 +753,13 @@ pub fn repair(s: &mut Session) -> Vec<u64> { /// This session's area in `store`, taken now if it has none there yet: a fresh area, held for the /// session's lifetime (locked, or with a heartbeat and an announcement where the store has them). pub fn claim(s: &mut Session, store: &Arc<dyn RecoveryStore>) -> Result<String> { - if let Some(own) = &s.recovery.own { - if own.store.location() == store.location() { + if s.recovery.own.as_ref().is_some_and(|o| o.store.location() == store.location()) { + // Documents whose copies went are left without one, so the caller writes them again. + keep_hold(s); + if let Some(own) = &s.recovery.own { return Ok(own.area.clone()); } + } else if s.recovery.own.is_some() { // The store moved (the preference names another folder): copies start again there. release(s); } @@ -512,6 +779,9 @@ pub fn claim(s: &mut Session, store: &Arc<dyn RecoveryStore>) -> Result<String> } }; s.recovery.own = Some(Own { store: store.clone(), area: area.clone(), hold, beats }); + // The entries written before are in the area this session had (released or left). + s.recovery.marked.clear(); + mark_left(s); return Ok(area); } Err(EngineError::Other("no free recovery area".into())) @@ -522,13 +792,22 @@ pub fn release(s: &mut Session) { for st in &mut s.docs { st.recovery = None; } + // Copies left in an area this session had to leave go too. + let left: Vec<u64> = s.recovery.left.keys().copied().collect(); + for uid in left { + drop_left(s, uid); + } let Some(Own { store, area, hold, .. }) = s.recovery.own.take() else { return }; + // Its `keeps-` entries go with the area's other entries. + s.recovery.marked.clear(); let mine = |n: &String| n.split_once('/').is_some_and(|(a, _)| a == area); for name in store.list().unwrap_or_default().iter().filter(|n| mine(n)) { let _ = store.remove(name); } - drop(hold); + // Held until it is gone, as in `tidy`. store.remove_area(&area); + drop(hold); + store.remove_empty_area(&area); } /// Let go of this session's area but leave its copies, as a crash would, so the next app started @@ -666,6 +945,21 @@ fn sweep(store: &dyn RecoveryStore, area: &str) { } } +/// The document's file `path` as a reply names it: under automation read roots, only inside them. +fn shown_path(path: Option<String>) -> Option<String> { + path.filter(|p| crate::file_access::check_read(p).is_ok()) +} + +/// Where `store` keeps its copies, as a reply names it: a recovery folder outside the automation +/// read roots is `null`. +fn shown_location(store: &dyn RecoveryStore) -> Value { + let location = store.location(); + if store.in_folder() && crate::file_access::check_read(&location).is_err() { + return Value::Null; + } + json!(location) +} + fn read_meta(store: &dyn RecoveryStore, file: &str) -> Meta { store.read(&format!("{file}{META_EXT}")).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default() } @@ -682,12 +976,16 @@ pub struct RecoveryJob { pub title: String, meta: Meta, save: SaveJob, + /// The store the copy goes to (the preference can name another folder before it is finished). + store: Arc<dyn RecoveryStore>, } impl RecoveryJob { /// Encode the snapshot and store it with its details and the images the area doesn't have - /// yet → `{file, title, bytes (the document's), imageBytes (images written now)}`. - pub fn write(&self, store: &dyn RecoveryStore) -> std::result::Result<Value, String> { + /// yet, in the store the job was made for → `{file, title, bytes (the document's), imageBytes + /// (images written now)}`. + pub fn write(&self) -> std::result::Result<Value, String> { + let store = self.store.as_ref(); let doc = self.save.doc(); // A linked image keeps its preview, as a save writes it. let linked = doc.linked_only_images(); @@ -740,13 +1038,36 @@ impl RecoveryJob { /// Once stored: the document (if still open) remembers the copy, so it isn't written again /// while unchanged and goes when the document is saved or closed. A document saved or closed - /// meanwhile has nothing left to recover: its copy goes at once. + /// meanwhile has nothing left to recover: its copy goes at once. So does a copy written in an + /// area the session left meanwhile (`keep_hold`), and its document gets a new one. pub fn finish(self, s: &mut Session) { let snapshot = self.save.snapshot().clone(); let copy = RecoveryCopy { file: self.file.clone(), doc: snapshot }; + let area = self.file.split_once('/').map(|(a, _)| a); + let current = s.recovery.own.as_ref().is_some_and(|o| o.store.location() == self.store.location() && Some(o.area.as_str()) == area); match s.document_mut(self.uid).filter(|st| st.is_dirty()) { - Some(st) => st.recovery = Some(copy), - None => remove_copy(s, &self.file), + Some(st) if current => { + st.recovery = Some(copy); + drop_left(s, self.uid); + } + // Written in an area left meanwhile: kept, in place of the copy left there before, + // until the document has a copy in the new area. + Some(st) if st.recovery.is_none() => { + let before = s.recovery.left.insert(self.uid, (self.store.clone(), self.file.clone())); + // The copy left there before, unless this one was written over it. Best effort, + // as in `remove_copy`. + if let Some((store, file)) = before.filter(|(old, f)| old.location() != self.store.location() || *f != self.file) { + let _ = store.remove(&format!("{file}{DOC_EXT}")); + let _ = store.remove(&format!("{file}{META_EXT}")); + } + mark_left(s); + } + // Best effort, as in `remove_copy`. + _ => { + let _ = self.store.remove(&format!("{}{DOC_EXT}", self.file)); + let _ = self.store.remove(&format!("{}{META_EXT}", self.file)); + drop_left(s, self.uid); + } } } } @@ -799,6 +1120,11 @@ fn fresh_name(area: &str, stem: &str, taken: &[String]) -> String { /// when it has none and a copy is needed) → (jobs, skipped: `[{title, reason}]` for modified /// documents that get none). pub fn jobs(s: &mut Session, store: &Arc<dyn RecoveryStore>) -> Result<(Vec<RecoveryJob>, Vec<Value>)> { + // A lost lock is taken again first: copies that go with it are written again, even of + // documents unchanged since. + if s.recovery.own.as_ref().is_some_and(|o| o.store.location() == store.location()) { + keep_hold(s); + } // Copies another app removed are written again. repair(s); let skipped: Vec<Value> = s @@ -837,6 +1163,7 @@ pub fn jobs(s: &mut Session, store: &Arc<dyn RecoveryStore>) -> Result<(Vec<Reco folder: None, modified: None, notes: Vec::new(), + lossy_source: None, }; let save = fileio::job_for(s, st, plan)?; let meta = Meta { @@ -855,7 +1182,7 @@ pub fn jobs(s: &mut Session, store: &Arc<dyn RecoveryStore>) -> Result<(Vec<Reco // Filled in as the copy is written. images: BTreeMap::new(), }; - out.push(RecoveryJob { uid: st.uid, file, title, meta, save }); + out.push(RecoveryJob { uid: st.uid, file, title, meta, save, store: store.clone() }); } Ok((out, skipped)) } @@ -886,7 +1213,7 @@ pub(crate) fn save_copies(s: &mut Session) -> Result<()> { return Err(EngineError::Other("a document with unsaved changes has no recovery copy".into())); } for j in jobs { - j.write(store.as_ref()).map_err(EngineError::Other)?; + j.write().map_err(EngineError::Other)?; j.finish(s); } Ok(()) @@ -898,6 +1225,8 @@ pub fn forget(s: &mut Session, uid: u64) { if s.script_in_run { return; } + // So does a copy of it left in an area this session left. + drop_left(s, uid); let Some(copy) = s.document_mut(uid).and_then(|st| st.recovery.take()) else { return }; remove_copy(s, ©.file); } @@ -907,12 +1236,16 @@ pub fn forget_all(s: &mut Session) { release(s); } -/// The copies of documents with no unsaved changes left (undone back to the saved state) go. +/// The copies of documents with no unsaved changes left (undone back to the saved state) go, and +/// the copies left in an area this session left of documents closed since. pub fn forget_clean(s: &mut Session) { let uids: Vec<u64> = s.documents().iter().filter(|d| !d.is_dirty() && d.recovery.is_some()).map(|d| d.uid).collect(); for uid in uids { forget(s, uid); } + if !s.script_in_run { + drop_left_done(s); + } } fn save(s: &mut Session, _: &Value) -> Result<Value> { @@ -920,12 +1253,12 @@ fn save(s: &mut Session, _: &Value) -> Result<Value> { let (jobs, skipped) = jobs(s, &store)?; let mut saved = vec![]; for j in jobs { - saved.push(j.write(store.as_ref()).map_err(EngineError::Other)?); + saved.push(j.write().map_err(EngineError::Other)?); j.finish(s); } forget_clean(s); heartbeat(s); - Ok(json!({ "saved": saved, "skipped": skipped, "location": store.location() })) + Ok(json!({ "saved": saved, "skipped": skipped, "location": shown_location(store.as_ref()) })) } /// Who an area of the store belongs to. @@ -943,13 +1276,18 @@ enum Owner { /// dropped) and, with `take` in a store without locks, taken over with a fresh heartbeat, so /// another app leaves it alone meanwhile. In a store without locks an area is gone only when /// nothing says its app runs: no announcement (or the store can't tell) and no heartbeat for three -/// intervals but the one this session wrote taking it over. -fn owner(s: &mut Session, store: &dyn RecoveryStore, area: &str, hold: &mut Vec<Hold>, take: bool) -> Owner { +/// intervals but the one this session wrote taking it over. `held` names the gone apps' areas the +/// caller already holds. +fn owner(s: &mut Session, store: &dyn RecoveryStore, area: &str, hold: &mut Vec<Hold>, take: bool, held: &[&str]) -> Owner { if s.recovery.own.as_ref().is_some_and(|o| o.area == area && o.store.location() == store.location()) { return Owner::Mine; } match store.lock(area) { Ok(Lock::Held(h)) => { + // Copies an app left here when it had to leave the area stay its own while it runs. + if let Some(who) = keeper(s, store, area, held) { + return who; + } hold.push(h); Owner::Gone } @@ -958,6 +1296,9 @@ fn owner(s: &mut Session, store: &dyn RecoveryStore, area: &str, hold: &mut Vec< if store.announced(area).unwrap_or(false) || beating(store, area, stale_after(s), s.recovery.adopted.get(area).copied()) { return Owner::Running; } + if let Some(who) = keeper(s, store, area, held) { + return who; + } // Best effort: without it another app might offer the copies too, which loses nothing. if take && let Ok(t) = beat(store, area) { s.recovery.adopted.insert(area.to_string(), t); @@ -967,7 +1308,47 @@ fn owner(s: &mut Session, store: &dyn RecoveryStore, area: &str, hold: &mut Vec< } } -/// Tidy away a gone app's area `area` once no copies are left in it, then let it go (`hold`). +/// Who keeps the copies left in `area` by an app that had to leave it, from the entries +/// `<its area>/keeps-<area>` ([`mark_left`]): this session, or another app that is running. `None`: +/// no app that runs keeps them. An entry counts only in an area this account can lock or tell is +/// held ([`holder`]), so an entry in a folder of another account, or in one whose lock can't be +/// checked, keeps nothing. So does an entry in one of the gone apps' areas the caller holds +/// (`held`), whose lock this session would otherwise find taken. A store that can't be listed now +/// keeps them (a copy kept loses nothing). +fn keeper(s: &Session, store: &dyn RecoveryStore, area: &str, held: &[&str]) -> Option<Owner> { + let Ok(names) = store.list() else { return Some(Owner::Running) }; + let mark = format!("/{KEEPS}{area}"); + let mut who = None; + for k in names.iter().filter_map(|n| n.strip_suffix(mark.as_str())).filter(|k| *k != area && !held.contains(k)) { + match holder(s, store, k) { + Owner::Mine => return Some(Owner::Mine), + Owner::Running => who = Some(Owner::Running), + Owner::Gone => {} + } + } + who +} + +/// Whose area `area` is, without taking it over: this session's, a running app's, or nobody's (a +/// lock taken to tell goes at once). An area whose lock fails (not a recovery area of this +/// account, a lock file that can't be opened) is nobody's. +fn holder(s: &Session, store: &dyn RecoveryStore, area: &str) -> Owner { + if s.recovery.own.as_ref().is_some_and(|o| o.area == area && o.store.location() == store.location()) { + return Owner::Mine; + } + match store.lock(area) { + Ok(Lock::Held(_)) | Err(_) => Owner::Gone, + Ok(Lock::Busy) => Owner::Running, + Ok(Lock::Unsupported) => { + let runs = store.announced(area).unwrap_or(false) || beating(store, area, stale_after(s), s.recovery.adopted.get(area).copied()); + if runs { Owner::Running } else { Owner::Gone } + } + } +} + +/// Tidy away a gone app's area `area` once no copies are left in it, then let it go (`hold`). The +/// area is removed while it is still held, so an app taking a new area of that name meanwhile +/// finds it held or gone and takes the next name. fn tidy(store: &dyn RecoveryStore, area: &str, hold: Vec<Hold>) { let names = store.list().unwrap_or_default(); let mine: Vec<&String> = names.iter().filter(|n| n.split_once('/').is_some_and(|(a, _)| a == area)).collect(); @@ -977,8 +1358,9 @@ fn tidy(store: &dyn RecoveryStore, area: &str, hold: Vec<Hold>) { for n in mine { let _ = store.remove(n); } - drop(hold); store.remove_area(area); + drop(hold); + store.remove_empty_area(area); } /// The copies of documents open now in this session. @@ -986,21 +1368,27 @@ fn open_copies(s: &Session) -> Vec<String> { s.documents().iter().filter_map(|d| d.recovery.as_ref()).map(|c| c.file.clone()).collect() } +/// The copies of documents open now in this session that are in an area it left, in `store`. +fn left_copies(s: &Session, store: &dyn RecoveryStore) -> Vec<String> { + s.recovery.left.values().filter(|(st, _)| st.location() == store.location()).map(|(_, f)| f.clone()).collect() +} + fn list(s: &mut Session, _: &Value) -> Result<Value> { let store = need_store(s, "file.recovery.list")?; let open = open_copies(s); + let left = left_copies(s, store.as_ref()); let copies = copies_in(&store.list().map_err(EngineError::Other)?); let mut rows = vec![]; for area in store.areas().map_err(EngineError::Other)? { let mut hold = vec![]; - let who = owner(s, store.as_ref(), &area, &mut hold, false); + let who = owner(s, store.as_ref(), &area, &mut hold, false, &[]); let files: Vec<&String> = copies.iter().filter(|(a, _)| *a == area).map(|(_, f)| f).collect(); for f in &files { let meta = read_meta(store.as_ref(), f); let title = if meta.title.is_empty() { f.rsplit('/').next().unwrap_or(f).to_string() } else { meta.title }; rows.push(json!({ - "file": f, "title": title, "path": meta.path, "format": meta.format, "saved": meta.saved, - "open": who == Owner::Mine && open.contains(f), "running": who == Owner::Running, + "file": f, "title": title, "path": shown_path(meta.path), "format": meta.format, "saved": meta.saved, + "open": (who == Owner::Mine && open.contains(f)) || left.contains(f), "running": who == Owner::Running, })); } // A gone app's empty area is tidied away. @@ -1008,7 +1396,7 @@ fn list(s: &mut Session, _: &Value) -> Result<Value> { tidy(store.as_ref(), &area, hold); } } - Ok(json!({ "copies": rows, "location": store.location() })) + Ok(json!({ "copies": rows, "location": shown_location(store.as_ref()) })) } /// A gone app's area to act on: its name, the copies to act on, and its lock. @@ -1024,12 +1412,20 @@ fn targets(s: &mut Session, store: &dyn RecoveryStore, cmd: &str, p: &Value) -> { return Err(bad(cmd, format!("no recovery copy `{f}` (see file.recovery.list)"))); } - let picked = |c: &str| file.is_none_or(|f| f == c); + // A copy this session left in an area it had to leave is still its own. + let left = left_copies(s, store); + if let Some(f) = file + && left.iter().any(|c| c == f) + { + return Err(bad(cmd, format!("`{f}` is the copy of a document open now"))); + } + let picked = |c: &str| file.is_none_or(|f| f == c) && !left.iter().any(|l| l == c); let areas: BTreeSet<&str> = copies.iter().filter(|(_, c)| picked(c)).map(|(a, _)| a.as_str()).collect(); - let mut out = vec![]; + let mut out: Vec<Target> = vec![]; for area in areas { let mut hold = vec![]; - match (owner(s, store, area, &mut hold, true), file) { + let held: Vec<&str> = out.iter().map(|(a, _, _)| a.as_str()).collect(); + match (owner(s, store, area, &mut hold, true, &held), file) { (Owner::Gone, _) => { let files = copies.iter().filter(|(a, c)| a == area && picked(c)).map(|(_, c)| c.clone()).collect(); out.push((area.to_string(), files, hold)); @@ -1114,7 +1510,10 @@ fn restore_one(s: &mut Session, store: &Arc<dyn RecoveryStore>, file: &str) -> R // The copy stays until the document is saved or closed. st.recovery = Some(RecoveryCopy { file: mine.clone(), doc: st.doc.clone() }); let title = st.title(); - Ok(super::fileio::merge(json!({ "index": index, "title": title, "file": mine, "path": meta.path, "warnings": warnings }), links.to_json())) + Ok(super::fileio::merge( + json!({ "index": index, "title": title, "file": mine, "path": shown_path(meta.path), "warnings": warnings }), + links.to_json(), + )) } fn restore(s: &mut Session, p: &Value) -> Result<Value> { @@ -1158,7 +1557,7 @@ pub fn specs() -> Vec<CommandSpec> { "Save Recovery Data", [], None, - "{} write a recovery copy of every modified document changed since its last copy, in this app's own area of the store (the app does this every autosaveInterval minutes while autosaveRecovery is on; documents of more than 20000 objects are skipped while recoveryOffForComplex is on). Images are stored apart, each once while unchanged. A copy goes when its document is saved, reverted or closed → {saved: [{file, title, bytes, imageBytes (images written this time)}], skipped: [{title, reason}], location} (location: the recovery folder, or browser storage on the web)", + "{} write a recovery copy of every modified document changed since its last copy, in this app's own area of the store (the app does this every autosaveInterval minutes while autosaveRecovery is on; documents of more than 20000 objects are skipped while recoveryOffForComplex is on). Images are stored apart, each once while unchanged. A copy goes when its document is saved, reverted or closed → {saved: [{file, title, bytes, imageBytes (images written this time)}], skipped: [{title, reason}], location} (location: the recovery folder, or browser storage on the web; null under automation read roots when the folder is outside them)", has_store, save ), @@ -1167,7 +1566,7 @@ pub fn specs() -> Vec<CommandSpec> { "Recovery Data", [], None, - "{} the recovery copies in the store → {copies: [{file (\"<area>/<name>\"), title, path (the document's file, if it had one), format, saved (Unix seconds or null), open (the copy of a document open here), running (kept by another VectorCraft that is running)}], location}; copies neither open nor running were left behind by a crash", + "{} the recovery copies in the store → {copies: [{file (\"<area>/<name>\"), title, path (the document's file, if it had one), format, saved (Unix seconds or null), open (the copy of a document open here), running (kept by another VectorCraft that is running)}], location}; copies neither open nor running were left behind by a crash; under automation read roots, path is null when the document's file is outside them, and location when the recovery folder is", has_store, list ), @@ -1176,7 +1575,7 @@ pub fn specs() -> Vec<CommandSpec> { "Restore Recovered Documents", [], None, - "{file?} open a copy left behind by a crash (default: every one; a running VectorCraft's copies are never taken) as a new document titled \"<name> [Recovered]\": modified, and Save asks where to save it (suggesting its original file) → {restored: [{index, title, file, path, warnings, missingLinks, modifiedLinks, updatedLinks}], failed: [{file, error}] (damaged copies, when restoring every one; a named one fails the command)}. The copy moves to this app's area and stays until the document is saved or closed", + "{file?} open a copy left behind by a crash (default: every one; a running VectorCraft's copies are never taken) as a new document titled \"<name> [Recovered]\": modified, and Save asks where to save it (suggesting its original file) → {restored: [{index, title, file, path, warnings, missingLinks, modifiedLinks, updatedLinks}], failed: [{file, error}] (damaged copies, when restoring every one; a named one fails the command)}; under automation read roots, path is null when the original file is outside them. The copy moves to this app's area and stays until the document is saved or closed", has_store, restore ), diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 6f64528cc0..f5edf1f91d 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> { "Run Script", [], None, - "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file being run (empty for text) and $.includePath the #includepath list; alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine and #engine are refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB, and writing, the file dialogs and execute return false or null with error set. An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file being run (empty for text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB, and writing, the file dialogs and execute return false or null with error set. An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), @@ -45,6 +45,24 @@ pub fn specs() -> Vec<CommandSpec> { always, stop ), + cmd!( + query "script.engines", + "List Script Engines", + [], + None, + "{} the named engines (#targetengine) this session keeps, in the order they were made: a named engine keeps its globals between the runs that name it until it is dropped or the session ends; main, the engine of a script without #targetengine, is new for each run and is not listed; a session keeps at most 8, each with at most 64 MiB of heap (VectorCraft's own limits; none on the web) → {engines: [{name, heapBytes: its heap after its last run, running: a run has it now}], limit: 8, heapLimit: 67108864}", + always, + engines + ), + cmd!( + query "script.engine.drop", + "Drop Script Engine", + [], + None, + "{name: a named engine script.engines lists} drop the engine and the globals its runs left; the next run that names it gets a new one; main, an engine no run made and the engine of the running script are refused → {dropped: true, name}", + always, + engine_drop + ), cmd!( query "script.console", "Script Console", @@ -175,6 +193,22 @@ fn stop(s: &mut Session, _: &Value) -> Result<Value> { Ok(json!({"stopped": s.script_request_stop()})) } +fn engines(s: &mut Session, _: &Value) -> Result<Value> { + let list: Vec<Value> = + s.script_engines().into_iter().map(|(name, heap, running)| json!({"name": name, "heapBytes": heap, "running": running})).collect(); + Ok(json!({"engines": list, "limit": script::MAX_ENGINES, "heapLimit": script::ENGINE_HEAP_BYTES})) +} + +fn engine_drop(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "script.engine.drop"; + let name = match p.get("name") { + Some(Value::String(name)) if !name.is_empty() => name.clone(), + _ => return Err(bad(C, "`name` must be the name of a script engine")), + }; + s.drop_script_engine(&name)?; + Ok(json!({"dropped": true, "name": name})) +} + fn console_lines(s: &mut Session, _: &Value) -> Result<Value> { Ok(s.script_console().to_json()) } @@ -199,6 +233,43 @@ impl Session { self.scripts_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32")) } + /// The last run's report ([`Session::script_report`]) as a reply shows it: under automation read + /// roots, a file the run wrote outside them (`written`) and the file a failed run stopped in + /// (`file`, also in the run's error line in `console`) are named by their file name. What the + /// script wrote itself (`log`, its output lines) stays as written. + pub fn shown_script_report(&self) -> Option<Value> { + let mut report = self.script_report()?.clone(); + if let Some(written) = report.get_mut("written").and_then(Value::as_array_mut) { + for path in written.iter_mut() { + if let Some(name) = path.as_str().and_then(hidden_name) { + *path = json!(name); + } + } + } + if let Some(file) = report.get("file").and_then(Value::as_str).map(str::to_string) + && let Some(name) = hidden_name(&file) + { + // The run's error lines come after every line the script wrote. They are written again + // from the report with the file's name, which also covers a line the console cut inside + // the path. A console that dropped its oldest lines may hold only the last of them. + let before = script::error_lines(&report); + report["file"] = json!(name); + if let Some(message) = report.get("message").and_then(Value::as_str) { + report["message"] = json!(message.replace(&file, &name)); + } + let after = script::error_lines(&report); + if let Some(lines) = report.pointer_mut("/console/lines").and_then(Value::as_array_mut) { + let kept = (1..=before.len().min(lines.len())) + .rev() + .find(|&n| lines.iter().rev().take(n).map(Value::as_str).eq(before.iter().rev().take(n).map(|l| Some(l.as_str())))) + .unwrap_or(0); + lines.truncate(lines.len() - kept); + lines.extend(after.iter().skip(after.len().saturating_sub(kept)).map(|l| json!(l))); + } + } + Some(report) + } + /// The text of the script at `path`, which a listing of the Scripts folder gave /// ([`script::folder::read`]), checked as `script.run` checks a file's. pub fn installed_script(&self, path: &str) -> Result<String> { @@ -214,12 +285,20 @@ impl Session { } } +/// The file name a reply names `path` by when the file is outside the automation read roots; `None` +/// when a reply may name it whole. +fn hidden_name(path: &str) -> Option<String> { + let shown = super::fileio::shown_path(path); + (shown != path).then(|| shown.into_owned()) +} + fn list_installed(s: &mut Session, _: &Value) -> Result<Value> { let Some(root) = s.scripts_dir() else { return Ok(json!({"folder": null, "scripts": [], "truncated": false, "unreadable": false})); }; let folder = root.to_string_lossy(); - crate::file_access::check_read(&folder).map_err(EngineError::Other)?; + // The Scripts folder is the app's: a refusal names it as the request may see it. + crate::file_access::check_read(&folder).map_err(|e| super::fileio::naming_in_error(EngineError::Other(e), &folder))?; let listing = script::folder::list(root); let scripts: Vec<Value> = listing .scripts() diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index aeeac58855..ac9ca365f4 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -11,6 +11,7 @@ use super::object::can_align; use super::wand::{fill_of, stroke_of}; use super::{ CommandSpec, Result, Session, bad, bool_or, checked_id, checked_ids_param, cmd, color_value, has_doc, has_selection, index, ok, str_param, + switch_or, text_param, }; use crate::DocState; @@ -48,6 +49,15 @@ pub fn specs() -> Vec<CommandSpec> { has_doc, set ), + cmd!( + "select.storedPath", + "Select Path", + [], + None, + "{id: object id, fingerprint: text (\"v1:\" and 16 lowercase hex digits)} the Actions panel's Select Path step: select only the path or compound path `id` when its fingerprint (a hash of its kind, fill rule and anchors, its members' for a compound path) is still `fingerprint` and it can be selected: not hidden or locked, nor in a hidden or locked layer or group, a template layer or on a locked artboard, and inside the isolated object in isolation mode. A missing object, another kind of object, a path whose kind, fill rule or anchors changed, or one that cannot be selected is an error, and the selection stays as it was → {count, ids} (the resulting selection)", + has_doc, + stored_path + ), cmd!( "select.add", "Add to Selection", @@ -103,6 +113,15 @@ pub fn specs() -> Vec<CommandSpec> { has_doc, select_color ), + cmd!( + "select.byNote", + "Select by Note", + [], + None, + "{note, caseSensitive?: bool, wholeWord?: bool} select the objects whose Attributes note (attributes.set) holds `note`, without its leading and trailing spaces (1 to 1,024 bytes): anywhere in the note and in any letter case by default; caseSensitive (default false) asks for the same letter case, and wholeWord (default false) for no letter, digit or _ right before or after it. It looks at the objects Select All takes and the objects inside them, leaving out hidden and locked objects and art on a locked artboard; an object whose note matches is selected without the objects inside it. The objects found replace the selection, in paint order. No object found is an error that leaves the selection as it was. Not an undo step; Select > Reselect repeats it. The Actions panel's Select Object step (ui.action.insertSelectObject) runs this → {count, ids} (resulting selection)", + has_doc, + by_note + ), cmd!( "select.same.fillColor", "Fill Color", @@ -184,7 +203,7 @@ pub fn specs() -> Vec<CommandSpec> { "Not Aligned to Pixel Grid", ["Select", "Object"], None, - "{} the paths (not guides) and compound paths whose pixel-aligned property (object.setPixelAligned) is off, looking into groups but not into compound paths → {count}", + "{} the paths (not guides) and compound paths whose pixel-aligned property (object.setPixelAligned) is off, looking into groups, clip groups, blends, envelopes, repeats and Intertwine groups but not into compound paths → {count}", has_doc, not_pixel_aligned ), @@ -439,6 +458,150 @@ fn selection_result(s: &Session) -> Result<Value> { Ok(json!({ "count": selection.len(), "ids": selection.objects })) } +/// The prefix of every fingerprint [`path_fingerprint`] gives: the version of its hash. +const FINGERPRINT_PREFIX: &str = "v1:"; + +/// FNV-1a (64 bits) over the bytes written to it, starting from the offset basis. +pub(crate) struct Fnv(pub(crate) u64); + +impl Default for Fnv { + fn default() -> Self { + Self(0xcbf2_9ce4_8422_2325) + } +} + +impl std::io::Write for Fnv { + fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> { + self.0 = buf.iter().fold(self.0, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x0100_0000_01b3)); + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +/// The fingerprint of the path or compound path `n` that `select.storedPath` compares: FNV-1a (64 +/// bits) over a kind byte, the fill rule and the anchors of the path, or of each member of the +/// compound path in order, as JSON, written as [`FINGERPRINT_PREFIX`] and 16 lowercase hex digits. +/// None for any object [`is_storable_kind`] does not take. +pub fn path_fingerprint(n: &Node) -> Option<String> { + fn feed(h: &mut Fnv, n: &Node) -> Option<()> { + use std::io::Write; + match &n.kind { + NodeKind::Path { path, rule, .. } => { + h.write_all(b"P").ok()?; + serde_json::to_writer(&mut *h, rule).ok()?; + serde_json::to_writer(&mut *h, path).ok() + } + NodeKind::Compound { children, rule } => { + h.write_all(b"C").ok()?; + serde_json::to_writer(&mut *h, rule).ok()?; + h.write_all(&(children.len() as u64).to_le_bytes()).ok()?; + children.iter().try_for_each(|c| feed(h, c)) + } + _ => None, + } + } + if !is_storable_kind(n) { + return None; + } + let mut h = Fnv::default(); + feed(&mut h, n)?; + Some(format!("{FINGERPRINT_PREFIX}{:016x}", h.0)) +} + +/// Whether `n` is an object a Select Path step can store: a path that is not a guide, or a compound +/// path whose members all are. +fn is_storable_kind(n: &Node) -> bool { + let path = |n: &Node| matches!(n.kind, NodeKind::Path { guide: false, .. }); + match &n.kind { + NodeKind::Compound { children, .. } => children.iter().all(|c| path(c)), + _ => path(n), + } +} + +/// The `id` and `fingerprint` of `select.storedPath`'s params `p`, or why they are not ones: an +/// object with only a non-negative whole `id` and a `fingerprint` that [`path_fingerprint`] could give. +pub fn stored_path_params(p: &Value) -> std::result::Result<(NodeId, &str), String> { + let o = p.as_object().ok_or("`params` must be an object")?; + if let Some(key) = o.keys().find(|k| !matches!(k.as_str(), "id" | "fingerprint")) { + let keys = "id, fingerprint"; + return Err(format!("unknown parameter `{key}`; the command takes: {keys}")); + } + let value = o.get("id").unwrap_or(&Value::Null); + let id = value.as_u64().map(NodeId).ok_or_else(|| format!("invalid object id {value}: expected a non-negative integer"))?; + let fingerprint = o.get("fingerprint").and_then(Value::as_str).unwrap_or_default(); + let hex = fingerprint.strip_prefix(FINGERPRINT_PREFIX).unwrap_or_default(); + if hex.len() != 16 || !hex.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) { + return Err("`fingerprint` must be \"v1:\" and 16 lowercase hex digits".into()); + } + Ok((id, fingerprint)) +} + +/// Why the object `id` of `st` cannot be the path of a Select Path step: it is not there, is not a +/// path (not a guide) or compound path ([`is_storable_kind`]), is a member of a compound path, cannot +/// be selected ([`is_selectable`]), or is on a locked artboard, in isolation mode too. +fn storable_path(st: &DocState, id: NodeId) -> std::result::Result<(), String> { + let value = id.0; + let n = st.doc.node(id).ok_or_else(|| format!("no such object id {value}"))?; + let in_compound = st.doc.parent_of(id).and_then(|p| st.doc.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Compound { .. })); + if !is_storable_kind(n) || in_compound { + return Err(WHOLE_PATH.into()); + } + // In isolation mode `is_selectable` does not look at the locked artboards, so they are checked here too. + let locks = st.doc.locked_artboards(); + if !is_selectable(&st.doc, st.isolation, &locks, id) || locks.holds_id(id) { + return Err("the path is hidden or locked, or cannot be selected here".into()); + } + Ok(()) +} + +/// What [`storable_selection`] asks for when the selection is not a whole path or compound path. +const WHOLE_PATH: &str = "select one whole path or compound path"; + +/// The one object selected in `st` when it can be the path of a Select Path step: a whole path or +/// compound path that can be selected ([`storable_path`]). An error for no selection, several +/// objects, a path with ruler guides, anchors or segments of a path alone, a group, type or any other object, a guide, or a +/// member of a compound path. It does not hash the path, so menus can ask it every frame. +pub fn storable_selection(st: &DocState) -> std::result::Result<NodeId, String> { + let sel = &st.selection; + let id = match sel.objects.as_slice() { + [] => return Err("select a path".into()), + [id] if sel.guides.is_empty() => *id, + _ => return Err("select only one path".into()), + }; + if sel.anchors.get(&id).is_some_and(|a| !a.is_empty()) || sel.segments.get(&id).is_some_and(|s| !s.is_empty()) { + return Err(WHOLE_PATH.into()); + } + storable_path(st, id)?; + Ok(id) +} + +/// The params of a `select.storedPath` step for the path selected in `st` ([`storable_selection`]): +/// `{id, fingerprint}`. +pub fn stored_path_step(st: &DocState) -> std::result::Result<Value, String> { + let id = storable_selection(st)?; + let fingerprint = st.doc.node(id).and_then(path_fingerprint).ok_or(WHOLE_PATH)?; + Ok(json!({ "id": id.0, "fingerprint": fingerprint })) +} + +/// `select.storedPath {id, fingerprint}`: selects only the path `id` when it is still the path the +/// step stored ([`path_fingerprint`]) and can be selected ([`storable_path`]); else an error, and +/// the selection stays as it was. +fn stored_path(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "select.storedPath"; + let (id, fingerprint) = stored_path_params(p).map_err(|e| bad(C, e))?; + let st = s.doc()?; + let value = id.0; + let n = st.doc.node(id).ok_or_else(|| bad(C, format!("no such object id {value}")))?; + if path_fingerprint(n).as_deref() != Some(fingerprint) { + return Err(bad(C, format!("object {value} is not the stored path: it changed, or the document is another one"))); + } + storable_path(st, id).map_err(|e| bad(C, e))?; + s.select(|_, sel| sel.set([id]))?; + selection_result(s) +} + fn key(s: &mut Session, p: &Value) -> Result<Value> { let id = p.get("id").map(|value| checked_id(s, value, "select.key")).transpose()?; let guide = match p.get("guide").filter(|v| !v.is_null()) { @@ -730,6 +893,124 @@ fn select_color(s: &mut Session, p: &Value) -> Result<Value> { select_where(s, C, p, |d, n| paint_reported(d, n) && reads_as(fill_of(n), fill.as_deref()) && reads_as(stroke_of(n).0, stroke.as_deref())) } +/// The longest note, in bytes, that Select by Note searches for. +const MAX_NOTE_QUERY: usize = 1024; + +/// Select by Note: the objects whose Attributes note holds `note` ([`note_matches`]). An object +/// whose note matches is selected without the objects inside it. With none found, the selection +/// stays as it was. +fn by_note(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "select.byNote"; + let query = text_param(p, "note", C)?.map(str::trim).unwrap_or_default(); + if query.is_empty() { + return Err(bad(C, "the note is empty")); + } + if query.len() > MAX_NOTE_QUERY { + return Err(bad(C, "the note is longer than 1,024 bytes")); + } + let case_sensitive = switch_or(p, "caseSensitive", false, C)?; + let whole_word = switch_or(p, "wholeWord", false, C)?; + let not_found = || bad(C, format!("no object that can be selected has a note matching “{query}”")); + let st = s.doc()?; + let locks = st.doc.locked_artboards(); + let mut ids = vec![]; + walk_selectable(&st.doc, st.isolation, |n| { + let note = n.extras().attrs.as_deref().map_or("", |a| a.note.as_str()); + if note_matches(note, query, case_sensitive, whole_word) && is_selectable(&st.doc, st.isolation, &locks, n.id) { + ids.push(n.id); + return false; + } + true + }); + // The selection leaves out guides under Lock Guides and hidden slices, whatever selects them. + let mut found = st.selection.clone(); + found.set(ids.iter().copied()); + crate::deselect_hidden(&s.menu, &st.doc, &mut found); + if found.objects.is_empty() { + return Err(not_found()); + } + let before = st.selection.objects.clone(); + s.select(|_, sel| sel.set(ids.iter().copied()))?; + let st = s.doc_mut()?; + st.last_selection_cmd = Some((C.to_string(), p.clone(), before)); + selection_result(s) +} + +/// Whether `note` holds `query`: anywhere, and in any letter case unless `case_sensitive`. With +/// `whole_word`, the match starts and ends on whole characters of `note`, and the characters of +/// `note` right before and right after it are not a letter, a digit or `_`. +/// +/// Letter case is compared one character at a time ([`fold_case`]), so a final Σ still matches σ, +/// and each folded character keeps the byte offset of the character of `note` it comes from. +fn note_matches(note: &str, query: &str, case_sensitive: bool, whole_word: bool) -> bool { + if note.is_empty() || query.is_empty() { + return false; + } + let fold = |text: &str| -> Vec<(char, usize)> { + let mut out = Vec::with_capacity(text.len()); + for (at, c) in text.char_indices() { + if case_sensitive { + out.push((c, at)); + } else { + out.extend(fold_case(c).map(|f| (f, at))); + } + } + out + }; + let folded = fold(note); + let query: Vec<char> = fold(query).into_iter().map(|(c, _)| c).collect(); + let word = |c: char| c.is_alphanumeric() || c == '_'; + // Whether the match of `query` that starts at `folded[i]` counts. + let accept = |i: usize| { + if !whole_word { + return true; + } + let (start, last) = (folded[i].1, folded[i + query.len() - 1].1); + let starts_whole = i == 0 || folded[i - 1].1 != start; + let ends_whole = folded.get(i + query.len()).is_none_or(|(_, at)| *at != last); + if !starts_whole || !ends_whole { + return false; + } + let end = last + note[last..].chars().next().map_or(0, char::len_utf8); + !note[..start].chars().next_back().is_some_and(word) && !note[end..].chars().next().is_some_and(word) + }; + // Knuth-Morris-Pratt, so a long note takes time in proportion to its length, and every place + // the query occurs is tried, also places that overlap. `fail[k]` is the length of the longest + // proper prefix of `query[..=k]` that is also its suffix. + let mut fail = vec![0; query.len()]; + let mut k = 0; + for i in 1..query.len() { + while k > 0 && query[i] != query[k] { + k = fail[k - 1]; + } + if query[i] == query[k] { + k += 1; + } + fail[i] = k; + } + let mut k = 0; + for (j, (c, _)) in folded.iter().enumerate() { + while k > 0 && *c != query[k] { + k = fail[k - 1]; + } + if *c == query[k] { + k += 1; + } + if k == query.len() { + if accept(j + 1 - k) { + return true; + } + k = fail[k - 1]; + } + } + false +} + +/// `c` in lowercase for a comparison that ignores letter case, with the final sigma ς read as σ. +fn fold_case(c: char) -> impl Iterator<Item = char> { + c.to_lowercase().map(|l| if l == 'ς' { 'σ' } else { l }) +} + /// Does `document.inspect` report a fill and stroke for `n`? A compound path's are its own, though /// it holds its members, and its members report none. fn paint_reported(d: &Document, n: &Node) -> bool { diff --git a/crates/engine/src/cmd/shaper.rs b/crates/engine/src/cmd/shaper.rs index 44ec938bc2..228251fa13 100644 --- a/crates/engine/src/cmd/shaper.rs +++ b/crates/engine/src/cmd/shaper.rs @@ -2,7 +2,9 @@ //! art retained underneath. Recipes select topology regions; source edits re-evaluate them in //! the same undo transaction. Rendering and exporters only see ordinary groups and paths. use super::pathops::Beside; -use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_param, cmd, f64_or, has_doc, id_param, object_param, point_param}; +use super::{ + CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_param, cmd, f64_or, has_doc, id_param, number_or, object_param, point_param, +}; use serde_json::{Value, json}; use std::{ collections::{BTreeMap, HashMap}, @@ -34,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> { "Select Shaper Face", [], None, - "{point: [x,y], source?: bool} click selects a group, then a face; source enters construction isolation and selects an original (while an opacity mask or a pattern is edited, it selects the original and the editing layer stays isolated); while a group's originals are isolated, it selects one of that group's originals → {id}", + "{point: [x,y], source?: bool, tolerance?: pt (3)} click selects a group, then a face; with the group or one of its faces selected, a click within tolerance of an original shape's outline enters construction isolation and selects that original; source enters construction isolation and selects an original (while an opacity mask or a pattern is edited, it selects the original and the editing layer stays isolated); while a group's originals are isolated, it selects one of that group's originals → {id}", has_doc, select ), @@ -734,16 +736,50 @@ fn group_at(d: &Document, point: Point, construction: bool, within: Option<NodeI }); groups.last().copied() } +/// The topmost editable Shaper Group that is selected, or has a face selected, with a visible, +/// unlocked original shape whose outline lies within `tolerance` of `point`, and the topmost such +/// shape in it; `None` when a Shaper Group that [`group_at`] finds at `point` lies above it. +fn outline_at(d: &Document, selection: &vectorcraft_doc::Selection, point: Point, tolerance: f64) -> Option<(NodeId, NodeId)> { + let mut hit = None; + let editable = d.editable(); + d.walk(|n| { + if n.extras().shaper.is_none() || !editable(n.id) { + return; + } + let picked = selection.contains(n.id) || selection.objects.iter().any(|id| d.parent_of(*id) == Some(n.id)); + let on_outline = + |s: &&Arc<Node>| b::node_outline(s).is_some_and(|(path, _)| path.nearest(point).is_some_and(|(_, _, _, _, dist)| dist <= tolerance)); + let source = if picked { sources(n).iter().rev().filter(|s| s.visible && !s.locked).find(on_outline).map(|s| s.id) } else { None }; + if let Some(source) = source { + hit = Some((n.id, source)); + } else if n.geometric_bounds().is_some_and(|b| b.inflate(6.0, 6.0).contains(point)) { + hit = None; + } + }); + hit +} fn select(s: &mut Session, p: &Value) -> Result<Value> { let point = point_param(p, "point").filter(|p| finite(*p)).ok_or_else(|| bad("shaper.select", "missing point"))?; let st = s.doc()?; let source = bool_or(p, "source", false); + let tolerance = number_or(p, "tolerance", 3.0, "shaper.select")?; + if !tolerance.is_finite() || !(0.0..=1000.0).contains(&tolerance) { + return Err(bad("shaper.select", "invalid tolerance")); + } // In Construction mode a source pick stays in the group whose source shapes are isolated. let isolated = st.isolation.and_then(|i| st.doc.parent_of(i)).filter(|g| st.doc.node(*g).and_then(source_group).is_some_and(|s| st.isolation == Some(s.id))); - let Some(group) = group_at(&st.doc, point, source, isolated.filter(|_| source)) else { return Ok(json!({"id": null})) }; + // With a group or one of its faces selected, a click on one of its original shapes' outlines + // enters Construction mode with the topmost such shape selected, wherever the outline lies. + let outline = if source { None } else { outline_at(&st.doc, &st.selection, point, tolerance) }; + let Some(group) = outline.map(|(g, _)| g).or_else(|| group_at(&st.doc, point, source, isolated.filter(|_| source))) else { + return Ok(json!({"id": null})); + }; let node = st.doc.node(group).ok_or(EngineError::NoNode(group))?; - let target = if source { + let source = source || outline.is_some(); + let target = if let Some((_, id)) = outline { + id + } else if source { sources(node) .iter() .rev() diff --git a/crates/engine/src/cmd/slices.rs b/crates/engine/src/cmd/slices.rs index 06ec067934..746be9c244 100644 --- a/crates/engine/src/cmd/slices.rs +++ b/crates/engine/src/cmd/slices.rs @@ -13,7 +13,7 @@ use vectorcraft_doc::{Appearance, CellAlign, CellVAlign, Document, Node, NodeKin use vectorcraft_geom::{Rect, shapes}; use super::{ - CommandSpec, EngineError, NodeId, Result, Session, bad, bool_or, cmd, f64_or, f64_req, has_doc, has_selection, id_param, ids_param, index, + CommandSpec, EngineError, NodeId, Result, Session, bad, cmd, f64_req, has_doc, has_selection, ids_param, index, number_or, object_param, switch_or, targets, }; @@ -380,7 +380,8 @@ fn from_selection(s: &mut Session, p: &Value) -> Result<Value> { fn duplicate(s: &mut Session, p: &Value) -> Result<Value> { let targets = selected(s)?; - let (dx, dy) = (f64_or(p, "dx", 10.0), f64_or(p, "dy", 10.0)); + let dx = number_or(p, "dx", 10.0, "object.slice.duplicate")?; + let dy = number_or(p, "dy", 10.0, "object.slice.duplicate")?; let ids = s.edit("Duplicate Slice", |d, sel| { let mut out = vec![]; for id in &targets { @@ -679,7 +680,7 @@ fn create(s: &mut Session, p: &Value) -> Result<Value> { fn set_rect(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "object.slice.setRect"; - let id = id_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?; let r = rect_param(p, C)?; let d = &s.doc()?.doc; if d.slice(id).is_none() { @@ -737,7 +738,7 @@ fn delete(s: &mut Session, p: &Value) -> Result<Value> { fn select(s: &mut Session, p: &Value) -> Result<Value> { let slices = p.get("slices").filter(|v| !v.is_null()).cloned().unwrap_or(json!([])); let ids = slice_targets(s, &json!({ "slices": slices }), "object.slice.select")?; - let toggle = bool_or(p, "toggle", false); + let toggle = switch_or(p, "toggle", false, "object.slice.select")?; s.select(|_, sel| { let mut now = if toggle { sel.slices.clone() } else { vec![] }; for id in ids { diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index e97659bfc9..fe846ad8af 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -4,8 +4,10 @@ use serde_json::{Value, json}; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{ - ArrowAlign, Arrowhead, CharStyle, Dash, LineCap, LineJoin, Node, NodeKind, SavedProfile, Scaling, StrokeAlign, StrokeLayer, Unit, WidthProfile, + ArrowAlign, Arrowhead, CharStyle, CustomArrowhead, Dash, LineCap, LineJoin, Node, NodeKind, SavedProfile, Scaling, StrokeAlign, StrokeLayer, + Unit, WidthProfile, }; +use vectorcraft_geom::PathData; use super::appearance::{ItemTarget, edit_items, item_target}; use super::paint::painted; @@ -20,7 +22,7 @@ pub fn specs() -> Vec<CommandSpec> { "Stroke Options", ["Window", "Stroke"], None, - "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does) → {objects: how many objects took the stroke options}", + "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path}} (a custom head with its art, as document.inspect reports one; refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does) → {objects: how many objects took the stroke options}", has_doc, stroke_set ), @@ -206,11 +208,31 @@ fn no_targets(ids: &[vectorcraft_doc::NodeId], p: &Value) -> bool { ids.is_empty() && p.get("ids").is_none() && p.get("id").is_none() } +/// The objects `stroke.set` edits with no `item`: a selected group or layer with a stroke row of +/// its own edits that row, as the Stroke panel does with the group targeted (#6739); the other +/// targets reach their painted leaves, as before. +fn own_stroke_or_leaves(s: &Session, p: &Value) -> Result<Vec<vectorcraft_doc::NodeId>> { + let picked = super::targets(s, p)?; + let d = &s.doc()?.doc; + let own = |id: &vectorcraft_doc::NodeId| { + d.node(*id).is_some_and(|n| { + matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && !n.is_compound_shape() && n.appearance.stroke().is_some() + }) + }; + let (mut out, rest): (Vec<_>, Vec<_>) = picked.into_iter().partition(own); + for id in super::leaf_targets(s, &rest)? { + if !out.contains(&id) { + out.push(id); + } + } + Ok(out) +} + fn stroke_set(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "stroke.set"; let change = StrokeChange::parse(p, C)?; let item = item_target(s, p, C)?.of_kind(s, false); - let mut ids = item.targets(s, p)?; + let mut ids = if item == ItemTarget::Top { own_stroke_or_leaves(s, p)? } else { item.targets(s, p)? }; let new_art = no_targets(&ids, p); if item == ItemTarget::Top { // Images and symbol instances take no stroke from the panel. @@ -222,6 +244,34 @@ fn stroke_set(s: &mut Session, p: &Value) -> Result<Value> { None => Ok(None), Some(Value::Null) => Ok(Some(None)), Some(Value::String(n)) if n == "none" => Ok(Some(None)), + // A custom head by name, from the arrowheads file (stroke.arrowheads.list). + Some(Value::Object(o)) if o.len() == 1 && o.contains_key("custom") => { + let Some(Value::String(name)) = o.get("custom") else { return Err(bad(C, format!("{k}: custom must be a name"))) }; + let head = s.arrowheads.get(name).ok_or_else(|| bad(C, format!("no custom arrowhead {name} (see stroke.arrowheads.list)")))?; + Ok(Some(Some(Arrowhead::Custom(head)))) + } + // A custom head with its art: an outline the head would drop is refused, not drawn empty. + Some(Value::Object(o)) if o.contains_key("Custom") => { + let raw = o.get("Custom").and_then(|c| c.get("path")).cloned().unwrap_or(Value::Null); + let path: PathData = serde_json::from_value(raw).map_err(|e| bad(C, format!("{k}: bad custom arrowhead path: {e}")))?; + // The region the outline fills (non-zero rule), down to slivers a millionth of a + // head unit thin. Measured only once `fits` has bounded the anchors. + let fills = |p: &PathData| { + let area = vectorcraft_pathops::unite_all_with(&[(p, vectorcraft_geom::FillRule::NonZero)], 1e-6); + area.subpaths.iter().map(|sp| sp.area().abs()).sum::<f64>() > 1e-12 + }; + if !CustomArrowhead::fits(&path) || !fills(&path) { + let (most, far) = (CustomArrowhead::MAX_ANCHORS, CustomArrowhead::MAX_UNITS); + return Err(bad( + C, + format!( + "{k}: a custom arrowhead's path needs an area to fill and at most {most} anchors and {most} subpaths, each anchor within {far} head units of its tip" + ), + )); + } + let head = p.get(k).cloned().unwrap_or(Value::Null); + serde_json::from_value::<Arrowhead>(head).map(|a| Some(Some(a))).map_err(|e| bad(C, format!("{k}: bad custom arrowhead: {e}"))) + } Some(v) => serde_json::from_value::<Arrowhead>(v.clone()).map(|a| Some(Some(a))).map_err(|_| bad(C, format!("unknown arrowhead {v}"))), } }; @@ -238,11 +288,11 @@ fn stroke_set(s: &mut Session, p: &Value) -> Result<Value> { }; let set = |st: &mut StrokeLayer| { change.apply(st); - if let Some(a) = sa { - st.start_arrow = a; + if let Some(a) = &sa { + st.start_arrow = a.clone(); } - if let Some(a) = ea { - st.end_arrow = a; + if let Some(a) = &ea { + st.end_arrow = a.clone(); } if let Some(a) = arrow_align { st.arrow_align = a; @@ -261,7 +311,11 @@ fn stroke_set(s: &mut Session, p: &Value) -> Result<Value> { return Ok(()); } if index.is_none() && n.appearance.stroke().is_none() { - n.appearance.set_stroke(Paint::solid(Color::BLACK)); + // Options alone (cap, join, miter limit, dashes, alignment) don't make a stroke + // visible: the row made for them has no paint. A weight, an arrowhead or a profile + // still gives the object the black stroke the panel draws (#6739). + let visible = change.weight.is_some() || sa.is_some() || ea.is_some() || profile.is_some(); + n.appearance.set_stroke(if visible { Paint::solid(Color::BLACK) } else { Paint::None }); } if let Some(st) = n.appearance.stroke_at_mut(index) { set(st); diff --git a/crates/engine/src/cmd/style.rs b/crates/engine/src/cmd/style.rs index d31031d5d4..65fe18b282 100644 --- a/crates/engine/src/cmd/style.rs +++ b/crates/engine/src/cmd/style.rs @@ -13,11 +13,12 @@ //! to loses its characters' own fill (stroke) when the style has fills (strokes), so the style's //! paint shows instead of the character colour under it. -use std::collections::HashMap; +use std::borrow::Cow; +use std::collections::{HashMap, HashSet}; use serde_json::{Value, json}; use vectorcraft_color::Paint; -use vectorcraft_doc::{Appearance, DEFAULT_GRAPHIC_STYLE, Document, GraphicStyle, Node, NodeId, NodeKind}; +use vectorcraft_doc::{Appearance, DEFAULT_GRAPHIC_STYLE, Document, GraphicStyle, Node, NodeId, NodeKind, Shared}; use vectorcraft_geom::Rect; use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, index, object_param, ok, str_param, unique_name}; @@ -30,7 +31,7 @@ pub fn specs() -> Vec<CommandSpec> { "Apply Graphic Style", ["Window", "Graphic Styles"], None, - "{name, add?: bool, ids?|id? (layers too), target?: \"object\"|\"contents\"} give the objects (default: the selection; a group or layer itself, its fills and strokes painting its members and its effects applying to them as one piece; target contents: the objects inside instead) the style's appearance, opacity, blend mode, isolate and knockout, and link them to it (placed gradients land at the same place relative to each object's bounds); add: true (Alt-click) adds its fills, strokes and effects on top of the existing appearance instead and unlinks. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (with `add`: of the kinds of row the style shows) and, without `add`, the object's opacity and blend mode (exceptions: docs/mcp.md). With nothing selected (and no ids) the next object drawn takes the style instead (see appearance.newArt) → {newArt: true}", + "{name, add?: bool, ids?|id? (layers too), target?: \"object\"|\"contents\"} give the objects (default: the selection; a group or layer itself, its fills and strokes painting its members and its effects applying to them as one piece; target contents: the objects inside instead) the style's appearance, opacity, blend mode, isolate and knockout, and link them to it (placed gradients land at the same place relative to each object's bounds); add: true (Alt-click) adds its fills, strokes and effects on top of the existing appearance instead and unlinks. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (with `add`: of the kinds of row the style shows) and, without `add`, the object's opacity and blend mode (exceptions: docs/mcp.md). With nothing selected (and no ids) the next object drawn takes the style instead (see appearance.newArt) → {newArt: true}", has_doc, style_apply ), @@ -39,7 +40,7 @@ pub fn specs() -> Vec<CommandSpec> { "New Graphic Style", ["Window", "Graphic Styles"], None, - "{name?, id?} a style from object `id` or the first selected object: its appearance, opacity, blend mode, isolate and knockout (a group without fills or strokes of its own lends its topmost object's, type its characters'; placed gradients are kept relative to its bounds); links the object. Names are made unique → {name}", + "{name?, id?} a style from object `id` or the first selected object: its appearance, opacity, blend mode, isolate and knockout (a group without fills or strokes of its own lends its topmost object's, type its characters'; a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own stands for the topmost path directly in it; placed gradients are kept relative to its bounds); links the object. Names are made unique → {name}", has_doc, style_new ), @@ -67,7 +68,7 @@ pub fn specs() -> Vec<CommandSpec> { "Redefine Graphic Style", ["Window", "Appearance"], None, - "{name?, id?} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object; the objects still linked to it update, and that object becomes linked. On a linked path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md) → {name}", + "{name?, id?} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object (a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own: the topmost path directly in it); the objects still linked to it update, and that object becomes linked. A linked graph series group passes the style to the paths directly in it, other than the source and paths linked to the style whose look was edited, and is left cleared (as appearance.clear) and unlinked. On a linked path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md) → {name}", has_doc, style_redefine ), @@ -76,7 +77,7 @@ pub fn specs() -> Vec<CommandSpec> { "Break Link to Graphic Style", ["Window", "Graphic Styles"], None, - "{ids?|id?, target?: \"object\"|\"contents\"} unlink the objects (default: the selection) from their graphic style; they keep their look", + "{ids?|id?, target?: \"object\"|\"contents\"} unlink the objects (default: the selection) from their graphic style; they keep their look. A graph series group's id stands for the group and the paths directly in it", has_doc, style_break_link ), @@ -260,9 +261,14 @@ fn override_chars(n: &mut Node, ap: &Appearance) { } /// Give `n` style `g`: its appearance (a group or layer too: its own, above its contents; type its -/// characters' colour too with `chars`, Override Character Color) and transparency. -fn style_node(n: &mut Node, g: &GraphicStyle, chars: bool) { - n.appearance = g.appearance_on(n).into_owned().into(); +/// characters' colour too with `chars`, Override Character Color) and transparency. Objects that +/// take `g`'s appearance as it is share one copy of it, made in `shared` the first time; an object +/// whose placed gradients land on its own bounds gets its own. +fn style_node(n: &mut Node, g: &GraphicStyle, shared: &mut Option<Shared<Appearance>>, chars: bool) { + n.appearance = match g.appearance_on(n) { + Cow::Borrowed(ap) => shared.get_or_insert_with(|| Shared::new(ap.clone())).clone(), + Cow::Owned(ap) => ap.into(), + }; if chars { override_chars(n, &g.appearance); } @@ -270,9 +276,9 @@ fn style_node(n: &mut Node, g: &GraphicStyle, chars: bool) { } /// Give `id` style `g` ([`style_node`]) and link it. -fn apply_style(d: &mut Document, id: NodeId, g: &GraphicStyle, chars: bool) { +fn apply_style(d: &mut Document, id: NodeId, g: &GraphicStyle, shared: &mut Option<Shared<Appearance>>, chars: bool) { if let Some(n) = d.node_mut(id) { - style_node(n, g, chars); + style_node(n, g, shared, chars); n.extras_mut().graphic_style = Some(g.id); super::object::snap_if_aligned(n); } @@ -301,10 +307,11 @@ fn source<'a>(s: &'a Session, p: &Value, cmd: &str) -> Result<(NodeId, &'a Node) impl Session { /// The graphic style of the first selected object: the one it was last linked to, and whether - /// it is still linked (still has that style's look). + /// it is still linked (still has that style's look). A graph series group that holds nothing of its own stands + /// for the topmost path directly inside it, which a style applied to the group links. pub fn selection_graphic_style(&self) -> Option<(&GraphicStyle, bool)> { let st = self.active()?; - let n = st.doc.node(*st.selection.subjects().first()?)?; + let n = super::appearance::look_holder(&st.doc, st.doc.node(*st.selection.subjects().first()?)?); let g = st.doc.graphic_style_by_id(n.extras().graphic_style?)?; Some((g, in_sync(n, g))) } @@ -313,7 +320,7 @@ impl Session { /// Color as set): the Graphic Styles panel's previews. pub fn styled(&self, n: &Node, g: &GraphicStyle) -> Node { let mut n = n.clone(); - style_node(&mut n, g, self.prefs.override_char_color); + style_node(&mut n, g, &mut None, self.prefs.override_char_color); n } } @@ -325,7 +332,11 @@ fn style_apply(s: &mut Session, p: &Value) -> Result<Value> { let i = style_index(&s.doc()?.doc, name)?; let add = bool_or(p, "add", false); let chars = s.prefs.override_char_color; - let ids = super::appearance::appearance_targets(s, p)?; + let own = super::appearance::appearance_targets(s, p)?; + let ids = super::appearance::rowless_series_marks(&s.doc()?.doc, &own); + // The series groups their paths stand for: a style that replaces the appearance clears what they hold themselves, + // and a style added on top unlinks them. + let groups = super::appearance::stood_for(&own, &ids); if ids.is_empty() { if p.get("ids").is_some() || p.get("id").is_some() { return Err(bad("graphicStyle.apply", "no such objects")); @@ -347,6 +358,8 @@ fn style_apply(s: &mut Session, p: &Value) -> Result<Value> { n.extras_mut().graphic_style = None; } } + // The series groups their paths stand for are unlinked with them. + set_link(d, &groups, None); // The graph stores the rows of the kinds the style shows, now on top of each stack. let shows = |kind: bool| g.appearance.items.iter().any(|it| it.is_fill() == kind && it.visible()); let kinds = (shows(true), shows(false)); @@ -354,9 +367,11 @@ fn style_apply(s: &mut Session, p: &Value) -> Result<Value> { } else { d.graphic_style_id(i); let g = d.graphic_styles[i].clone(); + let mut shared = None; for id in &ids { - apply_style(d, *id, &g, chars); + apply_style(d, *id, &g, &mut shared, chars); } + super::appearance::clear_stood_for(d, &groups); super::appearance::capture_series_writes(&before, d, &ids, (true, true), (true, true), false, true); } Ok(()) @@ -365,8 +380,11 @@ fn style_apply(s: &mut Session, p: &Value) -> Result<Value> { } fn style_new(s: &mut Session, p: &Value) -> Result<Value> { - let (src, n) = source(s, p, "graphicStyle.new")?; + let (_, n) = source(s, p, "graphicStyle.new")?; let d = &s.doc()?.doc; + // A series group that holds nothing of its own shows the look of its paths: the style is made from the topmost. + let n = super::appearance::look_holder(d, n); + let src = n.id; let name = match str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()) { Some(n) => unique_name(n, |x| d.graphic_style(x).is_some()), None => d.new_graphic_style_name(), @@ -452,6 +470,9 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result<Value> { let cmd = "graphicStyle.redefine"; let (src, n) = source(s, p, cmd)?; let d = &s.doc()?.doc; + // A series group that holds nothing of its own is redefined from the topmost of its paths, which a style links. + let n = super::appearance::look_holder(d, n); + let src = if n.id == src { src } else { n.id }; let i = match str_param(p, "name") { Some(name) => style_index(d, name)?, None => n @@ -473,11 +494,18 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result<Value> { let linked = objects_where(d, |n| n.extras().graphic_style == Some(id) && n.id != src); let (follow, edited): (Vec<NodeId>, Vec<NodeId>) = linked.into_iter().partition(|nid| d.node(*nid).is_some_and(|n| in_sync(n, &old))); set_link(d, &edited, None); + // A linked graph series group passes the style to the paths directly inside it, so the graph stores it, and + // goes back to the empty appearance the graph draws it with. The source and the edited paths keep their look. + let mut follow_marks = super::graph::series_group_marks(d, &follow); + let edited: HashSet<NodeId> = edited.into_iter().collect(); + follow_marks.retain(|nid| *nid != src && !edited.contains(nid)); + super::appearance::clear_stood_for(d, &super::appearance::stood_for(&follow, &follow_marks)); let g = d.graphic_styles[i].clone(); - for nid in &follow { - apply_style(d, *nid, &g, chars); + let mut shared = None; + for nid in &follow_marks { + apply_style(d, *nid, &g, &mut shared, chars); } - super::appearance::capture_series_writes(&before, d, &follow, (true, true), (true, true), false, true); + super::appearance::capture_series_writes(&before, d, &follow_marks, (true, true), (true, true), false, true); set_link(d, &[src], Some(id)); Ok(()) })?; @@ -485,7 +513,7 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result<Value> { } fn style_break_link(s: &mut Session, p: &Value) -> Result<Value> { - let ids = super::appearance::appearance_targets(s, p)?; + let ids = super::appearance::whole_targets(s, p)?; s.edit("Break Link to Graphic Style", |d, _| { set_link(d, &ids, None); Ok(()) diff --git a/crates/engine/src/cmd/swatch.rs b/crates/engine/src/cmd/swatch.rs index 1cd9849990..d0713a243a 100644 --- a/crates/engine/src/cmd/swatch.rs +++ b/crates/engine/src/cmd/swatch.rs @@ -1,11 +1,11 @@ //! The Swatches panel: new, delete and duplicate swatches, colour groups and sorting. -use std::collections::{HashMap, HashSet}; +use std::collections::{HashMap, HashSet, VecDeque}; use serde_json::{Value, json}; use vectorcraft_color::{Color, Gradient, GradientKind, GradientMethod, GradientStop, Paint, Swatch, SwatchGroup, tint_percent}; use vectorcraft_doc::pattern::pattern_paint; -use vectorcraft_doc::swatches::{LinkFn, color_name, map_node_solid_paints, node_colors}; +use vectorcraft_doc::swatches::{LinkFn, PaintFn, color_name, map_node_paints, map_node_solid_paints, node_colors}; use vectorcraft_doc::{Document, NodeId}; use super::paint::paint_from; @@ -84,7 +84,7 @@ pub fn specs() -> Vec<CommandSpec> { "Select All Unused", ["Window", "Swatches"], None, - "{} → {names: [the swatches nothing uses, in panel order]}: a colour is used when a paint links to it or an unlinked paint, gradient stop or mesh point has its colour; a gradient when a gradient links to it or has its stops; a pattern when it fills or strokes anything (art, symbols, pattern tiles and graphic styles count). None is never listed", + "{} → {names: [the swatches nothing uses, in panel order]}: a colour is used when a paint links to it or an unlinked paint, gradient stop or mesh point has its colour; a gradient when a gradient links to it or has its stops; a pattern when it fills or strokes anything (art, symbols, pattern tiles and graphic styles count); a color, spot or process, when an image placed from a DCS file that the art shows has a spot plate of its name. None is never listed", has_doc, swatch_unused ), @@ -222,9 +222,10 @@ fn swatch_new(s: &mut Session, p: &Value) -> Result<Value> { /// The `names` list and `name` parameters, without repeats; at least one is required. pub(super) fn names_param(p: &Value, cmd: &str) -> Result<Vec<String>> { + let mut seen: HashSet<String> = HashSet::new(); let mut names: Vec<String> = vec![]; for n in str_list(p, "names").into_iter().chain(str_param(p, "name").map(str::to_string)) { - if !names.contains(&n) { + if seen.insert(n.clone()) { names.push(n); } } @@ -234,17 +235,73 @@ pub(super) fn names_param(p: &Value, cmd: &str) -> Result<Vec<String>> { Ok(names) } +/// Take swatches `names` out of the document in that order, as [`Document::remove_swatch`] for +/// each name in turn would, in one pass over the swatches: a name takes the first swatch of that +/// name still there (ungrouped first, then each colour group's) when `take` accepts it, and +/// nothing when `take` refuses it or no swatch has the name. +fn take_swatches(d: &mut Document, names: &[String], take: impl Fn(&Swatch) -> bool) -> Vec<Swatch> { + let wanted: HashSet<&str> = names.iter().map(String::as_str).collect(); + // Each wanted name's swatches in lookup order: (list, index, accepted), where list 0 holds the + // ungrouped swatches and list g + 1 colour group g's. + let mut places: HashMap<&str, VecDeque<(usize, usize, bool)>> = HashMap::new(); + let lists = std::iter::once(&d.swatches[..]).chain(d.swatch_groups.iter().map(|g| &g.swatches[..])); + for (l, list) in lists.enumerate() { + for (i, w) in list.iter().enumerate() { + if let Some(n) = wanted.get(w.name.as_str()) { + places.entry(n).or_default().push_back((l, i, take(w))); + } + } + } + let mut picked: Vec<(usize, usize)> = vec![]; + for n in names { + if let Some(q) = places.get_mut(n.as_str()) + && let Some(&(l, i, true)) = q.front() + { + q.pop_front(); + picked.push((l, i)); + } + } + if picked.is_empty() { + return vec![]; + } + let hit: HashSet<(usize, usize)> = picked.iter().copied().collect(); + let hit_lists: HashSet<usize> = picked.iter().map(|&(l, _)| l).collect(); + let mut taken: HashMap<(usize, usize), Swatch> = HashMap::with_capacity(picked.len()); + let mut split = |l: usize, list: &mut Vec<Swatch>| { + for (i, w) in std::mem::take(list).into_iter().enumerate() { + if hit.contains(&(l, i)) { + taken.insert((l, i), w); + } else { + list.push(w); + } + } + }; + // Both lists are copied on write, so each is only written when a swatch leaves it. + if hit_lists.contains(&0) { + split(0, &mut d.swatches); + } + if hit_lists.iter().any(|&l| l > 0) { + for (g, group) in d.swatch_groups.iter_mut().enumerate() { + if hit_lists.contains(&(g + 1)) { + split(g + 1, &mut group.swatches); + } + } + } + picked.iter().filter_map(|k| taken.remove(k)).collect() +} + fn swatch_delete(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "swatch.delete"; let names = names_param(p, C)?; check_switches(p, &["unlink"], C)?; let d = &s.doc()?.doc; + let by_name = swatches_by_name(d); // Global swatches going away (named ones and those in named groups): their links are dropped. - let mut global: Vec<String> = vec![]; + let mut global: HashSet<String> = HashSet::new(); for n in &names { let swatches: Vec<&Swatch> = match d.swatch_groups.iter().find(|g| g.name == *n) { Some(g) => g.swatches.iter().collect(), - None => vec![d.swatch(n).ok_or_else(|| bad(C, format!("no swatch or colour group `{n}`")))?], + None => vec![by_name.get(n.as_str()).copied().ok_or_else(|| bad(C, format!("no swatch or colour group `{n}`")))?], }; if swatches.iter().any(|w| w.is_reserved()) { return Err(bad(C, format!("`{n}` can't be deleted"))); @@ -258,10 +315,9 @@ fn swatch_delete(s: &mut Session, p: &Value) -> Result<Value> { |_: &mut Color, link: &mut Option<String>, _: &mut f32| link.as_ref().is_some_and(|l| global.contains(l)) && link.take().is_some(); let colorized_ok = super::paint::check_colorized(d).is_ok(); let unlinked = s.edit("Delete Swatch", |d, _| { - d.swatch_groups.retain(|g| !names.contains(&g.name)); - for n in &names { - d.remove_swatch(n); - } + let named: HashSet<&str> = names.iter().map(String::as_str).collect(); + d.swatch_groups.retain(|g| !named.contains(g.name.as_str())); + take_swatches(d, &names, |_| true); let unlinked = map_swatch_links(d, &mut unlink); super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(C, e))?; Ok(unlinked) @@ -337,23 +393,27 @@ fn float_key(v: f32) -> Option<u32> { /// keys. type StopKey<'a> = (u32, ColorKey, u32, u32, Option<&'a str>, u32, Option<[u32; 4]>); -/// A gradient's kind, method, dither and stops, as keys. -type GradientKey<'a> = (u8, u8, bool, Vec<StopKey<'a>>); +/// A gradient's kind, method, dither, spread and count as it paints them, and stops, as keys. +type GradientKey<'a> = (u8, u8, bool, (vectorcraft_color::GradientSpread, u32), Vec<StopKey<'a>>); -/// A key that is equal for two gradients exactly when the gradients are equal (`==`); `None` when -/// any of its numbers is NaN, so the gradient equals no gradient. +/// A key that is equal for two gradients exactly when the gradients are equal (`==`), apart from +/// a count that a gradient which pads does not use ([`Gradient::painted_spread`]); `None` when any +/// of its numbers is NaN, so the gradient equals no gradient. fn gradient_key(g: &Gradient) -> Option<GradientKey<'_>> { let kind = match g.kind { GradientKind::Linear => 0, GradientKind::Radial => 1, GradientKind::Freeform => 2, GradientKind::Conic => 3, + GradientKind::Diamond => 4, }; let method = match g.method { GradientMethod::Classic => 0, GradientMethod::Perceptual => 1, + GradientMethod::HueClockwise => 2, + GradientMethod::HueCounterclockwise => 3, }; - Some((kind, method, g.dither, g.stops.iter().map(stop_key).collect::<Option<_>>()?)) + Some((kind, method, g.dither, g.painted_spread(), g.stops.iter().map(stop_key).collect::<Option<_>>()?)) } /// A stop's key for [`gradient_key`]; `None` when any of its numbers is NaN. @@ -420,15 +480,9 @@ fn swatch_new_group(s: &mut Session, p: &Value) -> Result<Value> { new.extend(art.into_iter().map(|c| (c, to_global))); } let name = d.free_swatch_name(requested.as_deref().unwrap_or("Color Group")); - let mut group = SwatchGroup { name: name.clone(), swatches: vec![] }; // Colour groups hold solid colours only. - for n in &names { - if d.swatch(n).is_some_and(|sw| matches!(sw.paint, Paint::Solid { .. })) - && let Some(sw) = d.remove_swatch(n) - { - group.swatches.push(sw); - } - } + let swatches = take_swatches(d, &names, |sw| matches!(sw.paint, Paint::Solid { .. })); + let mut group = SwatchGroup { name: name.clone(), swatches }; // The global swatches made from the art's colours, which its unlinked paints link to. let mut links: Vec<(Color, String)> = vec![]; let mut free = d.free_swatch_names(); @@ -484,8 +538,9 @@ fn swatch_move(s: &mut Session, p: &Value) -> Result<Value> { insert_before(&mut d.swatch_groups, items, at.as_deref(), |g| &g.name); return Ok(()); } + let by_name = swatches_by_name(d); for n in &names { - let sw = d.swatch(n).ok_or_else(|| bad(C, format!("no swatch `{n}` (swatches and colour groups move separately)")))?; + let sw = by_name.get(n.as_str()).ok_or_else(|| bad(C, format!("no swatch `{n}` (swatches and colour groups move separately)")))?; if sw.is_reserved() { return Err(bad(C, format!("`{n}` can't be moved"))); } @@ -504,7 +559,7 @@ fn swatch_move(s: &mut Session, p: &Value) -> Result<Value> { } } let at = anchor(list(d, dest), to, &names, |w| &w.name); - let items: Vec<Swatch> = names.iter().filter_map(|n| d.remove_swatch(n)).collect(); + let items = take_swatches(d, &names, |_| true); insert_before(list(d, dest), items, at.as_deref(), |w| &w.name); Ok(()) })?; @@ -628,32 +683,16 @@ pub(super) fn map_default_paints(s: &mut Session, f: &mut LinkFn) { /// paint changed is merged into its entry ([`merge_stored`]), so fields the brush definition does /// not read are kept at every level. pub(super) fn map_swatch_links(d: &mut Document, f: &mut LinkFn) -> usize { - use vectorcraft_brush::{Brush, BrushKind, Colorization}; - let mut n = d.map_solid_paints(f); - // Each stored entry, its brush when it parses, the brush as written before the edit (only - // when its paint changed), and whether its paint changed. - let mut lib: Vec<(Value, Option<Brush>, Value, bool)> = match d.unknown.get(vectorcraft_brush::DOC_KEY) { - Some(v) => v.as_array().into_iter().flatten().map(|e| (e.clone(), Brush::from_json(e.clone()).ok(), Value::Null, false)).collect(), - None => { - vectorcraft_brush::library(d).into_iter().map(|b| (serde_json::to_value(&b).unwrap_or_default(), Some(b), Value::Null, false)).collect() - } - }; - let mut in_brushes = 0; - for (_, b, base, changed) in lib.iter_mut() { - let Some(b) = b else { continue }; - let before_edit = serde_json::to_value(&*b).unwrap_or_default(); + use vectorcraft_brush::{BrushKind, Colorization}; + let n = d.map_solid_paints(f); + n + edit_brush_library(d, &mut |b| { let key = match b.kind.colorization() { Colorization::HueShift { key } => Some(key), _ => None, }; let before = key.map(|_| art_paint_colors(b.art())); - let in_brush = b.art_mut().into_iter().map(|art| map_node_solid_paints(art, f)).sum::<usize>(); - *changed = in_brush > 0; - if *changed { - *base = before_edit; - } - in_brushes += in_brush; - let (Some(key), Some(before)) = (key, before) else { continue }; + let in_brush = b.art_mut().into_iter().map(|art| map_node_solid_paints(art, &mut *f)).sum::<usize>(); + let (Some(key), Some(before)) = (key, before) else { return in_brush }; // Colors are compared by hex value, as `art_colors` (Brush Options' key colors) lists them. let same = |a: &Color, b: &Color| a.to_hex() == b.to_hex(); let after = art_paint_colors(b.art()); @@ -666,10 +705,47 @@ pub(super) fn map_swatch_links(d: &mut Document, f: &mut LinkFn) -> usize { BrushKind::Art(a) => &mut a.colorization, BrushKind::Scatter(s) => &mut s.colorization, BrushKind::Pattern(p) => &mut p.colorization, - BrushKind::Calligraphic(_) | BrushKind::Bristle(_) => continue, + BrushKind::Calligraphic(_) | BrushKind::Bristle(_) => return in_brush, }; *c = Colorization::HueShift { key }; } + in_brush + }) +} + +/// Apply a paint rewrite ([`Document::map_paints`]) to the document and to the art of the brushes +/// in its library ([`edit_brush_library`]). Returns the number of changed paints. +pub(super) fn map_all_paints(d: &mut Document, f: &mut PaintFn) -> usize { + let n = d.map_paints(f); + n + edit_brush_library(d, &mut |b| b.art_mut().into_iter().map(|art| map_node_paints(art, &mut *f)).sum()) +} + +/// Apply `edit` to each brush of the document's library, the stored entries or, with none stored, +/// the built-in library; `edit` returns how many paints of the brush's art it changed. The library +/// is stored again only when a brush's paint changed. Stored entries are stored again as they were +/// read, except that a brush whose paint changed is merged into its entry ([`merge_stored`]), so +/// fields the brush definition does not read are kept at every level. Returns the number of +/// changed paints. +fn edit_brush_library(d: &mut Document, edit: &mut dyn FnMut(&mut vectorcraft_brush::Brush) -> usize) -> usize { + use vectorcraft_brush::Brush; + // Each stored entry, its brush when it parses, the brush as written before the edit (only + // when its paint changed), and whether its paint changed. + let mut lib: Vec<(Value, Option<Brush>, Value, bool)> = match d.unknown.get(vectorcraft_brush::DOC_KEY) { + Some(v) => v.as_array().into_iter().flatten().map(|e| (e.clone(), Brush::from_json(e.clone()).ok(), Value::Null, false)).collect(), + None => { + vectorcraft_brush::library(d).into_iter().map(|b| (serde_json::to_value(&b).unwrap_or_default(), Some(b), Value::Null, false)).collect() + } + }; + let mut in_brushes = 0; + for (_, b, base, changed) in lib.iter_mut() { + let Some(b) = b else { continue }; + let before_edit = serde_json::to_value(&*b).unwrap_or_default(); + let in_brush = edit(b); + *changed = in_brush > 0; + if *changed { + *base = before_edit; + } + in_brushes += in_brush; } if in_brushes > 0 { let lib = lib @@ -680,9 +756,8 @@ pub(super) fn map_swatch_links(d: &mut Document, f: &mut LinkFn) -> usize { }) .collect(); d.unknown.insert(vectorcraft_brush::DOC_KEY.into(), Value::Array(lib)); - n += in_brushes; } - n + in_brushes } /// `new` (a definition as written after an edit) with the parts of `raw` (its stored entry) that @@ -935,8 +1010,28 @@ fn swatch_unused(s: &mut Session, _: &Value) -> Result<Value> { let colors: HashSet<ColorKey> = colors.iter().filter_map(color_key).collect(); let patterns: HashSet<&String> = patterns.iter().collect(); let gradients: HashSet<GradientKey> = gradients.iter().filter_map(gradient_key).collect(); + // The spot inks the images placed from DCS files have plates for: their swatches print them. + // Only images the art shows count: a deleted one's pixels stay for undo. + let mut shown: HashSet<&str> = HashSet::new(); + for root in d + .layers + .iter() + .chain(d.symbols.iter().map(|s| &s.art)) + .chain(d.graph_designs.iter().map(|g| &g.art)) + .chain(d.patterns.iter().flat_map(|p| &p.art)) + { + vectorcraft_doc::swatches::walk_with_masks(root, &mut |n| { + if let vectorcraft_doc::NodeKind::Image(im) = &n.kind { + shown.insert(im.key.as_str()); + } + }); + } + let plate_inks: HashSet<String> = + shown.iter().filter_map(|k| d.images.get(*k)).flat_map(vectorcraft_doc::ImageBlob::spot_plates).map(|(name, _)| name).collect(); let used = |w: &Swatch| { gradient_links.contains(&w.name) + // A spot swatch prints the plate; a process one gives the color it prints as process. + || (w.paint.color().is_some() && plate_inks.contains(&w.name)) || match w.tint_of() { Some((base, tint)) => float_key(tint).is_some_and(|t| link_tints.contains(&(base, t))), None => link_names.contains(w.name.as_str()), @@ -956,8 +1051,9 @@ fn swatch_merge(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "swatch.merge"; let names = names_param(p, C)?; let d = &s.doc()?.doc; + let by_name = swatches_by_name(d); for n in &names { - let sw = d.swatch(n).ok_or_else(|| bad(C, format!("no swatch `{n}`")))?; + let sw = by_name.get(n.as_str()).ok_or_else(|| bad(C, format!("no swatch `{n}`")))?; if sw.is_reserved() { return Err(bad(C, format!("`{n}` can't be merged"))); } @@ -971,9 +1067,10 @@ fn swatch_merge(s: &mut Session, p: &Value) -> Result<Value> { } let kept = d.swatch(keep).ok_or_else(|| bad(C, format!("no swatch `{keep}`")))?; let (color, link) = (d.linked_color(kept.paint.color().unwrap_or_default(), kept.spot), kept.global.then(|| keep.clone())); + let merged_names: HashSet<&str> = merged.iter().map(String::as_str).collect(); // Tints keep their tint (of the kept colour). let mut relink = |c: &mut Color, l: &mut Option<String>, t: &mut f32| { - if !l.as_ref().is_some_and(|l| merged.contains(l)) { + if !l.as_ref().is_some_and(|l| merged_names.contains(l.as_str())) { return false; } *c = color.tinted(*t); @@ -982,9 +1079,7 @@ fn swatch_merge(s: &mut Session, p: &Value) -> Result<Value> { }; let colorized_ok = super::paint::check_colorized(d).is_ok(); let relinked = s.edit("Merge Swatches", |d, _| { - for n in merged { - d.remove_swatch(n); - } + take_swatches(d, merged, |_| true); let relinked = map_swatch_links(d, &mut relink); super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(C, e))?; Ok(relinked) diff --git a/crates/engine/src/cmd/swatchlib.rs b/crates/engine/src/cmd/swatchlib.rs index 45320066cf..8101cfff97 100644 --- a/crates/engine/src/cmd/swatchlib.rs +++ b/crates/engine/src/cmd/swatchlib.rs @@ -85,7 +85,7 @@ pub fn specs() -> Vec<CommandSpec> { "Copy to User Defined", ["Window", "Swatch Libraries"], None, - "{library: id or name of a loaded library (category \"loaded\", swatch.library.load)} copy it into the user library folder of the desktop app, whose libraries VectorCraft lists as User Defined every time it starts (a loaded library is listed until the app quits): a library file as it is, the swatches of a document or a library loaded from data as a .vcswatches file. A name the folder already has gets a number (\"Brand 2.ase\") and no file is replaced; when the folder already holds the same file, that file is used. The library is then listed as User Defined only, and until the app quits commands given its loaded id use the copy; a User Defined library comes back as it is → {library: its User Defined id, name, count, path, copied: false when nothing was written}", + "{library: id or name of a loaded library (category \"loaded\", swatch.library.load)} copy it into the user library folder of the desktop app, whose libraries VectorCraft lists as User Defined every time it starts (a loaded library is listed until the app quits): a library file as it is, the swatches of a document or a library loaded from data as a .vcswatches file. A name the folder already has gets a number (\"Brand 2.ase\") and no file is replaced; when the folder already holds the same file, that file is used. The library is then listed as User Defined only, and until the app quits commands given its loaded id use the copy; a User Defined library comes back as it is → {library: its User Defined id, name, count, path (left out when it is outside the read roots), copied: false when nothing was written}", has_user_folder, copy_to_user ), @@ -368,7 +368,9 @@ impl<L: LibraryFile> Libraries<L> { .ok_or_else(|| bad(cmd, format!("`{id}` isn't a loaded library")))?; let (file, bytes) = match source.filter(|p| L::EXTS.contains(&extension(p).as_str())) { Some(p) => { - // Outside the request's read roots: the error names no path. + // The file's bytes are read: outside the request's read roots, the error names no + // path. A document's swatches (the arm below) are written from the loaded library, + // and the document is not read again. if !readable(&p) { return Err(bad(cmd, "the library's file is outside the read roots")); } @@ -469,19 +471,34 @@ fn file_name(path: &str) -> String { std::path::Path::new(path).file_name().map_or_else(|| path.to_string(), |n| n.to_string_lossy().to_string()) } +/// The file name a concealed library or path is shown by: the last part of `path` as this platform +/// splits a path, so that outside Windows a `\` stays part of the name. Another platform's absolute +/// path ([`crate::file_access::written_elsewhere`]), and a path this platform gives no file name (one +/// that ends in `..`), are split after the last `/` or `\` instead. `path` itself when it has no such part. +pub fn concealed_file_name(path: &str) -> String { + let native = (!crate::file_access::written_elsewhere(path)).then(|| std::path::Path::new(path).file_name()).flatten(); + native.map_or_else(|| path.rsplit(['/', '\\']).find(|part| !part.is_empty()).unwrap_or(path).to_string(), |n| n.to_string_lossy().into_owned()) +} + /// May the request being served read `path` ([`crate::file_access::check_read`])? Always, without -/// roots in force. +/// roots in force. Another platform's absolute path ([`crate::file_access::written_elsewhere`]) is +/// never readable under a read root. fn readable(path: &str) -> bool { - crate::file_access::check_read(path).is_ok() + !crate::file_access::written_elsewhere(path) && crate::file_access::check_read(path).is_ok() } /// The loaded library ids (`loaded/<path>`) whose file the request being served may not read, each /// with the id a reply shows instead: `loaded/<file name>`, as a library loaded without a path is -/// named. The ids are those of the session's swatch, brush, symbol and graphic style libraries, then -/// `others` (ids the UI state refers to). When another id already is or shows that id, the next free -/// one of `loaded/<file name> (2)`, `(3)` and so on is shown, so that two libraries stay two. The -/// session's libraries are numbered first, in the sorted order of their full ids, so a library shows -/// the same id whatever `others` holds; then `others`, in the same order. Without roots in force, none. +/// named. The file name is [`concealed_file_name`], and a path saved as another platform's absolute +/// path counts as one the request may not read. The ids are those of the +/// session's swatch, brush, symbol and graphic style libraries, then `others` (ids the UI state refers +/// to). When another id already is or shows that id, the next free +/// one of `loaded/<file name> (2)`, `(3)` and so on is shown, so that two libraries stay two. A library +/// keeps the id it was first shown under for the rest of the session, so an id a client was given +/// finds the same library after another one with the same file name is loaded; only a library that +/// shows that id itself (one loaded later without a file under that name) moves it to the next free +/// one. Libraries shown for the first time are numbered the session's first, in the sorted order of +/// their full ids, then `others`, in the same order. Without roots in force, none. pub fn concealed_library_ids(s: &Session, others: impl IntoIterator<Item = String>) -> Vec<(String, String)> { if crate::file_access::current().is_none() { return vec![]; @@ -493,7 +510,7 @@ pub fn concealed_library_ids(s: &Session, others: impl IntoIterator<Item = Strin let mut taken = BTreeSet::new(); for ids in [session, others] { for id in ids { - let name = id.strip_prefix("loaded/").filter(|path| !path.is_empty()).map(|path| (file_name(path), path)); + let name = id.strip_prefix("loaded/").filter(|path| !path.is_empty()).map(|path| (concealed_file_name(path), path)); match name { Some((name, path)) if name != path && !readable(path) => hidden.push((id, name)), _ => { @@ -502,16 +519,32 @@ pub fn concealed_library_ids(s: &Session, others: impl IntoIterator<Item = Strin } } } + let mut assigned = s.shown_library_ids.lock().unwrap_or_else(|e| e.into_inner()); + let mut kept = vec![None; hidden.len()]; + for (slot, (id, _)) in kept.iter_mut().zip(&hidden) { + if let Some(shown) = assigned.get(id).filter(|shown| !taken.contains(*shown)) { + taken.insert(shown.clone()); + *slot = Some(shown.clone()); + } + } + // A new id is never one given to another library earlier in the session. + let mut given: BTreeSet<String> = assigned.values().cloned().collect(); hidden .into_iter() - .map(|(id, name)| { - let mut shown = format!("loaded/{name}"); - let mut n = 2; - while taken.contains(&shown) { - shown = format!("loaded/{name} ({n})"); - n += 1; - } - taken.insert(shown.clone()); + .zip(kept) + .map(|((id, name), kept)| { + let shown = kept.unwrap_or_else(|| { + let mut shown = format!("loaded/{name}"); + let mut n = 2; + while taken.contains(&shown) || given.contains(&shown) { + shown = format!("loaded/{name} ({n})"); + n += 1; + } + taken.insert(shown.clone()); + given.insert(shown.clone()); + assigned.insert(id.clone(), shown.clone()); + shown + }); (id, shown) }) .collect() @@ -746,8 +779,12 @@ fn copy_to_user(s: &mut Session, p: &Value) -> Result<Value> { "user" => (info, lib, false), _ => return Err(bad(C, format!("`{}` is built in and always listed", info.name))), }; - let path = s.swatch_libraries.shown_path(&info.id); - Ok(json!({"library": info.id, "name": info.name, "count": lib.len(), "path": path, "copied": copied})) + let mut out = json!({"library": info.id, "name": info.name, "count": lib.len(), "copied": copied}); + // As the saves with `user: true`: no `path` when the request may not read the file. + if let Some(path) = s.swatch_libraries.shown_path(&info.id) { + out["path"] = json!(path); + } + Ok(out) } /// The library swatches `names` stand for, each once, with the colour group it goes into (`None`: diff --git a/crates/engine/src/cmd/symboledit.rs b/crates/engine/src/cmd/symboledit.rs index a5f677f5dd..606ab40fcf 100644 --- a/crates/engine/src/cmd/symboledit.rs +++ b/crates/engine/src/cmd/symboledit.rs @@ -19,7 +19,7 @@ use vectorcraft_doc::symbol_overrides::SymbolOverride; use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Selection, SymbolEdit, SymbolRegistration}; use vectorcraft_geom::{Affine, Point}; -use super::brushsym::{natural_size, place_xf}; +use super::brushsym::{fit_parts, natural_size, place_xf}; use super::{EngineError, Result, Session, bad, number_or, object_param, ok, str_param}; /// The name of the undo step that enters symbol editing mode. @@ -425,8 +425,8 @@ fn each_changed_instance(n: &mut Node, name: &str, f: &mut dyn FnMut(&mut Vec<Sy } /// Each instance's appearance changes to objects of symbol `name`'s art follow those objects -/// through an edit of the editing layer (see [`follow_paths`]), and keep only the changes to -/// objects the art still has. That covers the instances on the layers and in the art of the +/// through an edit of the editing layer (see [`follow_paths`]), and keep only the changes the art +/// still draws ([`fit_parts`]). That covers the instances on the layers and in the art of the /// document's other symbols, graph designs, pattern tiles (the tiles pattern editing's Cancel puts /// back included) and brushes, opacity-mask art included. The editing layer holds no instance of /// the symbol, since [`sync`] refuses one. @@ -435,7 +435,7 @@ fn follow_objects(d: &mut Document, name: &str, old: (&[Arc<Node>], bool), new: let mut follow = |o: &mut Vec<SymbolOverride>| { follow_paths(o, old, new); match &art { - Some(art) => vectorcraft_doc::symbol_overrides::retain_parts(o, art), + Some(art) => fit_parts(o, art), None => o.clear(), } }; diff --git a/crates/engine/src/cmd/tabs.rs b/crates/engine/src/cmd/tabs.rs index 331227e3be..c047b94900 100644 --- a/crates/engine/src/cmd/tabs.rs +++ b/crates/engine/src/cmd/tabs.rs @@ -13,7 +13,7 @@ pub fn specs() -> Vec<CommandSpec> { "Set Tab Stops", ["Window", "Tabs"], None, - "{stops: [{position: pt, align?: left|center|right|decimal, leader?: \". \", alignOn?: \".\"}], ids?|id?, start?: byte, end?: byte} replace the tab stops of the selected text (with a range: of the paragraphs it touches); supplied align, leader and alignOn must be strings, and alignOn cannot be empty", + "{stops: [{position: pt, align?: left|center|right|decimal, leader?: \". \", alignOn?: \".\"}], ids?|id?, start?: byte, end?: byte} replace the tab stops of the selected text (with a range: of the paragraphs it touches); at most 256 stops, or no more than each targeted paragraph already holds, positions 0..=100000 pt; supplied align, leader and alignOn must be strings, a leader has at most 8 characters and alignOn exactly one; stops are sorted by position, and of stops at one position the first given is kept", has_selection, set ), @@ -41,7 +41,7 @@ fn parse_stops(p: &Value) -> Result<Vec<TabStop>> { let mut stops = vec![]; for s in arr { let position = s.get("position").and_then(Value::as_f64).ok_or_else(|| bad(C, "each stop needs a position"))?; - if !(0.0..=100_000.0).contains(&position) { + if !(0.0..=TabStop::MAX_POSITION).contains(&position) { return Err(bad(C, "positions must be between 0 and 100000 pt")); } let align = match s.get("align") { @@ -60,16 +60,25 @@ fn parse_stops(p: &Value) -> Result<Vec<TabStop>> { None | Some(Value::Null) => "", Some(Value::String(value)) => value.as_str(), Some(_) => return Err(bad(C, "`leader` must be a string")), + }; + let (label, max) = ("`leader`", TabStop::MAX_LEADER); + if leader.chars().count() > max { + return Err(bad(C, format!("{label} must be at most {max} characters"))); } - .chars() - .take(8) - .collect(); let align_on = match s.get("alignOn") { None | Some(Value::Null) => '.', - Some(Value::String(value)) => value.chars().next().ok_or_else(|| bad(C, "`alignOn` cannot be empty"))?, + Some(Value::String(value)) => { + let mut chars = value.chars(); + let c = chars.next().ok_or_else(|| bad(C, "`alignOn` cannot be empty"))?; + if chars.next().is_some() { + let label = "`alignOn`"; + return Err(bad(C, format!("{label} must be one character"))); + } + c + } Some(_) => return Err(bad(C, "`alignOn` must be a string")), }; - stops.push(TabStop { position, align, leader, align_on }); + stops.push(TabStop { position, align, leader: leader.to_string(), align_on }); } stops.sort_by(|a, b| a.position.total_cmp(&b.position)); stops.dedup_by(|a, b| (a.position - b.position).abs() < 1e-6); @@ -77,10 +86,39 @@ fn parse_stops(p: &Value) -> Result<Vec<TabStop>> { } fn set(s: &mut Session, p: &Value) -> Result<Value> { + // More than the limit is taken only when every targeted paragraph already holds at least as + // many stops, so a paragraph that holds more can still lose them one at a time. The supplied + // list is counted before it is read. + let max = TabStop::MAX_STOPS; + let supplied = p.get("stops").and_then(Value::as_array).map_or(0, Vec::len); + if supplied > max && supplied > fewest_held(s, p)? { + return Err(bad("text.tabs.set", format!("at most {max} tab stops"))); + } let stops = parse_stops(p)?; apply(s, p, stops, "Tab Stops") } +/// The fewest tab stops a paragraph that `text.tabs.set` with `p` targets holds (0 with none). +fn fewest_held(s: &Session, p: &Value) -> Result<usize> { + let ids = text_targets(s, p, "text.tabs.set")?; + let range = TextRange::parse(p, "text.tabs.set")?; + let doc = &s.doc()?.doc; + let mut fewest: Option<usize> = None; + for id in &ids { + if let Some(NodeKind::Text(t)) = doc.node(*id).map(|node| &node.kind) { + let held = match para_span(range, t) { + None => t.para_styles().map(|pa| pa.tabs.len()).min(), + Some(r) => r.map(|i| t.para_at(i).tabs.len()).min(), + }; + fewest = match (fewest, held) { + (Some(a), Some(b)) => Some(a.min(b)), + (a, b) => a.or(b), + }; + } + } + Ok(fewest.unwrap_or(0)) +} + fn apply(s: &mut Session, p: &Value, stops: Vec<TabStop>, label: &str) -> Result<Value> { let ids = text_targets(s, p, "text.tabs.set")?; let range = TextRange::parse(p, "text.tabs.set")?; @@ -128,7 +166,7 @@ fn get(s: &mut Session, p: &Value) -> Result<Value> { #[cfg(test)] mod tests { - use serde_json::json; + use serde_json::{Value, json}; use crate::Session; @@ -139,6 +177,59 @@ mod tests { } } + /// A leader of more than eight characters, an `alignOn` of more than one character and a list + /// of more than 256 stops are errors, not cut short. + #[test] + fn long_leaders_long_align_on_and_too_many_stops_are_errors() { + let err = |stops: Value| super::parse_stops(&json!({ "stops": stops })).unwrap_err().to_string(); + assert!(err(json!([{"position": 40, "leader": "123456789"}])).contains("`leader` must be at most 8 characters")); + assert!(err(json!([{"position": 40, "alignOn": ",."}])).contains("`alignOn` must be one character")); + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("text.create", &json!({"x": 10, "y": 20, "text": "a\tb"})).unwrap(); + let many: Vec<Value> = (0..257).map(|i| json!({"position": i})).collect(); + let e = s.execute("text.tabs.set", &json!({ "stops": many.clone() })).unwrap_err().to_string(); + assert!(e.contains("at most 256 tab stops"), "{e}"); + // The supplied list is counted, not the stops left once those at one position merge. + let same: Vec<Value> = (0..257).map(|_| json!({"position": 5})).collect(); + assert!(s.execute("text.tabs.set", &json!({ "stops": same })).unwrap_err().to_string().contains("at most 256 tab stops")); + assert_eq!(s.execute("text.tabs.set", &json!({ "stops": &many[..256] })).unwrap()["stops"], json!(256)); + let ok = super::parse_stops(&json!({"stops": [{"position": 0, "leader": "12345678", "alignOn": "€"}]})).unwrap(); + assert_eq!((ok[0].leader.as_str(), ok[0].align_on), ("12345678", '€')); + } + + /// A paragraph that already holds more than 256 stops (from a file) can lose them one at a + /// time: a list no longer than every targeted paragraph's own is taken, a longer one is not, and + /// a paragraph with fewer stops targeted beside it keeps the limit. + #[test] + fn stops_can_be_removed_from_a_paragraph_holding_more_than_the_limit() { + use vectorcraft_doc::{NodeId, NodeKind, TabAlign, TabStop}; + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let id = NodeId(s.execute("text.create", &json!({"x": 10, "y": 20, "text": "a\tb\nc\td"})).unwrap()["id"].as_u64().unwrap()); + let held: Vec<TabStop> = + (0..300).map(|i| TabStop { position: f64::from(i), align: TabAlign::Left, leader: String::new(), align_on: '.' }).collect(); + s.edit("Load", |d, _| { + if let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) { + t.edit_paras(None, |pa| pa.tabs = held.clone()); + } + Ok(()) + }) + .unwrap(); + let list = |n: i32| json!({ "stops": (0..n).map(|i| json!({"position": i})).collect::<Vec<_>>() }); + assert!(s.execute("text.tabs.set", &list(301)).unwrap_err().to_string().contains("at most 256 tab stops")); + assert_eq!(s.execute("text.tabs.set", &list(299)).unwrap()["stops"], json!(299)); + assert_eq!(s.execute("text.tabs.get", &json!({})).unwrap()["stops"].as_array().unwrap().len(), 299); + // The second paragraph (bytes 4 on) now holds 2 stops: 298 for both paragraphs is refused, + // and 298 for the first alone is taken. + s.execute("text.tabs.set", &json!({"stops": [{"position": 1}, {"position": 2}], "start": 4, "end": 4})).unwrap(); + let mut both = list(298); + assert!(s.execute("text.tabs.set", &both).is_err()); + both["start"] = json!(0); + both["end"] = json!(0); + assert_eq!(s.execute("text.tabs.set", &both).unwrap()["stops"], json!(298)); + } + #[test] fn set_get_clear_tabs() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index 00f1dd8adb..6fc8b12edc 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -11,8 +11,8 @@ use super::menucmds::whole_or; use super::stroke::StrokeChange; use super::typecmd::refresh_bounds; use super::{ - CommandSpec, EngineError, Result, Session, bad, bool_or, check_numbers, check_switches, cmd, color_value, has_doc, has_selection, id_param, - index, number_or, point_param, str_param, switch_or, targets, text_param, + CommandSpec, EngineError, Result, Session, bad, bool_or, check_numbers, check_switches, cmd, color_value, has_doc, has_selection, index, + number_or, object_param, point_param, str_param, switch_or, targets, text_param, }; pub fn specs() -> Vec<CommandSpec> { @@ -40,7 +40,7 @@ pub fn specs() -> Vec<CommandSpec> { "Character", [], None, - "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), fill?: colour|\"none\", stroke?: colour|\"none\" (#rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], featureChanges?: [\"tnum\", \"-onum\", …] (OpenType features turned on, or with - off, on top of each character's own; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; on a vertical path a positive Up/Down moves it toward the path's start and a positive Left/Right to the path's left; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", + "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\" (the space after each character), kerningBefore?: 1/1000 em -1000..10000 (the space before a character that starts a line by itself: the first character of the text, of a paragraph or after a forced line break; no effect elsewhere; 0 by default), baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), fill?: colour|\"none\", stroke?: colour|\"none\" (#rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", \"salt=2\", …] (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; the range is shaped with its word, so a letter's alternate keeps it joined to its neighbours), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; on a vertical path a positive Up/Down moves it toward the path's start and a positive Left/Right to the path's left; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options: space before and after each character in reading order, on its left and right in left-to-right type, on its right and left in right-to-left type, above and below it in vertical type; a ligature or a letter with its marks takes the values of its first character; line wrapping counts it, alignment keeps it at a line's ends and justification does not stretch or narrow it; 0 by default; a value that is not a number or is outside the range is refused, naming the key), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes), glyphAlternate?: null (takes away the glyph choice text.setGlyphAlternate made on the characters, in the same undo step as the other attributes; any other value is refused)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", has_doc, set_range_style ), @@ -58,7 +58,7 @@ pub fn specs() -> Vec<CommandSpec> { "Glyphs", [], None, - "{id, start: byte (a character of it), gid: glyph id|null} draw that one character with another glyph of its font as one undo step, what a double-click in the Glyphs panel's Show › Alternates for Current Selection does: gid is one of the glyphs text.glyphAlternates lists for it; its own default glyph, or null, puts the default glyph back. The text keeps the character, and its other attributes do not change. The choice is saved with the character's style and names the face it was made in (PostScript name and version): set in another font or version, or after the font goes missing, the character takes its default glyph; typed characters take their default glyphs. Choosing the glyph the character already draws is not an edit. An error when the character's font is not available, the glyph is not one of its alternates, or the character's style does not draw it (All Caps, Small Caps, another numeral system) → {id, start, end (the character's bytes), gid (the glyph drawn)}", + "{id, start: byte (a character of it), gid: glyph id|null} draw that one character with another glyph of its font as one undo step, what a double-click in the Glyphs panel's Show › Alternates for Current Selection does: gid is one of the glyphs text.glyphAlternates lists for it, a glyph no character maps and no feature reaches whose name is not another letter's (`a.salt` for a), its own default glyph, or null, puts the default glyph back. The text keeps the character, and its other attributes do not change. The choice is saved with the character's style and names the face it was made in (PostScript name and version): set in another font or version, or after the font goes missing, the character takes its default glyph; typed characters take their default glyphs. Choosing the glyph the character already draws is not an edit. An error when the character's font is not available, the glyph is not one of those, or the character's style does not draw it (All Caps, Small Caps, another numeral system) → {id, start, end (the character's bytes), gid (the glyph drawn)}", has_doc, set_glyph_alternate ), @@ -85,7 +85,7 @@ pub fn specs() -> Vec<CommandSpec> { "Area / Path Type", [], None, - "{path: id, mode: \"area\"|\"onPath\", text?: \"\", vertical?: bool = false, at?: [x, y] (on-path start: nearest point), size?, font?, style?, color?, keepModel? (as text.create), fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (area: as text.areaOptions; default autoHeight when the autoSizeAreaType preference is on), placeholder?: bool (placeholder text instead, as text.create), justify?, leadingModel?, charAlign? (as text.create)} turn a path into an area-type frame or a type-on-a-path baseline (the path's paint is dropped) → {id, bounds: {x, y, width, height} (as text.create), overflow?: [id] (the text doesn't fit; left out when it fits)}", + "{path: id, mode: \"area\"|\"onPath\", text?: \"\", vertical?: bool = false, at?: [x, y] (on-path start: nearest point), size?: pt 0.1..1296 (outside it: an error), font?, style?, color?, keepModel? (as text.create), fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (area: as text.areaOptions; default autoHeight when the autoSizeAreaType preference is on), placeholder?: bool (placeholder text instead, as text.create), justify?, leadingModel?, charAlign? (as text.create)} turn a path into an area-type frame or a type-on-a-path baseline (the path's paint is dropped) → {id, bounds: {x, y, width, height} (as text.create), overflow?: [id] (the text doesn't fit; left out when it fits)}", has_doc, create_in_path ), @@ -103,7 +103,7 @@ pub fn specs() -> Vec<CommandSpec> { "Step Type", [], None, - "{attribute: \"size\"|\"leading\"|\"tracking\"|\"kerning\"|\"baselineShift\", by?: steps (1; negative steps down), id?, start?: byte, end?: byte, ids?: [id…] (instead of id)} step type by the Preferences › Type increments (size and leading: typeSizeIncrement, pt; tracking and kerning: trackingIncrement, 1/1000 em; baseline shift: baselineShiftIncrement, pt), what the Type tool's Alt+arrows do (Cmd/Ctrl too: five steps; horizontal: ←/→ kerning at the caret or tracking of the selection, ↑/↓ leading, Shift+↑/↓ baseline shift; vertical: ↓/↑ with or without Shift kerning or tracking, ←/→ leading, Shift+→/← baseline shift; mixed selected text objects use the horizontal mapping). The range of `id`, else the type objects in `ids`, else the text the Type tool has selected (at a caret: kerning steps the character before it, leading its paragraph), else every selected type object → {ids}", + "{attribute: \"size\"|\"leading\"|\"tracking\"|\"kerning\"|\"baselineShift\", by?: steps (1; negative steps down), id?, start?: byte, end?: byte, ids?: [id…] (instead of id)} step type by the Preferences › Type increments (size and leading: typeSizeIncrement, pt; tracking and kerning: trackingIncrement, 1/1000 em; baseline shift: baselineShiftIncrement, pt), what the Type tool's Alt+arrows do (Cmd/Ctrl too: five steps; horizontal: ←/→ kerning at the caret or tracking of the selection, ↑/↓ leading, Shift+↑/↓ baseline shift; vertical: ↓/↑ with or without Shift kerning or tracking, ←/→ leading, Shift+→/← baseline shift; mixed selected text objects use the horizontal mapping). The range of `id`, else the type objects in `ids`, else the text the Type tool has selected (at a caret: kerning steps the space after the character before it, or at the start of a line (of the text, a paragraph, or after a forced line break) the space before the character after it (kerningBefore, as text.setRangeStyle), and nothing at an empty line's start; leading its paragraph), else every selected type object → {ids}", has_doc, type_step ), @@ -148,7 +148,7 @@ pub fn specs() -> Vec<CommandSpec> { "Reset Tracking and Kerning", [], Some("Cmd+Alt+Q"), - "{ids?: [id…]} set tracking to 0 and clear manual kerning without changing the automatic method in all the text of the type objects in `ids`, else in the text the Type tool has selected (at a caret: only the kerning of the character before it), else in every selected type object, as one undo step → {ids}", + "{ids?: [id…]} set tracking to 0 and clear manual kerning (kerning and kerningBefore) without changing the automatic method in all the text of the type objects in `ids`, else in the text the Type tool has selected (at a caret: only the kerning there, as type.step steps it), else in every selected type object, as one undo step → {ids}", has_selection, reset_tracking ), @@ -272,7 +272,7 @@ fn range_of(p: &Value, len: usize, cmd: &str) -> Result<(usize, usize)> { fn edit_range(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "text.editRange"; - let id = id_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?; let t = text_ref(s, id)?; let len = edit::runs_len(&t.runs); let (a, b) = range_of(p, len, C)?; @@ -337,7 +337,7 @@ fn clear_param(s: &Session, p: &Value, id: NodeId, c: &str) -> Result<Vec<NodeId fn start_list(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "text.startList"; - let id = id_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?; let t = text_ref(s, id)?; let len = edit::runs_len(&t.runs); let at = offset_or(p, "at", len, C)?.min(len); @@ -365,7 +365,7 @@ fn start_list(s: &mut Session, p: &Value) -> Result<Value> { } fn get_range(s: &mut Session, p: &Value) -> Result<Value> { - let id = id_param(p, "id").ok_or_else(|| bad("text.getRange", "missing `id`"))?; + let id = object_param(p, "id", "text.getRange")?.ok_or_else(|| bad("text.getRange", "missing `id`"))?; if switch_or(p, "story", false, "text.getRange")? { return get_story(s, p, id); } @@ -430,6 +430,8 @@ pub(crate) struct CharChange { leading: Option<Option<f64>>, tracking: Option<f64>, kerning: Option<Option<f64>>, + /// The space before a character that starts a line by itself (`kerningBefore`). + kerning_before: Option<f64>, optical_kerning: Option<bool>, baseline_shift: Option<f64>, h_scale: Option<f64>, @@ -457,6 +459,9 @@ pub(crate) struct CharChange { /// Tate-chu-yoko Settings › Up/Down and Left/Right, in points. tcy_up_down: Option<f64>, tcy_left_right: Option<f64>, + /// Insert Aki Left and Right, in 1/1000 em. + aki_left: Option<f64>, + aki_right: Option<f64>, standard_vertical_roman: Option<bool>, no_break: Option<bool>, digits: Option<vectorcraft_doc::Digits>, @@ -464,6 +469,8 @@ pub(crate) struct CharChange { language: Option<Option<String>>, font_axes: Option<AxisChange>, font_height_reference: Option<vectorcraft_doc::FontHeightReference>, + /// Take away the glyph choice ([`CharStyle::glyph_alternate`]) of the characters (`glyphAlternate: null`). + clear_glyph_alternate: bool, } /// `charDirection: "default"|"leftToRight"|"rightToLeft"` → the Character Direction to set (`None` @@ -488,6 +495,15 @@ pub(crate) fn tcy_offset_param(p: &Value, key: &str, cmd: &str) -> Result<Option if (lo..=hi).contains(&v) { Ok(Some(v)) } else { Err(bad(cmd, format!("`{key}` must be from {lo} to {hi}"))) } } +/// `akiLeft` or `akiRight` (Insert Aki Left and Right): a number of thousandths of an em from 0 to +/// [`vectorcraft_doc::text::MAX_AKI`]. Any other value is an error. +pub(crate) fn aki_param(p: &Value, key: &str, cmd: &str) -> Result<Option<f64>> { + let Some(v) = p.get(key).filter(|v| !v.is_null()) else { return Ok(None) }; + let v = v.as_f64().filter(|v| v.is_finite()).ok_or_else(|| bad(cmd, format!("`{key}` must be a number")))?; + let (lo, hi) = (0.0, vectorcraft_doc::text::MAX_AKI); + if (lo..=hi).contains(&v) { Ok(Some(v)) } else { Err(bad(cmd, format!("`{key}` must be from {lo} to {hi}"))) } +} + /// `digits: "default"|"arabic"|"hindi"|"farsi"|"devanagari"|…` ([`Digits::id`]) → the numeral /// system the digits are drawn in. /// @@ -565,7 +581,8 @@ pub(crate) fn change_font_axes(st: &mut CharStyle, change: &AxisChange) { } } -/// `features: ["dlig", "-liga", …]` → the canonical tag list (differences from the defaults). +/// `features: ["dlig", "-liga", "salt=2", …]` → the canonical tag list (differences from the +/// defaults; `salt=1` is written `salt`, `salt=0` and `-salt` leave it out). pub(crate) fn features_param(p: &Value, cmd: &str) -> Result<Option<Vec<String>>> { let Some(v) = p.get("features").filter(|v| !v.is_null()) else { return Ok(None) }; let not_tags = || bad(cmd, "features must be a list of tags"); @@ -574,7 +591,8 @@ pub(crate) fn features_param(p: &Value, cmd: &str) -> Result<Option<Vec<String>> return Err(bad( cmd, format!( - "unknown OpenType feature `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom; prefix - to turn off)" + "unknown OpenType feature `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt; prefix - to turn off; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take an alternate's number as `tag=N` with N from 0 to {}, as `salt=2`)", + vectorcraft_text::MAX_FEATURE_VALUE ), )); } @@ -584,9 +602,9 @@ pub(crate) fn features_param(p: &Value, cmd: &str) -> Result<Option<Vec<String>> /// The most entries a `featureChanges` list may have. const MAX_FEATURE_CHANGES: usize = 256; -/// A feature tag without its `-` or `+` prefix. +/// A feature tag without its `-` or `+` prefix and its `=N` value. fn feature_name(tag: &str) -> &str { - tag.strip_prefix(['-', '+']).unwrap_or(tag) + vectorcraft_text::OtFeatures::tag_name(tag) } /// `featureChanges: ["tnum", "-onum", …]` → the features to turn on (or, with `-`, off) on top of @@ -691,7 +709,7 @@ fn auto_or_num(p: &Value, k: &str, cmd: &str) -> Result<Option<Option<f64>>> { impl CharChange { /// `setup` gives the superscript, subscript and small caps proportions. pub(crate) fn parse(p: &Value, cmd: &str, setup: &vectorcraft_doc::DocSetup) -> Result<Self> { - check_numbers(p, &["size", "tracking", "baselineShift", "hScale", "vScale", "rotation", "strokeWidth"], cmd)?; + check_numbers(p, &["size", "tracking", "kerningBefore", "baselineShift", "hScale", "vScale", "rotation", "strokeWidth"], cmd)?; check_switches( p, &["underline", "strikethrough", "allCaps", "proportionalMetrics", "tateChuYoko", "standardVerticalRoman", "noBreak", "kashidas"], @@ -711,7 +729,7 @@ impl CharChange { let c = Self { font: text_param(p, "font", cmd)?.map(str::to_string), style: text_param(p, "style", cmd)?.map(str::to_string), - size: num("size"), + size: num("size").map(|v| super::typecmd::given_type_size(v, cmd)).transpose()?, leading: auto_or_num(p, "leading", cmd)?, tracking: num("tracking"), kerning: match p.get("kerning") { @@ -720,6 +738,7 @@ impl CharChange { Some(Value::String(v)) if v.eq_ignore_ascii_case("optical") || v.eq_ignore_ascii_case("auto") => Some(None), Some(v) => Some(Some(v.as_f64().ok_or_else(|| bad(cmd, "kerning must be a number, \"auto\", or \"optical\""))?)), }, + kerning_before: num("kerningBefore"), optical_kerning: match p.get("kerning") { Some(Value::String(v)) if v.eq_ignore_ascii_case("optical") => Some(true), Some(Value::String(v)) if v.eq_ignore_ascii_case("auto") => Some(false), @@ -747,16 +766,22 @@ impl CharChange { tate_chu_yoko: flag("tateChuYoko"), tcy_up_down: tcy_offset_param(p, "tcyUpDown", cmd)?, tcy_left_right: tcy_offset_param(p, "tcyLeftRight", cmd)?, + aki_left: aki_param(p, "akiLeft", cmd)?, + aki_right: aki_param(p, "akiRight", cmd)?, standard_vertical_roman: flag("standardVerticalRoman"), no_break: flag("noBreak"), digits: digits_param(p, cmd)?, language: language_param(p, cmd)?, font_axes: font_axes_param(p, cmd)?, font_height_reference: font_height_reference_param(p, cmd)?, + clear_glyph_alternate: match p.get("glyphAlternate") { + None => false, + Some(Value::Null) => true, + Some(_) => { + return Err(bad(cmd, "`glyphAlternate` takes only null, which takes a glyph choice away (text.setGlyphAlternate makes one)")); + } + }, }; - if c.size.is_some_and(|v| v <= 0.0) { - return Err(bad(cmd, "size must be positive")); - } Ok(c) } @@ -777,6 +802,7 @@ impl CharChange { && self.leading.is_none() && self.tracking.is_none() && self.kerning.is_none() + && self.kerning_before.is_none() && self.optical_kerning.is_none() && self.baseline_shift.is_none() && self.h_scale.is_none() @@ -799,12 +825,15 @@ impl CharChange { && self.tate_chu_yoko.is_none() && self.tcy_up_down.is_none() && self.tcy_left_right.is_none() + && self.aki_left.is_none() + && self.aki_right.is_none() && self.standard_vertical_roman.is_none() && self.no_break.is_none() && self.digits.is_none() && self.language.is_none() && self.font_axes.is_none() && self.font_height_reference.is_none() + && !self.clear_glyph_alternate } pub(crate) fn localize(&mut self, t: &TextObject, cmd: &str) -> Result<()> { @@ -864,6 +893,12 @@ impl CharChange { if let Some(v) = self.tcy_left_right { st.tcy_left_right = v; } + if let Some(v) = self.aki_left { + st.aki_left = v; + } + if let Some(v) = self.aki_right { + st.aki_right = v; + } if let Some(v) = self.standard_vertical_roman { st.standard_vertical_roman = v; } @@ -883,6 +918,9 @@ impl CharChange { if let Some(v) = self.kerning { st.kerning = v.map(|k| k.clamp(-1000.0, 10000.0)); } + if let Some(v) = self.kerning_before { + st.kerning_before = v.clamp(-1000.0, 10000.0); + } if let Some(v) = self.optical_kerning { st.optical_kerning = v; } @@ -944,6 +982,9 @@ impl CharChange { if let Some(v) = &self.language { st.language.clone_from(v); } + if self.clear_glyph_alternate { + st.glyph_alternate = None; + } } } @@ -1254,7 +1295,7 @@ fn drawn_glyph( fn set_glyph_alternate(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "text.setGlyphAlternate"; - let id = id_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?; let gid = match p.get("gid") { None => return Err(bad(C, "missing `gid` (a glyph id, or null for the default glyph)")), Some(Value::Null) => None, @@ -1262,7 +1303,9 @@ fn set_glyph_alternate(s: &mut Session, p: &Value) -> Result<Value> { }; let t = text_ref(s, id)?; let (ch, bytes, face) = glyph_target(&t, p, C)?; - let default = face.glyph_for(ch); + let db = vectorcraft_text::FontDb::global(); + let context = std::cell::OnceCell::new(); + let contextual = || context.get_or_init(|| vectorcraft_text::alternates_in_context(db, &t, bytes.start)); let holder = t .runs .iter() @@ -1283,6 +1326,16 @@ fn set_glyph_alternate(s: &mut Session, p: &Value) -> Result<Value> { let mut probe = t.clone(); edit::style_range(&mut probe.runs, bytes.start, bytes.end, |st| st.glyph_alternate = None); let probe_lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &probe); + // Choices belong to the supplying face, including fallback for a missing grapheme. When the + // character overflows, the contextual probe finds that face in an unconstrained frame. + let face = probe_lay + .glyphs + .iter() + .find(|g| g.byte <= bytes.start && bytes.start < g.byte.saturating_add(g.len)) + .and_then(|g| db.face_by_id(g.font_id)) + .or_else(|| contextual().as_ref().and_then(|f| db.face_by_id(f.font_id))) + .unwrap_or(face); + let default = face.glyph_for(ch); let unchosen = holder .as_ref() .filter(|_| !styled) @@ -1290,7 +1343,14 @@ fn set_glyph_alternate(s: &mut Session, p: &Value) -> Result<Value> { let substituted = unchosen.is_some_and(|g| g != default); let choice = match gid.filter(|g| *g != default || substituted) { None => None, - Some(g) if g == default || face.alternates(ch).iter().any(|a| a.gid == g) => Some(face.choice(ch, g)), + Some(g) + if g == default + || face.alternates(ch).iter().any(|a| a.gid == g) + || face.is_unlisted_alternate(ch, g) + || contextual().as_ref().is_some_and(|f| f.font_id == face.id() && f.alternates.iter().any(|a| a.gid == g)) => + { + Some(face.choice(ch, g)) + } Some(g) => return Err(bad(C, format!("glyph {g} is not an alternate of {ch} in {} {}", face.family, face.style))), }; // Without a choice, the glyph drawn in whatever face draws the character, as @@ -1344,7 +1404,7 @@ fn set_glyph_alternate(s: &mut Session, p: &Value) -> Result<Value> { fn glyph_alternates(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "text.glyphAlternates"; - let id = id_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?; let t = text_ref(s, id)?; let (ch, bytes, face) = glyph_target(&t, p, C)?; let default = face.glyph_for(ch); @@ -1359,7 +1419,7 @@ fn glyph_alternates(s: &mut Session, p: &Value) -> Result<Value> { fn touch_type(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "text.touchType"; - let id = id_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?; check_numbers(p, &["start"], C)?; let start = byte_param(p, "start").ok_or_else(|| bad(C, "missing `start` (the byte offset of a character)"))?; if !["dx", "dy", "hScale", "vScale", "rotation"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) { @@ -1585,7 +1645,7 @@ fn touch_type(s: &mut Session, p: &Value) -> Result<Value> { fn create_in_path(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "text.createInPath"; - let pid = id_param(p, "path").ok_or_else(|| bad(C, "missing `path` (a path object id)"))?; + let pid = object_param(p, "path", C)?.ok_or_else(|| bad(C, "missing `path` (a path object id)"))?; let on_path = match str_param(p, "mode").unwrap_or("area") { "area" => false, "onPath" | "path" => true, @@ -1603,7 +1663,7 @@ fn create_in_path(s: &mut Session, p: &Value) -> Result<Value> { check_numbers(p, &["size"], C)?; check_switches(p, &["vertical", "placeholder"], C)?; super::color_param(p, "color", C)?; - let style = super::create::new_type_style(s, p); + let style = super::create::new_type_style(s, p, C)?; let text = str_param(p, "text").unwrap_or("").to_string(); let start = match point_param(p, "at") { Some(at) if on_path => vectorcraft_geom::ArcPath::new(path).fraction_at(at).unwrap_or(0.0), @@ -1694,17 +1754,16 @@ pub(crate) fn editing_story(s: &Session) -> Vec<NodeId> { s.active().map(|st| super::threads::story_of(&st.doc, id)).unwrap_or_default() } +/// A text range a type shortcut changes: its type object, its bytes, and the caret's byte when it +/// came from a caret ([`type_ranges`]). +pub(crate) type TypeRange = (NodeId, usize, usize, Option<usize>); + /// The text ranges a type shortcut changes: the range of `id`, else all the text of the type /// objects in `ids`, else the text the Type tool has selected (all the text of every frame of the /// story after Select All in threaded text, [`editing_story`]), else all the text of every selected /// type object. At a caret, `at_caret` gives the range from the plain text and the caret's byte -/// (None: nothing changes there). Each range comes with whether it came from a caret. -pub(crate) fn type_ranges( - s: &mut Session, - p: &Value, - c: &str, - at_caret: impl Fn(&str, usize) -> Option<(usize, usize)>, -) -> Result<Vec<(NodeId, usize, usize, bool)>> { +/// (None: nothing changes there). Each range comes with the caret's byte when it came from a caret. +pub(crate) fn type_ranges(s: &mut Session, p: &Value, c: &str, at_caret: impl Fn(&str, usize) -> Option<(usize, usize)>) -> Result<Vec<TypeRange>> { // (text, its range; None: all of it). let targets: Vec<(NodeId, Option<(usize, usize)>)> = match super::object_param(p, "id", c)? { // An object that isn't type is refused as `ids` of it is. @@ -1728,10 +1787,10 @@ pub(crate) fn type_ranges( let text = text_ref(s, id)?.plain_text(); let (a, b) = range.map_or((0, text.len()), |(a, b)| (a.min(text.len()), b.min(text.len()))); let (a, b, caret) = if a < b { - (a, b, false) + (a, b, None) } else { match at_caret(&text, a) { - Some((a, b)) => (a, b, true), + Some((x, y)) => (x, y, Some(a)), None => continue, } }; @@ -1763,24 +1822,31 @@ fn type_step(s: &mut Session, p: &Value) -> Result<Value> { Step::Tracking | Step::Kerning => prefs.tracking_increment, Step::BaselineShift => prefs.baseline_shift_increment, }; - // The ranges stepped. At a caret: kerning is the space after the character before it, leading - // the paragraph's; the rest wait for a selection. + // The ranges stepped. At a caret: kerning is the space after the character before it, or at + // the start of a line the space before the character after it (#5111), leading the + // paragraph's; the rest wait for a selection. let ranges = type_ranges(s, p, C, |text, a| match step { - Step::Kerning => Some((edit::prev_char(text, a), a)), + Step::Kerning => edit::caret_kerning_target(text, a).map(|(r, _)| (r.start, r.end)), Step::Leading => { let para = edit::paragraph_at(text, a); Some((para.start, para.end)) } _ => None, })?; + // At a caret, the kerning stepped: (whether it is the space before the character, its value). let mut caret_kerning = Vec::with_capacity(ranges.len()); for &(id, a, b, caret) in &ranges { - let value = if matches!(step, Step::Kerning) && caret { - let t = text_ref(s, id)?; - let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); - Some(effective_kerning(vectorcraft_text::FontDb::global(), &t, &lay, a, b)) - } else { - None + let value = match caret { + Some(c) if matches!(step, Step::Kerning) => { + let t = text_ref(s, id)?; + if edit::caret_kerning_target(&t.plain_text(), c).is_some_and(|(_, before)| before) { + Some((true, edit::style_at(&t.runs, a + 1).kerning_before)) + } else { + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + Some((false, effective_kerning(vectorcraft_text::FontDb::global(), &t, &lay, a, b))) + } + } + _ => None, }; caret_kerning.push(value); } @@ -1829,10 +1895,13 @@ fn type_step(s: &mut Session, p: &Value) -> Result<Value> { st.leading = Some(super::typecmd::local_type_value(t, leading * points + inc, (0.1, 5000.0), false, C)?); } Step::Tracking => st.tracking = (st.tracking + inc).clamp(-1000.0, 10000.0), - Step::Kerning => { - let current = caret_kerning.get(range_index).copied().flatten().unwrap_or_else(|| st.kerning.unwrap_or(0.0)); - st.kerning = Some((current + inc).clamp(-1000.0, 10000.0)); - } + Step::Kerning => match caret_kerning.get(range_index).copied().flatten() { + Some((true, current)) => st.kerning_before = (current + inc).clamp(-1000.0, 10000.0), + caret => { + let current = caret.map_or_else(|| st.kerning.unwrap_or(0.0), |(_, v)| v); + st.kerning = Some((current + inc).clamp(-1000.0, 10000.0)); + } + }, Step::BaselineShift => { st.baseline_shift = super::typecmd::local_type_value(t, st.baseline_shift * points + inc, (-1296.0, 1296.0), false, C)?; } @@ -1849,17 +1918,22 @@ fn type_step(s: &mut Session, p: &Value) -> Result<Value> { /// Cmd/Ctrl+Alt+Q: tracking 0 and manual kerning cleared in the type objects in /// `ids`, else in the Type tool's selected text, else in every selected type object. At a caret, -/// only the kerning of the character before it changes, as Alt+←/→ in horizontal type or Alt+↓/↑ in vertical type kerns there. -/// The automatic method remains selected. +/// only the kerning there changes, as Alt+←/→ in horizontal type or Alt+↓/↑ in vertical type kerns +/// there: of the character before it, or at the start of a line the space before the character +/// after it ([`edit::caret_kerning_target`]). The automatic method remains selected. fn reset_tracking(s: &mut Session, p: &Value) -> Result<Value> { - let ranges = type_ranges(s, p, "type.resetTracking", |text, a| Some((edit::prev_char(text, a), a)))?; + let ranges = type_ranges(s, p, "type.resetTracking", |text, a| edit::caret_kerning_target(text, a).map(|(r, _)| (r.start, r.end)))?; if !ranges.is_empty() { s.edit("Reset Tracking and Kerning", |d, _| { for &(id, a, b, caret) in &ranges { let t = text_mut(d, id).ok_or(EngineError::NoNode(id))?; - edit::style_range(&mut t.runs, a, b, |st| { - st.kerning = None; - if !caret { + let before = caret.and_then(|c| edit::caret_kerning_target(&t.plain_text(), c)).map(|(_, before)| before); + edit::style_range(&mut t.runs, a, b, |st| match before { + Some(true) => st.kerning_before = 0.0, + Some(false) => st.kerning = None, + None => { + st.kerning = None; + st.kerning_before = 0.0; st.tracking = 0.0; } }); @@ -1975,7 +2049,7 @@ fn fit_headline(s: &mut Session, p: &Value) -> Result<Value> { fn discard_empty(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "text.discardEmpty"; - let id = id_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?; if edit::runs_len(&text_ref(s, id)?.runs) > 0 { return Ok(json!({"removed": false})); } diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index d30e69df68..8134976144 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -8,7 +8,7 @@ use serde::Serialize; use serde::de::DeserializeOwned; use serde_json::{Map, Value, json}; -use vectorcraft_doc::{CharStyle, Document, Node, NodeId, NodeKind, ParaStyle, TextStyleDef}; +use vectorcraft_doc::{CharStyle, Document, Node, NodeId, NodeKind, ParaStyle, TabStop, TextStyleDef}; use super::clipboard::resources::import_text_styles; use super::typecmd::{refresh_bounds, text_targets}; @@ -125,7 +125,7 @@ macro_rules! style_cmds { } /// The params of `charStyle.load`, `paraStyle.load` and `textStyle.loadAll`. -const LOAD_PARAMS: &str = "{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} copy the styles of this kind (textStyle.loadAll: character and paragraph styles) from a document VectorCraft opens (see document.formats) into this one, after its own, in one undo step, with the swatches and patterns they paint with, the symbols and brushes those patterns use, and the styles of either kind that type in those patterns and symbols is set in, as Paste brings those of pasted type (a global or spot color whose name this document gives another color is this document's). A style that is the same as the style here of its name, or of its name with a number (`Body 2`), isn't added again; any other is added under a free name (`Body 2`). The file's Normal styles aren't loaded, and a style whose attributes don't read or are out of the range charStyle.new takes, or whose name is empty, is skipped → {added: [names here], existing: [names already here], skipped: [names in the file]} (textStyle.loadAll: {charStyles: {…}, paraStyles: {…}}); charStyle.load and paraStyle.load list only the styles of their own kind"; +const LOAD_PARAMS: &str = "{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} copy the styles of this kind (textStyle.loadAll: character and paragraph styles) from a document VectorCraft opens (see document.formats) into this one, after its own, in one undo step, with the swatches and patterns they paint with, the symbols and brushes those patterns use, and the styles of either kind that type in those patterns and symbols is set in, as Paste brings those of pasted type (a global or spot color whose name this document gives another color is this document's). A style that is the same as the style here of its name, or of its name with a number (`Body 2`), isn't added again; any other is added under a free name (`Body 2`). The file's Normal styles aren't loaded, and a style whose attributes don't read or are out of the range charStyle.new or paraStyle.new takes, or whose name is empty, is skipped → {added: [names here], existing: [names already here], skipped: [names in the file]} (textStyle.loadAll: {charStyles: {…}, paraStyles: {…}}); charStyle.load and paraStyle.load list only the styles of their own kind"; pub fn specs() -> Vec<CommandSpec> { let mut v = style_cmds!( @@ -148,13 +148,13 @@ pub fn specs() -> Vec<CommandSpec> { "paraStyle", "Paragraph Styles", "Paragraph", - "; changed numeric attrs: indents, space_before and space_after -1296..=1296 pt; hyphenation words_longer_than 1..=25, after_first and before_last 1..=15, hyphen_limit 0..=25, zone 0..=1296 pt; justification word_spacing 0..=1000%, letter_spacing -100..=500%, glyph_scaling 50..=200% (each [min, desired, max] in order), auto_leading 0..=500%; tab positions 0..=100000 pt" + "; changed numeric attrs: indents, space_before and space_after -1296..=1296 pt; hyphenation words_longer_than 1..=25, after_first and before_last 1..=15, hyphen_limit 0..=25, zone 0..=1296 pt; justification word_spacing 0..=1000%, letter_spacing -100..=500%, glyph_scaling 50..=200% (each [min, desired, max] in order), auto_leading 0..=500%; changed tabs: at most 256 stops, each changed stop's position 0..=100000 pt and leader at most 8 characters, sorted by position keeping the first of stops at one position" )); v.push(spec( "paraStyle.edit", "Edit Paragraph Style", &[], - "{name, to, attrs: {…}} replace name and sparse attributes in one undo step; users keep local overrides; changed numeric attrs: indents, space_before and space_after -1296..=1296 pt; hyphenation words_longer_than 1..=25, after_first and before_last 1..=15, hyphen_limit 0..=25, zone 0..=1296 pt; justification word_spacing 0..=1000%, letter_spacing -100..=500%, glyph_scaling 50..=200% (each [min, desired, max] in order), auto_leading 0..=500%; tab positions 0..=100000 pt", + "{name, to, attrs: {…}} replace name and sparse attributes in one undo step; users keep local overrides; changed numeric attrs: indents, space_before and space_after -1296..=1296 pt; hyphenation words_longer_than 1..=25, after_first and before_last 1..=15, hyphen_limit 0..=25, zone 0..=1296 pt; justification word_spacing 0..=1000%, letter_spacing -100..=500%, glyph_scaling 50..=200% (each [min, desired, max] in order), auto_leading 0..=500%; changed tabs: at most 256 stops, each changed stop's position 0..=100000 pt and leader at most 8 characters, sorted by position keeping the first of stops at one position", |s, p| edit_style(s, p, Kind::Para), true, )); @@ -188,8 +188,10 @@ fn to_attrs<T: Serialize>(v: &T) -> Map<String, Value> { /// from a style instead leaves the text's own value alone. pub fn char_attrs(v: &CharStyle) -> Map<String, Value> { let mut m = to_attrs(v); - // A chosen glyph belongs to one character, not to a reusable character style. + // A chosen glyph belongs to one character, and the space before a line's first character to + // where it stands (#5111), not to a reusable character style. m.remove("glyphAlternate"); + m.remove("kerningBefore"); for (k, x) in [ ("font_version", json!(v.font_version)), ("fontAxes", json!(v.font_axes)), @@ -213,6 +215,8 @@ pub fn char_attrs(v: &CharStyle) -> Map<String, Value> { ("tateChuYoko", json!(v.tate_chu_yoko)), ("tcyUpDown", json!(v.tcy_up_down)), ("tcyLeftRight", json!(v.tcy_left_right)), + ("akiLeft", json!(v.aki_left)), + ("akiRight", json!(v.aki_right)), ("standardVerticalRoman", json!(v.standard_vertical_roman)), ("noBreak", json!(v.no_break)), ("digits", json!(v.digits)), @@ -241,8 +245,10 @@ pub fn para_attrs(v: &ParaStyle) -> Map<String, Value> { ("burasagari", json!(v.burasagari)), ("kinsoku", json!(v.kinsoku)), ("kinsoku_type", json!(v.kinsoku_type)), + ("bunri_kinshi", json!(v.bunri_kinshi)), ("roman_hanging", json!(v.roman_hanging)), ("kashida", json!(v.kashida)), + ("korean_line_break_anywhere", json!(v.korean_line_break_anywhere)), ] { m.insert(k.into(), x); } @@ -500,6 +506,13 @@ pub(crate) fn style_attrs(d: &Document, para: bool, name: &str) -> Option<Map<St if para { Kind::Para } else { Kind::Char }.attrs(d, name) } +/// `attrs` in the form `charStyle.new` (`para`: `paraStyle.new`) stores them in `d`, or `None` +/// when they don't pass its checks. +pub(crate) fn stored_style_attrs(d: &Document, para: bool, attrs: &Map<String, Value>) -> Option<Map<String, Value>> { + let kind = if para { Kind::Para } else { Kind::Char }; + attrs_param(d, &json!({ "attrs": attrs }), kind, "new", None).ok().flatten() +} + /// The name `charStyle.new` (`para`: `paraStyle.new`) gives a style when it is given none: the /// first "Character Style N" ("Paragraph Style N") that no character style (paragraph style) of the /// document has. @@ -530,6 +543,12 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma if m.contains_key("glyphAlternate") { return Err(bad(&c, "`glyphAlternate` belongs to one character, not to a character style (text.setGlyphAlternate sets it)")); } + if m.contains_key("kerningBefore") { + return Err(bad( + &c, + "`kerningBefore` belongs to a line's first character, not to a character style (text.setRangeStyle sets it)", + )); + } let mut st = with_attrs(&CharStyle::default(), m, &c)?; let changed = |key: &str| m.contains_key(key) && kept.and_then(|k| k.get(key)) != m.get(key); for (key, value, lo, hi) in @@ -548,6 +567,12 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma return Err(bad(&c, format!("`{key}` must be from {} to {shift_max}", -shift_max))); } } + let (lo, hi) = (0.0, vectorcraft_doc::text::MAX_AKI); + for (key, value) in [("akiLeft", st.aki_left), ("akiRight", st.aki_right)] { + if changed(key) && !(lo..=hi).contains(&value) { + return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}"))); + } + } // A language of the list, stored as its tag (as text.setFormat takes it). if let Some(l) = &st.language && kept.and_then(|k| k.get("language")) != m.get("language") @@ -569,8 +594,9 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma char_attrs(&st) } Kind::Para => { - let st = with_attrs(&ParaStyle::default(), m, &c)?; + let mut st = with_attrs(&ParaStyle::default(), m, &c)?; para_ranges(&st, m, kept, &c)?; + sort_tabs(&mut st, m, kept); para_attrs(&st) } }; @@ -587,7 +613,8 @@ const PARA_DISTANCE: f64 = 1296.0; /// Check the paragraph attributes of `st` (read from `attrs`) that differ from `kept` against the /// ranges `text.setFormat` keeps them to: the indents and the space before and after, each /// Hyphenation option, each Justification option (Minimum, Desired and Maximum in order, as -/// `attrs` gives them) and the position of each tab stop. A value `kept` has is not checked. +/// `attrs` gives them), and the number of tab stops with the position and leader of each stop +/// `kept` does not hold. A value `kept` has is not checked. fn para_ranges(st: &ParaStyle, attrs: &Map<String, Value>, kept: Option<&Map<String, Value>>, c: &str) -> Result<()> { let within = |key: &str, value: f64, lo: f64, hi: f64| { if (lo..=hi).contains(&value) { Ok(()) } else { Err(bad(c, format!("`{key}` must be from {lo} to {hi}"))) } @@ -644,18 +671,37 @@ fn para_ranges(st: &ParaStyle, attrs: &Map<String, Value>, kept: Option<&Map<Str } } if changed("tabs") { - let kept_tabs: Vec<f64> = kept - .and_then(|k| k.get("tabs")) - .and_then(Value::as_array) - .map(|stops| stops.iter().filter_map(|s| s.get("position").and_then(Value::as_f64)).collect()) - .unwrap_or_default(); - for stop in st.tabs.iter().filter(|stop| !kept_tabs.contains(&stop.position)) { - within("tabs.position", stop.position, 0.0, 100_000.0)?; + let kept_tabs = kept_tab_stops(kept); + let max = TabStop::MAX_STOPS; + if st.tabs.len() > max.max(kept_tabs.len()) { + return Err(bad(c, format!("at most {max} tab stops"))); + } + for stop in st.tabs.iter().filter(|stop| !kept_tabs.contains(stop)) { + within("tabs.position", stop.position, 0.0, TabStop::MAX_POSITION)?; + let (label, max) = ("`tabs.leader`", TabStop::MAX_LEADER); + if stop.leader.chars().count() > max { + return Err(bad(c, format!("{label} must be at most {max} characters"))); + } } } Ok(()) } +/// The tab stops `kept` holds, each as it reads (a stop that does not read is left out). +fn kept_tab_stops(kept: Option<&Map<String, Value>>) -> Vec<TabStop> { + let stops = kept.and_then(|k| k.get("tabs")).and_then(Value::as_array); + stops.into_iter().flatten().filter_map(|s| serde_json::from_value(s.clone()).ok()).collect() +} + +/// `st`'s tab stops sorted by position, keeping the first of stops within 1e-6 pt of each other, +/// as `text.tabs.set` keeps them, when `attrs` changes them from `kept`. +fn sort_tabs(st: &mut ParaStyle, attrs: &Map<String, Value>, kept: Option<&Map<String, Value>>) { + if attrs.contains_key("tabs") && kept.and_then(|k| k.get("tabs")) != attrs.get("tabs") { + st.tabs.sort_by(|a, b| a.position.total_cmp(&b.position)); + st.tabs.dedup_by(|a, b| (a.position - b.position).abs() < 1e-6); + } +} + /// Check a character style's `fill` or `stroke` (`key`): each solid color and gradient stop has a /// tint from 0 to 1, and a link to a global swatch of `d`, whose color at that tint it takes. fn style_paint(d: &Document, paint: &mut vectorcraft_color::Paint, key: &str, c: &str) -> Result<()> { @@ -1011,10 +1057,31 @@ fn unused(s: &mut Session, kind: Kind) -> Result<Value> { /// The styles of `kind` in `src` that load, with their source names so that art in the file keeps /// referring to them: not the Normal style, and not one whose attributes don't read, whose sizes, -/// scales, leading, shifts or stroke width are out of the range `charStyle.new` takes, or whose name -/// is empty, which are skipped. → (the styles, the names in `src` of those skipped) +/// scales, leading, shifts, Insert Aki or stroke width are out of the range `charStyle.new` takes, whose +/// indents, spacing, Hyphenation or Justification options or tab stops are out of the range +/// `paraStyle.new` takes, or whose name is empty, which are skipped. → (the styles, the names in +/// `src` of those skipped) fn loadable(src: &Document, kind: Kind) -> (Vec<TextStyleDef>, Vec<String>) { - const RANGED: [&str; 8] = ["size", "h_scale", "v_scale", "leading", "baseline_shift", "tcyUpDown", "tcyLeftRight", "stroke_width"]; + const RANGED: [&str; 18] = [ + "size", + "h_scale", + "v_scale", + "leading", + "baseline_shift", + "akiLeft", + "akiRight", + "tcyUpDown", + "tcyLeftRight", + "stroke_width", + "left_indent", + "right_indent", + "first_line_indent", + "space_before", + "space_after", + "hyphenation", + "justification", + "tabs", + ]; let (mut defs, mut skipped) = (vec![], vec![]); for def in kind.defs(src) { let name = def.name.as_str(); diff --git a/crates/engine/src/cmd/textstyles/tests.rs b/crates/engine/src/cmd/textstyles/tests.rs index 87bca29048..188f2ed49e 100644 --- a/crates/engine/src/cmd/textstyles/tests.rs +++ b/crates/engine/src/cmd/textstyles/tests.rs @@ -309,12 +309,12 @@ fn character_style_color_and_features_reach_text_and_follow_swatch_edits() { // The command takes the color of the link at the tint, whatever color is sent. tinted["tint"] = json!(0.4); let attrs = json!({"fill": brand, "stroke": tinted, "stroke_width": 2.0, "overprint_fill": true, "overprint_stroke": false, - "features": ["dlig", "-liga", "tnum", "lnum", "-onum", "-pnum", "ss02", "-ss01"]}); + "features": ["dlig", "-liga", "tnum", "lnum", "-onum", "-pnum", "ss02", "-ss01", "salt=2"]}); s.execute("charStyle.new", &json!({"name": "Ink", "attrs": attrs})).unwrap(); s.execute("charStyle.apply", &json!({"name": "Ink", "id": id})).unwrap(); let want_stroke = s.doc().unwrap().doc.tint_paint("Brand", 0.4).unwrap(); assert_eq!(run_paints(&s, id), (brand, want_stroke.clone(), 2.0, true, false)); - assert_eq!(runs(&s, id)[0].style.features, ["dlig", "-liga", "tnum", "lnum", "-onum", "-pnum", "ss02", "-ss01"]); + assert_eq!(runs(&s, id)[0].style.features, ["dlig", "-liga", "tnum", "lnum", "-onum", "-pnum", "ss02", "-ss01", "salt=2"]); let def = |s: &Session| s.doc().unwrap().doc.char_styles.iter().find(|d| d.name == "Ink").unwrap().attrs.clone(); assert_eq!(def(&s)["stroke"], serde_json::to_value(&want_stroke).unwrap()); let saved = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); @@ -355,6 +355,8 @@ fn character_style_color_and_features_are_checked() { (json!({"stroke_width": 5.0e6}), "`stroke_width` must be from 0 to 4000000"), (json!({"features": ["dlig", "zzzz"]}), "unknown OpenType feature `zzzz`"), (json!({"features": ["--liga"]}), "unknown OpenType feature `--liga`"), + (json!({"features": ["salt=x"]}), "unknown OpenType feature `salt=x`"), + (json!({"features": ["-salt=2"]}), "unknown OpenType feature `-salt=2`"), (json!({"features": many}), "features lists at most 256 tags"), (json!({"fill": {"type": "solid"}}), "missing field"), ] { @@ -393,6 +395,8 @@ fn character_style_dimensions_are_checked_before_a_definition_changes() { json!({"baseline_shift": 1296.1}), json!({"tcyUpDown": 1296.1}), json!({"tcyLeftRight": -1296.1}), + json!({"akiLeft": -0.1}), + json!({"akiRight": 1000.1}), ] { let key = attrs.as_object().unwrap().keys().next().unwrap(); for cmd in ["charStyle.edit", "charStyle.setAttrs", "charStyle.new"] { @@ -414,7 +418,8 @@ fn character_style_dimensions_are_checked_before_a_definition_changes() { "size": 1296.0, "leading": 5000.0, "h_scale": 1.0, "v_scale": 10000.0, "baseline_shift": -1296.0, - "tcyUpDown": 1296.0, "tcyLeftRight": -1296.0 + "tcyUpDown": 1296.0, "tcyLeftRight": -1296.0, + "akiLeft": 0.0, "akiRight": 1000.0 }}), ) .unwrap(); @@ -1336,7 +1341,8 @@ fn para_style_redefined_to_the_defaults_updates_its_paragraphs() { /// The same for character styles: Auto kerning and the Roman baseline alignment, which the /// run's JSON leaves out, are captured and reach the style's users. A glyph choice belongs to -/// one character, so it is not a reusable style attribute. +/// one character, and the space before a line's first character to where it stands (#5111), so +/// neither is a reusable style attribute. #[test] fn char_style_redefined_to_the_defaults_updates_its_text() { use vectorcraft_doc::CharAlign; @@ -1356,6 +1362,7 @@ fn char_style_redefined_to_the_defaults_updates_its_text() { assert_eq!((kerning(&s), aligns(&s)), ([None, None, Some(60.0)], [CharAlign::RomanBaseline; 3])); let mut reusable = settable::<CharStyle>(); reusable.remove("glyphAlternate"); + reusable.remove("kerningBefore"); assert_eq!(defined(&s, 0), reusable, "Redefine captures every reusable attribute"); s.execute("charStyle.new", &json!({"name": "Copy", "id": local})).unwrap(); assert_eq!(defined(&s, 1), reusable, "New captures every reusable attribute"); @@ -1729,3 +1736,77 @@ fn paragraph_style_attributes_are_checked_before_a_definition_changes() { assert!(error.contains(&format!("`{key}`")), "{attrs}: {error}"); } } + +/// A paragraph style's changed tab stops are checked stop by stop: a stop the style holds is kept +/// as it is, and a stop at a held position with another alignment is a changed stop. A changed +/// stop's leader has at most eight characters and its Align On one character, a changed list has +/// at most 256 stops (or as many as the style holds, here 300), and the stops are stored sorted by position, +/// keeping the first of stops at one position. +#[test] +fn paragraph_style_tab_stops_are_checked_by_stop_and_sorted() { + let (mut s, _) = session_with_text("Text"); + s.execute("paraStyle.new", &json!({"name": "Body", "attrs": {}})).unwrap(); + let def = |s: &Session| s.doc().unwrap().doc.para_styles.iter().find(|d| d.name == "Body").unwrap().attrs.clone(); + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let held: Vec<Value> = + (0..300).map(|i| json!({"position": 200000.0 + f64::from(i), "align": "left", "leader": "123456789", "alignOn": "."})).collect(); + doc.para_styles.iter_mut().find(|d| d.name == "Body").unwrap().attrs.insert("tabs".into(), Value::from(held.clone())); + let before = s.doc().unwrap().doc.clone(); + let mut moved = held.clone(); + moved[0]["align"] = json!("right"); + for (stops, why) in [ + (Value::from(moved), "`tabs.position`"), + (json!([{"position": 36.0, "leader": "123456789"}]), "`tabs.leader` must be at most 8 characters"), + (Value::from((0..301).map(|i| json!({"position": f64::from(i)})).collect::<Vec<_>>()), "at most 256 tab stops"), + (json!([{"position": 36.0, "alignOn": ",."}]), "expected a character"), + ] { + for cmd in ["paraStyle.edit", "paraStyle.setAttrs"] { + let params = match cmd { + "paraStyle.edit" => json!({"name": "Body", "to": "Body", "attrs": {"tabs": stops}}), + _ => json!({"name": "Body", "attrs": {"tabs": stops}}), + }; + let error = s.execute(cmd, ¶ms).unwrap_err().to_string(); + assert!(error.contains(why), "{cmd}: {error}"); + } + } + let many = Value::from((0..257).map(|i| json!({"position": f64::from(i)})).collect::<Vec<_>>()); + let error = s.execute("paraStyle.new", &json!({"name": "Other", "attrs": {"tabs": many}})).unwrap_err().to_string(); + assert!(error.contains("at most 256 tab stops"), "{error}"); + assert_eq!(s.doc().unwrap().doc, before); + // The held stops stay while one is dropped and another attribute changes. + s.execute("paraStyle.setAttrs", &json!({"name": "Body", "attrs": {"tabs": &held[1..], "left_indent": 4.0}})).unwrap(); + assert_eq!(def(&s)["tabs"].as_array().map(Vec::len), Some(299)); + let stops = json!([{"position": 72.0, "align": "right"}, {"position": 36.0}, {"position": 36.0000001, "align": "center"}, {"position": 0.0, "leader": "12345678"}]); + s.execute("paraStyle.setAttrs", &json!({"name": "Body", "attrs": {"tabs": stops}})).unwrap(); + assert_eq!( + def(&s)["tabs"], + json!([{"position": 0.0, "align": "left", "leader": "12345678", "alignOn": "."}, {"position": 36.0, "align": "left", "alignOn": "."}, + {"position": 72.0, "align": "right", "alignOn": "."}]) + ); + s.execute("paraStyle.setAttrs", &json!({"name": "Body", "attrs": {"tabs": []}})).unwrap(); + assert_eq!(def(&s)["tabs"], json!([]), "an empty list stays set"); +} + +/// Load Paragraph Styles and Load All Styles skip a paragraph style whose indents, spacing, +/// Hyphenation or Justification options or tab stops are out of the range `paraStyle.new` takes, +/// and load the others with their stops. +#[test] +fn loading_skips_paragraph_styles_out_of_range() { + let file = [ + ("Good", json!({"left_indent": 6.0, "tabs": [{"position": 36.0, "align": "decimal", "alignOn": ","}]})), + ("Indent", json!({"left_indent": 2000.0})), + ("Space", json!({"space_after": -1300.0})), + ("Hyphens", json!({"hyphenation": {"words_longer_than": 40}})), + ("Spacing", json!({"justification": {"word_spacing": [120.0, 100.0, 133.0]}})), + ("Leader", json!({"tabs": [{"position": 10.0, "leader": "123456789"}]})), + ]; + let data = styles_file(&[], &file); + for cmd in ["paraStyle.load", "textStyle.loadAll"] { + let (mut s, _) = session_with_text("Title"); + let r = s.execute(cmd, &json!({"dataBase64": data, "name": "Other.vectorcraft"})).unwrap(); + let r = if cmd == "textStyle.loadAll" { r["paraStyles"].clone() } else { r }; + assert_eq!(r, json!({"added": ["Good"], "existing": [], "skipped": ["Indent", "Space", "Hyphens", "Spacing", "Leader"]}), "{cmd}"); + let good = super::style_attrs(&s.doc().unwrap().doc, true, "Good").unwrap(); + assert_eq!(good["tabs"], json!([{"position": 36.0, "align": "decimal", "alignOn": ","}]), "{cmd}"); + } +} diff --git a/crates/engine/src/cmd/threads.rs b/crates/engine/src/cmd/threads.rs index 6c80c962d6..c1c3801e40 100644 --- a/crates/engine/src/cmd/threads.rs +++ b/crates/engine/src/cmd/threads.rs @@ -135,6 +135,7 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) { let mut story: Vec<TextRun> = vec![]; let mut sources: Vec<TextObject> = vec![]; let mut later_wins = vec![]; + let mut earlier_wins = vec![]; let mut live = vec![]; for id in &thread { match (text_of(doc, *id), text_of(before, *id)) { @@ -143,6 +144,9 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) { // A frame whose first paragraph was just restyled gives the paragraph it // shares with the frame before it that style. later_wins.push(old.is_some_and(|o| o.para_at(0) != t.para_at(0))); + // A frame whose last paragraph was just restyled keeps that style in the + // paragraph it shares with the frame after it, even when it is empty. + earlier_wins.push(old.is_some_and(|o| o.para_at(o.paragraph_count() - 1) != t.para_at(t.paragraph_count() - 1))); sources.push(t.clone()); live.push(*id); } @@ -151,6 +155,7 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) { (None, Some(old)) => { story.extend(old.runs.iter().cloned()); later_wins.push(false); + earlier_wins.push(false); sources.push(old.clone()); } (None, None) => {} @@ -160,7 +165,7 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) { continue; } let source_refs: Vec<&TextObject> = sources.iter().collect(); - let paras = vectorcraft_text::thread::story_paras(&source_refs, &later_wins); + let paras = vectorcraft_text::thread::story_paras_restyled(&source_refs, &later_wins, &earlier_wins); vectorcraft_text::edit::normalize(&mut story); if live.len() >= 2 { // Threaded frames keep their size: Auto Size is off for them (as in Illustrator). diff --git a/crates/engine/src/cmd/threads/tests.rs b/crates/engine/src/cmd/threads/tests.rs index 48a1e46fbc..a622901c01 100644 --- a/crates/engine/src/cmd/threads/tests.rs +++ b/crates/engine/src/cmd/threads/tests.rs @@ -60,6 +60,130 @@ fn a_restyled_empty_frame_keeps_its_style_before_an_unedited_empty_frame() { assert_eq!([hyphenates(a, 0), hyphenates(a, 1), hyphenates(b, 0), hyphenates(c, 0)], [false, true, true, true]); } +/// Every paragraph's left indent in frame `id`. +fn left_indents(s: &Session, id: u64) -> Vec<f64> { + match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.paragraph_styles().iter().map(|p| p.left_indent).collect(), + _ => panic!("not text"), + } +} + +/// Area type `height` high holding `text`, threaded into `empties` empty rectangles after it. +fn tail_thread(text: &str, height: f64, empties: usize) -> (Session, Vec<u64>) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 300})).unwrap(); + let a = new_id(s.execute("text.create", &json!({"x": 10, "y": 10, "text": text, "area": {"width": 150, "height": height}})).unwrap()); + let mut ids = vec![a]; + for k in 0..empties { + let x = 200.0 * (k + 1) as f64; + ids.push(new_id(s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 150, "height": 60})).unwrap())); + } + s.execute("select.set", &json!({"ids": ids})).unwrap(); + s.execute("text.thread.create", &json!({})).unwrap(); + (s, ids) +} + +/// Restyling a frame's empty last paragraph (after its final paragraph break) gives that +/// paragraph the style in the next frame as well, instead of the next frame's old style. +#[test] +fn editing_a_frames_empty_last_paragraph_survives_thread_reflow() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 300})).unwrap(); + let a = + s.execute("text.create", &json!({"x": 10, "y": 10, "text": "a\n", "area": {"width": 150, "height": 60}})).unwrap()["id"].as_u64().unwrap(); + let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": 60})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + s.execute("text.thread.create", &json!({})).unwrap(); + assert_eq!([text(&s, a), text(&s, b)], ["a\n", ""]); + let steps = s.doc().unwrap().history.undo.len(); + s.execute("text.setFormat", &json!({"ids": [a], "start": 2, "end": 2, "leftIndent": 30})).unwrap(); + assert_eq!((left_indents(&s, a), left_indents(&s, b)), (vec![0.0, 30.0], vec![30.0])); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); + // The same format again changes nothing and records no undo step. + s.execute("text.setFormat", &json!({"ids": [a], "start": 2, "end": 2, "leftIndent": 30})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((left_indents(&s, a), left_indents(&s, b)), (vec![0.0, 0.0], vec![0.0])); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!((left_indents(&s, a), left_indents(&s, b)), (vec![0.0, 30.0], vec![30.0])); + s.execute("edit.undo", &json!({})).unwrap(); + + // A format of the whole frame changes its last paragraph as well. + s.execute("text.setFormat", &json!({"ids": [a], "leftIndent": 20})).unwrap(); + assert_eq!((left_indents(&s, a), left_indents(&s, b)), (vec![20.0, 20.0], vec![20.0])); + // Both frames formatted in one command agree. + s.execute("text.setFormat", &json!({"ids": [a, b], "leftIndent": 40})).unwrap(); + assert_eq!((left_indents(&s, a), left_indents(&s, b)), (vec![40.0, 40.0], vec![40.0])); +} + +/// The restyled empty last paragraph keeps its style when the next frame holds text that +/// continues it, and across an unedited empty frame; a later restyle of a later frame still wins. +#[test] +fn a_restyled_empty_last_paragraph_keeps_its_style_against_later_frames() { + // One line high: the text added to the next frame stays there. + let (mut s, ids) = tail_thread("a\n", 20.0, 1); + let (a, b) = (ids[0], ids[1]); + s.execute("text.editRange", &json!({"id": b, "start": 0, "end": 0, "insert": "def"})).unwrap(); + assert_eq!([text(&s, a), text(&s, b)], ["a\n", "def"]); + s.execute("text.setFormat", &json!({"ids": [a], "start": 2, "end": 2, "leftIndent": 30})).unwrap(); + assert_eq!([text(&s, a), text(&s, b)], ["a\n", "def"]); + assert_eq!((left_indents(&s, a), left_indents(&s, b)), (vec![0.0, 30.0], vec![30.0])); + + let (mut s, ids) = tail_thread("a\n", 60.0, 2); + s.execute("text.setFormat", &json!({"ids": [ids[0]], "start": 2, "end": 2, "leftIndent": 30})).unwrap(); + assert_eq!(ids.iter().map(|id| left_indents(&s, *id)).collect::<Vec<_>>(), [vec![0.0, 30.0], vec![30.0], vec![30.0]]); + s.execute("text.setFormat", &json!({"ids": [ids[2]], "leftIndent": 10})).unwrap(); + assert_eq!(ids.iter().map(|id| left_indents(&s, *id)).collect::<Vec<_>>(), [vec![0.0, 10.0], vec![10.0], vec![10.0]]); +} + +/// The restyled last paragraph keeps its style with type on a path on either side of the boundary. +#[test] +fn a_restyled_empty_last_paragraph_flows_onto_type_on_a_path() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 300})).unwrap(); + let a = new_id(s.execute("text.create", &json!({"x": 10, "y": 10, "text": "a\n", "area": {"width": 150, "height": 60}})).unwrap()); + let on_path = type_on_a_line(&mut s); + s.execute("text.thread.add", &json!({"from": a, "to": on_path})).unwrap(); + assert_eq!([text(&s, a), text(&s, on_path)], ["a\n", ""]); + s.execute("text.setFormat", &json!({"ids": [a], "start": 2, "end": 2, "leftIndent": 30})).unwrap(); + assert_eq!((left_indents(&s, a), left_indents(&s, on_path)), (vec![0.0, 30.0], vec![30.0])); + + // Type on a path before area type. + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 300})).unwrap(); + let on_path = type_on_a_line(&mut s); + s.execute("text.editRange", &json!({"id": on_path, "start": 0, "end": 0, "insert": "a\n"})).unwrap(); + let b = new_id(s.execute("shape.rectangle", &json!({"x": 400, "y": 10, "width": 150, "height": 60})).unwrap()); + s.execute("text.thread.add", &json!({"from": on_path, "to": b})).unwrap(); + assert_eq!([text(&s, on_path), text(&s, b)], ["a\n", ""]); + s.execute("text.setFormat", &json!({"ids": [on_path], "start": 2, "end": 2, "leftIndent": 30})).unwrap(); + assert_eq!((left_indents(&s, on_path), left_indents(&s, b)), (vec![0.0, 30.0], vec![30.0])); +} + +/// A restyled empty last paragraph in a numbered list is counted once, and the next frame's +/// first paragraph does not continue the paragraph before the break. +#[test] +fn a_restyled_empty_last_list_paragraph_keeps_the_counts() { + let (mut s, ids) = tail_thread("One\nTwo\n", 60.0, 1); + let (a, b) = (ids[0], ids[1]); + s.execute("text.setFormat", &json!({"ids": [a, b], "list": "number"})).unwrap(); + s.execute("text.setFormat", &json!({"ids": [a], "start": 8, "end": 8, "leftIndent": 30})).unwrap(); + let doc = &s.doc().unwrap().doc; + let frame = |id| match &doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => (**t).clone(), + _ => panic!("not text"), + }; + let (ta, tb) = (frame(a), frame(b)); + let shown = [ta.plain_text(), tb.plain_text()].concat(); + assert_eq!(shown, "One\nTwo\n"); + let split = ta.paragraph_count() - 1; + assert_eq!(ta.para_at(split).left_indent, 30.0, "{:?}", [ta.plain_text(), tb.plain_text()]); + assert_eq!(tb.para_at(0).left_indent, 30.0); + assert!(tb.para_at(0).list.is_some()); + assert_eq!(tb.list_count as usize, split, "the paragraphs before the shared one are counted once"); + assert_eq!(tb.first_para_continues, !ta.plain_text().ends_with('\n')); +} + #[test] fn thread_flows_reflows_on_edit_and_survives_delete() { let (mut s, a, b) = setup(); @@ -1679,3 +1803,164 @@ fn the_frame_a_release_leaves_alone_has_the_bounds_of_the_whole_story() { let cached = t.cached_bounds.unwrap(); assert!((cached.y0 - bounds.y0).abs() < 1e-6 && (cached.y1 - bounds.y1).abs() < 1e-6, "{cached:?} {bounds:?}"); } + +/// Twelve paragraphs that wrap, threaded through three frames, the first two of which end inside +/// a paragraph; the last frame's paragraphs are indented 10 pt. → the session and the frames. +fn split_story() -> (Session, [u64; 3]) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 900, "height": 1000})).unwrap(); + let words = "aaa bbb ccc ddd eee fff ggg hhh iii jjj ".repeat(3); + let story = (1..=12).map(|i| format!("p{i} {}", words.trim_end())).collect::<Vec<_>>().join("\n"); + let a = s.execute("text.create", &json!({"x": 10, "y": 10, "text": story, "size": 12, "area": {"width": 150, "height": 50}})).unwrap()["id"] + .as_u64() + .unwrap(); + let b = s.execute("text.thread.add", &json!({"from": a, "rect": [300, 10, 150, 50]})).unwrap()["id"].as_u64().unwrap(); + let c = s.execute("text.thread.add", &json!({"from": b, "rect": [600, 10, 250, 950]})).unwrap()["id"].as_u64().unwrap(); + s.execute("text.setFormat", &json!({"ids": [c], "leftIndent": 10})).unwrap(); + for id in [b, c] { + assert!(text_of(&s.doc().unwrap().doc, NodeId(id)).unwrap().first_para_continues, "frame {id} starts inside a paragraph"); + } + (s, [a, b, c]) +} + +/// Each frame's text, paragraph styles and whether it continues a paragraph. +fn frames_of(s: &Session, frames: &[u64]) -> Vec<(String, Vec<vectorcraft_doc::ParaStyle>, bool)> { + frames + .iter() + .map(|id| { + let t = text_of(&s.doc().unwrap().doc, NodeId(*id)).unwrap(); + (t.plain_text(), t.paragraph_styles(), t.first_para_continues) + }) + .collect() +} + +/// One entry for each paragraph of the story: a paragraph split between frames by its piece in the +/// later frame. Each takes indents of its own, wide enough to move text between the frames. +fn indent_entries(s: &Session, frames: &[u64]) -> Vec<Value> { + let mut out = vec![]; + for (k, id) in frames.iter().enumerate() { + let t = text_of(&s.doc().unwrap().doc, NodeId(*id)).unwrap(); + let next_continues = frames.get(k + 1).is_some_and(|n| text_of(&s.doc().unwrap().doc, NodeId(*n)).unwrap().first_para_continues); + let plain = t.plain_text(); + let pieces: Vec<&str> = plain.split('\n').collect(); + let mut start = 0; + for (i, piece) in pieces.iter().enumerate() { + if i + 1 < pieces.len() || !next_continues { + let n = out.len() as f64; + out.push(json!({"id": id, "start": start, "leftIndent": 20.0 + n, "firstLineIndent": 15.0 - n})); + } + start += piece.len() + 1; + } + } + out +} + +/// `paragraphIndents` sets each paragraph of a threaded story as one `text.setFormat` command for +/// each paragraph would, the story's last paragraph first, with a paragraph split between frames +/// set once; the story flows again once, and Undo and Redo take the whole change as one step. +#[test] +fn paragraph_indents_flow_a_threaded_story_once_as_one_command_per_paragraph_would() { + let (mut one, frames) = split_story(); + let (mut each, _) = split_story(); + let entries = indent_entries(&one, &frames); + assert_eq!(entries.len(), 12, "one entry for each paragraph of the story: {entries:?}"); + let commands: Vec<Value> = entries + .iter() + .rev() + .map(|e| { + json!({"command": "text.setFormat", "params": { + "ids": [e["id"]], "start": e["start"], "end": e["start"], "leftIndent": e["leftIndent"], "firstLineIndent": e["firstLineIndent"] + }}) + }) + .collect(); + each.execute("command.batch", &json!({"label": "Left Indent", "commands": commands})).unwrap(); + let start = frames_of(&one, &frames); + let undo = one.doc().unwrap().history.undo.len(); + let copied = COPIED.with(std::cell::Cell::get); + let r = one.execute("text.setFormat", &json!({"paragraphIndents": entries})).unwrap(); + assert_eq!(COPIED.with(std::cell::Cell::get), copied + 1, "the story flows again once"); + // The first frame holds only the start of the paragraph that runs on into the second. + assert_eq!(r, json!({"ids": frames[1..]})); + assert_eq!(one.doc().unwrap().history.undo.len(), undo + 1); + let set = frames_of(&one, &frames); + assert_ne!(set, start); + assert_eq!(set, frames_of(&each, &frames)); + one.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(frames_of(&one, &frames), start); + one.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(frames_of(&one, &frames), set); +} + +/// Thousands of paragraphs of a threaded story are set by one edit, which flows the story again +/// once. +#[test] +fn paragraph_indents_over_thousands_of_paragraphs_flow_the_story_once() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 900, "height": 1000})).unwrap(); + let story = vec!["x"; 5000].join("\n"); + let a = s.execute("text.create", &json!({"x": 10, "y": 10, "text": story, "size": 12, "area": {"width": 150, "height": 300}})).unwrap()["id"] + .as_u64() + .unwrap(); + let b = s.execute("text.thread.add", &json!({"from": a, "rect": [300, 10, 150, 300]})).unwrap()["id"].as_u64().unwrap(); + let entries: Vec<Value> = [a, b] + .into_iter() + .flat_map(|id| { + let t = text_of(&s.doc().unwrap().doc, NodeId(id)).unwrap(); + let count = t.paragraph_count(); + (0..count).map(move |i| json!({"id": id, "start": 2 * i, "leftIndent": (i % 7) as f64})) + }) + .collect(); + assert!(entries.len() >= 5000, "{}", entries.len()); + let (undo, copied) = (s.doc().unwrap().history.undo.len(), COPIED.with(std::cell::Cell::get)); + s.execute("text.setFormat", &json!({"paragraphIndents": entries})).unwrap(); + assert_eq!((s.doc().unwrap().history.undo.len(), COPIED.with(std::cell::Cell::get)), (undo + 1, copied + 1)); + let t = text_of(&s.doc().unwrap().doc, NodeId(a)).unwrap(); + assert_eq!((t.para_at(0).left_indent, t.para_at(1).left_indent, t.para_at(8).left_indent), (0.0, 1.0, 1.0)); +} + +/// `paragraphIndents` that would change no paragraph leaves the document and its history alone, and +/// a bad one is refused before anything changes. +#[test] +fn paragraph_indents_check_every_entry_and_skip_a_change_that_changes_nothing() { + let (mut s, [a, b, c]) = split_story(); + let start = frames_of(&s, &[a, b, c]); + let undo = s.doc().unwrap().history.undo.len(); + let copied = COPIED.with(std::cell::Cell::get); + let r = + s.execute("text.setFormat", &json!({"paragraphIndents": [{"id": a, "start": 0, "leftIndent": 0}, {"id": c, "start": 0, "leftIndent": 10}]})); + assert_eq!(r.unwrap(), json!({"ids": [a, c]})); + assert_eq!((s.doc().unwrap().history.undo.len(), COPIED.with(std::cell::Cell::get)), (undo, copied), "nothing to change"); + let paragraph = text(&s, c).find('\n').unwrap() + 1; + let rect = s.execute("shape.rectangle", &json!({"x": 10, "y": 900, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + let undo = s.doc().unwrap().history.undo.len(); + let ok = json!({"id": c, "start": paragraph, "leftIndent": 30}); + for bad in [ + json!({"paragraphIndents": []}), + json!({"paragraphIndents": {"id": a, "start": 0, "leftIndent": 30}}), + json!({"paragraphIndents": [ok, {"id": a, "start": 0, "leftIndent": 30}], "ids": [a]}), + json!({"paragraphIndents": [ok, {"id": a, "start": 0, "leftIndent": 30}], "leftIndent": 5}), + json!({"paragraphIndents": [ok, 3]}), + json!({"paragraphIndents": [ok, {"id": a, "start": 0}]}), + json!({"paragraphIndents": [ok, {"id": a, "start": 0, "leftIndent": "30"}]}), + json!({"paragraphIndents": [ok, {"id": a, "start": 0, "leftIndent": 1300}]}), + json!({"paragraphIndents": [ok, {"id": a, "start": 0, "firstLineIndent": -1297}]}), + json!({"paragraphIndents": [ok, {"id": a, "start": 0, "leftIndent": 30, "spaceBefore": 4}]}), + json!({"paragraphIndents": [ok, {"id": "a", "start": 0, "leftIndent": 30}]}), + json!({"paragraphIndents": [ok, {"id": rect, "start": 0, "leftIndent": 30}]}), + json!({"paragraphIndents": [ok, {"id": 999_999, "start": 0, "leftIndent": 30}]}), + json!({"paragraphIndents": [ok, {"id": a, "leftIndent": 30}]}), + json!({"paragraphIndents": [ok, {"id": a, "start": -1, "leftIndent": 30}]}), + json!({"paragraphIndents": [ok, {"id": a, "start": 1, "leftIndent": 30}]}), + json!({"paragraphIndents": [ok, {"id": c, "start": paragraph, "leftIndent": 31}]}), + json!({"paragraphIndents": [ok, {"id": c, "start": paragraph, "leftIndent": 30, "firstLineIndent": 0}]}), + json!({"paragraphIndents": vec![ok.clone(); crate::cmd::panelcmds::MAX_PARAGRAPH_INDENTS + 1]}), + ] { + assert!(s.execute("text.setFormat", &bad).is_err(), "{bad}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{bad}"); + assert_eq!(frames_of(&s, &[a, b, c]), start, "{bad}"); + } + // The same entry twice is one change. + s.execute("text.setFormat", &json!({"paragraphIndents": [ok, ok]})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + assert_eq!(text_of(&s.doc().unwrap().doc, NodeId(c)).unwrap().para_at(1).left_indent, 30.0); +} diff --git a/crates/engine/src/cmd/typecmd.rs b/crates/engine/src/cmd/typecmd.rs index 33dad39d93..e996591f91 100644 --- a/crates/engine/src/cmd/typecmd.rs +++ b/crates/engine/src/cmd/typecmd.rs @@ -10,8 +10,8 @@ use vectorcraft_geom::{Affine, PathData, Vec2}; use super::edit::selected_roots; use super::pathops::{length_given, number_given, shape_node}; use super::{ - CommandSpec, EngineError, Result, Session, bad, check_numbers, cmd, color_value, f64_req, has_doc, has_selection, id_param, index, number_or, ok, - str_param, switch_or, targets, text_param, + CommandSpec, EngineError, Result, Session, bad, check_numbers, cmd, color_value, f64_req, has_doc, has_selection, index, number_or, object_param, + ok, str_param, switch_or, targets, text_param, }; pub fn specs() -> Vec<CommandSpec> { @@ -138,7 +138,7 @@ pub fn specs() -> Vec<CommandSpec> { "Character", [], None, - "{ids?|id?, font?, style? (font alone: the style is kept when the new family has it, else its closest), size?: pt, leading?: pt|\"auto\", tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour|\"none\", stroke?: colour|\"none\" (characters without a stroke weight get 1 pt; #rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt (the character stroke's weight, in document points as stroke.set), features?: [\"dlig\", \"-liga\", …] OpenType, featureChanges?: [\"tnum\", \"-onum\", …] (OpenType features turned on, or with - off, on top of each character's own; its other features are kept), start?: byte, end?: byte} (size/leading are document points after object scaling; with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits), warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", + "{ids?|id?, font?, style? (font alone: the style is kept when the new family has it, else its closest), size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour|\"none\", stroke?: colour|\"none\" (characters without a stroke weight get 1 pt; #rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt (the character stroke's weight, in document points as stroke.set), features?: [\"dlig\", \"-liga\", \"salt=2\", …] OpenType (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), start?: byte, end?: byte} (size/leading are document points after object scaling; with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits), warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", has_doc, set_style ), @@ -715,6 +715,20 @@ pub(crate) fn text_targets(s: &Session, p: &Value, cmd: &str) -> Result<Vec<Node Ok(t) } +/// The type sizes a command takes, in points. +pub(crate) const TYPE_SIZES: (f64, f64) = (0.1, 1296.0); + +/// A type size `size` that a command was given: an error naming the range when it is outside +/// [`TYPE_SIZES`]. +pub(crate) fn given_type_size(size: f64, cmd: &str) -> Result<f64> { + let (lo, hi) = TYPE_SIZES; + if !(lo..=hi).contains(&size) { + let key = "size"; + return Err(bad(cmd, format!("`{key}` must be from {lo} to {hi}"))); + } + Ok(size) +} + /// Clamp in the units shown to the user, then compensate the text's affine. Clamping /// the local result would make small sizes impossible after enlarging an object. pub(crate) fn local_type_value(t: &TextObject, value: f64, limits: (f64, f64), horizontal: bool, cmd: &str) -> Result<f64> { @@ -820,10 +834,7 @@ fn set_style(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "text.setStyle"; let font = text_param(p, "font", C)?.map(str::to_string); let style = text_param(p, "style", C)?.map(str::to_string); - let size = length_given(p, "size", C)?; - if size.is_some_and(|v| v <= 0.0) { - return Err(bad(C, "size must be positive")); - } + let size = length_given(p, "size", C)?.map(|v| given_type_size(v, C)).transpose()?; let leading = match p.get("leading") { None | Some(Value::Null) => None, Some(Value::String(a)) if a.eq_ignore_ascii_case("auto") => Some(None), @@ -1273,7 +1284,7 @@ fn reshape_area(s: &mut Session, p: &Value) -> Result<Value> { }; let mut items = Vec::with_capacity(raw.len()); for it in raw { - let id = id_param(it, "id").ok_or_else(|| bad(C, "missing id"))?; + let id = object_param(it, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; let mut refs = super::select::checked_refs(it.get("anchors"), C)?; refs.sort_unstable(); refs.dedup(); @@ -1304,7 +1315,7 @@ fn reshape_area(s: &mut Session, p: &Value) -> Result<Value> { fn reshape_path(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "text.reshapePath"; - let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; let mut refs = super::select::checked_refs(p.get("anchors"), C)?; refs.sort_unstable(); refs.dedup(); @@ -1335,7 +1346,7 @@ fn reshape_path(s: &mut Session, p: &Value) -> Result<Value> { fn set_path_handle(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "text.setPathHandle"; - let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; let si = super::draw2::usize_opt(p, "subpath", C)?.unwrap_or(0); let ai = p.get("anchor").and_then(Value::as_u64).map(index).ok_or_else(|| bad(C, "missing anchor"))?; let out = super::object::choice(p, C, "which", &["in", "out"])? != Some("in"); @@ -1365,6 +1376,7 @@ fn set_path_handle(s: &mut Session, p: &Value) -> Result<Value> { #[cfg(test)] mod area_tests; mod block; +pub(crate) use block::needed_room; #[cfg(test)] mod block_tests; diff --git a/crates/engine/src/cmd/typecmd/area_tests.rs b/crates/engine/src/cmd/typecmd/area_tests.rs index 571c9c3469..e71948086f 100644 --- a/crates/engine/src/cmd/typecmd/area_tests.rs +++ b/crates/engine/src/cmd/typecmd/area_tests.rs @@ -397,6 +397,102 @@ fn roman_hanging_punctuation_is_set_per_paragraph_and_saved_only_when_on() { assert!(text(&s).para_at(1).roman_hanging); } +/// Paragraph panel menu › Korean Line Break Anywhere: new type has it off and saves that; +/// `text.setFormat {koreanLineBreakAnywhere}` sets it per paragraph in one undo step and refuses a +/// value that is not true or false, a paragraph saved before the option opens with it on, and +/// paragraph styles carry it. `text.setRangeStyle`, a character command, does not take it. +#[test] +fn korean_line_break_anywhere_is_set_per_paragraph_and_saved_only_when_off() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let id = s.execute("text.create", &json!({"x": 10, "y": 10, "size": 20, "text": "가나다\n라마"})).unwrap()["id"].as_u64().unwrap(); + let text = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => (**t).clone(), + _ => panic!("text"), + }; + assert!(!text(&s).para_at(0).korean_line_break_anywhere, "new type has it off"); + assert_eq!(serde_json::to_value(text(&s).para_at(0)).unwrap()["korean_line_break_anywhere"], false); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + // Only the first paragraph (the caret's range). + s.execute("text.setFormat", &json!({"koreanLineBreakAnywhere": true, "start": 0, "end": 0})).unwrap(); + assert!(text(&s).para_at(0).korean_line_break_anywhere && !text(&s).para_at(1).korean_line_break_anywhere); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); + assert!(serde_json::to_value(text(&s).para_at(0)).unwrap().get("korean_line_break_anywhere").is_none()); + let back: vectorcraft_doc::ParaStyle = serde_json::from_value(serde_json::to_value(text(&s).para_at(0)).unwrap()).unwrap(); + assert!(back.korean_line_break_anywhere); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(!text(&s).para_at(0).korean_line_break_anywhere); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(text(&s).para_at(0).korean_line_break_anywhere); + // Saved before the option: on, the line breaks it was laid out with. + let old: vectorcraft_doc::ParaStyle = serde_json::from_value(json!({"justify": "Left"})).unwrap(); + assert!(old.korean_line_break_anywhere); + assert!(s.execute("text.setFormat", &json!({"ids": [id], "koreanLineBreakAnywhere": "yes"})).is_err()); + assert!(s.execute("text.setRangeStyle", &json!({"id": id, "koreanLineBreakAnywhere": false})).is_err()); + assert!(text(&s).para_at(0).korean_line_break_anywhere, "a refused call changes nothing"); + // A paragraph style carries it. + s.execute("paraStyle.new", &json!({"name": "Anywhere", "attrs": {"korean_line_break_anywhere": true}})).unwrap(); + s.execute("paraStyle.apply", &json!({"name": "Anywhere", "id": id})).unwrap(); + assert!(text(&s).para_at(1).korean_line_break_anywhere); + s.execute("paraStyle.new", &json!({"name": "Words", "attrs": {"korean_line_break_anywhere": false}})).unwrap(); + s.execute("paraStyle.apply", &json!({"name": "Words", "id": id})).unwrap(); + assert!(!text(&s).para_at(0).korean_line_break_anywhere && !text(&s).para_at(1).korean_line_break_anywhere); +} + +/// Paragraph panel menu › Bunri-Kinshi: off for new type and for a paragraph saved before it, and +/// saved only when on; `text.setFormat {bunriKinshi}` sets it per paragraph in one undo step and +/// refuses a value that is not true or false, kinsoku None keeps it, and paragraph styles carry it. +#[test] +fn bunri_kinshi_is_set_per_paragraph_and_saved_only_when_on() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let id = s.execute("text.create", &json!({"x": 10, "y": 10, "size": 20, "text": "あ——い\nう……え"})).unwrap()["id"].as_u64().unwrap(); + let text = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => (**t).clone(), + _ => panic!("text"), + }; + assert!(!text(&s).para_at(0).bunri_kinshi, "new type has it off"); + assert!(serde_json::to_value(text(&s).para_at(0)).unwrap().get("bunri_kinshi").is_none()); + let old: vectorcraft_doc::ParaStyle = serde_json::from_value(json!({"justify": "Left"})).unwrap(); + assert!(!old.bunri_kinshi, "saved before the option: off"); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + // Only the second paragraph. + let second = "あ——い\n".len(); + s.execute("text.setFormat", &json!({"bunriKinshi": true, "start": second, "end": second})).unwrap(); + assert!(!text(&s).para_at(0).bunri_kinshi && text(&s).para_at(1).bunri_kinshi); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); + let saved = serde_json::to_value(text(&s).para_at(1)).unwrap(); + assert_eq!(saved["bunri_kinshi"], true); + let back: vectorcraft_doc::ParaStyle = serde_json::from_value(saved).unwrap(); + assert!(back.bunri_kinshi); + let reopened = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + let Some(NodeKind::Text(back)) = reopened.node(NodeId(id)).map(|n| &n.kind) else { panic!("text") }; + assert!(!back.para_at(0).bunri_kinshi && back.para_at(1).bunri_kinshi, "the file keeps it per paragraph"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(!text(&s).para_at(1).bunri_kinshi); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(text(&s).para_at(1).bunri_kinshi); + for bad in [json!("yes"), json!(1)] { + assert!(s.execute("text.setFormat", &json!({"ids": [id], "bunriKinshi": bad, "kinsoku": "none"})).is_err(), "{bad}"); + } + assert!(s.execute("text.setRangeStyle", &json!({"id": id, "bunriKinshi": false})).is_err()); + assert!(text(&s).para_at(1).bunri_kinshi && text(&s).para_at(1).kinsoku != vectorcraft_doc::Kinsoku::None, "a refused call changes nothing"); + // Kinsoku None keeps the setting, without effect, and turning kinsoku back on restores it. + s.execute("text.setFormat", &json!({"ids": [id], "kinsoku": "none"})).unwrap(); + assert!(text(&s).para_at(1).bunri_kinshi); + s.execute("text.setFormat", &json!({"ids": [id], "kinsoku": "hard"})).unwrap(); + assert!(text(&s).para_at(1).bunri_kinshi); + // A paragraph style carries it. + s.execute("paraStyle.new", &json!({"name": "Pairs", "attrs": {"bunri_kinshi": true}})).unwrap(); + s.execute("paraStyle.apply", &json!({"name": "Pairs", "id": id})).unwrap(); + assert!(text(&s).para_at(0).bunri_kinshi && text(&s).para_at(1).bunri_kinshi); + s.execute("paraStyle.new", &json!({"name": "Split", "attrs": {"bunri_kinshi": false}})).unwrap(); + s.execute("paraStyle.apply", &json!({"name": "Split", "id": id})).unwrap(); + assert!(!text(&s).para_at(0).bunri_kinshi && !text(&s).para_at(1).bunri_kinshi); +} + /// Paragraph panel › Insert Kashidas: `text.setFormat {kashida}` sets it per paragraph in one /// undo step, the paragraph is saved with it only when it is not None and opens with it, an /// unknown value changes nothing, and paragraph styles carry it. @@ -1567,6 +1663,63 @@ fn tate_chu_yoko_settings_are_character_attributes_saved_only_when_set() { assert_eq!(offsets(&s), before); } +/// Insert Aki Left and Right (Character panel, East Asian options): character attributes in +/// thousandths of an em, 0 by default and saved only when not 0. Both commands set either side +/// alone, keeping the other side of every run, in one undo step; a value that is not a number or +/// lies outside 0 to 1000 is refused, naming the key, before anything changes; a character style +/// captured from the characters carries them. +#[test] +fn insert_aki_is_a_character_attribute_set_one_side_at_a_time() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "(日本)"})).unwrap()["id"].as_u64().unwrap(); + let runs = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.runs.clone(), + _ => panic!("text"), + }; + let aki = |s: &Session| runs(s).iter().map(|r| (r.text.clone(), r.style.aki_left, r.style.aki_right)).collect::<Vec<_>>(); + let saved = serde_json::to_value(&runs(&s)[0].style).unwrap(); + assert!(saved.get("akiLeft").is_none() && saved.get("akiRight").is_none()); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.execute("text.setFormat", &json!({"akiLeft": 250})).unwrap(); + assert_eq!(aki(&s), [("(日本)".to_string(), 250.0, 0.0)]); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(aki(&s), [("(日本)".to_string(), 0.0, 0.0)], "one undo step"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(aki(&s), [("(日本)".to_string(), 250.0, 0.0)]); + + // One side on part of the text: the runs keep their other side. + let paren = "(".len(); + s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": paren, "akiRight": 500})).unwrap(); + assert_eq!(aki(&s), [("(".to_string(), 250.0, 500.0), ("日本)".to_string(), 250.0, 0.0)]); + s.execute("text.setFormat", &json!({"akiLeft": 0})).unwrap(); + assert_eq!(aki(&s), [("(".to_string(), 0.0, 500.0), ("日本)".to_string(), 0.0, 0.0)]); + let saved = serde_json::to_value(&runs(&s)[0].style).unwrap(); + assert_eq!((saved.get("akiLeft"), saved["akiRight"].clone()), (None, json!(500.0))); + // Saved and reopened as they were. + let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + let NodeKind::Text(t) = &back.node(NodeId(id)).unwrap().kind else { panic!("text") }; + let reopened: Vec<_> = t.runs.iter().map(|r| (r.text.clone(), r.style.aki_left, r.style.aki_right)).collect(); + assert_eq!(reopened, aki(&s)); + let attrs = super::super::textstyles::char_attrs(&runs(&s)[0].style); + assert_eq!((attrs["akiLeft"].clone(), attrs["akiRight"].clone()), (json!(0.0), json!(500.0))); + + let before = aki(&s); + let undo = s.doc().unwrap().history.undo.len(); + for (cmd, p, want) in [ + ("text.setFormat", json!({"akiLeft": "250"}), "`akiLeft` must be a number"), + ("text.setFormat", json!({"akiRight": -1}), "`akiRight` must be from 0 to 1000"), + ("text.setFormat", json!({"akiLeft": 250, "akiRight": 1000.5}), "`akiRight` must be from 0 to 1000"), + ("text.setRangeStyle", json!({"id": id, "akiRight": true}), "`akiRight` must be a number"), + ("text.setRangeStyle", json!({"id": id, "start": 0, "end": paren, "akiLeft": 2000}), "`akiLeft` must be from 0 to 1000"), + ] { + let e = s.execute(cmd, &p).unwrap_err(); + assert!(matches!(&e, EngineError::BadParams { msg, .. } if msg == want), "{cmd} {p}: {e}"); + } + assert_eq!(aki(&s), before); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step for a refused call"); +} + /// Standard Vertical Roman Alignment (Character panel menu, East Asian options): a character /// attribute, off by default and saved only when on. Documents written before it read as off; a /// character style captured from the characters carries it. @@ -1955,6 +2108,60 @@ fn new_type_is_composed_with_line_end_half_width_punctuation() { assert!(serde_json::to_value(&old).unwrap().get("mojikumi").is_none()); } +/// `text.setFormat {mojikumi}` takes each predefined Mojikumi set as one undo step, refuses any +/// other value without changing the type, and each set survives a native save and reopen and a +/// paragraph style that captures it. +#[test] +fn every_predefined_mojikumi_set_is_set_saved_and_carried_by_styles() { + use vectorcraft_doc::Mojikumi; + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "「雅楽」。"})).unwrap()["id"].as_u64().unwrap(); + let para = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.para.clone(), + _ => panic!("text"), + }; + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let sets = [ + ("yakumonoHankaku", Mojikumi::YakumonoHankaku), + ("gyomatsuYakumonoHankaku", Mojikumi::GyomatsuYakumonoHankaku), + ("gyomatsuYakumonoZenkaku", Mojikumi::GyomatsuYakumonoZenkaku), + ("yakumonoZenkaku", Mojikumi::YakumonoZenkaku), + ("none", Mojikumi::None), + ("lineEndHalf", Mojikumi::LineEndHalf), + ]; + for (key, set) in sets { + s.execute("text.setFormat", &json!({"mojikumi": key})).unwrap(); + assert_eq!(para(&s).mojikumi, set, "{key}"); + let doc = s.doc().unwrap().doc.clone(); + let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap(); + match &back.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => assert_eq!(t.para.mojikumi, set, "{key} saved"), + _ => panic!("text"), + } + let style = format!("Spacing {key}"); + s.execute("paraStyle.new", &json!({"name": style, "attrs": {"mojikumi": key}})).unwrap(); + s.execute("text.setFormat", &json!({"mojikumi": if set == Mojikumi::None { "lineEndHalf" } else { "none" }})).unwrap(); + s.execute("paraStyle.apply", &json!({"name": style, "id": id})).unwrap(); + assert_eq!(para(&s).mojikumi, set, "{key} from a paragraph style"); + } + // One undo step back to the set before. + s.execute("text.setFormat", &json!({"mojikumi": "yakumonoHankaku"})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(para(&s).mojikumi, Mojikumi::LineEndHalf); + // A value that is no set, or not a string, is refused and leaves the type as it was. + s.execute("text.setFormat", &json!({"mojikumi": "gyomatsuYakumonoZenkaku"})).unwrap(); + for bad in [json!("YakumonoHankaku"), json!("lineEnd"), json!(""), json!(1)] { + assert!(s.execute("text.setFormat", &json!({"mojikumi": bad, "leftIndent": 12})).is_err(), "{bad}"); + let p = para(&s); + assert_eq!((p.mojikumi, p.left_indent), (Mojikumi::GyomatsuYakumonoZenkaku, 0.0), "{bad}"); + } + // A null value leaves the set as it is. + s.execute("text.setFormat", &json!({"mojikumi": null, "leftIndent": 12})).unwrap(); + let p = para(&s); + assert_eq!((p.mojikumi, p.left_indent), (Mojikumi::GyomatsuYakumonoZenkaku, 12.0)); +} + #[test] fn vertical_point_type_keeps_its_anchor_on_the_column_centre_line() { let mut s = Session::new(); @@ -2113,3 +2320,127 @@ fn set_path_handle_reshapes_type_on_a_path() { assert!(s.execute("text.setPathHandle", &json!({"id": id.0, "anchor": 9, "which": "out", "x": 0, "y": 0})).is_err(), "no such anchor"); assert!(s.execute("text.setPathHandle", &json!({"id": path["id"], "anchor": 0, "which": "out", "x": 0, "y": 0})).is_err(), "not type"); } + +/// `text.setFormat` refuses a number or switch given as another type, naming the key, and +/// changes nothing; null leaves the attribute as it is. +#[test] +fn set_format_refuses_a_param_of_the_wrong_type() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "One\nTwo"})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let state = |s: &Session| (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + let before = state(&s); + for key in [ + "baselineShift", + "hScale", + "vScale", + "rotation", + "leftIndent", + "rightIndent", + "firstLineIndent", + "spaceBefore", + "spaceAfter", + "wordsLongerThan", + "afterFirst", + "beforeLast", + "hyphenLimit", + "hyphenationZone", + ] { + for wrong in [json!("30"), json!(true), json!([30])] { + let err = s.execute("text.setFormat", &json!({ key: wrong })).unwrap_err().to_string(); + assert!(err.contains(&format!("`{key}` must be a number, not {wrong}")), "{key}: {err}"); + } + } + for key in ["underline", "allCaps", "hyphenate", "noBreak"] { + let err = s.execute("text.setFormat", &json!({ key: "true" })).unwrap_err().to_string(); + assert!(err.contains(&format!("`{key}` must be true or false")), "{key}: {err}"); + } + let err = s.execute("text.setFormat", &json!({"leftIndent": 30, "firstLineIndent": "12"})).unwrap_err().to_string(); + assert!(err.contains("`firstLineIndent` must be a number"), "{err}"); + assert!(state(&s) == before, "a refused call changes nothing and records no undo step"); + s.execute("text.setFormat", &json!({"leftIndent": 30, "firstLineIndent": null})).unwrap(); + let NodeKind::Text(t) = &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind else { panic!("text") }; + assert_eq!((t.para_at(0).left_indent, t.para_at(0).first_line_indent), (30.0, 0.0)); +} + +/// `text.setFormat` reads a null value as one left out: a call whose attributes are all null has +/// nothing to change, and records no edit, no undo step and no new revision. +#[test] +fn set_format_with_only_null_values_changes_nothing() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "One\nTwo"})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let state = |s: &Session| { + let st = s.doc().unwrap(); + (st.doc.clone(), st.history.undo.len(), st.revision) + }; + let before = state(&s); + for params in [ + json!({"leftIndent": null}), + json!({"leftIndent": null, "firstLineIndent": null, "underline": null}), + json!({"kerning": null, "antiAlias": null, "list": null, "wordSpacing": null}), + json!({"mojikumi": null}), + json!({"kinsoku": null, "kinsokuType": null, "direction": null, "leadingModel": null}), + json!({"burasagari": null, "kashida": null, "singleWordJustification": null, "autoLeading": null}), + json!({"ids": [id], "start": 0, "end": 3, "spaceBefore": null}), + ] { + let err = s.execute("text.setFormat", ¶ms).unwrap_err().to_string(); + assert!(err.contains("nothing to change"), "{params}: {err}"); + assert!(state(&s) == before, "{params}: no edit, no undo step and no new revision"); + } + // A null beside a value leaves only its own attribute. + let para = |d: &vectorcraft_doc::Document| { + let NodeKind::Text(t) = &d.node(NodeId(id)).unwrap().kind else { panic!("text") }; + (t.para_at(0).mojikumi, t.para_at(0).kinsoku) + }; + let mojikumi = para(&before.0).0; + s.execute("text.setFormat", &json!({"mojikumi": null, "kinsoku": "soft"})).unwrap(); + assert_eq!(para(&s.doc().unwrap().doc), (mojikumi, vectorcraft_doc::Kinsoku::Soft)); + assert_eq!(s.doc().unwrap().history.undo.len(), before.1 + 1, "one undo step"); +} + +/// `text.setFormat` with the values the text already has succeeds and names its objects, but +/// records no edit, no undo step and no new revision. +#[test] +fn set_format_with_the_current_values_records_nothing() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "One\nTwo"})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let state = |s: &Session| { + let st = s.doc().unwrap(); + (st.doc.clone(), st.history.undo.len(), st.revision) + }; + let before = state(&s); + let NodeKind::Text(t) = &before.0.node(NodeId(id)).unwrap().kind else { panic!("text") }; + let hyphenate = t.para_at(0).hyphenate; + for params in [ + json!({"leftIndent": 0, "firstLineIndent": 0}), + json!({"underline": false, "strikethrough": false, "hyphenate": hyphenate}), + json!({"ids": [id], "start": 0, "end": 3, "spaceBefore": 0, "spaceAfter": 0}), + json!({"ids": [id], "start": 4, "end": 7, "leftIndent": null, "rightIndent": 0}), + ] { + let out = s.execute("text.setFormat", ¶ms).unwrap(); + assert_eq!(out["ids"], json!([id]), "{params}"); + assert!(state(&s) == before, "{params}: no edit, no undo step and no new revision"); + } + // A call that changes a value is one undo step; the same call again records nothing. + s.execute("text.setFormat", &json!({"leftIndent": 24})).unwrap(); + let changed = state(&s); + assert_eq!((changed.1, changed.2), (before.1 + 1, before.2 + 1), "one undo step and one revision"); + s.execute("text.setFormat", &json!({"leftIndent": 24})).unwrap(); + assert!(state(&s) == changed, "the same value again records nothing"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc == before.0, "one undo restores the text"); + // The anti-aliasing method is compared the same way. + s.execute("text.setFormat", &json!({"antiAlias": "none"})).unwrap(); + s.execute("text.setFormat", &json!({"antiAlias": "strong"})).unwrap(); + let strong = state(&s); + assert!(strong.1 > before.1, "a new method is an undo step"); + let NodeKind::Text(t) = &strong.0.node(NodeId(id)).unwrap().kind else { panic!("text") }; + assert_eq!(t.anti_alias, vectorcraft_doc::text::TypeAntiAlias::Strong); + s.execute("text.setFormat", &json!({"antiAlias": "strong"})).unwrap(); + assert!(state(&s) == strong, "the same method again records nothing"); +} diff --git a/crates/engine/src/cmd/typecmd/block.rs b/crates/engine/src/cmd/typecmd/block.rs index 06453f4983..c10abbc965 100644 --- a/crates/engine/src/cmd/typecmd/block.rs +++ b/crates/engine/src/cmd/typecmd/block.rs @@ -89,6 +89,39 @@ fn line_widths(db: &vectorcraft_text::FontDb, t: &TextObject) -> std::collection out } +/// The room along its lines that a frame of `t`'s text needs for Block to keep the widest line as +/// typed at its present size: that line's width plus its paragraph's indents, as [`block_fit`] +/// measures them, and a margin of under half a size step so that the line is not made a step +/// smaller; with the widest line's first byte and its paragraph's index. A line whose negative +/// indents take more than its width needs its own width. None when no line has a width. +pub(crate) fn needed_room(t: &TextObject) -> Option<(f64, usize, usize)> { + let points = t.style_scale().map(|s| s.points).filter(|p| p.is_finite() && *p > 1e-12)?; + let text = t.plain_text(); + let lines = typed_lines(&text); + let widths = line_widths(vectorcraft_text::FontDb::global(), t); + let sizes = first_sizes(&t.runs, &lines); + lines + .iter() + .zip(&sizes) + .filter_map(|(l, size)| { + let width = widths.get(&l.start).copied().filter(|w| w.is_finite() && *w > 1e-9)?; + let size = size * points; + if l.content == l.start || !(size.is_finite() && size > 0.0) { + return None; + } + let para = t.para_at(l.para); + let first = if l.para_start { para.first_line_indent } else { 0.0 }; + let indents = para.laid_out_left_indent() + para.right_indent + first; + // Negative indents that take more than the line's width leave the line no room at its + // size; the frame is then as wide as the line itself, and Block makes it larger. + let room = if width + indents > 1e-9 { width + indents } else { width }; + // A tenth of a point more size widens the line by 0.1 * width / size. + Some((room + 0.04 * width / size, l.start, l.para)) + }) + .filter(|r| r.0.is_finite() && r.0 > 1e-9) + .reduce(|a, b| if b.0 > a.0 { b } else { a }) +} + /// The size a line set at `size` points and `width` wide takes to fill `avail`, its width growing /// by `slope` a point of size (`width / size` when the whole line follows its size): rounded down /// to tenths and kept within [`SIZES`]. A line that fits and would not fit a tenth larger keeps its @@ -152,7 +185,7 @@ pub(crate) fn block_fit(t: &mut TextObject) -> bool { let width = widths.get(&l.start).copied().filter(|w| w.is_finite() && *w > 1e-9)?; let para = t.para_at(l.para); let first = if l.para_start { para.first_line_indent } else { 0.0 }; - let avail = cell - para.left_indent - para.right_indent - first; + let avail = cell - para.laid_out_left_indent() - para.right_indent - first; let size = size * points; if !(size.is_finite() && size > 0.0) { return None; diff --git a/crates/engine/src/cmd/typecmd/block_tests.rs b/crates/engine/src/cmd/typecmd/block_tests.rs index 2dda356146..0354a630b3 100644 --- a/crates/engine/src/cmd/typecmd/block_tests.rs +++ b/crates/engine/src/cmd/typecmd/block_tests.rs @@ -140,6 +140,35 @@ fn block_turns_off_keeping_its_sizes_and_records_nothing_when_nothing_changes() assert_eq!(undo_len(&s), n + 2, "already off: no undo step"); } +#[test] +fn convert_to_point_type_turns_block_off_keeping_its_sizes() { + let mut s = session(); + let id = area(&mut s, 300.0, 400.0, "BIG\na much longer second line"); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + let sizes = |t: &TextObject| t.runs.iter().map(|r| (r.text.clone(), r.style.size, r.style.leading)).collect::<Vec<_>>(); + let fitted = sizes(&text(&s, id)); + let n = undo_len(&s); + s.execute("type.convertToPointType", &json!({})).unwrap(); + assert_eq!(undo_len(&s), n + 1, "one undo step"); + let t = text(&s, id); + assert!(matches!(t.kind, TextKind::Point)); + assert!(!t.dynamic_text, "point type has Dynamic Text off"); + assert_eq!(sizes(&t), fitted, "point type keeps the sizes Block set"); + assert!(serde_json::to_value(&t).unwrap().get("dynamicText").is_none(), "saved without dynamicText"); + // Back to area type, the frame is not refitted: Block stays off. + s.execute("type.convertToAreaType", &json!({})).unwrap(); + let t = text(&s, id); + assert!(matches!(t.kind, TextKind::Area { .. })); + assert!(!t.dynamic_text, "Block does not come on again"); + assert_eq!(sizes(&t), fitted); + // Undo gives the Block frame back. + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + let t = text(&s, id); + assert!(t.dynamic_text && matches!(t.kind, TextKind::Area { .. })); + assert_eq!(sizes(&t), fitted); +} + #[test] fn bad_params_and_other_type_are_refused() { let mut s = session(); @@ -159,13 +188,25 @@ fn bad_params_and_other_type_are_refused() { assert!(!text(&s, id).dynamic_text); let point = s.execute("text.create", &json!({"x": 10, "y": 500, "text": "point"})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [point]})).unwrap(); + // Off leaves point type as it is, with no undo step, and a gap needs it turned on. + let n = undo_len(&s); + assert_eq!(s.execute("type.dynamicText", &json!({"on": false})).unwrap()["ids"], json!([point])); + let e = s.execute("type.dynamicText", &json!({"on": false, "wordGap": 200})).unwrap_err().to_string(); + assert!(e.contains("need area type"), "{e}"); + assert_eq!(undo_len(&s), n); + assert!(matches!(text(&s, point).kind, TextKind::Point)); + let shape = s.execute("shape.rectangle", &json!({"x": 500, "y": 500, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [shape]})).unwrap(); let e = s.execute("type.dynamicText", &json!({})).unwrap_err().to_string(); assert!(e.contains("select type on a path or area type"), "{e}"); - // With point type selected too, only the area type changes. + // With point type selected too, both turn on, the point type as area type with Block on. s.execute("select.set", &json!({"ids": [id, point]})).unwrap(); + let n = undo_len(&s); let r = s.execute("type.dynamicText", &json!({})).unwrap(); - assert_eq!(r["ids"], json!([id])); - assert!(text(&s, id).dynamic_text && !text(&s, point).dynamic_text); + assert_eq!(r["ids"], json!([id, point])); + assert!(text(&s, id).dynamic_text && text(&s, point).dynamic_text); + assert!(matches!(text(&s, point).kind, TextKind::Area { .. })); + assert_eq!(undo_len(&s), n + 1); // A gap with only type on a path selected is an error, and nothing changes. let path = s.execute("path.create", &json!({"d": "M60 550 L340 550"})).unwrap()["id"].as_u64().unwrap(); let along = s.execute("text.createInPath", &json!({"path": path, "mode": "onPath", "text": "Along"})).unwrap()["id"].as_u64().unwrap(); @@ -409,6 +450,228 @@ fn threaded_frames_are_refused_and_threading_turns_block_off() { assert!(matches!(text(&s, a).kind, TextKind::Area { .. })); } +/// 12 pt point type at (300, 100) with `extra` params for `text.create`, selected. +fn point(s: &mut Session, text: &str, extra: Value) -> u64 { + let mut p = json!({"x": 300, "y": 100, "size": 12, "text": text}); + if let (Some(p), Some(extra)) = (p.as_object_mut(), extra.as_object()) { + p.extend(extra.clone()); + } + let id = s.execute("text.create", &p).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + id +} + +/// Where the first glyph of the laid-out line starting at byte `start` is in the document. +fn line_start(t: &TextObject, start: usize) -> vectorcraft_geom::Point { + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + let l = lay.lines.iter().find(|l| l.start == start).expect("a line starts there"); + t.xf * lay.glyphs[l.glyph_start].origin +} + +#[test] +fn point_type_becomes_area_type_with_block_at_its_widest_line() { + for justify in ["left", "center", "right"] { + let mut s = session(); + let id = point(&mut s, "Short\nA much longer line", json!({})); + s.execute("text.setStyle", &json!({"ids": [id], "justify": justify})).unwrap(); + let before = line_start(&text(&s, id), 6); + let n = undo_len(&s); + let r = s.execute("type.dynamicText", &json!({})).unwrap(); + assert_eq!((r["on"].clone(), r["ids"].clone()), (json!(true), json!([id]))); + assert_eq!((r["wordGap"].clone(), r["lineGap"].clone()), (json!(100.0), json!(0.0)), "the reply gives the new frame's gaps"); + assert_eq!(undo_len(&s), n + 1, "{justify}: one undo step"); + assert_eq!(s.doc().unwrap().history.undo.last().unwrap().label, "Dynamic Text"); + let t = text(&s, id); + assert!(t.dynamic_text && matches!(t.kind, TextKind::Area { .. }), "{justify}"); + assert_eq!(t.area.fit, AreaFit::None); + assert_block(&t); + assert_eq!(size_at(&t, 6), 12.0, "{justify}: the widest line keeps its size"); + assert!(size_at(&t, 0) > 24.0, "{justify}: the short line grows to the frame's width: {}", size_at(&t, 0)); + // Across, the widest line stays where it was; the short line above it grew, so it moved down. + let after = line_start(&t, 6); + assert!((after.x - before.x).abs() < 0.05, "{justify}: the widest line stays where it was across: {before:?} → {after:?}"); + assert!(after.y > before.y + 12.0, "{justify}"); + assert!(!vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).overflow, "{justify}: the frame holds every line"); + // Edits fit it again as area type; undo brings the point type back as it was. + s.execute("edit.undo", &json!({})).unwrap(); + let back = text(&s, id); + assert!(matches!(back.kind, TextKind::Point) && !back.dynamic_text && size_at(&back, 0) == 12.0, "{justify}"); + } +} + +#[test] +fn point_type_with_gaps_indents_and_vertical_type_turns_into_block() { + let mut s = session(); + // The gaps apply to the frame point type becomes. + let id = point(&mut s, "one\ntwo words here", json!({})); + let r = s.execute("type.dynamicText", &json!({"wordGap": 300, "lineGap": 4})).unwrap(); + assert_eq!((r["wordGap"].clone(), r["lineGap"].clone()), (json!(300.0), json!(4.0))); + let t = text(&s, id); + assert!(t.dynamic_text && (t.area.word_gap, t.area.line_gap) == (300.0, 4.0)); + assert_block(&t); + assert!(!vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).overflow); + // Indents: the frame takes them in, so the widest line keeps its size. + let id = point(&mut s, "Tiny\nThe widest line of all", json!({"y": 300})); + s.execute("text.setFormat", &json!({"ids": [id], "leftIndent": 20, "firstLineIndent": 10})).unwrap(); + let before = line_start(&text(&s, id), 5); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + let t = text(&s, id); + assert_block(&t); + assert_eq!(size_at(&t, 5), 12.0); + assert!((line_start(&t, 5).x - before.x).abs() < 0.05, "{before:?} → {:?}", line_start(&t, 5)); + // A nested list item: the frame takes in the level's indent too. + let id = point(&mut s, "Tiny\nThe widest item of all", json!({"y": 200})); + s.execute("text.setFormat", &json!({"ids": [id], "list": "bullet", "listLevel": 3})).unwrap(); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + let t = text(&s, id); + assert_eq!(size_at(&t, 5), 12.0, "nested list"); + assert!(size_at(&t, 0) > 12.0); + assert!(!vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).overflow); + // Mixed alignments: the widest line keeps its size and its place. + let id = point(&mut s, "Left\nThe widest line, right aligned", json!({"y": 400})); + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + if let Some(NodeKind::Text(t)) = doc.node_mut(NodeId(id)).map(|n| &mut n.kind) { + let right = vectorcraft_doc::ParaStyle { justify: vectorcraft_doc::Justify::Right, ..t.para.clone() }; + t.set_paragraph_styles(vec![t.para.clone(), right]); + } + let before = line_start(&text(&s, id), 5); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + let t = text(&s, id); + assert_eq!(size_at(&t, 5), 12.0, "mixed alignments"); + assert!((line_start(&t, 5).x - before.x).abs() < 0.05, "{before:?} → {:?}", line_start(&t, 5)); + // A right-to-left list, whose indents the layout mirrors. + let id = point(&mut s, "קצר\nשורה ארוכה בהרבה מהראשונה", json!({"y": 450})); + s.execute("text.setFormat", &json!({"ids": [id], "list": "bullet", "rightIndent": 9})).unwrap(); + let widest = "קצר\n".len(); + let before = line_start(&text(&s, id), widest); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + let t = text(&s, id); + assert_eq!(size_at(&t, widest), 12.0, "right-to-left list"); + assert!((line_start(&t, widest).x - before.x).abs() < 0.05, "{before:?} → {:?}", line_start(&t, widest)); + // Point type that was area type with its own options: the new frame takes the defaults but the + // gaps. + let id = point(&mut s, "Was\nonce a frame of two columns", json!({"y": 500})); + s.execute("type.convertToAreaType", &json!({"ids": [id]})).unwrap(); + s.execute( + "text.areaOptions", + &json!({"columns": 2, "gutter": 12, "inset": 6, "verticalAlign": "bottom", "firstBaselineMin": 40, "wordGap": 150}), + ) + .unwrap(); + s.execute("type.convertToPointType", &json!({"ids": [id]})).unwrap(); + let before = line_start(&text(&s, id), 4); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + let t = text(&s, id); + let defaults = vectorcraft_doc::AreaOptions { word_gap: 150.0, ..Default::default() }; + assert_eq!(t.area, defaults); + assert_eq!(size_at(&t, 4), 12.0, "options from an earlier frame"); + assert!((line_start(&t, 4).x - before.x).abs() < 0.05, "{before:?} → {:?}", line_start(&t, 4)); + assert!(!vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).overflow); + // Vertical type: the frame is as tall as the longest column and grows to the left. + let id = point(&mut s, "縦書き\nもっと長い縦書きの行", json!({"x": 600, "y": 40, "vertical": true})); + let before = line_start(&text(&s, id), "縦書き\n".len()); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + let t = text(&s, id); + assert!(t.vertical && t.dynamic_text && matches!(t.kind, TextKind::Area { .. })); + assert_block(&t); + assert_eq!(size_at(&t, "縦書き\n".len()), 12.0); + let after = line_start(&t, "縦書き\n".len()); + assert!((after.y - before.y).abs() < 0.05, "the longest column stays where it was down the page: {before:?} → {after:?}"); + assert!(after.x < before.x - 12.0, "the short column before it grew, so it moved left: {before:?} → {after:?}"); + assert!(!vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).overflow); +} + +#[test] +fn point_type_with_negative_indents_wider_than_its_line_turns_into_block() { + // Block makes the line larger; it keeps its start, center or end by its alignment. + let ends = |t: &TextObject| { + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + let l = &lay.lines[0]; + ((t.xf * vectorcraft_geom::Point::new(l.x0, l.baseline)).x, (t.xf * vectorcraft_geom::Point::new(l.x1 - l.trailing, l.baseline)).x) + }; + for justify in ["left", "center", "right"] { + let mut s = session(); + let id = point(&mut s, "Short", json!({})); + s.execute("text.setStyle", &json!({"ids": [id], "justify": justify})).unwrap(); + s.execute("text.setFormat", &json!({"ids": [id], "leftIndent": -200})).unwrap(); + let (b0, b1) = ends(&text(&s, id)); + let n = undo_len(&s); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + assert_eq!(undo_len(&s), n + 1, "{justify}"); + let t = text(&s, id); + assert!(t.dynamic_text && matches!(t.kind, TextKind::Area { .. }), "{justify}: the frame is as wide as the line"); + assert!(!vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).overflow, "{justify}"); + assert!(size_at(&t, 0) > 12.0, "{justify}: Block makes the line larger"); + let (a0, a1) = ends(&t); + let kept = match justify { + "left" => (a0, b0), + "center" => ((a0 + a1) / 2.0, (b0 + b1) / 2.0), + _ => (a1, b1), + }; + assert!((kept.0 - kept.1).abs() < 0.05, "{justify}: the line keeps its aligned point: {b0},{b1} → {a0},{a1}"); + } +} + +#[test] +fn point_type_under_a_text_wrap_object_turns_into_block_that_holds_every_line() { + let mut s = session(); + let id = point(&mut s, "One\nTwo\nThree\nA much longer line than the rest", json!({})); + // A wrap object above the type, across the top of the frame it becomes. + let r = s.execute("shape.rectangle", &json!({"x": 250, "y": 80, "width": 400, "height": 40})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [r]})).unwrap(); + s.execute("object.textWrap.make", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + let t = text(&s, id); + assert!(t.dynamic_text && matches!(t.kind, TextKind::Area { .. })); + assert!(!t.wrap.is_empty(), "the new area type takes the wrap object"); + assert!(!vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).overflow, "the frame holds every line around the wrap"); + // A wrap object deeper than any size Block sets, across the whole frame: the lines go below it. + let id = point(&mut s, "Below", json!({"x": 1000, "y": 100})); + let r = s.execute("shape.rectangle", &json!({"x": 900, "y": 80, "width": 400, "height": 9000})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [r]})).unwrap(); + s.execute("object.textWrap.make", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + let t = text(&s, id); + assert!(t.dynamic_text && !t.wrap.is_empty()); + assert!(!vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).overflow, "the frame reaches past a deep wrap object"); + // An inverted wrap object far below the type holds the lines inside it: the frame reaches it. + let id = point(&mut s, "Inside", json!({"x": 1600, "y": 100})); + let r = s.execute("shape.rectangle", &json!({"x": 1550, "y": 9000, "width": 400, "height": 100})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [r]})).unwrap(); + s.execute("object.textWrap.make", &json!({})).unwrap(); + s.execute("object.textWrap.options", &json!({"invert": true})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + let t = text(&s, id); + assert!(t.dynamic_text && !t.wrap.is_empty()); + assert!(!vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).overflow, "the frame reaches a distant inverted wrap object"); +} + +#[test] +fn point_type_with_nothing_to_fit_is_left_as_it_is() { + let mut s = session(); + for blank in ["", " ", "\n\n"] { + let id = point(&mut s, blank, json!({})); + let before = text(&s, id); + let n = undo_len(&s); + let r = s.execute("type.dynamicText", &json!({})).unwrap(); + assert_eq!(r["on"], json!(true)); + assert_eq!(undo_len(&s), n, "{blank:?}: no undo step"); + assert_eq!(text(&s, id), before, "{blank:?}"); + // A gap needs type it can apply to. + let e = s.execute("type.dynamicText", &json!({"wordGap": 200})).unwrap_err().to_string(); + assert!(e.contains("need area type"), "{blank:?}: {e}"); + } + // A line far shorter than the widest one stops at the size limit, and the frame still holds it. + let id = point(&mut s, &format!(".\n{}", "w".repeat(400)), json!({"size": 6})); + s.execute("type.dynamicText", &json!({})).unwrap(); + let t = text(&s, id); + assert!(t.dynamic_text); + assert_eq!(size_at(&t, 0), 1296.0); + assert!(!vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).overflow); +} + #[test] fn long_text_fits_in_a_bounded_number_of_layouts() { let mut s = session(); @@ -422,4 +685,16 @@ fn long_text_fits_in_a_bounded_number_of_layouts() { // pass and the caches), plus the reply's own. let bound = 2 * (2 + 2 * super::block::BLOCK_PASSES as u64) + 4; assert!(used <= bound, "{used} layouts"); + // Long point type: measured, fitted in its frame and fitted again at its depth, with the + // layouts that place and measure the frame. + let id = point(&mut s, &story, json!({})); + let before = vectorcraft_text::test_fonts::layouts_on_this_thread(); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + let used = vectorcraft_text::test_fonts::layouts_on_this_thread() - before; + let t = text(&s, id); + assert!(t.dynamic_text && matches!(t.kind, TextKind::Area { .. })); + assert_block(&t); + assert!(!vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).overflow); + let bound = 2 * (2 + 2 * super::block::BLOCK_PASSES as u64) + 8; + assert!(used <= bound, "point type: {used} layouts"); } diff --git a/crates/engine/src/cmd/typemenu.rs b/crates/engine/src/cmd/typemenu.rs index 03681c556a..faada86d5f 100644 --- a/crates/engine/src/cmd/typemenu.rs +++ b/crates/engine/src/cmd/typemenu.rs @@ -7,7 +7,7 @@ use vectorcraft_doc::{AreaFit, CharStyle, Document, Justify, LockedArtboards, No use vectorcraft_geom::{Affine, Rect, shapes}; use super::object::choice; -use super::typecmd::{area_text, block_gaps, refresh_bounds}; +use super::typecmd::{area_text, block_gaps, needed_room, refresh_bounds}; use super::{ CommandSpec, EngineError, Result, Session, bad, checked_ids_param, cmd, find_command, has_clipboard, has_doc, has_selection, number_or, switch_or, targets, text_param, @@ -47,7 +47,7 @@ pub fn specs() -> Vec<CommandSpec> { "Convert To Point Type", ["Type"], None, - "{ids?|id?} area type → point type; soft line wraps become line breaks, and a frame of threaded text leaves its thread with the text it holds → {ids}", + "{ids?|id?} area type → point type; soft line wraps become line breaks, a frame of threaded text leaves its thread with the text it holds, and Dynamic Text (Block) is turned off, keeping the sizes it set → {ids}", has_selection, to_point ), @@ -60,15 +60,42 @@ pub fn specs() -> Vec<CommandSpec> { has_selection, path_options ), + cmd!( + "type.pathCenter.top", + "Center on Top", + ["Type", "Type on a Path"], + None, + "{ids?|id?} slide the selected type on a closed path along it so that the middle of the span between its start and end brackets lands on the path's topmost point as the object is drawn (after its transform, so a rotated, scaled or skewed path is measured as it appears; on a level stretch such as a rectangle's top edge, its middle; with several separate topmost points, the middle of the shortest part of the path that holds them all), keeping the span's length (a full turn stays a full turn), and set the first paragraph's alignment to Center unless it is Center or Justify Center, so the type is centered there. Point type and area type in the selection are left as they are. Type on an open or compound path, type in a thread, and type on a path with no length or no height are refused with an error that names them, and nothing changes. When every object is already centered there, nothing changes and no undo step is recorded → {ids, start, end} (the first object's brackets)", + has_closed_path_type, + path_center_top + ), + cmd!( + "type.pathCenter.bottom", + "Center on Bottom", + ["Type", "Type on a Path"], + None, + "{ids?|id?} as type.pathCenter.top, on the path's bottommost point as drawn. The type is not flipped: on the bottom of a path that runs clockwise it reads upside down until Type on a Path Options › Flip turns it → {ids, start, end} (the first object's brackets)", + has_closed_path_type, + path_center_bottom + ), cmd!( "type.dynamicText", "Dynamic Text", ["Type"], None, - "{ids?|id?, on?: bool, wordGap?: % of a word space 0..1000 (100), lineGap?: pt -1296..1296 (0)} turn Dynamic Text on or off for the selected type on a path and area type (on omitted: the opposite of the first object's setting, or on when a gap is given). On type on a path, the layout scales the text by one factor (every character's size, leading and baseline shift; Type on a Path Options › Spacing stays) so that it fills the span between its start and end brackets, larger or smaller, and fits it again after every edit to the text, the path or the brackets; the first character's size moves in steps of 0.1 pt within 0.1 to 1,296 pt, and at 0.1 pt text that still runs past the end bracket overflows. The stored sizes keep their proportions. On area type it is Block: each line as typed (each paragraph, and each forced line break in one; lines are not broken again) is set to the frame's width, less the inset, the gutters and the paragraph's indents, by changing its font size only: its first character's size, in steps of 0.1 pt within 0.1 to 1,296 pt, the line's other characters keeping their proportions to it, with baseline shifts following. Every character's leading is its size plus lineGap, and the layout sets every paragraph with wordGap as its Desired word spacing, its Minimum or Maximum moving out to wordGap when wordGap lies outside it (the paragraphs keep their own Justification… values, which apply again when Block is off; the gaps are area type's, and are kept while Block is off; a gap with no area type in the selection is an error). The sizes are written into the characters and fitted again after every edit to the text or the frame, in the same undo step; at a size limit a line can be narrower than the frame or wrap. An empty line keeps its size. Block replaces Auto Size and Shrink Text to Fit (Area Type Options › Block is the same setting). Off, the text keeps the sizes it was drawn at. Point type in the selection is left as it is; a selection holding type in a thread is refused (threading type turns Dynamic Text off, keeping its drawn sizes). When nothing changes, no undo step is recorded → {on, ids, fitScale (the first object's factor; 1 when off and for area type), wordGap?, lineGap? (the first area type's; left out without area type)}", + "{ids?|id?, on?: bool, wordGap?: % of a word space 0..1000 (100), lineGap?: pt -1296..1296 (0)} turn Dynamic Text on or off for the selected type on a path and area type, or turn it on for point type (on omitted: the opposite of the first object's setting, point type counting as off, or on when a gap is given). On type on a path, the layout scales the text by one factor (every character's size, leading and baseline shift; Type on a Path Options › Spacing stays) so that it fills the span between its start and end brackets, larger or smaller, and fits it again after every edit to the text, the path or the brackets; the first character's size moves in steps of 0.1 pt within 0.1 to 1,296 pt, and at 0.1 pt text that still runs past the end bracket overflows. The stored sizes keep their proportions. On area type it is Block: each line as typed (each paragraph, and each forced line break in one; lines are not broken again) is set to the frame's width, less the inset, the gutters and the paragraph's indents, by changing its font size only: its first character's size, in steps of 0.1 pt within 0.1 to 1,296 pt, the line's other characters keeping their proportions to it, with baseline shifts following. Every character's leading is its size plus lineGap, and the layout sets every paragraph with wordGap as its Desired word spacing, its Minimum or Maximum moving out to wordGap when wordGap lies outside it (the paragraphs keep their own Justification… values, which apply again when Block is off; the gaps are area type's, and are kept while Block is off; a gap with no area type in the selection, and no point type it turns into area type, is an error). The sizes are written into the characters and fitted again after every edit to the text or the frame, in the same undo step; at a size limit a line can be narrower than the frame or wrap. An empty line keeps its size. Block replaces Auto Size and Shrink Text to Fit (Area Type Options › Block is the same setting). Off, the text keeps the sizes it was drawn at. Turning it on turns point type into area type with Block on, with the default Area Type Options but the gaps (options kept from an earlier frame do not carry over): the frame is as wide (along the lines) as the widest line as typed with its paragraph's indents, so that line keeps its size and sits where it was (by its own alignment), the other lines are set to that width (when negative indents take more than that line's width, the frame is as wide as the line, and Block makes it larger), and the frame then grows in depth (down, or to the left for vertical type) to hold every fitted line, around any Text Wrap objects above it; the gaps apply to it as to area type. Point type with no line to fit (empty, or only spaces and breaks) is left as it is, and so is point type when it is turned off; a selection holding type in a thread is refused (threading type turns Dynamic Text off, keeping its drawn sizes). When nothing changes, no undo step is recorded → {on, ids, fitScale (the first object's factor; 1 when off and for area type), wordGap?, lineGap? (the first area type's; left out without area type)}", has_dynamic_type, dynamic_text ), + cmd!( + "type.dynamicTextPreset", + "Dynamic Text Presets", + ["Type", "Dynamic Text Presets"], + None, + "{preset: \"circle\"|\"arch\"|\"bow\", position?: \"above\"|\"center\"|\"below\", flip?: bool, ids?|id?} put the selected point type and type on a path on a new path of the preset's shape with Dynamic Text on, so the text is sized to fill it (see type.dynamicText). Circle: a circle as wide as the text, the text running clockwise round all of it from its bottom; Arch: an arc of a circle bulging upward over 120°, as wide as the text; Bow: the same arc bulging downward. The width is, for point type, the length on the page of the longer side of the text's bounds, and for type on a path the longer side of its path's bounds on the page (so the same preset again leaves it as it is); the new path is centered where they were, and the shape is upright on the page when the object is rotated or scaled. position (omitted: above) sets Type on a Path Options › Align to Path: above stands the type on the path (descender), center centers it on the path (center), below hangs it from the path (ascender); flip true then turns the text to the other side of its path, running the other way. Type on a Path Options › effect and spacing stay. Area type in the selection is left as it is; a selection holding type on a path in a thread is refused. When nothing changes, no undo step is recorded → {ids, fitScale (the first object's factor)}", + has_preset_type, + dynamic_text_preset + ), cmd!( "type.fillPlaceholder", "Fill with Placeholder Text", @@ -302,7 +329,10 @@ fn to_area(s: &mut Session, p: &Value) -> Result<Value> { continue; } let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); - let mut b = if lay.bounds.area() > 0.0 { lay.bounds } else { t.estimate_bounds() }; + // The frame is worked out in line space, where the lines are; vertical type turns it + // into text space with the lines. + let text_bounds = if lay.bounds.area() > 0.0 { lay.bounds } else { t.estimate_bounds() }; + let mut b = lay.line_xf.inverse().transform_rect_bbox(text_bounds); // Across, the frame spans the lines as they are aligned: from their starts to their ends // without the tracking after their last characters (`LineInfo::trailing`), not to the // ink, which tracking can pull past an advance. Area type aligns them alike. @@ -316,14 +346,8 @@ fn to_area(s: &mut Session, p: &Value) -> Result<Value> { // A little slack on the right so the text doesn't rewrap. let top = lay.lines.first().map(|l| l.baseline - l.ascent).unwrap_or(b.y0).min(b.y0); let slack = size * 0.5 + trailing; - // Slack goes where the alignment leaves room, so the text doesn't move or rewrap. - let (sl, sr) = match t.para_at(0).justify { - Justify::Center | Justify::JustifyCenter => (slack * 0.5, slack * 0.5), - Justify::Right | Justify::JustifyRight => (slack, 0.0), - Justify::Auto if lay.lines.first().is_some_and(|l| l.rtl) => (slack, 0.0), - _ => (0.0, slack), - }; - let frame = Rect::new(b.x0 - sl, top, b.x1 + sr, b.y1.max(top + 1.0)); + let (sl, sr) = slack_sides(t.para_at(0).justify, lay.lines.first().is_some_and(|l| l.rtl), slack); + let frame = lay.line_xf.transform_rect_bbox(Rect::new(b.x0 - sl, top, b.x1 + sr, b.y1.max(top + 1.0))); t.kind = TextKind::Area { frame: shapes::rectangle(frame) }; refresh_bounds(t); } @@ -332,6 +356,107 @@ fn to_area(s: &mut Session, p: &Value) -> Result<Value> { Ok(ids_json(&ids)) } +/// How `slack` added to point type's lines in a frame is shared before and after them: where the +/// alignment leaves room, so the text doesn't move or rewrap. +fn slack_sides(justify: Justify, rtl: bool, slack: f64) -> (f64, f64) { + match justify { + Justify::Center | Justify::JustifyCenter => (slack * 0.5, slack * 0.5), + Justify::Right | Justify::JustifyRight => (slack, 0.0), + Justify::Auto if rtl => (slack, 0.0), + _ => (0.0, slack), + } +} + +/// Point type `t` turned into area type with Dynamic Text's Block on, with the default Area Type +/// Options but its gaps: the frame takes the room along the lines that keeps the widest line as +/// typed at its size ([`needed_room`]), placed so that line stays where it is by its own +/// alignment, and after the fit it takes the depth that holds every line, so nothing overflows. +/// Lines run in line space (for vertical type, down the page), and the frame is mapped to the +/// type's own space by the layout's `line_xf`. `wrap` is the Text Wrap shapes the new area type +/// takes, in the type's own space, which the fit and the depth follow. When negative indents take +/// more than the widest line's width, the frame is as wide as that line and placed so that the +/// line keeps its aligned point. None when no line has a +/// width (empty text, or only spaces and breaks), which Block leaves at its size. +fn point_to_block(t: &TextObject, wrap: &[vectorcraft_doc::WrapShape]) -> Option<TextObject> { + let db = vectorcraft_text::FontDb::global(); + // Options point type kept from a frame it had before (columns, inset, alignment, first + // baseline) do not carry over to the new frame. + let mut t = t.clone(); + let (word_gap, line_gap) = (t.area.word_gap, t.area.line_gap); + t.area = vectorcraft_doc::AreaOptions { word_gap, line_gap, ..Default::default() }; + t.wrap = wrap.to_vec(); + let t = &t; + // The room is measured as Block sets the lines in a frame, with the word gap. + let as_block = TextObject { dynamic_text: true, kind: TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)) }, ..t.clone() }; + let (room, widest, para_index) = needed_room(&as_block)?; + let lay = vectorcraft_text::layout(db, t); + let first = lay.lines.first()?; + let line = lay.lines.iter().find(|l| l.start == widest)?; + // Across, the widest line as it is aligned, with its paragraph's indents, which the frame holds. + let para = t.para_at(para_index); + let starts = widest == 0 || t.plain_text().as_bytes().get(widest - 1) == Some(&b'\n'); + let start_indent = para.laid_out_left_indent() + if starts { para.first_line_indent } else { 0.0 }; + // A horizontal right-to-left list paragraph has its indents mirrored, as the layout sets them. + let mirror = line.rtl && !t.vertical && para.list.is_some(); + let (left, right) = if mirror { (para.right_indent, start_indent) } else { (start_indent, para.right_indent) }; + let (lo, hi) = (line.x0 - left, line.x1 - line.trailing + right); + let top = lay.lines.iter().map(|l| l.baseline - l.ascent).fold(first.baseline - first.ascent, f64::min); + let bottom = lay.lines.iter().map(|l| l.baseline + l.descent).fold(top, f64::max); + if ![lo, hi, top, bottom, room].iter().all(|v| v.is_finite()) { + return None; + } + // Negative indents can take more than the line's width (hi below lo); the frame is then wider + // than the line with its indents, and the same split of the difference keeps the line's + // aligned point (its start, center or end) where it was when Block makes the line fill it. + let (sl, _) = slack_sides(para.justify, line.rtl, room - (hi - lo)); + let frame = |depth: f64| lay.line_xf.transform_rect_bbox(Rect::new(lo - sl, top, lo - sl + room, top + depth.max(1.0))); + let start = frame(bottom - top); + let mut out = t.clone(); + out.kind = TextKind::Area { frame: shapes::rectangle(start) }; + out.dynamic_text = true; + refresh_bounds(&mut out); + // The lines fitted in one cell from the frame's top deep enough for all of them (every line at + // the largest size Block sets), around any wrap shapes, give the depth the frame takes. + let mut probe = out.clone(); + let points = t.style_scale().map_or(1.0, |s| s.points).max(1e-12); + let deep = (bottom - top) + (lay.lines.len() as f64 + 1.0) * 3.0 * (1296.0 + out.area.line_gap.abs()) / points; + // Wrap shapes push lines on past them (an inverted one holds them inside it), so the cell also + // reaches as far again as the farthest one reaches past the frame's top. + let inv = lay.line_xf.inverse(); + let deep = deep + + wrap + .iter() + .filter_map(|w| w.path.bounds().map(|r| inv.transform_rect_bbox(r)).map(|r| (r.y1 - top).max(0.0) + 2.0 * w.wrap.offset.abs())) + .filter(|d| d.is_finite()) + .fold(0.0, f64::max); + probe.kind = TextKind::Area { frame: shapes::rectangle(frame(deep)) }; + if !wrap.is_empty() { + refresh_bounds(&mut probe); + } + let laid = vectorcraft_text::layout(db, &probe); + if laid.overflow { + return Some(out); + } + let mut grown = start; + for l in &laid.lines { + for y in [l.baseline - l.ascent, l.baseline + l.descent] { + grown = grown.union_pt(laid.line_xf * vectorcraft_geom::Point::new(l.x0, y)); + } + } + // Only the depth grows (for vertical type, the columns run on to the left), with a hundredth + // of a point to spare. + if t.vertical { + (grown.y0, grown.y1, grown.x0) = (start.y0, start.y1, grown.x0 - 0.01); + } else { + (grown.x0, grown.x1, grown.y1) = (start.x0, start.x1, grown.y1 + 0.01); + } + if grown.is_finite() && grown != start { + out.kind = TextKind::Area { frame: shapes::rectangle(grown) }; + refresh_bounds(&mut out); + } + Some(out) +} + /// (run, byte within the run) for a byte offset into the plain text. fn locate(runs: &[TextRun], byte: usize) -> Option<(usize, usize)> { let mut off = 0; @@ -359,6 +484,8 @@ fn to_point(s: &mut Session, p: &Value) -> Result<Value> { // Point type is in no thread: its first paragraph starts in it. t.first_para_continues = false; let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + // The lines are in line space; the frame's bounds are taken there too. + let fb = lay.line_xf.inverse().transform_rect_bbox(fb); let plain = t.plain_text(); let baseline = lay.lines.first().map(|l| l.baseline).unwrap_or(fb.y0 + t.first_style().size * 0.8); // Soft wraps → explicit breaks (replace the space before the wrap when there is one). @@ -401,8 +528,14 @@ fn to_point(s: &mut Session, p: &Value) -> Result<Value> { Justify::Auto if lay.lines.first().is_some_and(|l| l.rtl) => x1, _ => x0, }; + // Point type has no Dynamic Text: Block is turned off, keeping the sizes it set, so + // converting back to area type does not turn it on again. + t.dynamic_text = false; t.kind = TextKind::Point; - t.xf *= Affine::translate((ox, baseline)); + // The origin is in the area type's line space; point type's line space puts its own + // origin there (vertical point type turns its lines about a different point). + let point_xf = if lay.vertical { vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).line_xf } else { Affine::IDENTITY }; + t.xf *= lay.line_xf * Affine::translate((ox, baseline)) * point_xf.inverse(); refresh_bounds(t); } Ok(()) @@ -410,6 +543,136 @@ fn to_point(s: &mut Session, p: &Value) -> Result<Value> { Ok(ids_json(&ids)) } +/// Whether type on a path `t` runs along one closed path (no open or compound path). +fn on_one_closed_path(t: &TextObject) -> bool { + matches!(&t.kind, TextKind::OnPath { path, .. } if path.subpaths.len() == 1 && path.is_closed()) +} + +/// Why `type.pathCenter.top` and `.bottom` refuse type on a path `ids`: those on an open or +/// compound path, then those in a thread; None when they take every one. +fn path_center_refusal(d: &Document, ids: &[NodeId]) -> Option<String> { + let open = ids.iter().filter(|id| !path_text(d.node(**id)).is_some_and(on_one_closed_path)).map(|id| id.0.to_string()).collect::<Vec<_>>(); + if !open.is_empty() { + let open = open.join(", "); + return Some(format!("type on an open or compound path cannot be centered on its top or bottom: {open}")); + } + let frames = threaded_ids(d, ids); + (!frames.is_empty()).then(|| format!("type on a path in a thread cannot be centered on its top or bottom: {frames}")) +} + +/// `type.pathCenter.top` and `.bottom` are enabled for a selection holding type on a path, all of +/// it on one closed path and none of it in a thread. +fn has_closed_path_type(s: &Session) -> std::result::Result<(), String> { + has_selection(s)?; + let st = s.active().ok_or("no document open")?; + let d = &st.doc; + let selected: Vec<NodeId> = st.selection.objects.to_vec(); + let paths: Vec<NodeId> = text_ids(d, &selected).into_iter().filter(|id| path_text(d.node(*id)).is_some()).collect(); + if paths.is_empty() { + return Err("select type on a closed path".into()); + } + path_center_refusal(d, &paths).map_or(Ok(()), Err) +} + +/// The brackets that center type on a path `t` on its path's topmost point (`bottom`: its +/// bottommost) as `t.xf` draws it, its span keeping its length; None for a path with no length or +/// no height. +fn centered_brackets(t: &TextObject, bottom: bool) -> Option<(f64, Option<f64>)> { + let TextKind::OnPath { path, end, .. } = &t.kind else { return None }; + let (from, to) = t.kind.path_span()?; + let arc = vectorcraft_geom::ArcPath::new(path); + if arc.is_empty() { + return None; + } + let flip = if bottom { Affine::FLIP_Y } else { Affine::IDENTITY }; + let middle = arc.topmost(flip * t.xf)? / arc.len(); + let run = to - from; + let start = (middle - run * 0.5).rem_euclid(1.0).clamp(0.0, 1.0); + // Without an end bracket the type runs once round; a full turn's end stays on its start. + let end = end.map(|_| if run >= 1.0 - 1e-12 { start } else { (start + run).rem_euclid(1.0).clamp(0.0, 1.0) }); + Some((start, end)) +} + +/// Whether brackets `a` and `b`, fractions of a closed path's length, are at one place within +/// rounding (0 and 1 are one place). +fn same_bracket(a: f64, b: f64) -> bool { + let d = (a - b).rem_euclid(1.0); + d.min(1.0 - d) <= 1e-9 +} + +fn path_center_top(s: &mut Session, p: &Value) -> Result<Value> { + path_center(s, p, false) +} + +fn path_center_bottom(s: &mut Session, p: &Value) -> Result<Value> { + path_center(s, p, true) +} + +/// Type › Type on a Path › Center on Top and Center on Bottom: slide the selected type on closed +/// paths along them so the middle of each span lands on the path's top (`bottom`: its bottom) as +/// drawn, and center the first paragraph, in one undo step; none when nothing changes. +fn path_center(s: &mut Session, p: &Value, bottom: bool) -> Result<Value> { + let c = if bottom { "type.pathCenter.bottom" } else { "type.pathCenter.top" }; + let centered = |j: Justify| matches!(j, Justify::Center | Justify::JustifyCenter); + // Each object the command changes, with its new brackets when they move and whether its first + // paragraph is set to Center. + let (ids, changes) = { + let d = &s.doc()?.doc; + let ids: Vec<NodeId> = texts(s, p, c)?.into_iter().filter(|i| path_text(d.node(*i)).is_some()).collect(); + if ids.is_empty() { + return Err(bad(c, "select type on a closed path")); + } + if let Some(why) = path_center_refusal(d, &ids) { + return Err(bad(c, why)); + } + let (mut changes, mut flat) = (vec![], vec![]); + for id in &ids { + let Some(t) = path_text(d.node(*id)) else { continue }; + let TextKind::OnPath { start, end, .. } = &t.kind else { continue }; + let Some((to_start, to_end)) = centered_brackets(t, bottom) else { + flat.push(id.0.to_string()); + continue; + }; + let stays = same_bracket(*start, to_start) + && match (end, to_end) { + (None, None) => true, + (Some(a), Some(b)) => same_bracket(*a, b), + _ => false, + }; + let align = !centered(t.para_at(0).justify); + if !stays || align { + changes.push((*id, (!stays).then_some((to_start, to_end)), align)); + } + } + if !flat.is_empty() { + let flat = flat.join(", "); + return Err(bad(c, format!("type on a path with no length or no height cannot be centered: {flat}"))); + } + (ids, changes) + }; + if !changes.is_empty() { + s.edit(if bottom { "Center on Bottom" } else { "Center on Top" }, |d, _| { + for (id, brackets, align) in &changes { + let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { continue }; + if let (Some(b), TextKind::OnPath { start, end, .. }) = (brackets, &mut t.kind) { + (*start, *end) = *b; + } + if *align { + t.edit_paras(Some(0..1), |para| para.justify = Justify::Center); + } + refresh_bounds(t); + } + Ok(()) + })?; + } + let d = &s.doc()?.doc; + let (start, end) = ids.first().and_then(|id| path_text(d.node(*id))).map_or((0.0, None), |t| match &t.kind { + TextKind::OnPath { start, end, .. } => (*start, *end), + _ => (0.0, None), + }); + Ok(json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "start": start, "end": end})) +} + /// The options `type.pathOptions` sets; with none of them given it queries. const PATH_OPTIONS: [&str; 6] = ["start", "end", "flip", "effect", "alignToPath", "spacing"]; @@ -530,14 +793,23 @@ fn dynamic_type(n: Option<&Node>) -> Option<&TextObject> { path_text(n).or_else(|| area_text(n)) } -/// `type.dynamicText` is enabled for a selection holding type on a path or area type, none of it -/// in a thread. +/// Type `type.dynamicText` takes: type on a path, area type, and point type, which it turns into +/// area type with Block on. +fn dynamic_target(n: Option<&Node>) -> Option<&TextObject> { + match n.map(|n| &n.kind) { + Some(NodeKind::Text(t)) if matches!(t.kind, TextKind::Point) => Some(t), + _ => dynamic_type(n), + } +} + +/// `type.dynamicText` is enabled for a selection holding type on a path, area type or point type, +/// none of it in a thread. fn has_dynamic_type(s: &Session) -> std::result::Result<(), String> { has_selection(s)?; let st = s.active().ok_or("no document open")?; let d = &st.doc; let selected: Vec<NodeId> = st.selection.objects.to_vec(); - let types: Vec<NodeId> = text_ids(d, &selected).into_iter().filter(|id| dynamic_type(d.node(*id)).is_some()).collect(); + let types: Vec<NodeId> = text_ids(d, &selected).into_iter().filter(|id| dynamic_target(d.node(*id)).is_some()).collect(); if types.is_empty() { return Err("select type on a path or area type".into()); } @@ -563,32 +835,46 @@ fn threaded_ids(d: &Document, ids: &[NodeId]) -> String { /// Type › Dynamic Text: set `on` (without it, the opposite of the first object's setting, or on /// when a gap is given) on the selected type on a path and area type (Block, with its gaps), in -/// one undo step, and none when nothing changes. Turning it off keeps the sizes the text was drawn -/// at ([`bake_dynamic_text`]). +/// one undo step, and none when nothing changes. Turning it on also turns the selected point type +/// into area type with Block on ([`point_to_block`]). Turning it off keeps the sizes the text was +/// drawn at ([`bake_dynamic_text`]). fn dynamic_text(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "type.dynamicText"; let (word_gap, line_gap) = block_gaps(p, C)?; - let (ids, on, planned) = { + let (ids, on, planned, converted) = { let d = &s.doc()?.doc; - let ids: Vec<NodeId> = texts(s, p, C)?.into_iter().filter(|i| dynamic_type(d.node(*i)).is_some()).collect(); + let ids: Vec<NodeId> = texts(s, p, C)?.into_iter().filter(|i| dynamic_target(d.node(*i)).is_some()).collect(); let first = *ids.first().ok_or_else(|| bad(C, "select type on a path or area type"))?; if let Some(why) = threaded_refusal(d, &ids) { return Err(bad(C, why)); } let gap_given = word_gap.is_some() || line_gap.is_some(); - if gap_given && !ids.iter().any(|id| area_text(d.node(*id)).is_some()) { + let on = switch_or(p, "on", gap_given || !dynamic_type(d.node(first)).is_some_and(|t| t.dynamic_text), C)?; + // Point type with a line to fit, which turning it on makes area type. + let converts = |id: &NodeId| on && dynamic_target(d.node(*id)).is_some_and(|t| matches!(t.kind, TextKind::Point) && needed_room(t).is_some()); + if gap_given && !ids.iter().any(|id| area_text(d.node(*id)).is_some() || converts(id)) { return Err(bad(C, "wordGap and lineGap need area type in the selection")); } - let on = switch_or(p, "on", gap_given || !dynamic_type(d.node(first)).is_some_and(|t| t.dynamic_text), C)?; // Each object as the command leaves it, and only those it changes. let mut planned: Vec<(NodeId, TextObject)> = vec![]; + // The point type that becomes area type, with the gaps applied, by id. + let mut converted: Vec<(NodeId, TextObject)> = vec![]; for id in &ids { - let Some(t) = dynamic_type(d.node(*id)) else { continue }; + let Some(t) = dynamic_target(d.node(*id)) else { continue }; let mut after = t.clone(); - if matches!(t.kind, TextKind::Area { .. }) { + if matches!(t.kind, TextKind::Area { .. } | TextKind::Point) { after.area.word_gap = word_gap.unwrap_or(t.area.word_gap); after.area.line_gap = line_gap.unwrap_or(t.area.line_gap); } + if matches!(t.kind, TextKind::Point) { + // Point type has no Dynamic Text of its own: on, it becomes area type with Block + // on; off, or with no line to fit, it stays as it is. + if let Some(block) = on.then(|| point_to_block(&after, &[])).flatten() { + planned.push((*id, block)); + converted.push((*id, after)); + } + continue; + } match (on, t.dynamic_text) { (true, true) => refresh_bounds(&mut after), (true, false) => { @@ -608,7 +894,7 @@ fn dynamic_text(s: &mut Session, p: &Value) -> Result<Value> { planned.push((*id, after)); } } - (ids, on, planned) + (ids, on, planned, converted) }; if !planned.is_empty() { s.edit("Dynamic Text", |d, _| { @@ -617,6 +903,19 @@ fn dynamic_text(s: &mut Session, p: &Value) -> Result<Value> { **t = after.clone(); } } + if converted.is_empty() { + return Ok(()); + } + // The new area type takes the Text Wrap shapes above it; one that has any is fitted + // again around them, with the depth that holds every line. + for id in vectorcraft_doc::text::resolve_wrap(None, d) { + let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) else { continue }; + let block = converted.iter().find(|(c, _)| *c == id).and_then(|(_, src)| point_to_block(src, &t.wrap)); + match block { + Some(block) => **t = block, + None => refresh_bounds(t), + } + } Ok(()) })?; } @@ -648,6 +947,196 @@ pub(crate) fn bake_dynamic_text(t: &mut TextObject) -> bool { true } +/// The shapes of `type.dynamicTextPreset`. +const PRESETS: [&str; 3] = ["circle", "arch", "bow"]; + +/// Point type and type on a path among `ids` and their descendants: the type +/// `type.dynamicTextPreset` puts on a path. +fn preset_ids(d: &Document, ids: &[NodeId]) -> Vec<NodeId> { + text_ids(d, ids) + .into_iter() + .filter(|id| matches!(d.node(*id).map(|n| &n.kind), Some(NodeKind::Text(t)) if matches!(t.kind, TextKind::Point | TextKind::OnPath { .. }))) + .collect() +} + +/// `type.dynamicTextPreset` is enabled for a selection holding point type or type on a path, and +/// no type on a path in a thread. +fn has_preset_type(s: &Session) -> std::result::Result<(), String> { + has_selection(s)?; + let st = s.active().ok_or("no document open")?; + let d = &st.doc; + let ids = preset_ids(d, &st.selection.objects); + if ids.is_empty() { + return Err("select point type or type on a path".into()); + } + let frames = threaded_ids(d, &ids); + if !frames.is_empty() { + return Err(format!("type on a path in a thread cannot use Dynamic Text: {frames}")); + } + Ok(()) +} + +/// The path of Dynamic Text preset `preset` (one of [`PRESETS`]) `w` wide, centered on `c`, with +/// the start bracket the text starts at. Circle: a circle `w` across, run clockwise from its +/// bottom; Arch and Bow: a 120° arc of a circle whose chord is `w`, bulging up or down, run from +/// left to right. +fn preset_path(preset: &str, c: vectorcraft_geom::Point, w: f64) -> (vectorcraft_geom::PathData, f64) { + let h = w / 2.0; + if preset == "circle" { + // `shapes::ellipse` runs clockwise on screen from its left: its bottom is 3/4 of the way. + return (shapes::ellipse(Rect::new(c.x - h, c.y - h, c.x + h, c.y + h)), 0.75); + } + // A chord of `w` under 120°: radius w/√3, and the arc rises a half radius above its chord. + let r = w / 3f64.sqrt(); + let arch = preset == "arch"; + let cy = if arch { c.y - r / 4.0 + r } else { c.y + r / 4.0 - r }; + let circle = Rect::new(c.x - r, cy - r, c.x + r, cy + r); + // `shapes::ellipse_arc` runs counterclockwise on screen: right to left over the top. + let mut path = if arch { + shapes::ellipse_arc(circle, 30.0, 150.0, shapes::EllipseMode::Arc) + } else { + shapes::ellipse_arc(circle, 210.0, 330.0, shapes::EllipseMode::Arc) + }; + if arch { + path.reverse(); + } + (path, 0.0) +} + +/// `t` (point type or type on a path) on the path of `preset` with Dynamic Text on, Align to Path +/// `align`, and flipped when `flip`. The shape is made upright on the page and mapped back through +/// the object's transform, so a rotated or scaled object still shows a circle, an arch or a bow. +/// Point type: the path is as wide as the longer side of the text's layout bounds is long on the +/// page, centered on them; with no layout area (empty text), four ems of its first character +/// wide, centered on its estimated bounds. Type on a path: as wide as the longer side of its +/// path's bounds on the page, centered on them, so the same preset again gives the same path. +/// When the object's transform can't be undone, or undoing it gives a path that isn't finite, the +/// shape is made in the text's own space. +fn with_preset(t: &TextObject, preset: &str, align: vectorcraft_doc::PathAlign, flip: bool) -> TextObject { + let invertible = t.xf.is_finite() && t.xf.determinant() != 0.0 && t.xf.inverse().is_finite(); + // The transform the shape was made upright through, with the shape. + let ((path, start, w), xf) = invertible + .then(|| preset_shape(t, preset, t.xf).map(|s| (s, t.xf))) + .flatten() + .or_else(|| preset_shape(t, preset, Affine::IDENTITY).map(|s| (s, Affine::IDENTITY))) + .unwrap_or_else(|| { + let (path, start) = preset_path(preset, vectorcraft_geom::Point::ZERO, 48.0); + ((path, start, 48.0), Affine::IDENTITY) + }); + let mut out = t.clone(); + out.kind = TextKind::OnPath { path, start, end: None }; + out.path_align = align; + out.dynamic_text = true; + if flip { + out.flip_on_path(); + } + // The same preset again measures the path it made, which can differ in the last bits: a path + // within a billionth of its width of the old one on the page keeps the old one, so nothing + // changes. + if let (TextKind::OnPath { path: old, .. }, TextKind::OnPath { path: new, .. }) = (&t.kind, &mut out.kind) + && same_path(&old.transformed(xf), &new.transformed(xf), w * 1e-9) + { + *new = old.clone(); + } + refresh_bounds(&mut out); + out +} + +/// The path of `preset` for `t` made upright through transform `xf` (see [`with_preset`]), in the +/// text's space, with its start bracket and its width on the page; None when the path isn't +/// finite. +fn preset_shape(t: &TextObject, preset: &str, xf: Affine) -> Option<(vectorcraft_geom::PathData, f64, f64)> { + // How long `(x, y)` in the text's space is on the page. + let on_page = |x: f64, y: f64| (xf * vectorcraft_geom::Point::new(x, y) - xf * vectorcraft_geom::Point::ZERO).hypot(); + // The center on the page, and the width measured (0 when nothing can be measured). + let (c, longer) = match &t.kind { + TextKind::OnPath { path, .. } => path + .transformed(xf) + .bounds() + .filter(|b| b.is_finite()) + .map_or((xf * vectorcraft_geom::Point::ZERO, 0.0), |b| (b.center(), b.width().max(b.height()))), + _ => { + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).bounds; + match Some(lay).filter(|b| b.area() > 0.0 && b.is_finite()) { + Some(b) => (xf * b.center(), on_page(b.width(), 0.0).max(on_page(0.0, b.height()))), + None => (xf * Some(t.estimate_bounds()).filter(|b| b.is_finite()).map_or(vectorcraft_geom::Point::ZERO, |b| b.center()), 0.0), + } + } + }; + // Without a measured width: four ems of the first character, else 48 pt. + let size = t.first_style().size; + let w = if longer.is_finite() && longer > 1e-6 { + longer + } else if size.is_finite() && size > 0.0 && on_page(size * 4.0, 0.0) > 1e-6 { + on_page(size * 4.0, 0.0) + } else { + 48.0 + }; + let (path, start) = preset_path(preset, c, w); + let path = path.transformed(xf.inverse()); + let finite = path.subpaths.iter().flat_map(|s| &s.anchors).all(|a| a.p.is_finite() && a.h_in.is_finite() && a.h_out.is_finite()); + (finite && w.is_finite()).then_some((path, start, w)) +} + +/// Whether paths `a` and `b` have the same subpaths, closed alike, with every anchor and handle +/// within `eps` of each other. +fn same_path(a: &vectorcraft_geom::PathData, b: &vectorcraft_geom::PathData, eps: f64) -> bool { + let near = |p: vectorcraft_geom::Point, q: vectorcraft_geom::Point| (p - q).hypot() <= eps; + a.subpaths.len() == b.subpaths.len() + && a.subpaths.iter().zip(&b.subpaths).all(|(s, t)| { + s.closed == t.closed + && s.anchors.len() == t.anchors.len() + && s.anchors.iter().zip(&t.anchors).all(|(x, y)| x.kind == y.kind && near(x.p, y.p) && near(x.h_in, y.h_in) && near(x.h_out, y.h_out)) + }) +} + +/// Type › Dynamic Text Presets: put the selected point type and type on a path on a new path of +/// the preset's shape with Dynamic Text on, in one undo step, and none when nothing changes. +fn dynamic_text_preset(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "type.dynamicTextPreset"; + let key = "preset"; + let preset = choice(p, C, key, &PRESETS)?.ok_or_else(|| bad(C, format!("`{key}` must be one of {}", PRESETS.join(", "))))?; + let align = match choice(p, C, "position", &["above", "center", "below"])? { + Some("center") => vectorcraft_doc::PathAlign::Center, + Some("below") => vectorcraft_doc::PathAlign::Ascender, + _ => vectorcraft_doc::PathAlign::Descender, + }; + let flip = switch_or(p, "flip", false, C)?; + let (ids, changed) = { + let d = &s.doc()?.doc; + let ids = preset_ids(d, &targets(s, p)?); + if ids.is_empty() { + return Err(bad(C, "select point type or type on a path")); + } + let frames = threaded_ids(d, &ids); + if !frames.is_empty() { + return Err(bad(C, format!("type on a path in a thread cannot use Dynamic Text: {frames}"))); + } + let changed: Vec<(NodeId, TextObject)> = ids + .iter() + .filter_map(|id| match d.node(*id).map(|n| &n.kind) { + Some(NodeKind::Text(t)) => Some((*id, with_preset(t, preset, align, flip))).filter(|(_, new)| new != &**t), + _ => None, + }) + .collect(); + (ids, changed) + }; + if !changed.is_empty() { + s.edit("Dynamic Text", |d, _| { + for (id, new) in &changed { + if let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) { + **t = new.clone(); + } + } + Ok(()) + })?; + } + let d = &s.doc()?.doc; + let fit = + ids.first().and_then(|id| path_text(d.node(*id))).map_or(1.0, |t| vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).fit_scale); + Ok(json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "fitScale": fit})) +} + // ---------- placeholder / insert ---------- /// VectorCraft's own placeholder copy (not the classical Latin text). diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index ad70f047bc..74c89d1089 100644 --- a/crates/engine/src/cmd/variablecmds.rs +++ b/crates/engine/src/cmd/variablecmds.rs @@ -27,6 +27,7 @@ mod csv; mod library; use csv::{MAX_GRAPH_CSV, dataset_export, dataset_import}; +pub(crate) use library::{give_svg_library, svg_library}; use library::{load_library, save_library}; /// The longest variable or dataset name, in characters (names arrive from MCP and files). @@ -46,9 +47,9 @@ fn selection_and_unlocked(s: &Session) -> std::result::Result<(), String> { variables_unlocked(s) } -/// Ends a typing session as [`Session::edit`] would, before a helper below compares the document, +/// Ends a typing session as [`Session::edit`] would, before a command compares the document, /// so the typing is its own undo step whether or not the command then changes anything. -fn settle_typing(s: &mut Session) -> Result<()> { +pub(super) fn settle_typing(s: &mut Session) -> Result<()> { if !s.previewing && super::typing_in_progress(s) { super::settle_interaction(s)?; } diff --git a/crates/engine/src/cmd/variablecmds/library.rs b/crates/engine/src/cmd/variablecmds/library.rs index 54f3689e99..e1f4ae0bd5 100644 --- a/crates/engine/src/cmd/variablecmds/library.rs +++ b/crates/engine/src/cmd/variablecmds/library.rs @@ -1,6 +1,8 @@ +use std::collections::HashMap; + use super::{ - BTreeMap, BTreeSet, DataSet, DataValue, EngineError, MAX_NAME, Result, Session, Value, Variable, VariableKind, absolute_path, bad, json, named, - read_file_head, str_param, variables_unlocked, write_file, + BTreeMap, BTreeSet, DataSet, DataValue, Document, EngineError, MAX_NAME, NodeId, NodeKind, Result, Session, Value, Variable, VariableKind, + Variables, absolute_path, bad, json, named, read_file_head, str_param, variables_unlocked, write_file, }; /// The namespace of a variable library's elements, the default namespace of its data sets' values, @@ -169,12 +171,20 @@ fn without_doctype(xml: &str, cmd: &str) -> Result<String> { } /// A variable library as Load Variable Library reads it: the names of its text variables in the -/// order it declares them, the name and `trait` of each variable of another kind, and its data -/// sets with their text values. -struct Library { +/// order it declares them, the name and `trait` of each variable of another kind, its data sets +/// with their text values, and the element id each text variable's `docRef` names. +pub(crate) struct Library { text: Vec<String>, other: Vec<(String, String)>, datasets: Vec<DataSet>, + refs: Vec<(String, String)>, +} + +impl Library { + /// The element ids the text variables' `docRef`s name. + pub(crate) fn elements(&self) -> std::collections::HashSet<String> { + self.refs.iter().map(|(_, e)| e.clone()).collect() + } } /// Read a variable library: XML whose `variableSets` element holds `variableSet` elements, each @@ -200,7 +210,7 @@ fn parse_library(xml: &str, cmd: &str) -> Result<Library> { return Err(bad(cmd, "the file holds no `variableSets` element")); }; let sets: Vec<roxmltree::Node> = root.children().filter(|n| is(n, "variableSet")).collect(); - let (mut text, mut other, mut declared) = (Vec::new(), Vec::new(), BTreeSet::new()); + let (mut text, mut other, mut declared, mut refs) = (Vec::new(), Vec::new(), BTreeSet::new(), Vec::new()); for var in sets.iter().flat_map(|s| s.children()).filter(|n| is(n, "variables")).flat_map(|v| v.children()).filter(|n| is(n, "variable")) { let name = named(var.attribute("varName"), "varName", cmd)?; if !declared.insert(name.clone()) { @@ -210,7 +220,14 @@ fn parse_library(xml: &str, cmd: &str) -> Result<Library> { return Err(bad(cmd, format!("the variable library declares more than {MAX_LIBRARY_VARIABLES} variables"))); } match var.attribute("trait") { - Some("textcontent") => text.push(name), + Some("textcontent") => { + // `docRef="id('…')"` names the element of the variable's bound object. + let element = var.attribute("docRef").and_then(|r| r.trim().strip_prefix("id('")?.strip_suffix("')")).filter(|e| !e.is_empty()); + if let Some(element) = element { + refs.push((name.clone(), element.to_string())); + } + text.push(name); + } Some(t) => other.push((name, t.chars().take(MAX_NAME).collect())), None => return Err(bad(cmd, format!("variable `{name}` has no `trait`"))), } @@ -253,7 +270,152 @@ fn parse_library(xml: &str, cmd: &str) -> Result<Library> { } datasets.push(DataSet { name, values }); } - Ok(Library { text, other, datasets }) + Ok(Library { text, other, datasets, refs }) +} + +/// The variable library an SVG carries (SVG Options › Include Variable Data), read as +/// [`parse_library`] reads one, or `None` when the SVG holds no `variableSets` element. The +/// element is read on its own, from its start tag to the end tag that closes it +/// ([`variable_sets_range`]), with each reference to an +/// entity whose name starts with `ns_` replaced by the value the text before the element declares +/// for it (up to [`MAX_LIBRARY_ENTITIES`] of them, plain text of at most [`MAX_NAME`] bytes), as +/// files name the library's namespaces with such entities. The `ns_vars`, `ns_custom` and +/// `ns_flows` entities take the library's namespaces when the file doesn't declare them. An +/// element larger than [`MAX_LIBRARY_BYTES`], before or after the replacements, is refused. +pub(crate) fn svg_library(svg: &str) -> Option<Result<Library>> { + const C: &str = "document.open"; + let (start, end) = variable_sets_range(svg)?; + let read = || { + let end = end.ok_or_else(|| bad(C, "the variable library declares no variables"))?; + let element = svg.get(start..end).unwrap_or_default(); + if element.len() > MAX_LIBRARY_BYTES { + return Err(bad(C, format!("the variable library is larger than {MAX_LIBRARY_BYTES} bytes"))); + } + let mut entities: Vec<(String, String)> = Vec::new(); + for decl in svg.get(..start).unwrap_or_default().split("<!ENTITY").skip(1).take(MAX_LIBRARY_ENTITIES) { + let decl = decl.trim_start(); + let Some((name, rest)) = decl.split_once(|c: char| c.is_ascii_whitespace()) else { continue }; + let rest = rest.trim_start(); + let Some(quote) = rest.chars().next().filter(|q| matches!(q, '"' | '\'')) else { continue }; + let Some(value) = rest.get(1..).and_then(|v| v.split(quote).next()) else { continue }; + if name.starts_with("ns_") && name.len() <= MAX_NAME && value.len() <= MAX_NAME && !value.contains(['<', '&', '%', '"']) { + entities.push((format!("&{name};"), value.to_string())); + } + } + for (name, value) in [("&ns_vars;", NS_VARIABLES), ("&ns_custom;", NS_CUSTOM), ("&ns_flows;", NS_FLOWS)] { + if !entities.iter().any(|(n, _)| n == name) { + entities.push((name.to_string(), value.to_string())); + } + } + // Counted before anything is replaced, so a hostile file can't make a large text first. + let grown = + entities.iter().map(|(name, value)| element.matches(name.as_str()).count() * value.len().saturating_sub(name.len())).sum::<usize>(); + if element.len() + grown > MAX_LIBRARY_BYTES { + return Err(bad(C, format!("the variable library's entities expand to more than {MAX_LIBRARY_BYTES} bytes"))); + } + let mut element = element.to_string(); + for (name, value) in &entities { + element = element.replace(name.as_str(), value); + } + parse_library(&format!("<svg>{element}</svg>"), C) + }; + Some(read()) +} + +/// Where the first `variableSets` element of `svg` that is markup starts, and where the end tag +/// that closes it ends (`None` when no end tag does), or `None` when there is no such element. +/// Comments, CDATA sections, processing instructions and the document type declaration are +/// skipped, so text inside them that looks like the element is not taken for it. +fn variable_sets_range(svg: &str) -> Option<(usize, Option<usize>)> { + const NAME: &str = "variableSets"; + // The element's name ends at white space, `>` or `/`. + let named = |rest: &str| rest.strip_prefix(NAME).is_some_and(|r| r.starts_with(|c: char| c.is_ascii_whitespace() || matches!(c, '>' | '/'))); + if !svg.contains("<variableSets") { + return None; + } + let (mut at, mut start, mut depth) = (0, None, 0usize); + while let Some(off) = svg.get(at..).and_then(|s| s.find('<')) { + at += off; + let rest = svg.get(at..).unwrap_or_default(); + // The end of a construct that holds text, or of the tag at `at`. + let past = |close: &str| rest.find(close).map(|e| at + e + close.len()); + let next = if rest.starts_with("<!--") { + past("-->") + } else if rest.starts_with("<![CDATA[") { + past("]]>") + } else if rest.starts_with("<?") { + past("?>") + } else if rest.starts_with("<!DOCTYPE") { + // An internal subset ends at `]`, then the declaration at `>`. + match (rest.find('['), rest.find('>')) { + (Some(open), Some(gt)) if open < gt => { + rest.get(open..).and_then(|s| s.find(']')).and_then(|c| rest.get(open + c..)?.find('>').map(|g| at + open + c + g + 1)) + } + (_, gt) => gt.map(|g| at + g + 1), + } + } else if let Some(close) = rest.strip_prefix("</") { + let tag_end = past(">"); + if let Some(s) = start + && named(close) + { + depth = depth.saturating_sub(1); + if depth == 0 { + return Some((s, tag_end)); + } + } + tag_end + } else { + let tag_end = past(">"); + if named(rest.get(1..).unwrap_or_default()) { + let empty = tag_end.and_then(|e| svg.get(..e)).is_some_and(|t| t.ends_with("/>")); + if start.is_none() { + start = Some(at); + } + if empty && depth == 0 { + return Some((at, tag_end)); + } + depth += usize::from(!empty); + } + tag_end + }; + let Some(next) = next else { break }; + at = next; + } + start.map(|s| (s, None)) +} + +/// Give `doc`, opened from an SVG, the variable data `lib` it carries ([`svg_library`]): the +/// library's text variables, its data sets, no active data set, and each text variable bound to +/// the type object made of the element its `docRef` names, or the one type object among the +/// objects a group made of it holds (`found`: the object made of each element, by id). A `docRef` +/// that names no type object, or one another variable is bound to already, binds nothing. The art +/// stays as the file draws it. The warning about the variables of other kinds that were left out, +/// if any. +pub(crate) fn give_svg_library(doc: &mut Document, lib: Library, found: &HashMap<String, NodeId>) -> Option<String> { + let mut vars = + Variables { variables: lib.text.iter().map(|n| Variable { name: n.clone(), kind: VariableKind::Text }).collect(), ..Variables::default() }; + vars.datasets = lib.datasets; + // A type object written with a paint of its own, or with fills and strokes of its appearance, + // is a group around its text (and the appearance's paths). + let text_of = |id: NodeId| match doc.node(id).map(|n| &n.kind) { + Some(NodeKind::Text(_)) => Some(id), + Some(NodeKind::Group { children, .. }) => { + let mut texts = children.iter().filter(|c| matches!(c.kind, NodeKind::Text(_))); + match (texts.next(), texts.next()) { + (Some(one), None) => Some(one.id), + _ => None, + } + } + _ => None, + }; + for (name, element) in &lib.refs { + let Some(id) = found.get(element).and_then(|id| text_of(*id)) else { continue }; + if !vars.bindings.contains_key(&id) { + vars.bind(id, name); + } + } + doc.variables = vars.into(); + left_out_warning(lib.other.iter().map(|(_, t)| t.as_str())) } /// Load Variable Library: replace the document's variables and data sets with a variable library's diff --git a/crates/engine/src/cmd/views.rs b/crates/engine/src/cmd/views.rs index 560da3942c..6e26e9a9e6 100644 --- a/crates/engine/src/cmd/views.rs +++ b/crates/engine/src/cmd/views.rs @@ -1,5 +1,6 @@ //! View → New View… / Edit Views…: saved views stored in the document; per-document view -//! toggles (Show Transparency Grid); the Character panel's Snap to Glyph options. +//! toggles (Show Transparency Grid); the Character panel's Snap to Glyph options; the Pixel +//! Snapping Options. use serde_json::{Value, json}; use vectorcraft_apischema::{Bound, Param, ParamSchema, Type, Writes}; @@ -72,6 +73,18 @@ static GLYPH_SNAP: ParamSchema = ParamSchema::new( .returns("the options") .writes(Writes::Preferences); +static PIXEL_SNAP: ParamSchema = ParamSchema::new( + &[ + Param::new("drawing", Type::Boolean).optional(), + Param::new("moving", Type::Boolean).optional(), + Param::new("scaling", Type::Boolean).optional(), + ], + "the Pixel Snapping Options, kept in the preferences (the pixelSnap group, all on by default): which edits View › Snap to Pixel lands on whole pixels: drawing (the points the drawing tools place, the rulers' origin and measured points), moving (the selection, its anchors and segments, artboards and ruler guides moved, and the Rotate, Reflect and Shear tools' drags) and scaling (the edges a bounding-box, Free Transform, artboard or slice handle drags, and the Scale tool's drag); an edit whose option is off snaps as it does with Snap to Pixel off; {} reads them", +) +.returns("the options") +.writes(Writes::Preferences) +.since(4); + pub fn specs() -> Vec<CommandSpec> { vec![ cmd!( @@ -125,6 +138,16 @@ pub fn specs() -> Vec<CommandSpec> { glyph_snap_options, schema: &GLYPH_SNAP ), + cmd!( + query "view.snapToPixel.options", + "Pixel Snapping Options", + [], + None, + "{drawing?: bool, moving?: bool, scaling?: bool} the Pixel Snapping Options, kept in the preferences (the pixelSnap group, all on by default): which edits View › Snap to Pixel lands on whole pixels: drawing (the points the drawing tools place, the rulers' origin and measured points), moving (the selection, its anchors and segments, artboards and ruler guides moved, and the Rotate, Reflect and Shear tools' drags) and scaling (the edges a bounding-box, Free Transform, artboard or slice handle drags, and the Scale tool's drag); an edit whose option is off snaps as it does with Snap to Pixel off; {} reads them → the options", + always, + pixel_snap_options, + schema: &PIXEL_SNAP + ), ] } @@ -133,6 +156,11 @@ fn glyph_snap_options(s: &mut Session, p: &Value) -> Result<Value> { Ok(json!(s.prefs.glyph_snap)) } +fn pixel_snap_options(s: &mut Session, p: &Value) -> Result<Value> { + s.prefs.pixel_snap = s.prefs.pixel_snap.merged(p).map_err(|e| bad("view.snapToPixel.options", e))?; + Ok(json!(s.prefs.pixel_snap)) +} + fn caps_lock(s: &mut Session, p: &Value) -> Result<Value> { if let Some(on) = p.get("on") { s.caps_lock = on.as_bool().ok_or_else(|| bad("view.capsLock", "on must be true or false"))?; @@ -379,15 +407,17 @@ mod tests { ("view.saved.list", json!({"all": true}), "`all`"), ("view.transparencyGrid", json!({"on": 1}), "`on`"), ("view.snapToGlyph.options", json!({"bounds": "off"}), "`bounds`"), + ("view.snapToPixel.options", json!({"moving": "off"}), "`moving`"), + ("view.snapToPixel.options", json!({"drawing": false, "rotating": false}), "`rotating`"), ] { let st = s.doc().unwrap(); let doc = (st.doc.views.clone(), st.history.undo.len(), st.is_dirty()); - let (grid, caps, snap) = (st.transparency_grid, s.caps_lock, s.prefs.glyph_snap); + let (grid, caps, snap, pixel) = (st.transparency_grid, s.caps_lock, s.prefs.glyph_snap, s.prefs.pixel_snap); let e = s.execute(id, ¶ms).unwrap_err().to_string(); assert!(e.contains(id) && e.contains(named), "{id} {params}: {e}"); let st = s.doc().unwrap(); assert_eq!((&st.doc.views, st.history.undo.len(), st.is_dirty()), (&doc.0, doc.1, doc.2), "{id} {params}"); - assert_eq!((st.transparency_grid, s.caps_lock, s.prefs.glyph_snap), (grid, caps, snap), "{id} {params}"); + assert_eq!((st.transparency_grid, s.caps_lock, s.prefs.glyph_snap, s.prefs.pixel_snap), (grid, caps, snap, pixel), "{id} {params}"); } } diff --git a/crates/engine/src/cmd/wand.rs b/crates/engine/src/cmd/wand.rs index c79ec0b86e..218871972f 100644 --- a/crates/engine/src/cmd/wand.rs +++ b/crates/engine/src/cmd/wand.rs @@ -8,7 +8,7 @@ use vectorcraft_color::Paint; use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; use super::select::selectable_ids; -use super::{CommandSpec, EngineError, Result, Session, always, bad, bool_or, cmd, has_doc, id_param, str_param}; +use super::{CommandSpec, EngineError, Result, Session, always, bad, bool_or, cmd, has_doc, object_param, str_param}; /// Magic Wand panel settings. Tolerances: colours as 0–255 RGB distance, stroke weight in /// points, opacity in percent. @@ -152,7 +152,7 @@ fn paintable(doc: &Document) -> Vec<NodeId> { } fn magic_wand(s: &mut Session, p: &Value) -> Result<Value> { - let id = id_param(p, "id").ok_or_else(|| bad("select.magicWand", "missing id"))?; + let id = object_param(p, "id", "select.magicWand")?.ok_or_else(|| bad("select.magicWand", "missing id"))?; let st = s.doc()?; let reference = st.doc.node(id).ok_or(EngineError::NoNode(id))?.clone(); let w = s.menu.wand.clone(); diff --git a/crates/engine/src/cmd/webexport.rs b/crates/engine/src/cmd/webexport.rs index 9e641a6e6a..d1c66d9d3c 100644 --- a/crates/engine/src/cmd/webexport.rs +++ b/crates/engine/src/cmd/webexport.rs @@ -645,7 +645,7 @@ fn flatten(rgba: &[u8], matte: [u8; 3]) -> impl Iterator<Item = [u8; 3]> + '_ { /// The File Info text `s.metadata` lets into the files: `(keyword, text)`. fn metadata(doc: &Document, s: &WebSettings) -> Vec<(&'static str, String)> { - doc.metadata.png_text(&doc.title).into_iter().filter(|(k, _)| s.metadata.keeps(k)).map(|(k, v)| (k, v.into_owned())).collect() + doc.metadata.png_text(doc.info_title()).into_iter().filter(|(k, _)| s.metadata.keeps(k)).map(|(k, v)| (k, v.into_owned())).collect() } /// Encode straight RGBA pixels (`w`×`h`) as `s` says; `doc` gives the metadata. diff --git a/crates/engine/src/cmd/wireframe.rs b/crates/engine/src/cmd/wireframe.rs new file mode 100644 index 0000000000..eeee004b07 --- /dev/null +++ b/crates/engine/src/cmd/wireframe.rs @@ -0,0 +1,148 @@ +//! Window › 3D and Materials › Quick Actions › Expand as Wireframes: each object with a 3D effect +//! becomes a group of stroked paths, the edges of the faces its effect draws. + +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::appearance::AppearanceItem; +use vectorcraft_doc::{Appearance, LineJoin, Node, NodeId, NodeKind, StrokeLayer}; +use vectorcraft_render::effects; + +use super::{CommandSpec, Result, Session, bad, checked_ids_or_selection, cmd, has_doc}; + +const C: &str = "effect.expandAsWireframes"; + +/// The name of the undo step. +const LABEL: &str = "Expand as Wireframes"; + +/// The weight of a wireframe edge's stroke, in points (VectorCraft's own). +pub const WIRE_WEIGHT: f64 = 0.5; + +pub fn specs() -> Vec<CommandSpec> { + vec![cmd!( + "effect.expandAsWireframes", + "Expand as Wireframes", + [], + None, + "{ids?: [..] (default: the selected objects)} replace each object that has a visible 3D effect (Extrude & Bevel, Revolve, Inflate, Rotate or one of their 3D (Classic) forms, on the object or on its fills and strokes) with a group of paths: the edges of the faces the effect draws, as the object is turned and projected now, each edge once (edges that meet end to end make one path, closed where it comes back to its start; curved edges stay curves; geometry effects after the 3D effect, on the object or on a fill or stroke, reshape them too), stroked 0.5 pt black with round joins and no fill (VectorCraft's own); the group takes the object's place, id, name, opacity, blending mode, opacity mask, attributes, slice and text wrap and is selected (a layer stays a layer holding the edges, which are selected, and its ruler guides and paths made into guides; a path inside a compound path in ids stands for the compound path); objects without a visible 3D effect are left as they are; one undo step. An error, with nothing changed, when no object is selected or given, when none has a visible 3D effect, when an object's solid can't be built or the canvas draws its source art in its place, or when one object's wireframe has more than 1,000,000 edges → {ids}", + has_doc, + expand_as_wireframes + )] +} + +/// A wireframe edge's appearance: a 0.5 pt black stroke with round joins and no fill. +fn wire_appearance() -> Appearance { + let mut stroke = StrokeLayer::new(Paint::solid(Color::BLACK), WIRE_WEIGHT); + stroke.join = LineJoin::Round; + Appearance { items: vec![AppearanceItem::Stroke(stroke)], ..Default::default() } +} + +/// The guides (ruler guides and paths made into guides) of layer `n` and then those of the groups +/// and sublayers inside it, in order, added to `out`. A guide from a hidden or locked sublayer, or +/// from one inside a hidden or locked group or sublayer, is hidden or locked itself. +fn guides(n: &Node, hidden: bool, locked: bool, out: &mut Vec<Arc<Node>>) { + let Some(children) = n.children() else { return }; + for c in children.iter().filter(|c| c.is_guide()) { + let mut g = c.clone(); + if hidden || locked { + let g = Arc::make_mut(&mut g); + g.visible &= !hidden; + g.locked |= locked; + } + out.push(g); + } + for c in children.iter().filter(|c| !c.is_guide()) { + guides(c, hidden || !c.visible, locked || c.locked, out); + } +} + +fn expand_as_wireframes(s: &mut Session, p: &Value) -> Result<Value> { + let roots = checked_ids_or_selection(s, p, C)?; + if roots.is_empty() { + return Err(bad(C, "select an object with a 3D effect, or give its id in ids")); + } + // Every wireframe is built before the edit, so a failure leaves the document and its history as + // they are. + let d = &s.doc()?.doc; + let mut wires = vec![]; + let mut seen = std::collections::HashSet::new(); + for id in roots { + // A path inside a compound path stands for the compound path, which draws it. An id given + // twice is expanded once. + let id = super::path::compound_or_self(d, id); + if !seen.insert(id) { + continue; + } + let Some(n) = d.node(id) else { continue }; + if !effects::has_revolve(n) && !effects::has_solid(n) { + continue; + } + let wire = effects::three_d_wireframe_in(Some(d), n).map_err(|e| bad(C, format!("object {}: {e}", id.0)))?; + wires.push((id, wire)); + } + if wires.is_empty() { + return Err(bad(C, "no selected or given object has a visible 3D effect")); + } + let ids: Vec<NodeId> = s.edit(LABEL, |d, sel| { + let mut out = vec![]; + let mut selected = vec![]; + for (id, wire) in wires { + let Some(source) = d.node(id) else { continue }; + if matches!(source.kind, NodeKind::Layer { .. }) { + // A layer stays a layer: its members become the edges, and its 3D effect is removed. + // Its guides and those of its sublayers are not art: they stay, after the edges. + let mut layer = source.clone(); + let mut kept = vec![]; + guides(source, false, false, &mut kept); + let mut children: Vec<Arc<Node>> = wire.into_iter().map(|path| Arc::new(Node::path(d.alloc_id(), path, wire_appearance()))).collect(); + selected.extend(children.iter().map(|c| c.id)); + children.extend(kept); + if let Some(members) = layer.children_mut() { + *members = children; + } + layer.appearance = Default::default(); + if let Some(slot) = d.node_mut(id) { + *slot = layer; + out.push(id); + } + continue; + } + // The group keeps the object's name, visibility, lock, bounding box angle, transparency + // (opacity, blending mode, isolation, knockout and opacity mask), attributes, slice and text + // wrap. + let mut group = Node::group(id, vec![]); + group.name = source.name.clone(); + group.visible = source.visible; + group.locked = source.locked; + group.opacity = source.opacity; + group.blend = source.blend; + group.isolate = source.isolate; + group.knockout = source.knockout; + group.knockout_shape = source.knockout_shape; + group.bbox_angle = source.bbox_angle; + let extras = source.extras(); + let (mask, attrs, slice, wrap) = (extras.mask.clone(), extras.attrs.clone(), extras.slice.clone(), extras.wrap); + if mask.is_some() || attrs.is_some() || slice.is_some() || wrap.is_some() { + let mut e = group.extras_mut(); + e.mask = mask; + e.attrs = attrs; + e.slice = slice; + e.wrap = wrap; + } + let children = wire.into_iter().map(|path| Arc::new(Node::path(d.alloc_id(), path, wire_appearance()))).collect(); + group.kind = NodeKind::Group { children, clip: false }; + if let Some(slot) = d.node_mut(id) { + *slot = group; + out.push(id); + selected.push(id); + } + } + sel.set(selected); + Ok(out) + })?; + Ok(json!({ "ids": ids.iter().map(|id| id.0).collect::<Vec<_>>() })) +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/wireframe/tests.rs b/crates/engine/src/cmd/wireframe/tests.rs new file mode 100644 index 0000000000..7d9265bdbc --- /dev/null +++ b/crates/engine/src/cmd/wireframe/tests.rs @@ -0,0 +1,240 @@ +#![allow(clippy::unwrap_used, clippy::panic)] +use serde_json::{Value, json}; +use vectorcraft_doc::appearance::AppearanceItem; +use vectorcraft_doc::{NodeId, NodeKind}; + +use crate::Session; + +/// A new document with a filled 100 pt square; `effect` is applied to it when given. +fn setup(effect: Option<&str>) -> (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(); + if let Some(effect) = effect { + s.execute("effect.apply", &json!({"effect":effect,"item":null,"params":{}})).unwrap(); + } + (s, id) +} + +fn undo_len(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn run(s: &mut Session, p: Value) -> crate::Result<Value> { + s.execute("effect.expandAsWireframes", &p) +} + +#[test] +fn a_3d_object_becomes_a_selected_group_of_stroked_edges_in_one_undo_step() { + for effect in [ + "threeD.extrude", + "threeD.classicExtrude", + "threeD.revolve", + "threeD.classicRevolve", + "threeD.inflate", + "threeD.rotate", + "threeD.classicRotate", + ] { + let (mut s, id) = setup(Some(effect)); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().name = Some("Box".into()); + let before = s.doc().unwrap().doc.clone(); + let history = undo_len(&s); + let out = run(&mut s, json!({})).unwrap_or_else(|e| panic!("{effect}: {e}")); + assert_eq!(out["ids"], json!([id.0]), "{effect}"); + let st = s.doc().unwrap(); + let group = st.doc.node(id).unwrap(); + let NodeKind::Group { children, clip: false } = &group.kind else { panic!("{effect}: a group") }; + assert!(!children.is_empty(), "{effect}"); + assert_eq!(group.name.as_deref(), Some("Box"), "{effect}"); + assert!(group.appearance.effects.is_empty(), "{effect}: the effect is gone"); + for c in children { + assert!(c.path_data().is_some(), "{effect}: paths only"); + let [AppearanceItem::Stroke(stroke)] = c.appearance.items.as_slice() else { panic!("{effect}: one stroke and no fill") }; + assert_eq!(stroke.width, super::WIRE_WEIGHT); + } + assert_eq!(st.selection.objects, vec![id], "{effect}"); + assert_eq!(undo_len(&s), history + 1, "{effect}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, before, "{effect}"); + } +} + +#[test] +fn the_group_keeps_the_object_s_transparency() { + let (mut s, id) = setup(Some("threeD.extrude")); + s.execute("transparency.set", &json!({"opacity": 50, "knockout": "on"})).unwrap(); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().bbox_angle = 0.25; + let before = s.doc().unwrap().doc.node(id).unwrap().clone(); + run(&mut s, json!({})).unwrap(); + let group = s.doc().unwrap().doc.node(id).unwrap().clone(); + assert!((group.opacity - 0.5).abs() < 1e-6, "{}", group.opacity); + assert_eq!((group.opacity, group.blend, group.knockout), (before.opacity, before.blend, before.knockout)); + assert_eq!(group.bbox_angle, 0.25, "the bounding box keeps its angle"); +} + +#[test] +fn a_layer_with_a_3d_effect_stays_a_layer_holding_the_edges() { + let (mut s, _) = setup(None); + let layer = s.doc().unwrap().doc.layers[0].id; + s.execute("effect.apply", &json!({"ids":[layer.0],"effect":"threeD.extrude","item":null,"params":{}})).unwrap(); + let history = undo_len(&s); + // An id given twice is expanded once. + let out = run(&mut s, json!({"ids":[layer.0, layer.0]})).unwrap(); + assert_eq!(out["ids"], json!([layer.0])); + let st = s.doc().unwrap(); + let node = st.doc.node(layer).unwrap(); + assert!(matches!(node.kind, NodeKind::Layer { .. })); + assert!(node.appearance.effects.is_empty()); + let children = node.children().unwrap(); + assert!(!children.is_empty() && children.iter().all(|c| c.path_data().is_some())); + assert_eq!(st.selection.objects, children.iter().map(|c| c.id).collect::<Vec<_>>()); + assert_eq!(undo_len(&s), history + 1); +} + +/// A layer's ruler guides are not art: they stay on the layer, after the edges, and are not selected. +#[test] +fn a_layer_keeps_its_ruler_guides() { + let (mut s, _) = setup(None); + let layer = s.doc().unwrap().doc.layers[0].id; + s.execute("guide.add", &json!({"vertical": true, "pos": 50})).unwrap(); + let guides = |s: &Session| -> Vec<NodeId> { + s.doc().unwrap().doc.node(layer).unwrap().children().unwrap().iter().filter(|c| c.is_ruler_guide()).map(|c| c.id).collect() + }; + let before = guides(&s); + assert_eq!(before.len(), 1); + s.execute("effect.apply", &json!({"ids":[layer.0],"effect":"threeD.extrude","item":null,"params":{}})).unwrap(); + run(&mut s, json!({"ids":[layer.0]})).unwrap(); + assert_eq!(guides(&s), before); + let st = s.doc().unwrap(); + let children = st.doc.node(layer).unwrap().children().unwrap(); + assert!(children.len() > 1 && children.last().is_some_and(|c| c.is_ruler_guide())); + assert!(!st.selection.objects.is_empty() && st.selection.objects.iter().all(|id| !before.contains(id))); +} + +/// A path made into a guide is not art either: it stays on the layer, after the edges, and is not +/// selected. +#[test] +fn a_layer_keeps_its_path_guides() { + let (mut s, id) = setup(None); + let layer = s.doc().unwrap().doc.layers[0].id; + s.execute("path.create", &json!({"d":"M0 300L300 300"})).unwrap(); + s.execute("view.guides.make", &json!({})).unwrap(); + let guides = |s: &Session| -> Vec<NodeId> { + s.doc().unwrap().doc.node(layer).unwrap().children().unwrap().iter().filter(|c| c.is_guide()).map(|c| c.id).collect() + }; + let before = guides(&s); + assert_eq!(before.len(), 1); + assert_ne!(before[0], id); + s.execute("effect.apply", &json!({"ids":[layer.0],"effect":"threeD.extrude","item":null,"params":{}})).unwrap(); + run(&mut s, json!({"ids":[layer.0]})).unwrap(); + assert_eq!(guides(&s), before); + let st = s.doc().unwrap(); + let children = st.doc.node(layer).unwrap().children().unwrap(); + assert!(children.len() > 1 && children.last().is_some_and(|c| c.is_guide())); + assert!(!st.selection.objects.is_empty() && st.selection.objects.iter().all(|i| !before.contains(i))); +} + +/// The number of segments in the wireframe group `id`. +fn segments(s: &Session, id: NodeId) -> usize { + let st = s.doc().unwrap(); + st.doc.node(id).unwrap().children().unwrap().iter().flat_map(|c| &c.path_data().unwrap().subpaths).map(|sp| sp.segment_count()).sum() +} + +#[test] +fn a_box_expands_to_the_nine_edges_of_its_three_faces() { + let (mut s, id) = setup(Some("threeD.extrude")); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + run(&mut s, json!({"ids":[id.0]})).unwrap(); + assert_eq!(segments(&s, id), 9); + // A stroke is outlined before the effect, so its own solid adds its edges. + let (mut s, id) = setup(Some("threeD.extrude")); + run(&mut s, json!({"ids":[id.0]})).unwrap(); + assert!(segments(&s, id) > 9); +} + +#[test] +fn objects_without_a_3d_effect_are_left_and_none_at_all_is_an_error() { + let (mut s, plain) = setup(None); + let history = undo_len(&s); + let before = s.doc().unwrap().doc.clone(); + let e = run(&mut s, json!({})).unwrap_err().to_string(); + assert!(e.contains("no selected or given object has a visible 3D effect"), "{e}"); + assert_eq!(undo_len(&s), history, "no undo step when nothing changes"); + assert_eq!(s.doc().unwrap().doc, before); + + // A hidden 3D effect draws nothing to expand. + s.execute("effect.apply", &json!({"effect":"threeD.extrude","item":null,"params":{}})).unwrap(); + s.execute("effect.setParams", &json!({"index":0,"item":null,"visible":false})).unwrap(); + assert!(run(&mut s, json!({})).is_err()); + + // With nothing selected. + s.execute("select.none", &json!({})).unwrap(); + let e = run(&mut s, json!({})).unwrap_err().to_string(); + assert!(e.contains("select an object with a 3D effect"), "{e}"); + + // A second object with a 3D effect expands; the plain one is left as it is. + let other = NodeId(s.execute("path.create", &json!({"d":"M250 250L300 250L300 300Z"})).unwrap()["id"].as_u64().unwrap()); + s.execute("effect.remove", &json!({"ids":[plain.0],"index":0,"item":null})).unwrap(); + s.execute("paint.setFill", &json!({"ids":[other.0],"color":"#ff0000"})).unwrap(); + s.execute("effect.apply", &json!({"ids":[other.0],"effect":"threeD.extrude","item":null,"params":{}})).unwrap(); + let kept = s.doc().unwrap().doc.node(plain).unwrap().clone(); + let out = run(&mut s, json!({"ids":[plain.0, other.0]})).unwrap(); + assert_eq!(out["ids"], json!([other.0])); + assert_eq!(s.doc().unwrap().doc.node(plain).unwrap(), &kept); +} + +/// A live-effect plug-in after a fill's 3D effect that links its pieces to one of the document's +/// swatches reshapes the edges, as it reshapes the drawn surface. +#[test] +fn a_painted_effect_after_a_fill_s_3d_effect_finds_the_document_s_swatches() { + use vectorcraft_geom::{PathData, Point, SubPath}; + let mut leaf = serde_json::to_value(vectorcraft_color::Paint::solid(vectorcraft_color::Color::from_hex("#00ff00").unwrap())).unwrap(); + leaf["swatch"] = json!("Leaf"); + let corners = [Point::new(300.0, 300.0), Point::new(320.0, 300.0), Point::new(320.0, 320.0), Point::new(300.0, 320.0)]; + let output = json!({"objects": [{"path": PathData::single(SubPath::polyline(&corners, true)), "fills": [leaf]}]}).to_string(); + let manifest = r#"{"id":"test.engine.wireleaf","name":"Test wireleaf","version":"1","kind":"effect","api":2,"paintOutput":true,"params":{}}"#; + let wasm = wat::parse_str(vectorcraft_plugins::wat::returning(manifest, &output)).unwrap(); + for effect in ["threeD.extrude", "threeD.revolve"] { + let (mut s, id) = setup(None); + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "replace": true})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("swatch.new", &json!({"name": "Leaf", "color": "#00ff00", "global": true})).unwrap(); + let items = &s.doc().unwrap().doc.node(id).unwrap().appearance.items; + let fill = items.iter().position(|i| matches!(i, AppearanceItem::Fill(_))).unwrap(); + for e in [effect, "plugin.test.engine.wireleaf"] { + s.execute("effect.apply", &json!({"ids": [id.0], "effect": e, "item": fill, "params": {}})).unwrap(); + } + run(&mut s, json!({"ids": [id.0]})).unwrap_or_else(|e| panic!("{effect}: {e}")); + let b = s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap(); + assert_eq!((b.x0, b.y0, b.x1, b.y1), (300.0, 300.0, 320.0, 320.0), "{effect}: the plug-in's square"); + assert_eq!(segments(&s, id), 4, "{effect}"); + } +} + +/// A path inside a compound path in `ids` stands for the compound path: the compound path becomes +/// the group, and no member is replaced by a group inside it. +#[test] +fn a_compound_path_member_in_ids_expands_the_compound_path() { + let (mut s, a) = setup(None); + 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 c = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("effect.apply", &json!({"ids":[c.0],"effect":"threeD.extrude","item":null,"params":{}})).unwrap(); + let member = s.doc().unwrap().doc.node(c).unwrap().children().unwrap()[0].id; + let out = run(&mut s, json!({"ids":[member.0]})).unwrap(); + assert_eq!(out["ids"], json!([c.0])); + let st = s.doc().unwrap(); + let NodeKind::Group { children, clip: false } = &st.doc.node(c).unwrap().kind else { panic!("the compound path is a group") }; + assert!(!children.is_empty() && children.iter().all(|ch| ch.path_data().is_some())); +} + +#[test] +fn bad_ids_are_errors() { + let (mut s, _) = setup(Some("threeD.extrude")); + for p in [json!({"ids":[9999]}), json!({"ids":"x"}), json!({"ids":[-1]})] { + let history = undo_len(&s); + assert!(run(&mut s, p.clone()).is_err(), "{p}"); + assert_eq!(undo_len(&s), history, "{p}"); + } +} diff --git a/crates/engine/src/cmd/xform.rs b/crates/engine/src/cmd/xform.rs index 9038598659..1e01c8f62e 100644 --- a/crates/engine/src/cmd/xform.rs +++ b/crates/engine/src/cmd/xform.rs @@ -4,12 +4,12 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_color::Paint; -use vectorcraft_doc::{Node, NodeKind, Scaling}; +use vectorcraft_doc::{Node, NodeKind, OrientedBox, Scaling}; use vectorcraft_geom::{Affine, Point, Rect, Vec2}; use super::edit::{outermost, selected_roots}; use super::{ - CommandSpec, NodeId, Result, Session, always, bad, bool_or, check_numbers, check_switches, checked_ids_param, cmd, color_value, f64_or, + CommandSpec, NodeId, Result, Session, always, bad, bool_or, check_numbers, check_switches, checked_ids_param, cmd, color_value, f64_or, f64_req, find_command, finite_numbers, has_doc, index, }; use crate::EngineError; @@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> { "Free Distort", [], None, - "{corners: [[x,y]×4] (TL, TR, BR, BL), from?: [x0,y0,x1,y1] (default: selection bounds), ids?} projective warp of anchors and handles", + "{corners: [[x,y]×4] (TL, TR, BR, BL), from?: [x0,y0,x1,y1] (default: selection bounds), angle?: degrees (counter-clockwise; `from`, or the selection bounds, is then a box in the frame turned by it, as a rotated bounding box is; default 0), ids?} projective warp of anchors and handles; a linked opacity mask's art is warped with its object, an unlinked one stays", has_doc, distort ), @@ -62,11 +62,14 @@ pub fn specs() -> Vec<CommandSpec> { pub struct Projective { m: [f64; 8], src: Rect, + /// Page → the frame `src` is measured in. + pre: Affine, } impl Projective { - /// Map `src`'s corners (TL, TR, BR, BL) onto `q`. - pub fn from_rect(src: Rect, q: [Point; 4]) -> Self { + /// Map the corners (TL, TR, BR, BL) of `src`, a box that may be turned, onto the page points `q`. + pub fn from_box(bx: OrientedBox, q: [Point; 4]) -> Self { + let src = bx.rect; let [p0, p1, p2, p3] = q; let (dx1, dx2, dx3) = (p1.x - p2.x, p3.x - p2.x, p0.x - p1.x + p2.x - p3.x); let (dy1, dy2, dy3) = (p1.y - p2.y, p3.y - p2.y, p0.y - p1.y + p2.y - p3.y); @@ -80,11 +83,12 @@ impl Projective { let b = p3.x - p0.x + h * p3.x; let d = p1.y - p0.y + g * p1.y; let e = p3.y - p0.y + h * p3.y; - Self { m: [a, b, p0.x, d, e, p0.y, g, h], src } + Self { m: [a, b, p0.x, d, e, p0.y, g, h], src, pre: bx.to_doc().inverse() } } pub fn apply(&self, p: Point) -> Point { let [a, b, c, d, e, f, g, h] = self.m; + let p = self.pre * p; let u = if self.src.width().abs() > 1e-12 { (p.x - self.src.x0) / self.src.width() } else { 0.0 }; let v = if self.src.height().abs() > 1e-12 { (p.y - self.src.y0) / self.src.height() } else { 0.0 }; let w = g * u + h * v + 1.0; @@ -104,7 +108,8 @@ impl Projective { } /// Warp `n`'s anchors and handles; gradients (pinned first if unplaced) follow the warp's affine -/// approximation at their centre. +/// approximation at their center. The art of a linked opacity mask is warped with the object it +/// masks; an unlinked one stays where it is. fn warp_node(n: &mut Node, pr: &Projective) { n.pin_gradients(); match &mut n.kind { @@ -131,6 +136,9 @@ fn warp_node(n: &mut Node, pr: &Projective) { return; } } + if let Some(m) = n.extras_if_any().and_then(|x| x.mask.as_mut()).filter(|m| m.linked) { + warp_node(Arc::make_mut(&mut m.art), pr); + } n.appearance.warp_gradients(&|p| pr.affine_near(p)); } @@ -148,17 +156,29 @@ fn distort(s: &mut Session, p: &Value) -> Result<Value> { if ids.is_empty() { return Err(bad(C, "nothing to distort")); } + let angle = p.get("angle").filter(|v| !v.is_null()).map(|_| f64_req(p, "angle", C)).transpose()?.map_or(0.0, vectorcraft_geom::normalize_deg); let src = match p.get("from").filter(|v| !v.is_null()) { - None => s.doc()?.doc.bounds_of(&ids, false).ok_or_else(|| bad(C, "nothing to distort"))?, + None if angle == 0.0 => OrientedBox::aligned(s.doc()?.doc.bounds_of(&ids, false).ok_or_else(|| bad(C, "nothing to distort"))?), + None => { + // The selection's bounds square to the turned frame. + let doc = &s.doc()?.doc; + let (symbols, to_local) = (doc.symbol_boxes(), OrientedBox { angle, rect: Rect::ZERO }.to_doc().inverse()); + let rect = ids + .iter() + .filter_map(|id| doc.node(*id)) + .fold(None, |acc, n| vectorcraft_geom::union_opt(acc, n.bounds_in(&symbols, to_local, false))); + OrientedBox { angle, rect: rect.ok_or_else(|| bad(C, "nothing to distort"))? } + } Some(v) => { let [x0, y0, x1, y1] = finite_numbers(v).ok_or_else(|| bad(C, "from must be [x0, y0, x1, y1]"))?; - Rect::new(x0, y0, x1, y1) + OrientedBox { angle, rect: Rect::new(x0, y0, x1, y1) } } }; - if !src.width().is_finite() || !src.height().is_finite() || src.width().abs() < 1e-9 || src.height().abs() < 1e-9 { + let r = src.rect; + if !r.width().is_finite() || !r.height().is_finite() || r.width().abs() < 1e-9 || r.height().abs() < 1e-9 { return Err(bad(C, "cannot distort a zero-size or non-finite bounding box")); } - let pr = Projective::from_rect(src, [tl, tr, br, bl]); + let pr = Projective::from_box(src, [tl, tr, br, bl]); s.edit("Free Distort", |d, _| { for id in &ids { if let Some(n) = d.node_mut(*id) { diff --git a/crates/engine/src/command_sets.rs b/crates/engine/src/command_sets.rs index 95b44776f0..ee594bae25 100644 --- a/crates/engine/src/command_sets.rs +++ b/crates/engine/src/command_sets.rs @@ -19,7 +19,9 @@ pub const ON_ACTIVE_ARTBOARD: [&str; 8] = [ /// The commands that resize the artboards the app passes (Object › Artboards): the app passes the /// selected artboards to Fit to Artwork Bounds as its `indices`, and the active artboard to Fit to /// Selected Art as its `index`. A `command.batch` given `artboard` passes it on, as `index`, to -/// each of their steps that names none. +/// each of their steps that names none; a Fit to Artwork Bounds step that names neither `index` nor +/// `indices`, while the Artboard tool is chosen with several artboards selected, gets those as its +/// `indices` instead. pub const FIT_ACTIVE_ARTBOARD: [&str; 2] = ["artboard.fitToArt", "artboard.fitToSelection"]; /// `(command, param)` pairs the journal records only so a replay reproduces the original run @@ -28,7 +30,7 @@ pub const FIT_ACTIVE_ARTBOARD: [&str; 2] = ["artboard.fitToArt", "artboard.fitTo /// Artboard tool had selected for its commands and for Paste in Place, in Front and in Back; the artboards and art Cut and Copy took with that /// tool chosen; the view's center the app passes to Edit Symbol); an action leaves them out /// ([`Session::journal_for_action`]). -const REPLAY_ONLY: [(&str, &str); 29] = [ +const REPLAY_ONLY: [(&str, &str); 35] = [ ("file.new", "created"), ("edit.newDocumentFromState", "created"), ("document.save", "modified"), @@ -50,6 +52,12 @@ const REPLAY_ONLY: [(&str, &str); 29] = [ ("artboard.cut", "selectedArtboards"), ("artboard.rename", "selectedArtboards"), ("artboard.switchOrientation", "selectedArtboards"), + ("artboard.align", "selectedArtboards"), + ("artboard.align", "activeArtboard"), + ("artboard.distribute", "selectedArtboards"), + ("artboard.distribute", "activeArtboard"), + ("artboard.distributeSpacing", "selectedArtboards"), + ("artboard.distributeSpacing", "activeArtboard"), ("edit.copy", "selectedArtboards"), ("edit.copy", "art"), ("edit.cut", "selectedArtboards"), @@ -84,7 +92,7 @@ pub(crate) fn strip_replay_only(id: &str, p: &mut Value) { /// Queries that apply the edit the active tool is computing before they run, as edits do /// ([`Session::finish_tool_edit`]): a batch runs edits, Find Objects with `select`, Select All /// Instances and Lock Guides change the selection, and the proof views, the preferences and added -/// fonts give the documents new revisions (they draw again, and type lays out again). +/// fonts can give the documents new revisions (they draw again, and type lays out again). const WAIT_FOR_TOOL_EDIT: &[&str] = &[ "script.run", "command.batch", @@ -156,6 +164,11 @@ pub(crate) const SELECTS_GIVEN_IDS: &[&str] = &[ "object.ungroup", ]; +/// Commands whose `ids` (or `id`) may name ruler guide nodes as well as objects: the Layers panel's +/// eye and lock on a guide's row, and a drag down either column that passes guide rows. Every other +/// command given a ruler guide's id refuses it (the guide commands take guides by index). +pub(crate) const TAKES_GUIDE_IDS: &[&str] = &["layer.setProps"]; + /// The non-empty `ids` given to a command whose params description names `ids` as a key (the /// key callers outside the app may pass it, [`cmd::params::takes_key`]), or its `id` as `ids` of /// one when no `ids` are given and the description takes `id` so diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index 08b8a2f294..10d21266ba 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -34,6 +34,9 @@ pub struct DocState { /// Select › Start Global Edit: the objects edited together until Stop Global Edit or Escape /// ([`cmd::globaledit`]). Editing state: not saved, not undoable. pub global_edit: Option<cmd::globaledit::GlobalEdit>, + /// The objects Start Global Edit would take, highlighted before it starts + /// ([`cmd::globaledit::similar`]), as of a revision. Not saved, not undoable. + pub(crate) similar_outlines: cmd::globaledit::SimilarCache, /// What leaving symbol editing mode goes back to ([`cmd::symboledit`]). pub(crate) symbol_edit_return: cmd::symboledit::Return, pub interaction: Option<Interaction>, @@ -52,6 +55,11 @@ pub struct DocState { pub recalled_selection: RecalledSelection, /// Process-unique id of this open document (tab indices shift when tabs close). pub uid: u64, + /// How many times File → Revert replaced the document's content in its tab + /// ([`Session::replace_document`]). Work started for the document (a file read for Place, a + /// pasted bitmap) is dropped when this has changed by the time it finishes; edits do not + /// change it, and a batch that fails puts it back with the document. + pub reverts: u64, /// Preferences › User Interface › Open Documents As Tabs when the document opened: cleared, /// the UI opens it in a floating window of its own. pub opened_as_tab: bool, @@ -302,6 +310,7 @@ impl DocState { variables_highlight: None, isolation: None, global_edit: None, + similar_outlines: Default::default(), symbol_edit_return: Default::default(), interaction: None, undo_group: None, @@ -309,6 +318,7 @@ impl DocState { last_selection_cmd: None, recalled_selection: RecalledSelection::default(), uid: NEXT_DOC_UID.fetch_add(1, std::sync::atomic::Ordering::Relaxed), + reverts: 0, opened_as_tab: true, mask_view: None, spelling_ignored: Default::default(), diff --git a/crates/engine/src/error.rs b/crates/engine/src/error.rs index d32fda613d..6ab1608bd7 100644 --- a/crates/engine/src/error.rs +++ b/crates/engine/src/error.rs @@ -3,6 +3,9 @@ use super::{NodeId, cancel}; /// The text of [`EngineError::Busy`], which ends every error a frontend reports for it. pub const SCRIPT_BUSY: &str = "a script is running: stop it or wait for it to finish"; +/// Stable prefix for a save refused by the filesystem: choose another destination. +pub const READ_ONLY_LOCATION: &str = "READ_ONLY_LOCATION"; + #[derive(Debug, thiserror::Error)] pub enum EngineError { #[error("unknown command `{0}`")] @@ -20,6 +23,10 @@ pub enum EngineError { NoNode(NodeId), #[error("{0}")] Other(String), + /// The save's terminal filesystem error refuses writes here. The reason keeps the path and + /// system message. This never means an automation-root refusal or a recovery-copy failure. + #[error("{code}: {0}", code = READ_ONLY_LOCATION)] + ReadOnlyLocation(String), /// The caller asked for the command to stop ([`cancel`]). It changed nothing. #[error("cancelled; nothing was changed")] Cancelled, diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 73c8ba8efe..6ca724d810 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -215,6 +215,20 @@ pub fn check_read(path: &str) -> Result<(), String> { current().map_or(Ok(()), |r| r.check(path, Access::Read)) } +/// Is `path`, under a read root, written as an absolute path of another platform: outside Windows, one +/// that starts with a drive (`C:`) or a `\`? [`check_read`] reads it as a name in the working folder. +pub fn written_elsewhere(path: &str) -> bool { + let foreign = path.starts_with('\\') || matches!(path.as_bytes(), [drive, b':', ..] if drive.is_ascii_alphabetic()); + !cfg!(windows) && foreign && current().is_some() +} + +/// Does a command param named `key` hold a file or folder path: `path`, `paths`, `file`, `files`, +/// `folder`, or a name ending in `Path`, `Paths`, `File`, `Files` or `Folder` (`diffPath`, +/// `destinationFolder`)? +pub fn is_path_key(key: &str) -> bool { + matches!(key, "path" | "paths" | "file" | "files" | "folder") || ["Path", "Paths", "File", "Files", "Folder"].iter().any(|end| key.ends_with(end)) +} + /// May `path` be written here? Always, without roots in force. pub fn check_write(path: &str) -> Result<(), String> { current().map_or(Ok(()), |r| r.check(path, Access::Write))?; diff --git a/crates/engine/src/history.rs b/crates/engine/src/history.rs index cc545b179f..3ab6a7dcb8 100644 --- a/crates/engine/src/history.rs +++ b/crates/engine/src/history.rs @@ -27,7 +27,8 @@ pub struct HistoryEntry { pub(crate) named: Option<NamedStep>, /// A number no other step takes ([`History::step`]). serial: u64, - /// Original and converted new-art colors, only for steps that change document color mode. + /// Original and changed new-art paints, only for steps that change them: a document color mode + /// change, and a pattern Cancel, Delete or rename that clears or renames a pattern paint. pub(crate) color_mode_paints: Option<(vectorcraft_tools::PaintDefaults, vectorcraft_tools::PaintDefaults)>, /// Owned new-art snapshots included in both directional estimates. color_mode_bytes: usize, diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 9bad62a6c8..146583778f 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -285,9 +285,10 @@ fn document_base(s: &Session) -> Value { json!({ "uid": st.uid, "title": st.title(), - // The File Info title (`file.info`), where `title` comes from the file name once the document has one. - "fileInfoTitle": d.title, - "path": st.path, + // The File Info title (`file.info`): the title the file gave itself, else the document's name. `title` is the tab's name. + "fileInfoTitle": d.info_title(), + // Null for a confined caller when the file is outside its read roots. + "path": st.path.as_deref().filter(|p| crate::file_access::check_read(p).is_ok()), "dirty": st.is_dirty(), "revision": st.revision, "units": d.units.label(), diff --git a/crates/engine/src/interaction.rs b/crates/engine/src/interaction.rs index 1de58228a2..e3cd563d55 100644 --- a/crates/engine/src/interaction.rs +++ b/crates/engine/src/interaction.rs @@ -27,6 +27,9 @@ pub struct Interaction { /// A transform or a perspective edit with `copy` keeps the copies it made of the snapshot here /// ([`PreviewCopies`]). pub(crate) copies: Option<Arc<PreviewCopies>>, + /// The bounding box of `selection` in `doc`, measured once for a move drag + /// ([`crate::Session::move_drag_box`]): each step offsets it by the drag's move. + pub(crate) move_box: std::sync::OnceLock<Option<vectorcraft_doc::OrientedBox>>, } /// What Object → Transform → Transform Again (⌘D) repeats ([`SessionState::last_transform`]). diff --git a/crates/engine/src/journal.rs b/crates/engine/src/journal.rs index 230bcfba0d..c9a2547b3c 100644 --- a/crates/engine/src/journal.rs +++ b/crates/engine/src/journal.rs @@ -25,6 +25,8 @@ pub struct Journal { bytes: usize, /// Keep every entry from this number on ([`Journal::hold`]). held: Option<usize>, + /// How many times kept entries were changed, dropped or renumbered ([`Journal::rewrites`]). + rewrites: u64, } /// Journals with the same entries (by number) are equal, whatever their history. @@ -66,14 +68,24 @@ impl Journal { self.entries.get(i.checked_sub(self.dropped)?) } pub fn get_mut(&mut self, i: usize) -> Option<&mut JournalEntry> { + self.rewrites += 1; self.entries.get_mut(i.checked_sub(self.dropped)?) } pub fn last(&self) -> Option<&JournalEntry> { self.entries.last() } pub fn last_mut(&mut self) -> Option<&mut JournalEntry> { + self.rewrites += 1; self.entries.last_mut() } + /// A number that grows whenever a kept entry may have changed, gone or been renumbered + /// ([`Journal::truncate`], [`Journal::remove`], [`Journal::replace`], [`Journal::get_mut`], + /// [`Journal::last_mut`]), and that [`Journal::push`] and letting old entries go leave as it + /// is. While it stays the same, the entries from a held number on are the ones counted before, + /// with the new ones after them. + pub fn rewrites(&self) -> u64 { + self.rewrites + } pub fn push(&mut self, e: JournalEntry) { let size = entry_bytes(&e); self.entries.push(e); @@ -83,6 +95,7 @@ impl Journal { } /// Drop the entries from number `len` on. pub fn truncate(&mut self, len: usize) { + self.rewrites += 1; let keep = len.saturating_sub(self.dropped); self.entries.truncate(keep); self.sizes.truncate(keep); @@ -92,6 +105,7 @@ impl Journal { /// Drop the entries numbered `numbers` (sorted, a number may repeat; the entries of canceled undo /// groups). The entries after them are numbered down to close the gaps. pub fn remove(&mut self, numbers: &[usize]) { + self.rewrites += 1; let dropped = self.dropped; let gone = |i: usize| numbers.binary_search(&(dropped + i)).is_ok(); let mut i = 0; @@ -115,6 +129,7 @@ impl Journal { } /// Put `e` in place of entry number `i`, if kept. pub fn replace(&mut self, i: usize, e: JournalEntry) { + self.rewrites += 1; let Some(k) = i.checked_sub(self.dropped) else { return }; if let (Some(old), Some(size)) = (self.entries.get_mut(k), self.sizes.get_mut(k)) { *size = entry_bytes(&e); @@ -253,4 +268,29 @@ mod tests { j.replace(29_000, big(0)); assert_eq!(j.bytes, j.iter().map(entry_bytes).sum::<usize>()); } + + #[test] + fn rewrites_count_changes_to_kept_entries_but_not_new_ones() { + let mut j = Journal::default(); + j.hold(Some(0)); + for i in 0..100 { + j.push(("object.move".into(), json!({"dx": i}))); + } + assert_eq!(j.rewrites(), 0, "pushes add entries after the counted ones"); + let changes: [fn(&mut Journal); 5] = [ + |j| j.truncate(90), + |j| j.remove(&[3]), + |j| j.replace(4, ("object.group".into(), json!({}))), + |j| { + let _ = j.get_mut(5); + }, + |j| { + let _ = j.last_mut(); + }, + ]; + for (i, change) in changes.into_iter().enumerate() { + change(&mut j); + assert_eq!(j.rewrites(), i as u64 + 1); + } + } } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index c3eeaa2777..e3f2b91ee7 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -26,12 +26,13 @@ use vectorcraft_doc::{Document, NodeId, NodeKind, Selection}; use vectorcraft_geom::Affine; use vectorcraft_tools::{PaintDefaults, Tool}; -pub use cmd::clipboard::Clipboard; +pub use cmd::clipboard::{Clipboard, SourceLayer}; pub use cmd::create::constrain_click; pub use cmd::distortcmds::perspective_click; pub use cmd::params::{check_keys, check_params}; pub use cmd::pathops::auto_simplify_level; pub use cmd::rasterfx::{export_pdf, flatten_raster_effects}; +pub use cmd::select::{path_fingerprint, storable_selection, stored_path_params, stored_path_step}; pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command}; pub use cmd::{EyedropperOptions, PathfinderOptions}; pub use journal::Journal; @@ -151,6 +152,11 @@ pub struct Session { pub symbol_libraries: cmd::symbollib::Libraries, /// User Defined and loaded brush libraries (Window → Brush Libraries); not saved. pub brush_libraries: cmd::brushlib::Libraries, + /// The custom arrowheads of the arrowheads file (`stroke.arrowheads.*`); none without one. + pub arrowheads: cmd::arrowheads::Arrowheads, + /// The id each loaded library outside a request's read roots has been shown under, by its own id + /// ([`cmd::swatchlib::concealed_library_ids`]), kept for the session. + shown_library_ids: std::sync::Mutex<std::collections::BTreeMap<String, String>>, /// The Libraries panel's libraries of graphics, colours and text styles (`library.*`). pub libraries: cmd::library::Libraries, /// Where the saved PDF presets are kept, one file each; `None`: only for the session @@ -171,10 +177,9 @@ pub struct Session { /// The Scripts folder, whose scripts File › Scripts lists; `None`: no folder /// ([`Session::attach_scripts_dir`]). scripts_dir: Option<std::path::PathBuf>, - /// The plug-in ids whose grant in the plug-in store should be gone but could not be removed: - /// [`Session::plugin_approver`] and a load of the store do not count those grants, and a successful - /// [`Session::store_grant`] for the id takes it out. - ignored_plugin_grants: std::sync::Mutex<std::collections::BTreeSet<String>>, + /// The folder of the New Document profiles `file.new` starts documents from; `None`: none, + /// every document starts with the defaults ([`Session::attach_new_doc_profiles`]). + new_doc_profile_dir: Option<std::path::PathBuf>, /// A filter's output that a run made in the background handed in for `plugin.run` to apply /// ([`cmd::plugin::FilterRun::hand_in`]); the next `plugin.run` takes it. plugin_output: Option<cmd::plugin::HandedIn>, @@ -212,9 +217,10 @@ pub struct Session { /// groups: for each step, the documents ([`DocState::uid`]) whose undo groups it belongs to, and /// the index of the document it left active when it changed the active document. pub(crate) batch_steps: Option<Vec<(Vec<u64>, Option<usize>)>>, - /// After `command.batch` kept a color-mode step's new-art colors, until the top-level command - /// has inherited the selection's appearance: the documents ([`DocState::uid`]) whose newest - /// history step takes the colors the batch finally left. + /// After `command.batch` kept a color-mode step's new-art colors, or a pattern command recorded + /// the new-art paints it changed, until the top-level command has inherited the selection's + /// appearance: the documents ([`DocState::uid`]) whose newest history step takes the colors the + /// command finally left. pub(crate) batch_paint_docs: Vec<u64>, /// The composite fonts (lowercase names) that the open documents defined when the font /// database was last brought in step with them ([`cmd::compositefonts::sync`]). @@ -258,6 +264,8 @@ pub struct Session { pub recovery: cmd::recovery::Recovery, /// The running script's job, while there is one: the mutation lease ([`script`]). pub(crate) script_key: Option<script::JobKey>, + /// The named script engines this session keeps ([`script`]). + pub(crate) script_engines: script::EnginesKey, /// Stops the running script at its next instruction; the same flag for every run. pub(crate) script_stop: vectorcraft_js::Interrupt, /// The report of the run that ended last. @@ -278,8 +286,14 @@ pub struct Session { /// While the active tool's actions run: their commands aren't "a command from outside the /// tool" ([`Session::after_command`]). pub(crate) in_tool_actions: bool, + /// The warnings of the previews that settling an interaction applied, while a top-level command + /// or the tool's actions collect them ([`Session::collect_settled_warnings`]). + settled_warnings: Option<Vec<String>>, /// While [`Session::preview`] runs its command: its edits are the interaction's own. previewing: bool, + /// The images Remove Background decoded during the interaction's preview steps, emptied when + /// it ends ([`cmd::DecodedImages`]). + pub(crate) decoded_images: cmd::DecodedImages, /// Envelope Options with no envelope selected: the options and fidelity new envelopes get /// (`None`: the reference app's defaults, fidelity 50); not saved. pub(crate) envelope_defaults: Option<(vectorcraft_doc::live::EnvelopeOptions, f64)>, @@ -301,6 +315,8 @@ pub struct Session { pub(crate) press_point: Option<Option<(usize, cmd::gradient::StopOwner)>>, /// A guide being dragged out of a ruler ([`Session::ruler_guide`]). pub(crate) ruler_guide: Option<vectorcraft_tools::rulerguide::NewGuide>, + /// The rulers' origin being dragged out of their corner ([`Session::ruler_origin_drag`]). + pub(crate) ruler_origin: Option<vectorcraft_tools::rulerguide::OriginDrag>, /// Which selected type overflows its frame, for the ports every tool but the Type tools shows. pub(crate) port_marks: vectorcraft_tools::text::PortMarks, /// The last search for the files of missing fonts (`text.findFontFiles`), until another @@ -379,7 +395,7 @@ pub(crate) use command_sets::SELECTS_GIVEN_IDS; use command_sets::given_ids; pub use command_sets::{FIT_ACTIVE_ARTBOARD, ON_ACTIVE_ARTBOARD, waits_for_tool_edit}; pub use doc_state::{DocState, OpenRows, RecalledSelection}; -pub use error::{EngineError, Result, SCRIPT_BUSY}; +pub use error::{EngineError, READ_ONLY_LOCATION, Result, SCRIPT_BUSY}; #[cfg(test)] use history::history_budget_for; pub use history::{History, HistoryEntry, NamedStep, default_history_budget}; diff --git a/crates/engine/src/link_watch.rs b/crates/engine/src/link_watch.rs index 747ce91545..c524f056a5 100644 --- a/crates/engine/src/link_watch.rs +++ b/crates/engine/src/link_watch.rs @@ -184,7 +184,9 @@ impl Session { if changed.is_empty() { return Ok(none()); } - let ids: Vec<u64> = changed.iter().flat_map(|(_, ids)| ids.iter().copied()).collect(); + // Each once: a DCS file and its plate files list the same objects. + let mut seen = HashSet::new(); + let ids: Vec<u64> = changed.iter().flat_map(|(_, ids)| ids.iter().copied()).filter(|id| seen.insert(*id)).collect(); let mode = if update { "automatically" } else { self.prefs.update_links.as_str() }; match mode { "automatically" => { diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index aa8b5c7f42..98813e999f 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -71,6 +71,11 @@ pub struct Prefs { /// A single-key tool shortcut held down chooses its tool until the key is let go, and then the /// tool active before comes back; a quick press chooses the tool for good. pub hold_tool_keys: bool, + /// With View › Show Bounding Box on, the bounding box stays visible while a drag moves the + /// selection, and the shape tools that show it draw it around the shape being drawn. Off (the + /// default), it hides during a move and while a shape is drawn, except that a Selection tool + /// move with Real-time Drawing off still moves the box. + pub bounding_box_while_moving_and_drawing: bool, /// Offset for Paste / duplicate (Illustrator pastes to the view centre; we offset by this). pub paste_offset: f64, // Selection & Anchor Display @@ -99,6 +104,9 @@ pub struct Prefs { pub font_names_in_english: bool, pub auto_size_area_type: bool, pub font_preview: bool, + /// Type › Show samples on white: the font menus draw each family's sample in dark type on a + /// white area in every brightness (off by default). + pub font_samples_on_white: bool, pub font_preview_size: String, pub recent_fonts_count: u32, pub missing_glyph_protection: bool, @@ -252,6 +260,9 @@ pub struct Prefs { /// Character panel › Show Snap to Glyph Options: which guides View › Snap to Glyph gives /// (`view.snapToGlyph.options`; a preference group, see [`cmd::prefscmds::PREF_GROUPS`]). pub glyph_snap: vectorcraft_tools::GlyphSnap, + /// Pixel Snapping Options: whether View › Snap to Pixel snaps drawing, moving and scaling + /// (`view.snapToPixel.options`; a preference group, see [`cmd::prefscmds::PREF_GROUPS`]). + pub pixel_snap: vectorcraft_tools::PixelSnap, /// Edit → Transparency Flattener Presets: the user's presets (the built-in ones aren't stored). /// Not a `prefs.set` key or group (resetting the preferences keeps them): `flattener.presets.*` /// edit it. @@ -397,6 +408,7 @@ impl Default for Prefs { scrub_numeric_fields: true, trackpad_rotate_view: true, hold_tool_keys: true, + bounding_box_while_moving_and_drawing: false, paste_offset: 10.0, selection_tolerance: 3.0, marquee_selection: "touching".into(), @@ -421,6 +433,7 @@ impl Default for Prefs { font_names_in_english: true, auto_size_area_type: false, font_preview: true, + font_samples_on_white: false, font_preview_size: s("medium"), recent_fonts_count: 10, missing_glyph_protection: true, @@ -513,6 +526,7 @@ impl Default for Prefs { eyedropper: Default::default(), pathfinder: Default::default(), glyph_snap: Default::default(), + pixel_snap: Default::default(), flattener_presets: vec![], trace_presets: vec![], gradient_presets: vec![], diff --git a/crates/engine/src/schemas.rs b/crates/engine/src/schemas.rs index fb08bb649c..8be87b5ab8 100644 --- a/crates/engine/src/schemas.rs +++ b/crates/engine/src/schemas.rs @@ -26,10 +26,11 @@ use crate::cmd::{CommandSpec, bad, command_specs}; use crate::{EngineError, Result}; /// The API level of the commands' parameters. -pub const API_VERSION: u32 = 3; +pub const API_VERSION: u32 = 4; /// [`schema_hash`] at each API level, oldest first; the last row is [`API_VERSION`]'s. -pub const SCHEMA_HASHES: &[(u32, u64)] = &[(1, 0x9cdb_1087_7074_855c), (2, 0x0e31_5d96_7bc9_2653), (3, 0xffe0_58a3_2f0c_aa2a)]; +pub const SCHEMA_HASHES: &[(u32, u64)] = + &[(1, 0x9cdb_1087_7074_855c), (2, 0x0e31_5d96_7bc9_2653), (3, 0xffe0_58a3_2f0c_aa2a), (4, 0x1be4_be72_fe16_54c4)]; /// The hash of every built-in command's schema ([`vectorcraft_apischema::hash`]). pub fn schema_hash() -> u64 { @@ -69,7 +70,7 @@ fn param_error(id: &str, e: &ParamError) -> EngineError { Problem::Unknown { keys } => bad(id, format!("unknown parameter `{path}`; it takes: {keys}", keys = keys.join(", "))), Problem::Missing => bad(id, format!("missing `{path}`")), Problem::WrongType { expected, got } => bad(id, format!("`{path}` must be {expected}, not {got}")), - Problem::TooDeep => EngineError::Internal { cmd: id.into(), msg: e.to_string() }, + Problem::TooDeep => bad(id, format!("`{path}` is nested too deeply")), } } @@ -246,6 +247,30 @@ mod tests { assert!(s.doc().unwrap().history.undo.is_empty()); } + /// A value nested past the limit of a sound schema is a parameter error that names it, not an + /// internal error: a color list at the nesting limit, where a color string still passes. + #[test] + fn a_value_nested_too_deeply_is_a_parameter_error() { + let levels = vectorcraft_apischema::MAX_DEPTH; + let ty = (0..levels).fold(Type::Color, |inner, _| Type::Array(Box::leak(Box::new(inner)))); + let params: &'static [Param] = Box::leak(Box::new([Param::new("fills", ty)])); + let schema = ParamSchema::new(params, ""); + assert_eq!(schema.definition_problem(), None); + let wrapped = |v: Value| (0..levels).fold(v, |inner, _| Value::Array(vec![inner])); + assert!(schema.validate(&json!({"fills": wrapped(json!("#ff0000"))})).is_ok()); + let e = schema.validate(&json!({"fills": wrapped(json!([1, 0, 0]))})).unwrap_err(); + let path = format!("fills{}", "[0]".repeat(levels)); + match param_error("view.synthetic", &e) { + EngineError::BadParams { cmd, msg } => { + assert_eq!(cmd, "view.synthetic"); + assert_eq!(msg, format!("`{path}` is nested too deeply")); + } + other => panic!("not a parameter error: {other}"), + } + let shown = param_error("view.synthetic", &e).to_string(); + assert!(shown.starts_with("invalid parameters for `view.synthetic`") && !shown.contains("report this bug"), "{shown}"); + } + /// Each command's JSON schema follows the 2020-12 rules, and a validator of those rules, which /// shares no code with the writer, gives the same answer as the schema check. None of these /// schemas has a lenient parameter. @@ -287,12 +312,17 @@ mod tests { ("view.transparencyGrid", json!({"on": 1})), ("view.snapToGlyph.options", json!({"bounds": false, "angular": true})), ("view.snapToGlyph.options", json!({"bounds": null})), + ("view.snapToPixel.options", json!({"drawing": false, "scaling": true})), + ("view.snapToPixel.options", json!({"moving": null})), + ("view.snapToPixel.options", json!({"moving": "off"})), + ("view.snapToPixel.options", json!({"rotating": false})), ("view.capsLock", json!(null)), ("view.saved.new", json!(null)), ("view.saved.edit", json!(null)), ("view.saved.list", json!(null)), ("view.transparencyGrid", json!(null)), ("view.snapToGlyph.options", json!(null)), + ("view.snapToPixel.options", json!(null)), ("view.capsLock", json!([])), ("view.saved.new", json!(5)), ("view.transparencyGrid", json!("on")), @@ -301,7 +331,7 @@ mod tests { ("engine.apiReference", json!({"prefix": "view."})), ("engine.apiReference", json!([])), ]; - assert_eq!(schemas().len(), 7); + assert_eq!(schemas().len(), 8); for (id, schema) in schemas() { let written = schema.to_json(); check_schema(&written, id).unwrap_or_else(|e| panic!("{e}\n{written:#}")); @@ -399,6 +429,7 @@ mod tests { ("view.saved.list", "nothing"), ("view.transparencyGrid", "session"), ("view.snapToGlyph.options", "preferences"), + ("view.snapToPixel.options", "preferences"), ]; for (id, writes) in expected { let got = listed.iter().find(|(c, _)| *c == id).map(|(_, w)| w.clone()); diff --git a/crates/engine/src/script/dialogs.rs b/crates/engine/src/script/dialogs.rs index 1faf624f16..a674396f4b 100644 --- a/crates/engine/src/script/dialogs.rs +++ b/crates/engine/src/script/dialogs.rs @@ -290,12 +290,12 @@ impl Dialogs { } } -/// Adds `alert`, `confirm` and `prompt` to the realm. -pub(super) fn install(realm: &mut Realm, host: &Rc<Host>) -> Result<(), RunError> { +/// Adds `alert`, `confirm` and `prompt` to the realm, for the run `link` holds. +pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunError> { use Arg::{Bool, Text, TextOrUndefined}; let call = |kind: DialogKind| -> HostFunction { - let h = host.clone(); - Rc::new(move |args| open(&h, kind, &args)) + let l = link.clone(); + Rc::new(move |args| open(&*super::current(&l)?, kind, &args)) }; realm.define_host_function("alert", vec![Text, TextOrUndefined, Bool], call(DialogKind::Alert))?; realm.define_host_function("confirm", vec![Text, Bool, TextOrUndefined], call(DialogKind::Confirm))?; diff --git a/crates/engine/src/script/dollar.rs b/crates/engine/src/script/dollar.rs index 3e6b005844..fcf6dbf542 100644 --- a/crates/engine/src/script/dollar.rs +++ b/crates/engine/src/script/dollar.rs @@ -4,14 +4,15 @@ //! the locale the global `localize` reads //! (<https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/>). //! -//! Every value here belongs to one run: a run starts with the locale of the interface, the -//! environment values of [`ENV_NAMES`] read from the process, localization off and a timer at zero, -//! and what a script changes ends with its run. `$.setenv` never changes the process's environment. +//! Every value here belongs to one run, in a named engine too ([`RunState`]): a run starts with the +//! locale of the interface, the environment values of [`ENV_NAMES`] read from the process, +//! localization off and a timer at zero, and what a script changes ends with its run. `$.setenv` +//! never changes the process's environment. //! //! These are VectorCraft's own values and rules: `$.appEncoding` is always UTF-8; `$.build` and -//! `$.version` give VectorCraft's version, `$.engineName` is `VectorCraft` and `$.buildDate` is -//! `null`; `$.flags` takes only 512, which turns localization on; `$.level` and `$.memCache` are 0 -//! and `$.screens` is empty; `$.os` names the system without its version; `$.strict` is whether the +//! `$.version` give VectorCraft's version, `$.engineName` is the name `#targetengine` gave, or +//! `VectorCraft` without one, and `$.buildDate` is `null`; `$.flags` takes only 512, which turns +//! localization on; `$.level` and `$.memCache` are 0 and `$.screens` is empty; `$.os` names the system without its version; `$.strict` is whether the //! realm reads scripts as strict mode code; `$.bp` and `$.colorPicker` throw, since scripts have no //! debugger and cannot show a dialog; `$.gc` does nothing, since the interpreter collects its own //! garbage; `$.getenv` and `$.setenv` know only [`ENV_NAMES`], with values of at most @@ -25,7 +26,7 @@ use std::time::Duration; use vectorcraft_js::{Data, HostError, HostItem, Localization, ScriptItem}; -use super::{Host, function}; +use super::{Link, current, function}; /// The longest `$.sleep`, in milliseconds. pub const MAX_SLEEP_MS: f64 = 1_000.0; @@ -36,12 +37,34 @@ pub const MAX_ENV_BYTES: usize = 64; /// The value of `$.flags` that turns localization on, the only one a script may set. pub const LOCALIZE_FLAG: f64 = 512.0; -/// What `$` knows of a run. +/// What `$` knows of its realm. pub(crate) struct RunInfo { - /// The locale the run starts with, such as `de_DE`. - pub locale: String, /// The realm reads scripts as strict mode code. pub strict: bool, + /// The name `#targetengine` gave the realm's engine. + pub engine: Option<String>, +} + +/// The values of `$` that belong to one run, which the run's host holds. +pub(crate) struct RunState { + /// The locale the run starts with, such as `de_DE`. + locale: String, + env: RefCell<Vec<(&'static str, Option<String>)>>, + /// The time since the run started at which `$.hiresTimer` was last read. + timer: Cell<Duration>, +} + +impl RunState { + pub(crate) fn new(locale: &str) -> RunState { + RunState { locale: locale.to_string(), env: RefCell::new(process_env()), timer: Cell::new(Duration::ZERO) } + } +} + +/// Sets `localization` as a run starts: `locale`, this system's platform and localization off. +pub(super) fn start_run(localization: &Localization, locale: &str) { + localization.set_enabled(false); + localization.set_locale(locale); + localization.set_platform(platform()); } /// The locale for an interface language code such as `de`, `pt-br` or `zh-hant`: the language, @@ -148,14 +171,10 @@ fn text(s: impl Into<String>) -> Data { Data::String(s.into()) } -/// The members `$` has besides `write`, `writeln`, `evalFile`, `fileName` and `includePath`. -pub(super) fn members(host: &Rc<Host>, info: RunInfo, localization: &Rc<Localization>) -> Vec<(String, HostItem)> { +/// The members `$` has besides `write`, `writeln`, `evalFile`, `fileName` and `includePath`. They +/// act for the run that `link` holds when they are called. +pub(super) fn members(link: &Link, info: RunInfo, localization: &Rc<Localization>) -> Vec<(String, HostItem)> { let version = env!("CARGO_PKG_VERSION"); - let host_locale = info.locale.clone(); - localization.set_locale(&info.locale); - localization.set_platform(platform()); - let env = Rc::new(RefCell::new(process_env())); - let timer = Rc::new(Cell::new(Duration::ZERO)); let getter = |f: Rc<dyn Fn() -> Data>| HostItem::Getter(function(move |_| Ok(f()))); let property = |get: Rc<dyn Fn() -> Data>, set: Rc<dyn Fn(Data) -> Result<(), HostError>>| HostItem::Property { get: function(move |_| Ok(get())), @@ -167,13 +186,13 @@ pub(super) fn members(host: &Rc<Host>, info: RunInfo, localization: &Rc<Localiza let fail = |message: &'static str| HostItem::Function(function(move |_| Err(HostError::Error(message.to_string())))); let locale = { - let (l, s) = (localization.clone(), localization.clone()); + let (l, s, run) = (localization.clone(), localization.clone(), link.clone()); property( Rc::new(move || text(l.locale())), Rc::new(move |v| { let locale = match v { - Data::Null | Data::Undefined => host_locale.clone(), - Data::String(t) if t.is_empty() => host_locale.clone(), + Data::Null | Data::Undefined => current(&run)?.dollar.locale.clone(), + Data::String(t) if t.is_empty() => current(&run)?.dollar.locale.clone(), Data::String(t) => script_locale(&t).ok_or_else(|| HostError::Range(BAD_LOCALE.to_string()))?, _ => return Err(HostError::Type(BAD_LOCALE.to_string())), }; @@ -224,31 +243,34 @@ pub(super) fn members(host: &Rc<Host>, info: RunInfo, localization: &Rc<Localiza let mem_cache = property(Rc::new(|| Data::Number(0.0)), Rc::new(|_| Err(HostError::Error("$.memCache: the memory cache size cannot be set".into())))); let hires_timer = { - let (h, last) = (host.clone(), timer.clone()); + let l = link.clone(); getter(Rc::new(move || { + let Ok(h) = current(&l) else { return Data::Number(0.0) }; let Some(now) = h.elapsed() else { return Data::Number(0.0) }; - let since = now.saturating_sub(last.replace(now)); + let since = now.saturating_sub(h.dollar.timer.replace(now)); #[allow(clippy::cast_precision_loss)] Data::Number(since.as_micros() as f64) })) }; let getenv = { - let (h, env) = (host.clone(), env.clone()); + let l = link.clone(); function(move |a| { let name = one_string(&a, "getenv")?; + let h = current(&l)?; h.charge_call(name.len() as u64 + 2)?; - let env = env.borrow(); + let env = h.dollar.env.borrow(); let found = env.iter().find(|(n, _)| *n == name).and_then(|(_, v)| v.clone()); Ok(found.map_or(Data::Null, Data::String)) }) }; let setenv = { - let (h, env) = (host.clone(), env.clone()); + let l = link.clone(); function(move |a| { let name = one_string(&a, "setenv")?; let Some(Data::String(v)) = a.get(1) else { return Err(HostError::Type("$.setenv: give a value, as a string".into())) }; + let h = current(&l)?; h.charge_call((name.len() + v.len()) as u64 + 4)?; - let mut env = env.borrow_mut(); + let mut env = h.dollar.env.borrow_mut(); let Some(slot) = env.iter_mut().find(|(n, _)| *n == name) else { return Err(HostError::Error(format!("$.setenv: only {} can be set", ENV_NAMES.join(", ")))); }; @@ -260,8 +282,9 @@ pub(super) fn members(host: &Rc<Host>, info: RunInfo, localization: &Rc<Localiza }) }; let sleep = { - let h = host.clone(); + let l = link.clone(); function(move |a| { + let h = current(&l)?; let ms = match a.first() { Some(Data::Number(n)) if (0.0..=MAX_SLEEP_MS).contains(n) => *n, Some(Data::Number(_)) => return Err(HostError::Range(format!("$.sleep: give a number of milliseconds from 0 to {MAX_SLEEP_MS}"))), @@ -282,7 +305,7 @@ pub(super) fn members(host: &Rc<Host>, info: RunInfo, localization: &Rc<Localiza ("buildDate".into(), value(Data::Null)), ("colorPicker".into(), fail("$.colorPicker: scripts cannot show a dialog yet")), ("decimalPoint".into(), decimal), - ("engineName".into(), value(text("VectorCraft"))), + ("engineName".into(), value(text(info.engine.unwrap_or_else(|| "VectorCraft".into())))), ("error".into(), HostItem::Script(ScriptItem::LastError)), ("flags".into(), flags), ("gc".into(), HostItem::Function(function(|_| Ok(Data::Undefined)))), diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 3f53814992..ec848a973e 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -40,6 +40,7 @@ use std::collections::HashMap; use std::path::Path; use std::rc::Rc; +use std::sync::atomic::{AtomicU32, Ordering}; use vectorcraft_js::{Data, HostError, HostItem, Realm, RunError}; @@ -77,6 +78,10 @@ pub(crate) const PATH_TOO_LONG: &str = "Script file path exceeds 32,767 characte pub(crate) const MASK_TOO_COSTLY: &str = "Script folder mask takes too many steps to match"; const OVER_RUN_BYTES: &str = "the script opened more file data than one run may open (32 MiB)"; +/// The id of the next file a script opens. Ids are unique across runs, so a `File` that a named +/// engine kept from an earlier run does not name a file a later run opened. +static NEXT_HANDLE: AtomicU32 = AtomicU32::new(1); + /// The script's file state: its scope, where `Folder.current` starts, the files it has open and how /// much it has read. pub(crate) struct Disk { @@ -84,7 +89,6 @@ pub(crate) struct Disk { home: String, start: String, open: HashMap<u32, Open>, - next: u32, temps: u32, bytes: usize, } @@ -94,7 +98,7 @@ impl Disk { pub(crate) fn new(scope: &ScriptScope) -> Self { let home = home_folder(); let start = scope.folder().map_or_else(|| home.clone(), |p| p.to_string_lossy().into_owned()); - Self { scope: scope.clone(), home, start, open: HashMap::new(), next: 1, temps: 0, bytes: 0 } + Self { scope: scope.clone(), home, start, open: HashMap::new(), temps: 0, bytes: 0 } } /// The path `text` names from the folder `base`, a platform path; `text`'s URI escapes are @@ -161,8 +165,10 @@ impl Disk { } self.bytes += bytes.len(); let file = Open::new(bytes, encoding).ok_or_else(|| HostError::Error(UNDECODABLE.to_string()))?; - let id = self.next; - self.next = self.next.wrapping_add(1).max(1); + let mut id = NEXT_HANDLE.fetch_add(1, Ordering::Relaxed); + while id == 0 || self.open.contains_key(&id) { + id = NEXT_HANDLE.fetch_add(1, Ordering::Relaxed); + } self.open.insert(id, file); Ok(id) } @@ -183,11 +189,15 @@ fn home_folder() -> String { } /// The folders `Folder.temp`, `Folder.desktop` and the others name, `null` where there is none. +/// On the web every one is `null`, and no platform folder is looked up. fn locations(home: &str) -> Data { + if cfg!(target_arch = "wasm32") { + return Data::Object(PLACES.iter().map(|k| (k.to_string(), Data::Null)).collect()); + } let env = |k: &str| std::env::var(k).ok().filter(|v| !v.is_empty()); let join = |a: &str, b: &str| Path::new(a).join(b).to_string_lossy().into_owned(); let exe = std::env::current_exe().ok().and_then(|p| p.parent().map(|d| d.to_string_lossy().into_owned())); - let temp = std::env::temp_dir().to_string_lossy().into_owned(); + let temp = temp_folder().to_string_lossy().into_owned(); let (user_data, app_data, common, system, trash) = if WINDOWS { (env("APPDATA"), env("PROGRAMDATA"), env("CommonProgramFiles"), env("SystemRoot"), None) } else if cfg!(target_os = "macos") { @@ -203,7 +213,6 @@ fn locations(home: &str) -> Data { (Some(data.clone()), Some("/usr/share".to_string()), Some("/usr/share".to_string()), Some("/".to_string()), Some(join(&data, "Trash"))) }; let s = |v: Option<String>| v.map_or(Data::Null, Data::String); - let web = cfg!(target_arch = "wasm32"); let places = vec![ ("appData", app_data), ("appPackage", exe.clone()), @@ -216,7 +225,15 @@ fn locations(home: &str) -> Data { ("trash", trash), ("userData", user_data), ]; - Data::Object(places.into_iter().map(|(k, v)| (k.to_string(), if web { Data::Null } else { s(v) })).collect()) + Data::Object(places.into_iter().map(|(k, v)| (k.to_string(), s(v))).collect()) +} + +/// The names [`locations`] gives. +const PLACES: [&str; 10] = ["appData", "appPackage", "commonFiles", "desktop", "myDocuments", "startup", "system", "temp", "trash", "userData"]; + +/// The folder for temporary files: the platform's, or on the web the root, where nothing is read. +fn temp_folder() -> std::path::PathBuf { + if cfg!(target_arch = "wasm32") { std::path::PathBuf::from("/") } else { std::env::temp_dir() } } /// The start of an absolute path. @@ -343,12 +360,12 @@ impl Pathname { } } -/// `s` with every character but letters, digits and `-_.!~*'()` written as `%xx` escapes of its +/// `s` with every character but letters, digits and `/-_.!~*'()` written as `%xx` escapes of its /// UTF-8 bytes (RFC 2396). fn encode(s: &str) -> String { let mut out = String::with_capacity(s.len()); for b in s.bytes() { - if b.is_ascii_alphanumeric() || b"-_.!~*'()".contains(&b) { + if b.is_ascii_alphanumeric() || b"/-_.!~*'()".contains(&b) { out.push(b as char); } else { out.push_str(&format!("%{b:02X}")); @@ -638,10 +655,11 @@ fn millis(t: Option<std::time::SystemTime>) -> Data { t.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map_or(Data::Null, |d| Data::Number(d.as_millis() as f64)) } -/// One host function of `__vcFiles`, counted and charged as a host call. -fn call(host: &Rc<Host>, f: fn(&Host, &[Data]) -> Result<Data, HostError>) -> HostItem { - let h = host.clone(); +/// One host function of `__vcFiles`, counted and charged as a host call of the run `link` holds. +fn call(link: &super::Link, f: fn(&Host, &[Data]) -> Result<Data, HostError>) -> HostItem { + let l = link.clone(); HostItem::Function(Rc::new(move |a| { + let h = super::current(&l)?; bump(&h.counts.file_calls); let r = f(&h, &a)?; h.charge_call(super::data_size(&r).saturating_add(a.iter().map(super::data_size).sum()))?; @@ -835,14 +853,39 @@ fn temp_name(host: &Host, _: &[Data]) -> Result<Data, HostError> { let mut disk = host.disk.borrow_mut(); disk.temps += 1; let name = format!("vc{:05}.tmp", disk.temps); - Ok(Data::String(std::env::temp_dir().join(name).to_string_lossy().into_owned())) + Ok(Data::String(temp_folder().join(name).to_string_lossy().into_owned())) } -/// Adds `File` and `Folder` to the realm. -pub(super) fn install(realm: &mut Realm, host: &Rc<Host>) -> Result<(), RunError> { - let (start, home) = { - let disk = host.disk.borrow(); - (disk.pathname(&disk.start, &disk.start, false).fs(), disk.home.clone()) +fn locations_of(host: &Host, _: &[Data]) -> Result<Data, HostError> { + Ok(locations(&host.disk.borrow().home)) +} + +fn encode_text(_: &Host, a: &[Data]) -> Result<Data, HostError> { + Ok(Data::String(encode(&arg_text(a, 0)))) +} + +fn decode_text(_: &Host, a: &[Data]) -> Result<Data, HostError> { + Ok(Data::String(decode(&arg_text(a, 0)))) +} + +fn encoding_available(_: &Host, a: &[Data]) -> Result<Data, HostError> { + Ok(Data::Bool(Encoding::parse(&arg_text(a, 0)).is_some())) +} + +/// The folder `Folder.current` starts at in the run `host` serves: the script's own folder. +fn start_folder(host: &Host, _: &[Data]) -> Result<Data, HostError> { + let disk = host.disk.borrow(); + Ok(Data::String(disk.pathname(&disk.start, &disk.start, false).fs())) +} + +/// Adds `File` and `Folder` to the realm, their host functions acting for the run `link` holds. +pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunError> { + let unchecked = |f: fn(&Host, &[Data]) -> Result<Data, HostError>| { + let l = link.clone(); + HostItem::Function(Rc::new(move |a| { + let h = super::current(&l)?; + f(&h, &a) + })) }; let value = |s: &str| HostItem::Value(Data::String(s.to_string())); let text = HostItem::Object(vec![ @@ -851,7 +894,6 @@ pub(super) fn install(realm: &mut Realm, host: &Rc<Host>) -> Result<(), RunError ("noPicker".into(), value(NO_PICKER)), ("badMode".into(), value(BAD_MODE)), ]); - let pure = |f: fn(&str) -> Data| HostItem::Function(Rc::new(move |a| Ok(f(&arg_text(&a, 0))))); let system = if WINDOWS { "Windows" } else if cfg!(target_os = "macos") { @@ -863,28 +905,28 @@ pub(super) fn install(realm: &mut Realm, host: &Rc<Host>) -> Result<(), RunError ("text".into(), text), ("system".into(), value(system)), ("lineFeed".into(), value(if WINDOWS { "Windows" } else { "Unix" })), - ("current".into(), HostItem::Function(Rc::new(move |_| Ok(Data::String(start.clone()))))), - ("locations".into(), HostItem::Function(Rc::new(move |_| Ok(locations(&home))))), - ("encode".into(), pure(|s| Data::String(encode(s)))), - ("decode".into(), pure(|s| Data::String(decode(s)))), - ("encodingAvailable".into(), pure(|s| Data::Bool(Encoding::parse(s).is_some()))), - ("parse".into(), call(host, parse)), - ("relative".into(), call(host, relative)), - ("tempName".into(), call(host, temp_name)), - ("stat".into(), call(host, stat)), - ("open".into(), call(host, open)), - ("close".into(), call(host, close)), - ("read".into(), call(host, read)), - ("readln".into(), call(host, readln)), - ("readch".into(), call(host, readch)), - ("seek".into(), call(host, seek)), - ("tell".into(), call(host, tell)), - ("eof".into(), call(host, eof)), - ("encoding".into(), call(host, encoding)), - ("setEncoding".into(), call(host, set_encoding)), - ("list".into(), call(host, list)), - ("resolve".into(), call(host, resolve)), - ("execute".into(), call(host, execute)), + ("current".into(), unchecked(start_folder)), + ("locations".into(), call(link, locations_of)), + ("encode".into(), call(link, encode_text)), + ("decode".into(), call(link, decode_text)), + ("encodingAvailable".into(), call(link, encoding_available)), + ("parse".into(), call(link, parse)), + ("relative".into(), call(link, relative)), + ("tempName".into(), call(link, temp_name)), + ("stat".into(), call(link, stat)), + ("open".into(), call(link, open)), + ("close".into(), call(link, close)), + ("read".into(), call(link, read)), + ("readln".into(), call(link, readln)), + ("readch".into(), call(link, readch)), + ("seek".into(), call(link, seek)), + ("tell".into(), call(link, tell)), + ("eof".into(), call(link, eof)), + ("encoding".into(), call(link, encoding)), + ("setEncoding".into(), call(link, set_encoding)), + ("list".into(), call(link, list)), + ("resolve".into(), call(link, resolve)), + ("execute".into(), call(link, execute)), ]; realm.define_file_classes(items) } @@ -935,7 +977,7 @@ mod tests { #[test] fn uri_escapes_are_utf8_both_ways() { assert_eq!(encode("caf\u{e9} 1"), "caf%C3%A9%201"); - assert_eq!(encode("a-_.!~*'()/b"), "a-_.!~*'()%2Fb"); + assert_eq!(encode("a-_.!~*'()/b"), "a-_.!~*'()/b"); assert_eq!(decode("caf%C3%A9%20x"), "caf\u{e9} x"); assert_eq!(decode("100%"), "100%"); assert_eq!(decode("%E9"), "%E9", "a lone Latin-1 escape is not UTF-8"); diff --git a/crates/engine/src/script/include.rs b/crates/engine/src/script/include.rs index 6cf0c60bef..f1928228df 100644 --- a/crates/engine/src/script/include.rs +++ b/crates/engine/src/script/include.rs @@ -16,8 +16,13 @@ //! the `JSINCLUDE` environment variable. A later `#includepath` replaces the list. //! - Files are read through the script's [`ScriptScope`]: a refused path ends the run, except a //! `JSINCLUDE` folder outside the scope, which is passed over. -//! - `#target` takes any value and changes nothing. `#targetengine` and `#engine` are refused as -//! unsupported, and any other `#name` as unknown; `//@name` with another name stays a comment. +//! - `#target` takes any value and changes nothing. `#engine` is refused as unsupported, and any +//! other `#name` as unknown; `//@name` with another name stays a comment. +//! - `#targetengine name` names the engine the script runs in ([`Expanded::engine`]). Only the +//! script itself may have one, at most once, and only before its first code or `#include` line: +//! blanks, comments and the other preprocessor lines may come before it. The name is an unquoted +//! name of ASCII letters, digits and `_` that does not start with a digit, or a quoted one of 1 to +//! [`MAX_ENGINE_NAME_BYTES`] bytes without control characters, compared as written. //! - The last `#strict on` or `#strict off` of the script and the files it includes sets the checks //! for the whole run; without one they are off. A write to a property that has only a getter is //! checked as a read-only one, the objects that take no new properties are those that are not @@ -50,6 +55,8 @@ pub const MAX_TOTAL_BYTES: usize = 32 << 20; pub const MAX_PROBES: usize = 1024; /// The longest value a preprocessor line may have, in bytes. const MAX_VALUE_BYTES: usize = 4096; +/// The longest name `#targetengine` may give, in bytes of UTF-8. +pub const MAX_ENGINE_NAME_BYTES: usize = 64; /// Where the lines of an expanded source came from: file 0 is the file expanded, the others the /// files it included. @@ -81,6 +88,13 @@ impl SourceMap { let name = self.files.get(seg.file).cloned().unwrap_or_else(|| Arc::from("")); (seg.file, name, seg.line.saturating_add(line - seg.out_line), column) } + + /// The memory the map holds, in bytes: its lists and its file names, each name counted in full + /// even when another map shares it. + pub(crate) fn bytes(&self) -> usize { + let names: usize = self.files.iter().map(|f| f.len() + 2 * size_of::<usize>()).sum(); + self.files.capacity() * size_of::<Arc<str>>() + self.segments.capacity() * size_of::<Segment>() + names + } } /// How a preprocessor failure ends the run. @@ -107,12 +121,78 @@ pub(crate) struct Failure { } /// A source with its preprocessor lines read: the text to run, where its lines came from, the -/// name its `#script` line gave, and what its last `#strict` line set (`None` without one). +/// name its `#script` line gave, what its last `#strict` line set (`None` without one), and the +/// engine its `#targetengine` line named, with that line's line and column. pub(crate) struct Expanded { pub source: String, pub map: SourceMap, pub name: Option<String>, pub strict: Option<bool>, + pub engine: Option<(String, u32, u32)>, +} + +/// What the preprocessor lines of a file have named so far: its `#script` name and its engine, and +/// whether code or an `#include` line has come before. +#[derive(Default)] +struct Named { + name: Option<String>, + engine: Option<(String, u32, u32)>, + code_seen: bool, +} + +/// Are `units` only blanks and comments? +fn only_blanks_and_comments(units: &[u16]) -> bool { + let mut i = 0; + while let Some(&u) = units.get(i) { + match u { + 0x2F if units.get(i + 1) == Some(&0x2F) => { + while units.get(i).is_some_and(|&c| !matches!(c, 0x0A | 0x0D | 0x2028 | 0x2029)) { + i += 1; + } + } + 0x2F if units.get(i + 1) == Some(&0x2A) => { + let Some(end) = units.get(i + 2..).and_then(|rest| rest.windows(2).position(|w| w == [0x2A, 0x2F])) else { return false }; + i += end + 4; + } + 0xFEFF => i += 1, + u if char::from_u32(u32::from(u)).is_some_and(char::is_whitespace) => i += 1, + _ => return false, + } + } + true +} + +/// The engine name of a `#targetengine` line's value `value` (as written, quotes included), or what +/// is wrong with it. +fn engine_name(value: &str) -> Result<String, &'static str> { + let name = match value.chars().next() { + None => return Err("needs a name"), + Some(q @ ('"' | '\'')) => { + let inner = value.get(1..).and_then(|v| v.strip_suffix(q)).ok_or("needs a closing quote after the name")?; + if inner.contains(q) { + return Err("takes one name"); + } + if inner.chars().any(char::is_control) { + return Err("needs a name without control characters"); + } + inner + } + _ => { + let mut chars = value.chars(); + let first_ok = chars.next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_'); + if !first_ok || !chars.all(|c| c.is_ascii_alphanumeric() || c == '_') { + return Err("needs a name of letters, digits and _, or a quoted name"); + } + value + } + }; + if name.is_empty() { + return Err("needs a name"); + } + if name.len() > MAX_ENGINE_NAME_BYTES { + return Err("needs a name of at most 64 bytes"); + } + Ok(name.to_string()) } /// A file being run: its name for people and the folder its relative paths start from (none for a @@ -241,7 +321,8 @@ impl Files { std::env::var("JSINCLUDE").map(|v| v.split(';').map(str::trim).filter(|p| !p.is_empty()).map(PathBuf::from).collect()).unwrap_or_default() } - /// The file being run now, as `$.fileName` gives it (empty for a script given as text). + /// The file being run now: the script, or the file `$.evalFile` is running (empty for a script + /// given as text). `$.fileName` gives it to code that `eval` or `Function` compiled. pub(crate) fn file_name(&self) -> String { self.frames.last().map(|f| f.shown.to_string()).unwrap_or_default() } @@ -347,8 +428,8 @@ impl Files { /// its `#script` line names the run. fn expand(&mut self, shown: Arc<str>, dir: Option<PathBuf>, text: &str, script: bool) -> Result<Expanded, Failure> { let mut out = Out { units: Vec::with_capacity(text.len()), line: 1, column: 0, after_cr: false, map: SourceMap::default(), strict: None }; - let mut name = None; - self.file(&mut out, shown, dir.as_deref(), text, script, &mut name)?; + let mut named = Named::default(); + self.file(&mut out, shown, dir.as_deref(), text, script, &mut named)?; let source = String::from_utf16(&out.units).map_err(|_| Failure { kind: FailKind::Syntax, message: "the script is not valid text".into(), @@ -357,20 +438,12 @@ impl Files { line: 0, column: 0, })?; - Ok(Expanded { source, map: out.map, name, strict: out.strict }) + Ok(Expanded { source, map: out.map, name: named.name, strict: out.strict, engine: named.engine }) } /// Adds file `shown` (in folder `dir`, with text `text`) to `out`, its included files in place /// of their lines. - fn file( - &mut self, - out: &mut Out, - shown: Arc<str>, - dir: Option<&Path>, - text: &str, - script: bool, - name: &mut Option<String>, - ) -> Result<(), Failure> { + fn file(&mut self, out: &mut Out, shown: Arc<str>, dir: Option<&Path>, text: &str, script: bool, named: &mut Named) -> Result<(), Failure> { let index = out.map.files.len(); out.map.files.push(shown.clone()); let units: Vec<u16> = text.encode_utf16().collect(); @@ -390,7 +463,11 @@ impl Files { units.get(..start).and_then(|u| u.iter().rposition(|&c| matches!(c, 0x0A | 0x0D | 0x2028 | 0x2029))).map_or(0, |i| i + 1); let column = u32::try_from(start - line_start + 1).unwrap_or(u32::MAX); let at = |kind, message: String| fail(kind, message, d.line, column); - out.emit(units.get(cursor..start).unwrap_or_default()); + let before = units.get(cursor..start).unwrap_or_default(); + if !named.code_seen && !only_blanks_and_comments(before) { + named.code_seen = true; + } + out.emit(before); cursor = end; let label = format!("{}{}", d.form, d.name); if d.value.len() > MAX_VALUE_BYTES { @@ -402,11 +479,12 @@ impl Files { if value.is_empty() { return Err(at(FailKind::Syntax, format!("{label} needs a file name"))); } + named.code_seen = true; let (real, bytes) = self.open(value, dir, true).map_err(|(kind, message)| at(kind, message))?; let included = self.admit(&real, bytes, value).map_err(|(kind, message)| at(kind, message))?; self.chain.push(real.clone()); self.levels += 1; - let r = self.file(out, display(&real), folder_of(&real).as_deref(), &included, false, name); + let r = self.file(out, display(&real), folder_of(&real).as_deref(), &included, false, named); self.chain.pop(); self.levels -= 1; r?; @@ -421,7 +499,7 @@ impl Files { return Err(at(FailKind::Syntax, format!("{label} needs a name"))); } if script && index == 0 { - *name = Some(value.to_string()); + named.name = Some(value.to_string()); } } Some(DirectiveName::Target) => { @@ -434,7 +512,19 @@ impl Files { "on" => out.strict = Some(true), _ => return Err(at(FailKind::Syntax, format!("{label} takes on or off"))), }, - Some(DirectiveName::TargetEngine) => return Err(at(FailKind::Syntax, format!("unsupported script directive: {label}"))), + Some(DirectiveName::TargetEngine) => { + if !script || index > 0 { + return Err(at(FailKind::Syntax, format!("{label} may only be in the script itself, not in a file it runs"))); + } + if named.engine.is_some() { + return Err(at(FailKind::Syntax, format!("the script has more than one {label} line"))); + } + if named.code_seen { + return Err(at(FailKind::Syntax, format!("{label} must come before the script's code and #include lines"))); + } + let engine = engine_name(&d.value).map_err(|why| at(FailKind::Syntax, format!("{label} {why}")))?; + named.engine = Some((engine, d.line, column)); + } None if d.name.eq_ignore_ascii_case("engine") => { return Err(at(FailKind::Syntax, format!("unsupported script directive: {label}"))); } diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 8d223f53c1..1edeb84e93 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -38,6 +38,13 @@ //! person's answer, and a run with nobody to ask takes its answers from `script.run`'s `answers`. //! //! `File` and `Folder` read files inside the script's own folder ([`files`]). +//! +//! A script with `#targetengine name` runs in that named engine, which the session keeps with the +//! globals its runs leave, at most [`MAX_ENGINES`] of them with [`ENGINE_HEAP_BYTES`] of heap each +//! (VectorCraft's own limits). A script without the line, or with `main`, gets a new realm for each +//! run. An engine keeps no document and no run: its host functions reach the run through a link +//! that holds the run's host only while the run goes on. An error, a limit or a stop puts the +//! documents back and keeps the engine's globals; an internal error drops the engine. pub mod console; pub mod dialogs; @@ -196,6 +203,207 @@ fn with_job<T>(key: &JobKey, f: impl FnOnce(&mut Job) -> T) -> Option<T> { JOBS.with(|jobs| jobs.borrow_mut().get_mut(&key.id).map(f)) } +/// The most named engines (`#targetengine`) a session keeps. +pub const MAX_ENGINES: usize = 8; +/// The heap a named engine may use, with what it keeps between runs. +pub const ENGINE_HEAP_BYTES: usize = 64 << 20; +/// The engine of a script without `#targetengine`, which `#targetengine main` also names: a new +/// one for each run, never kept. +pub const MAIN_ENGINE: &str = "main"; + +/// The run a script's host functions act for. A named engine keeps its functions between runs, so +/// they find the run through this link, which holds the run's [`Host`] only while the run goes on. +type Link = Rc<RefCell<Option<Rc<Host>>>>; + +/// The host of the run `link` holds, or an error when no run holds it. +fn current(link: &Link) -> std::result::Result<Rc<Host>, HostError> { + link.borrow().clone().ok_or_else(|| HostError::Error(NO_RUN.to_string())) +} + +/// A named engine: its interpreter, with the globals its runs left (`None` while a run has it), +/// the link its host functions use, its heap after its last run, and the source maps of the code +/// its earlier runs compiled. +struct Engine { + name: String, + realm: Option<Realm>, + link: Link, + heap: usize, + maps: Rc<RefCell<KeptMaps>>, +} + +/// A named engine taken for a run: its realm (`None` for an engine made now), its link and its +/// kept source maps. +type TakenEngine = (Option<Realm>, Link, Rc<RefCell<KeptMaps>>); + +/// The most bytes of source maps ([`include::SourceMap::bytes`]) a named engine keeps from its +/// earlier runs. +pub const KEPT_MAP_BYTES: usize = 8 << 20; + +/// A source map an engine kept from an earlier run: the realm's tag for the source +/// ([`Realm::error_tag`]), the map, and for the run's own script, that run's name, which stands for +/// a script given as text. +struct KeptMap { + tag: u32, + map: include::SourceMap, + script: Option<Arc<str>>, + bytes: usize, +} + +/// The source maps a named engine kept from its earlier runs, by tag, oldest first, in at most +/// [`KEPT_MAP_BYTES`]: the oldest go first to make room, and a map larger than that is not kept. +#[derive(Default)] +struct KeptMaps { + maps: std::collections::VecDeque<KeptMap>, + bytes: usize, +} + +impl KeptMaps { + fn keep(&mut self, tag: u32, map: include::SourceMap, script: Option<Arc<str>>) { + let bytes = map.bytes() + script.as_ref().map_or(0, |s| s.len()); + let limit = kept_map_bytes(); + if bytes > limit || self.maps.back().is_some_and(|m| m.tag >= tag) { + return; + } + while self.bytes + bytes > limit { + let Some(old) = self.maps.pop_front() else { break }; + self.bytes -= old.bytes; + } + self.bytes += bytes; + self.maps.push_back(KeptMap { tag, map, script, bytes }); + } + + fn get(&self, tag: u32) -> Option<&KeptMap> { + self.maps.binary_search_by_key(&tag, |m| m.tag).ok().and_then(|i| self.maps.get(i)) + } +} + +/// The bytes of source maps a named engine keeps. +fn kept_map_bytes() -> usize { + #[cfg(test)] + if let Some(n) = TEST_KEPT_MAP_BYTES.with(Cell::get) { + return n; + } + KEPT_MAP_BYTES +} + +/// The named engines of one thread's sessions, by their key, each in the order they were made. +struct ThreadEngines { + thread: std::thread::ThreadId, + by_key: HashMap<u64, Vec<Engine>>, +} + +impl ThreadEngines { + fn new() -> Self { + let thread = std::thread::current().id(); + released().insert(thread, Vec::new()); + Self { thread, by_key: HashMap::new() } + } +} + +impl Drop for ThreadEngines { + fn drop(&mut self) { + released().remove(&self.thread); + } +} + +thread_local! { + /// The named engines of this thread's sessions. They are held here, and not in their session, + /// because they hold interpreters, which stay on this thread. + static ENGINES: RefCell<ThreadEngines> = RefCell::new(ThreadEngines::new()); +} + +static NEXT_ENGINES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + +/// For each thread that holds engines, the keys of the ones sessions let go of on another thread. +/// The thread drops them the next time it uses its engines; a thread that has ended has no entry, +/// since its engines ended with it. +static RELEASED_ENGINES: std::sync::LazyLock<std::sync::Mutex<HashMap<std::thread::ThreadId, Vec<u64>>>> = + std::sync::LazyLock::new(|| std::sync::Mutex::new(HashMap::new())); + +fn released() -> std::sync::MutexGuard<'static, HashMap<std::thread::ThreadId, Vec<u64>>> { + RELEASED_ENGINES.lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} + +/// Lets the engines with key `id` go, for `thread`, which holds them, to drop. +fn release_engines(thread: std::thread::ThreadId, id: u64) { + if let Some(ids) = released().get_mut(&thread) { + ids.push(id); + } +} + +/// A session's hold on its named engines: their key, and the thread that holds them once a run +/// made one. Dropping it drops them. The engines stay on that thread, so a session used on another +/// thread lets them go and starts there with none. +#[derive(Debug)] +pub struct EnginesKey(std::sync::Mutex<(u64, Option<std::thread::ThreadId>)>); + +impl EnginesKey { + pub(crate) fn new() -> Self { + Self(std::sync::Mutex::new((NEXT_ENGINES.fetch_add(1, std::sync::atomic::Ordering::Relaxed), None))) + } + + /// The key of the session's engines on this thread. + fn here(&self) -> u64 { + let mut key = self.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let thread = std::thread::current().id(); + match key.1 { + Some(t) if t != thread => { + release_engines(t, key.0); + *key = (NEXT_ENGINES.fetch_add(1, std::sync::atomic::Ordering::Relaxed), Some(thread)); + } + Some(_) => {} + None => key.1 = Some(thread), + } + key.0 + } +} + +impl Drop for EnginesKey { + fn drop(&mut self) { + let (id, thread) = *self.0.get_mut().unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some(t) = thread.filter(|t| *t != std::thread::current().id()) { + release_engines(t, id); + return; + } + let gone = ENGINES.try_with(|engines| engines.try_borrow_mut().ok().and_then(|mut e| e.by_key.remove(&id))); + drop(gone); + } +} + +fn with_engines<T>(key: &EnginesKey, f: impl FnOnce(&mut Vec<Engine>) -> T) -> T { + let id = key.here(); + ENGINES.with(|engines| { + let gone: Vec<Vec<Engine>> = { + let mut here = engines.borrow_mut(); + let ids = released().get_mut(&here.thread).map(std::mem::take).unwrap_or_default(); + ids.iter().filter_map(|id| here.by_key.remove(id)).collect() + }; + drop(gone); + f(engines.borrow_mut().by_key.entry(id).or_default()) + }) +} + +/// Tests: the named engines this thread holds, for every session. +#[cfg(test)] +pub(crate) fn engines_on_this_thread() -> usize { + ENGINES.with(|engines| engines.borrow().by_key.values().map(Vec::len).sum()) +} + +/// Tests: whether engines can still be let go for `thread`, which holds an entry while it lives. +#[cfg(test)] +pub(crate) fn releases_kept_for(thread: std::thread::ThreadId) -> bool { + released().contains_key(&thread) +} + +/// The heap of a named engine. +fn engine_heap() -> usize { + #[cfg(test)] + if let Some(n) = TEST_ENGINE_HEAP.with(Cell::get) { + return n; + } + ENGINE_HEAP_BYTES +} + /// The state a script changes that a rollback puts back. struct World { docs: Vec<DocState>, @@ -464,6 +672,7 @@ impl Savepoint { s.pending_paint = self.pending_paint; self.choices.put(s); s.journal.truncate(self.journal); + s.sync_front_profiles(); exact } } @@ -514,6 +723,14 @@ struct Host { /// The file, line and column of each error `$.evalFile` raised for a file it could not run, in /// order: the error's mark ([`HostError::Marked`]) is its index. eval_failures: RefCell<Vec<(Arc<str>, u32, u32)>>, + /// The realm's tag for the script ([`Realm::script_tag`]) once the run has started it, and + /// [`vectorcraft_js::UNKNOWN_SOURCE`] before or when the script did not compile. + script_tag: Cell<u32>, + /// The run's name as its report gives it, which [`Host::name`] shortens for console lines. + report_name: Arc<str>, + /// The source maps the named engine of the run kept from its earlier runs; `None` for a run + /// without one. + kept_maps: Option<Rc<RefCell<KeptMaps>>>, /// When the run started, where the platform has a clock. started: Option<std::time::Instant>, /// The time since [`Host::started`] at which a `$.sleep` ends. @@ -522,6 +739,10 @@ struct Host { can_wait: Rc<Cell<bool>>, /// What the last `#strict` line of the file `$.evalFile` last gave set (`None` without one). eval_strict: Cell<Option<bool>>, + /// The values of `$` that belong to the run. + dollar: dollar::RunState, + /// The run's `args`, which `vc.args` gives, and their size as `vc.args` charges it. + args: RefCell<(Data, u64)>, } /// A run's host calls by kind, as its report gives them in `hostCallCounts`. @@ -585,6 +806,74 @@ pub(crate) fn slowest(times: &HashMap<&'static str, (u64, u128, u128)>) -> Vec<c } impl Host { + /// Gives the named engine of the run the source maps of the code the run compiled: its script + /// and each file `$.evalFile` gave. A run that never started its script compiled nothing. + fn keep_maps(&self) { + let (Some(kept), tag) = (&self.kept_maps, self.script_tag.get()) else { return }; + if tag == vectorcraft_js::UNKNOWN_SOURCE { + return; + } + let mut kept = kept.borrow_mut(); + kept.keep(tag, std::mem::take(&mut *self.script_map.borrow_mut()), Some(self.report_name.clone())); + for (n, map) in std::mem::take(&mut *self.eval_maps.borrow_mut()).into_iter().enumerate() { + match u32::try_from(n + 1).ok().and_then(|n| tag.checked_add(n)).filter(|t| *t != vectorcraft_js::UNKNOWN_SOURCE) { + Some(t) => kept.keep(t, map, None), + None => break, + } + } + } + + /// The file and line that line `line` of the source with tag `tag` came from, as `$.line` and + /// `$.stack` give them: the run's script, a file it included or a file `$.evalFile` gave, in + /// this run or in an earlier run of its named engine, with the run's name standing for a script + /// given as text. Code that `eval` or `Function` compiled has no map and keeps its own line, + /// named `[eval]`; code whose map is gone, such as one the named engine let go to stay within + /// [`KEPT_MAP_BYTES`], is at line 0 of `[unknown]`. + fn source_place(&self, tag: u32, line: u32) -> (String, u32) { + if tag == vectorcraft_js::UNKNOWN_SOURCE { + return ("[eval]".to_string(), line); + } + let named = |map: &include::SourceMap, script: Option<&Arc<str>>| { + let (index, file, line, _) = map.locate(line, 1); + match script { + Some(name) if index == 0 && file.is_empty() => (name.to_string(), line), + _ => (file.to_string(), line), + } + }; + let script = self.script_tag.get(); + let placed = match tag.checked_sub(script).filter(|_| script != vectorcraft_js::UNKNOWN_SOURCE) { + Some(0) => self.script_map.try_borrow().ok().map(|m| named(&m, Some(&self.report_name))), + Some(n) => self.eval_maps.try_borrow().ok().and_then(|maps| maps.get(n as usize - 1).map(|m| named(m, None))), + None => { + self.kept_maps.as_ref().and_then(|k| k.try_borrow().ok()).and_then(|k| k.get(tag).map(|kept| named(&kept.map, kept.script.as_ref()))) + } + }; + placed.unwrap_or_else(|| ("[unknown]".to_string(), 0)) + } + + /// `$.fileName` read by the code at `site`: the file that code is in, by the source map of the + /// source it came from (this run's script, a file `$.evalFile` gave, or code an earlier run of + /// the named engine compiled), so a function keeps the file it was defined in. Code from a file + /// `#include` inserted is in that file. A script given as text has no name, and neither has + /// code whose map the named engine no longer keeps. Code that `eval` or `Function` compiled has + /// no map, and is given the file being run now. + fn file_name_at(&self, site: vectorcraft_js::CallSite) -> String { + let name = |m: &include::SourceMap| m.locate(site.line, site.column).1.to_string(); + let tag = site.source; + if tag == vectorcraft_js::UNKNOWN_SOURCE { + return self.files.borrow().file_name(); + } + let script = self.script_tag.get(); + match tag.checked_sub(script).filter(|_| script != vectorcraft_js::UNKNOWN_SOURCE) { + Some(0) => name(&self.script_map.borrow()), + Some(n) => self.eval_maps.borrow().get(n as usize - 1).map(name).unwrap_or_default(), + None => { + let kept = self.kept_maps.as_ref().map(|k| k.borrow()); + kept.as_ref().and_then(|k| k.get(tag)).map(|k| name(&k.map)).unwrap_or_default() + } + } + } + /// Adds a line to the run's console and, during a slice, to the session's. fn line(&self, entry: console::Entry, cut: bool) { let line = console::ConsoleLine { run: self.run, name: self.name.clone(), entry }; @@ -704,6 +993,10 @@ impl Host { struct Job { realm: Realm, host: Rc<Host>, + /// The link the realm's host functions find `host` through. + link: Link, + /// The named engine the realm belongs to, which gets it back when the run ends. + engine: Option<String>, /// Between slices the working copy; during the last slice's commit the state before the run. world: World, /// The documents open when the run began, by [`DocState::uid`]. @@ -1013,13 +1306,14 @@ fn each_line(text: &str, mut done: impl FnMut(String, bool)) { /// The `$` object: `$.write(...values)` writes the values to the Script Console as `String(value)` /// gives them, one after another, and `$.writeln(...values)` does the same and ends the line. -/// `$.evalFile(path[, timeout])` runs a file and gives its last value, `$.fileName` is the file -/// being run and `$.includePath` the `#includepath` list. Its other members are -/// [`dollar::members`]. -fn dollar_object(host: &Rc<Host>, info: dollar::RunInfo, localization: &Rc<vectorcraft_js::Localization>) -> Vec<(String, HostItem)> { +/// `$.evalFile(path[, timeout])` runs a file and gives its last value, `$.fileName` is the file the +/// code reading it is in ([`Host::file_name_at`]) and `$.includePath` the `#includepath` list. Its +/// other members are [`dollar::members`]. +fn dollar_object(link: &Link, info: dollar::RunInfo, localization: &Rc<vectorcraft_js::Localization>) -> Vec<(String, HostItem)> { let writer = |end: bool| { - let h = host.clone(); + let l = link.clone(); HostItem::TextFunction(function(move |a| { + let h = current(&l)?; let text: String = a.iter().map(|d| if let Data::String(s) = d { s.as_str() } else { "" }).collect(); h.charge_call(text.len() as u64 + 2)?; bump(&h.counts.console_writes); @@ -1028,31 +1322,43 @@ fn dollar_object(host: &Rc<Host>, info: dollar::RunInfo, localization: &Rc<vecto })) }; let getter = |read: fn(&include::Files) -> String| { - let h = host.clone(); + let l = link.clone(); HostItem::Getter(function(move |_| { + let h = current(&l)?; let text = read(&h.files.borrow()); h.charge_call(text.len() as u64 + 2)?; Ok(Data::String(text)) })) }; + let file_name = { + let l = link.clone(); + HostItem::SiteGetter(Rc::new(move |site| { + let h = current(&l)?; + let text = h.file_name_at(site); + h.charge_call(text.len() as u64 + 2)?; + Ok(Data::String(text)) + })) + }; let eval_file = { - let h = host.clone(); - let end = host.clone(); - let strict = host.clone(); + let (l, end, strict) = (link.clone(), link.clone(), link.clone()); HostItem::Evaluator { - source: function(move |a| eval_file(&h, a)), - end: Rc::new(move || end.files.borrow_mut().end_eval()), - strict_writes: Rc::new(move || strict.eval_strict.get()), + source: function(move |a| eval_file(&*current(&l)?, a)), + end: Rc::new(move || { + if let Ok(h) = current(&end) { + h.files.borrow_mut().end_eval(); + } + }), + strict_writes: Rc::new(move || current(&strict).ok().and_then(|h| h.eval_strict.get())), } }; let mut items = vec![ ("write".into(), writer(false)), ("writeln".into(), writer(true)), ("evalFile".into(), eval_file), - ("fileName".into(), getter(include::Files::file_name)), + ("fileName".into(), file_name), ("includePath".into(), getter(include::Files::include_path)), ]; - items.extend(dollar::members(host, info, localization)); + items.extend(dollar::members(link, info, localization)); items } @@ -1099,32 +1405,46 @@ fn function(f: impl Fn(Vec<Data>) -> std::result::Result<Data, HostError> + 'sta Rc::new(f) } -fn vc_object(host: &Rc<Host>, args: Data) -> Vec<(String, HostItem)> { +/// The `vc` object, made once for each realm: its members act for the run `link` holds when they +/// are called. +fn vc_object(link: &Link) -> Vec<(String, HostItem)> { + let args = { + let l = link.clone(); + function(move |_| { + let h = current(&l)?; + let (args, size) = &*h.args.borrow(); + h.charge_call(*size)?; + Ok(args.clone()) + }) + }; let run = { - let h = host.clone(); - function(move |a| vc_run(&h, a)) + let l = link.clone(); + function(move |a| vc_run(¤t(&l)?, a)) }; let document = { - let h = host.clone(); + let l = link.clone(); function(move |_| { + let h = current(&l)?; h.charge_call(64)?; bump(&h.counts.document_reads); vc_document(&h) }) }; let commands = { - let h = host.clone(); + let l = link.clone(); let list = Rc::new(vc_commands()); let size = data_size(&list); function(move |_| { + let h = current(&l)?; h.charge_call(size)?; bump(&h.counts.command_list_reads); Ok((*list).clone()) }) }; let log = { - let h = host.clone(); + let l = link.clone(); function(move |a| { + let h = current(&l)?; h.charge_call(data_size(a.first().unwrap_or(&Data::Undefined)))?; bump(&h.counts.vc_log); vc_log(&h, a) @@ -1136,7 +1456,7 @@ fn vc_object(host: &Rc<Host>, args: Data) -> Vec<(String, HostItem)> { ("document".into(), HostItem::Getter(document)), ("commands".into(), HostItem::Getter(commands)), ("log".into(), HostItem::Function(log)), - ("args".into(), HostItem::Value(args)), + ("args".into(), HostItem::FrozenGetter(args)), ( "api".into(), HostItem::Object(vec![("version".into(), HostItem::Value(Data::String(API_VERSION.into()))), ("has".into(), HostItem::Function(has))]), @@ -1181,31 +1501,55 @@ fn preprocessor_error(f: include::Failure) -> (RunError, Option<Arc<str>>) { (RunError { kind, message, line: f.line, column: f.column }, file) } -/// `e`, which the realm raised in source `tag` ([`Realm::error_source`]) with host error mark `mark` -/// ([`Realm::error_mark`]), at the line and column of the file it is in, with that file's name -/// unless it is the script's own. -fn located(host: &Host, tag: u32, mark: Option<u32>, e: &RunError) -> (RunError, Option<Arc<str>>) { - let map = |m: &include::SourceMap, own: bool| { +/// `e`, the error `realm` raised in the run of `host`, at the line and column of the file it is in, +/// with that file's name unless it is the run's own script. +fn located(host: &Host, realm: &Realm, e: &RunError) -> (RunError, Option<Arc<str>>) { + let map = |m: &include::SourceMap| { let (index, file, line, column) = m.locate(e.line, e.column); let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, line, column) } else { e.message.clone() }; - (RunError { kind: e.kind.clone(), message, line, column }, (!own || index > 0).then_some(file)) + (RunError { kind: e.kind.clone(), message, line, column }, index, file) }; // An error `$.evalFile` raised for a file it could not run, and no script caught, is at that // file's place. - if let Some((file, line, column)) = mark.and_then(|m| host.eval_failures.borrow().get(m as usize).cloned()) { + if let Some((file, line, column)) = realm.error_mark().and_then(|m| host.eval_failures.borrow().get(m as usize).cloned()) { let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, line, column) } else { e.message.clone() }; return (RunError { kind: e.kind.clone(), message, line, column }, Some(file)); } if e.line == 0 { return (e.clone(), None); } - match tag { - 0 => map(&host.script_map.borrow(), true), + // An error in code from a source whose map is not at hand, such as code that `eval` compiled, + // is given without a place. + let unplaced = || (RunError { kind: e.kind.clone(), message: e.message.clone(), line: 0, column: 0 }, None); + match realm.error_source() { + 0 => { + let (e, index, file) = map(&host.script_map.borrow()); + (e, (index > 0).then_some(file)) + } n if n != vectorcraft_js::UNKNOWN_SOURCE => match host.eval_maps.borrow().get(n as usize - 1) { - Some(m) => map(m, false), - None => (e.clone(), None), + Some(m) => { + let (e, _, file) = map(m); + (e, Some(file)) + } + None => unplaced(), }, - _ => (e.clone(), None), + // Code an earlier run of the named engine compiled, such as a function it defined, is at + // its place in that run's files: the run's script, a file it included, or a file + // `$.evalFile` gave. A script given as text is named by that run's name. + _ => { + let kept = host.kept_maps.as_ref().map(|k| k.borrow()); + match kept.as_ref().and_then(|k| k.get(realm.error_tag())) { + Some(kept) => { + let (e, index, file) = map(&kept.map); + let file = match &kept.script { + Some(name) if index == 0 && file.is_empty() => name.clone(), + _ => file, + }; + (e, Some(file)) + } + None => unplaced(), + } + } } } @@ -1225,6 +1569,100 @@ impl Session { self.script_key.is_some() } + /// The named engine of the running script. + fn running_engine(&self) -> Option<String> { + self.script_key.as_ref().and_then(|k| with_job(k, |j| j.engine.clone())).flatten() + } + + /// The named engines (`#targetengine`) this session keeps, in the order they were made: each + /// one's name, its heap after its last run in bytes, and whether a run has it now. + pub fn script_engines(&self) -> Vec<(String, usize, bool)> { + with_engines(&self.script_engines, |engines| engines.iter().map(|e| (e.name.clone(), e.heap, e.realm.is_none())).collect()) + } + + /// Drops the named engine `name` and the globals its runs left; a later run that names it gets a + /// new one. + pub fn drop_script_engine(&mut self, name: &str) -> Result<()> { + if name == MAIN_ENGINE { + return Err(EngineError::Other(DROP_MAIN.to_string())); + } + if self.running_engine().as_deref() == Some(name) { + return Err(EngineError::Busy); + } + let gone = with_engines(&self.script_engines, |engines| { + let at = engines.iter().position(|e| e.name == name)?; + Some(engines.remove(at)) + }); + match gone { + Some(engine) => { + drop(engine); + Ok(()) + } + None => Err(EngineError::Other(format!("there is no script engine named {name:?}"))), + } + } + + /// The realm of the named engine `name` for a run, with the link its host functions use and the + /// source maps it kept: the realm its last run left, or `None` for an engine made now. → the + /// kind and text of the failure when the engine cannot be had. + fn take_engine(&mut self, name: &str) -> std::result::Result<TakenEngine, (include::FailKind, String)> { + if cfg!(target_arch = "wasm32") { + return Err((include::FailKind::Error, NO_ENGINES_ON_WEB.to_string())); + } + with_engines(&self.script_engines, |engines| { + if let Some(e) = engines.iter_mut().find(|e| e.name == name) { + let realm = e.realm.take().ok_or((include::FailKind::Error, ENGINE_BUSY.to_string()))?; + return Ok((Some(realm), e.link.clone(), e.maps.clone())); + } + if engines.len() >= MAX_ENGINES { + return Err(( + include::FailKind::Limit, + format!("a session keeps at most {MAX_ENGINES} script engines; drop one with script.engine.drop"), + )); + } + let link: Link = Rc::new(RefCell::new(None)); + let maps = Rc::new(RefCell::new(KeptMaps::default())); + engines.push(Engine { name: name.to_string(), realm: None, link: link.clone(), heap: 0, maps: maps.clone() }); + Ok((None, link, maps)) + }) + } + + /// The end of a run in engine `engine` (`None` for a realm that is not kept): the link no longer + /// holds the run, and the engine keeps `realm`, with the source maps of the code the run + /// compiled, or is dropped without one. + fn return_engine(&self, engine: Option<&str>, link: &Link, realm: Option<Realm>) { + let host = link.borrow_mut().take(); + if let (Some(h), Some(_)) = (&host, &realm) { + h.keep_maps(); + } + drop(host); + let Some(name) = engine else { return }; + let mut realm = realm; + let heap = realm.as_mut().map(Realm::collect_garbage); + let gone = with_engines(&self.script_engines, |engines| { + let at = engines.iter().position(|e| e.name == name)?; + match (realm.take(), engines.get_mut(at)) { + (Some(r), Some(e)) => { + e.realm = Some(r); + e.heap = heap.unwrap_or(0); + None + } + _ => Some(engines.remove(at)), + } + }); + drop(gone); + drop(realm); + } + + /// The end of `job`: its engine gets its realm back, with a run that was stopped where it was + /// ended, unless the run ended with an internal error, which drops the engine. + fn end_job(&self, job: Job, internal: bool) { + let Job { mut realm, link, engine, host, .. } = job; + drop(host); + realm.end(); + self.return_engine(engine.as_deref(), &link, (!internal).then_some(realm)); + } + /// The flag that stops the script running in this session from any thread, at its next /// instruction. pub fn script_interrupt(&self) -> Interrupt { @@ -1337,6 +1775,13 @@ impl Session { let line = console::ConsoleLine { run: key.run, name: key.name.clone(), entry: console::Entry::End(ending) }; self.script_console.push(line, false); drop(key); + // The realm of the job's named engine went with the job, so the engine is dropped. + let lost: Vec<Engine> = with_engines(&self.script_engines, |engines| { + let (lost, kept) = std::mem::take(engines).into_iter().partition(|e| e.realm.is_none()); + *engines = kept; + lost + }); + drop(lost); raise_ids(self); self.script_stop.clear(); self.reset_tool(); @@ -1374,10 +1819,40 @@ impl Session { Ok(include::Expanded { name: Some(name), .. }) if !request.name_given => name.clone(), _ => request.name, }; - let limits = Limits { fuel: request.fuel, heap_bytes: HEAP_BYTES, ..Limits::default() }; + // The engine named by `#targetengine`, other than `main`: its realm, kept from its last run, + // or none for an engine this run makes. + let named = match &expanded { + Ok(include::Expanded { engine: Some((engine, line, column)), .. }) if engine != MAIN_ENGINE => Some((engine.clone(), *line, *column)), + _ => None, + }; + let (expanded, kept) = match named { + None => (expanded, None), + Some((engine, line, column)) => match self.take_engine(&engine) { + Ok(kept) => (expanded, Some((engine, kept))), + Err((kind, message)) => { + let file = Arc::from(files.file_name()); + (Err(include::Failure { kind, message, index: 0, file, line, column }), None) + } + }, + }; + let heap_bytes = if kept.is_some() { engine_heap() } else { HEAP_BYTES }; + let limits = Limits { fuel: request.fuel, heap_bytes, ..Limits::default() }; + let (engine, realm, link, kept_maps) = match kept { + None => (None, None, Rc::new(RefCell::new(None)), None), + Some((engine, (realm, link, maps))) => (Some(engine), realm, link, Some(maps)), + }; + // A realm made here gets the script extensions, `$` and the dialogs; a kept one has them + // from its first run, and they act for the run that calls them. + let fresh = realm.is_none(); let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), ..Options::default() }; let strict = options.strict; - let mut realm = Realm::with_options(options, limits); + let mut realm = match realm { + Some(mut realm) => { + realm.set_limits(limits); + realm + } + None => Realm::with_options(options, limits), + }; realm.share_interrupt(&self.script_stop); realm.set_data_limits(DataLimits::default()); self.script_runs += 1; @@ -1410,33 +1885,68 @@ impl Session { script_map: RefCell::default(), eval_maps: RefCell::default(), eval_failures: RefCell::default(), + script_tag: Cell::new(vectorcraft_js::UNKNOWN_SOURCE), + report_name: Arc::from(name.as_str()), + kept_maps, started: clock(), wake_at: Cell::new(None), can_wait: realm.wait_flag(), eval_strict: Cell::new(None), + dollar: dollar::RunState::new(&request.locale), + args: RefCell::new((Data::Undefined, 0)), }); - let args = to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0)) - .map_err(|place| EngineError::BadParams { cmd: "script.run".into(), msg: format!("`args{place}` is nested more than 64 levels deep") })?; + *link.borrow_mut() = Some(host.clone()); + let args = match to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0)) { + Ok(args) => args, + Err(place) => { + self.return_engine(engine.as_deref(), &link, (!fresh).then_some(realm)); + return Err(EngineError::BadParams { cmd: "script.run".into(), msg: format!("`args{place}` is nested more than 64 levels deep") }); + } + }; + let size = data_size(&args); + *host.args.borrow_mut() = (args, size); let line = console::ConsoleLine { run: host.run, name: host.name.clone(), entry: console::Entry::Start }; self.script_console.push(line, false); - let info = dollar::RunInfo { locale: request.locale, strict }; + let engine_name = match &expanded { + Ok(include::Expanded { engine: Some((name, ..)), .. }) => Some(name.clone()), + _ => None, + }; + let info = dollar::RunInfo { strict, engine: engine_name }; let localization = realm.localization(); + dollar::start_run(&localization, &request.locale); let started = match expanded { Err(f) => Err(preprocessor_error(f)), Ok(expanded) => { *host.script_map.borrow_mut() = expanded.map; realm.set_strict_writes(expanded.strict == Some(true)); - realm - .add_script_extensions() - .and_then(|()| realm.define_host_object("vc", vc_object(&host, args))) - .and_then(|()| realm.define_host_object("$", dollar_object(&host, info, &localization))) - .and_then(|()| dialogs::install(&mut realm, &host)) - .and_then(|()| files::install(&mut realm, &host)) - .and_then(|()| realm.start(&expanded.source)) - .map_err(|e| located(&host, realm.error_source(), realm.error_mark(), &e)) + if fresh { + let l = link.clone(); + realm.set_source_locator(Rc::new(move |tag, line| match current(&l) { + Ok(h) => h.source_place(tag, line), + Err(_) => ("[unknown]".to_string(), 0), + })); + } + (if fresh { realm.add_script_extensions() } else { Ok(()) }) + .and_then(|()| if fresh { realm.define_host_object("vc", vc_object(&link)) } else { Ok(()) }) + .and_then(|()| if fresh { realm.define_host_object("$", dollar_object(&link, info, &localization)) } else { Ok(()) }) + .and_then(|()| if fresh { dialogs::install(&mut realm, &link) } else { Ok(()) }) + .and_then(|()| if fresh { files::install(&mut realm, &link) } else { realm.reset_folder_current() }) + .and_then(|()| { + let r = realm.start(&expanded.source); + // Source that does not compile defines no code, so its map is not kept. + if !matches!(&r, Err(e) if e.kind == RunErrorKind::Syntax) { + host.script_tag.set(realm.script_tag()); + } + r + }) + .map_err(|e| located(&host, &realm, &e)) } }; if let Err((e, file)) = started { + // An engine this run made is not kept: only a run that starts makes one. An internal + // error drops a kept one. + let keep = !fresh && e.kind != RunErrorKind::Internal; + self.return_engine(engine.as_deref(), &link, keep.then_some(realm)); let mut report = failure_report(&name, &e, file.as_deref(), &host, 0, 0); close_run(self, &host, &mut report, ending(&e.kind)); let message = failure_text(&report); @@ -1445,7 +1955,7 @@ impl Session { } let scope = crate::file_access::ScopeHandle::capture(); let (run, line_name) = (host.run, host.name.clone()); - let job = Job { realm, host, world: World::working(self), start_uids: open, name: name.clone(), scope }; + let job = Job { realm, host, link, engine, world: World::working(self), start_uids: open, name: name.clone(), scope }; let id = NEXT_JOB.fetch_add(1, std::sync::atomic::Ordering::Relaxed); JOBS.with(|jobs| jobs.borrow_mut().insert(id, job)); self.script_key = Some(JobKey { id, run, name: line_name }); @@ -1463,6 +1973,10 @@ impl Session { if let Some(e) = job.host.dialogs.take_failure() { return Some(self.script_failed(job, &e)); } + // A canceled request ends a sleep or a wait at this pump. + if vectorcraft_doc::cancel::check().is_err() { + self.script_stop.set(); + } if (job.host.waiting.get() || job.host.asleep().is_some() || job.host.dialogs.is_waiting()) && !self.script_stop.is_set() { JOBS.with(|jobs| jobs.borrow_mut().insert(key.id, job)); self.script_key = Some(key); @@ -1474,9 +1988,6 @@ impl Session { let e = RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line: 0, column: 0 }; return Some(self.script_failed(job, &e)); } - if vectorcraft_doc::cancel::check().is_err() { - self.script_stop.set(); - } job.host.calls_this_slice.set(0); let outcome = run_slice(self, &mut job); match outcome { @@ -1507,10 +2018,10 @@ impl Session { fn script_failed(&mut self, job: Job, e: &RunError) -> Result<Value> { job.host.dialogs.stopped(); let fuel_left = job.realm.fuel_left(); - let (e, file) = located(&job.host, job.realm.error_source(), job.realm.error_mark(), e); + let (e, file) = located(&job.host, &job.realm, e); let mut report = failure_report(&job.name, &e, file.as_deref(), &job.host, fuel_left, job.realm.limits().fuel.saturating_sub(fuel_left)); close_run(self, &job.host, &mut report, ending(&e.kind)); - drop(job); + self.end_job(job, e.kind == RunErrorKind::Internal); raise_ids(self); self.script_stop.clear(); self.reset_tool(); @@ -1592,6 +2103,7 @@ impl Session { "hostCalls": host.calls.get(), }); close_run(self, host, &mut report, console::Ending::Finished); + self.end_job(job, false); self.script_report = Some(report.clone()); Ok(report) } @@ -1630,6 +2142,10 @@ const NO_RECOVERY_COPY: &str = "a recovery copy could not be written, so the scr const EVAL_NO_PATH: &str = "$.evalFile requires a file path"; const EVAL_TIMEOUT: &str = "$.evalFile: the timeout must be a finite number of milliseconds, 0 or more"; const EVAL_ARGUMENTS: &str = "$.evalFile: takes a file path and a timeout"; +const NO_RUN: &str = "this function's script run has ended"; +const DROP_MAIN: &str = "the main script engine is new for each run and is never kept, so it cannot be dropped"; +const NO_ENGINES_ON_WEB: &str = "named script engines (#targetengine) are not available on the web"; +const ENGINE_BUSY: &str = "the script engine is in use by another run"; /// The report of a run that failed; `file` is the included file the error is in. fn failure_report(name: &str, e: &RunError, file: Option<&str>, host: &Host, fuel_left: u64, fuel_used: u64) -> Value { @@ -1671,6 +2187,27 @@ fn line_to(s: &mut Session, host: &Host, entry: console::Entry, cut: bool) { host.console.borrow_mut().push(line, cut); } +/// The error of the failed run `report` describes, as its console lines give it; `name` is the +/// run's name in those lines ([`console::line_name`]). +fn error_text(name: &str, report: &Value) -> String { + let (line, column) = (report["line"].as_u64().unwrap_or(0), report["column"].as_u64().unwrap_or(0)); + let message = report["message"].as_str().unwrap_or_default(); + match report["file"].as_str() { + Some(file) if line > 0 => format!("{name}: {file}:{line}:{column}: {message}"), + _ if line > 0 => format!("{name}:{line}:{column}: {message}"), + _ => format!("{name}: location unavailable: {message}"), + } +} + +/// The console lines of the error of the failed run `report` describes, each as the console keeps +/// it, cut to its limit. +pub(crate) fn error_lines(report: &Value) -> Vec<String> { + let name = console::line_name(report["name"].as_str().unwrap_or_default()); + let mut lines = vec![]; + each_line(&error_text(&name, report), |line, _| lines.push(line)); + lines +} + /// Ends the console lines of `host`'s run: the line `$.write` left unended, then for a failed run /// (`report["ok"]` false) its error as `name:line:column: message`, then an end line and a report /// line in the session's console. Adds the run's time, host calls by kind, slowest commands, @@ -1685,14 +2222,7 @@ fn close_run(s: &mut Session, host: &Host, report: &mut Value, ending: console:: } } if report["ok"] == false { - let (line, column) = (report["line"].as_u64().unwrap_or(0), report["column"].as_u64().unwrap_or(0)); - let message = report["message"].as_str().unwrap_or_default(); - let text = match report["file"].as_str() { - Some(file) if line > 0 => format!("{}: {file}:{line}:{column}: {message}", host.name), - _ if line > 0 => format!("{}:{line}:{column}: {message}", host.name), - _ => format!("{}: location unavailable: {message}", host.name), - }; - each_line(&text, |line, cut| line_to(s, host, console::Entry::Error(line), cut)); + each_line(&error_text(&host.name, report), |line, cut| line_to(s, host, console::Entry::Error(line), cut)); } let timing = clock().is_some(); let ms = millis(host.run_nanos.get()); @@ -1717,8 +2247,8 @@ fn failure_text(report: &Value) -> String { let s = |k: &str| report[k].as_str().unwrap_or_default(); let (line, column) = (report["line"].as_u64().unwrap_or(0), report["column"].as_u64().unwrap_or(0)); let at = match report["file"].as_str() { - Some(file) if line > 0 => format!(" line {line}, column {column} of {file}"), - _ if line > 0 => format!(" line {line}, column {column}"), + Some(file) if line > 0 => format!(": line {line}, column {column} of {file}"), + _ if line > 0 => format!(": line {line}, column {column}"), _ => String::new(), }; let written = report["written"].as_array().map_or(0, Vec::len); @@ -1728,7 +2258,7 @@ fn failure_text(report: &Value) -> String { } else { String::new() }; - format!("{}:{at}: {} ({}){kept}", s("name"), s("message"), s("kind")) + format!("{}{at}: {} ({}){kept}", s("name"), s("message"), s("kind")) } /// A run's slice: the working copy in, the real session lent to the host functions, one measured @@ -1737,6 +2267,9 @@ fn failure_text(report: &Value) -> String { fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result<std::result::Result<Progress, RunError>, String> { let depth = std::mem::replace(&mut s.depth, 0); job.world.swap(s); + // The run's front document draws and converts through its own profiles, and the interface's + // again after the slice. + s.sync_front_profiles(); s.script_in_run = true; let cell = job.host.session.clone(); std::mem::swap(s, &mut *cell.borrow_mut()); @@ -1759,6 +2292,7 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result<std::result: s.script_in_run = false; job.world.swap(s); s.depth = depth; + s.sync_front_profiles(); r } @@ -1795,6 +2329,10 @@ thread_local! { pub(crate) static PANIC_IN_SLICE: Cell<bool> = const { Cell::new(false) }; /// Tests: the objects a run may add in place of [`GROWTH_OBJECTS`]. pub(crate) static TEST_GROWTH: Cell<Option<u64>> = const { Cell::new(None) }; + /// Tests: the heap of a named engine in place of [`ENGINE_HEAP_BYTES`]. + pub(crate) static TEST_ENGINE_HEAP: Cell<Option<usize>> = const { Cell::new(None) }; + /// Tests: the bytes of source maps a named engine keeps, in place of [`KEPT_MAP_BYTES`]. + pub(crate) static TEST_KEPT_MAP_BYTES: Cell<Option<usize>> = const { Cell::new(None) }; /// Tests: the `JSINCLUDE` folders in place of the environment's. pub(crate) static TEST_JSINCLUDE: RefCell<Option<Vec<std::path::PathBuf>>> = const { RefCell::new(None) }; /// Tests: the time since a run started, in place of its clock's. diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 2c59c5630a..d6af60fee1 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -1,4 +1,4 @@ -use super::command_sets::{JOURNALED_READS, SELECTS_GIVEN_IDS, given_ids, strip_replay_only, waits_for_tool_edit}; +use super::command_sets::{JOURNALED_READS, SELECTS_GIVEN_IDS, TAKES_GUIDE_IDS, given_ids, strip_replay_only, waits_for_tool_edit}; use super::doc_state::DocState; use super::error::{EngineError, Result}; use super::history::NamedStep; diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 63fbcd5a78..da26dbfc71 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -80,6 +80,8 @@ impl Session { style_libraries: Default::default(), symbol_libraries: Default::default(), brush_libraries: Default::default(), + arrowheads: Default::default(), + shown_library_ids: Default::default(), libraries: Default::default(), pdf_preset_dir: None, dictionary_file: None, @@ -87,7 +89,7 @@ impl Session { color_settings_file: None, plugin_dir: None, scripts_dir: None, - ignored_plugin_grants: Default::default(), + new_doc_profile_dir: None, plugin_output: None, plugin_install_approval: None, plugin_grants_from_requests: false, @@ -114,7 +116,9 @@ impl Session { screens_hand_off: None, recovery: Default::default(), in_tool_actions: false, + settled_warnings: None, previewing: false, + decoded_images: Default::default(), envelope_defaults: None, liquify_stroke: None, plane_widget_press: false, @@ -123,6 +127,7 @@ impl Session { press_type_selection: None, press_point: None, ruler_guide: None, + ruler_origin: None, port_marks: Default::default(), font_search: None, link_search: None, @@ -134,6 +139,7 @@ impl Session { global_edit_options: Default::default(), keyboard_text: false, script_key: None, + script_engines: crate::script::EnginesKey::new(), script_stop: vectorcraft_js::Interrupt::new(), script_report: None, script_console: Default::default(), @@ -215,6 +221,7 @@ impl Session { self.active = Some(index); if switched { self.sync_front_composite_fonts(); + self.sync_front_profiles(); } true } else { @@ -222,6 +229,15 @@ impl Session { } } + /// Make the profiles the document in front is assigned the ones colors are drawn and converted + /// through, in place of the working spaces (with no document open, or none assigned: the working + /// spaces), after a switch, an open, a close, a revert or a restored document brought another + /// document or another assignment to the front. The open documents redraw when the active color + /// settings change. + pub(crate) fn sync_front_profiles(&mut self) { + cmd::colormgmt::use_front_profiles(self); + } + /// Register the composite fonts of the document now in front ([`cmd::compositefonts::sync`]), /// after a switch or a close brought it there. Its type set in a composite font that differs /// from the one of that name before (added, changed or removed) is measured again, and type not @@ -311,6 +327,7 @@ impl Session { let i = self.docs.len() - 1; self.active = Some(i); self.sync_opened_composite_fonts(i); + self.sync_front_profiles(); if self.depth == 0 && let Some(label) = self.explicit_undo_group.clone() { @@ -353,6 +370,8 @@ impl Session { st.history.limit = old.history.limit; // Same open document (caches keyed by uid stay valid); a new revision redraws it. st.uid = old.uid; + // Work started for the content being thrown away is dropped when it finishes. + st.reverts = old.reverts + 1; st.opened_as_tab = old.opened_as_tab; st.revision = old.revision + 1; st.format = old.format; @@ -379,16 +398,26 @@ impl Session { } match back_names { Some(names) => self.refresh_document_text_bounds(index, |t| t.cached_bounds.is_none() && !sets_in_any(t, &names)), - None => self.sync_opened_composite_fonts(index), + None => { + self.sync_opened_composite_fonts(index); + self.sync_front_profiles(); + } } true } + /// Close the document in tab `index` (`file.close`). Closing a tab other than the current one + /// keeps the current document current, and its tool keeps its state: no document is switched + /// to. Closing the current document makes the tab now at `index` current, or the last tab when + /// it was the last one. False, changing nothing, when `index` is past the last document. pub fn close_document(&mut self, index: usize) -> bool { if index >= self.docs.len() { return false; } - self.reset_tool_for_doc_switch(); + let front = self.active().map(|d| d.uid).filter(|_| self.active != Some(index)); + if front.is_none() { + self.reset_tool_for_doc_switch(); + } // Closed (saved or discarded): nothing left to recover. let uid = self.docs[index].uid; cmd::recovery::forget(self, uid); @@ -396,8 +425,13 @@ impl Session { if let Some(stash) = &mut self.batch_stash { stash.push(old); } + if let Some(uid) = front { + self.active = self.docs.iter().position(|d| d.uid == uid); + return true; + } self.active = if self.docs.is_empty() { None } else { Some(index.min(self.docs.len() - 1)) }; self.sync_front_composite_fonts(); + self.sync_front_profiles(); true } diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index 1762c96765..73977f7d64 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -31,6 +31,8 @@ impl Session { } // Pixel-aligned objects the edit changed go back on the pixel grid. cmd::refresh_pixel_aligned(&before, doc); + // Color masks of images whose own pixels the edit replaced are made for the new ones. + cmd::refresh_color_masks(Some(&*before), doc); let placed = cmd::objects_on_path::refresh(&before, doc); // Pixel-aligned members that placing moved go back on the pixel grid. cmd::keep_aligned_in(doc, &placed); @@ -232,6 +234,27 @@ impl Session { self.active().and_then(|d| d.interaction.as_ref().filter(|it| std::sync::Arc::ptr_eq(&it.doc, &d.doc)).and_then(|it| it.preview.clone())) } + /// Keep `warning`, from a preview that settling an interaction applied, for whatever collects + /// such warnings now ([`Session::collect_settled_warnings`]). Nothing keeps it when nothing + /// collects, so it is never reported with a later, unrelated command. + pub(crate) fn note_settled_warning(&mut self, warning: &str) { + if let Some(kept) = &mut self.settled_warnings + && !kept.iter().any(|w| w == warning) + { + kept.push(warning.to_string()); + } + } + + /// Run `f`, and → its result with the warnings of the previews that settling an interaction + /// applied while it ran ([`Session::note_settled_warning`]). Warnings an outer `f` collects are + /// kept for it. + pub(crate) fn collect_settled_warnings<R>(&mut self, f: impl FnOnce(&mut Self) -> R) -> (R, Vec<String>) { + let outer = self.settled_warnings.replace(Vec::new()); + let r = f(self); + let settled = std::mem::replace(&mut self.settled_warnings, outer).unwrap_or_default(); + (r, settled) + } + pub fn begin_interaction(&mut self, label: &str) -> Result<()> { if self.script_running() { return Err(EngineError::Busy); @@ -267,6 +290,7 @@ impl Session { isolation: st.isolation, perspective_again: None, copies: None, + move_box: std::sync::OnceLock::new(), }); Ok(()) } @@ -287,7 +311,10 @@ impl Session { st.revision += 1; } st.doc = it.doc.clone(); - let restore_paint = cmd == "command.batch" || it.preview.as_ref().is_some_and(|(id, _)| id == "command.batch"); + // A batch, or a preview that changed the new-art paints (a pattern rename), started from + // the paints the interaction began with. + let restore_paint = + cmd == "command.batch" || it.preview.as_ref().is_some_and(|(id, _)| id == "command.batch") || it.color_mode_paints.is_some(); let paint = it.paint.clone(); it.preview_paint = None; it.color_mode_paints = None; @@ -305,6 +332,8 @@ impl Session { self.paint = paint.clone(); } self.pending_paint = None; + // The previous preview's Assign Profile is undone with it. + self.sync_front_profiles(); let rw = cmd::distortcmds::perspective_rewrite(self, cmd, params).or_else(|| cmd::bounds_rewrite(self, cmd, params)); let (cmd, params) = rw.as_ref().map_or((cmd, params), |(c, p)| (c.as_str(), p)); // A selected object's converted appearance must not replace the current paints while @@ -335,6 +364,7 @@ impl Session { pub fn commit_interaction(&mut self) -> Result<()> { self.clear_deferred_overlay_cache(); + self.decoded_images.empty(); if let Some(paint) = self.active().and_then(|st| st.interaction.as_ref()).and_then(|it| it.preview_paint.clone()) { self.paint = paint; } @@ -414,11 +444,12 @@ impl Session { pub fn cancel_interaction(&mut self) -> Result<()> { self.clear_deferred_overlay_cache(); + self.decoded_images.empty(); self.pending_paint = None; if let Some(paint) = self .active() .and_then(|st| st.interaction.as_ref()) - .filter(|it| it.preview.as_ref().is_some_and(|(id, _)| id == "command.batch")) + .filter(|it| it.preview.as_ref().is_some_and(|(id, _)| id == "command.batch") || it.color_mode_paints.is_some()) .map(|it| it.paint.clone()) { self.paint = paint; @@ -428,6 +459,11 @@ impl Session { st.undo_interaction(); // Guides locked and slices locked or hidden during the interaction stay deselected. deselect_hidden(&menu, &st.doc, &mut st.selection); + // A canceled preview's Assign Profile is undone with it. + self.sync_front_profiles(); + // With New Art Has Basic Appearance off, new art takes the appearance of the selection as + // the document has it again, not as a preview left it. + self.inherit_new_art(); Ok(()) } diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index abe9121eff..3bc5c72378 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -1,8 +1,29 @@ use super::{ - CommandSpec, EngineError, JOURNALED_READS, NodeId, Result, SELECTS_GIVEN_IDS, Selection, Session, Value, cmd, find_command, given_ids, guard, - strip_replay_only, waits_for_tool_edit, + CommandSpec, EngineError, JOURNALED_READS, NodeId, Result, SELECTS_GIVEN_IDS, Selection, Session, TAKES_GUIDE_IDS, Value, cmd, find_command, + given_ids, guard, strip_replay_only, waits_for_tool_edit, }; +/// A command's result `r` with the warnings of the previews that settling an interaction applied +/// before it ran: `previewWarning` holds them, and `warning` too when the command gives none of its +/// own, so the status bar shows the command's own warning when there is one. A null result becomes +/// an object holding them; any other result that isn't an object is returned as it is. +fn with_settled_warnings(mut r: Value, settled: &[String]) -> Value { + if settled.is_empty() { + return r; + } + if r.is_null() { + r = Value::Object(serde_json::Map::new()); + } + if let Value::Object(m) = &mut r { + let w = Value::String(settled.join("; ")); + if m.get("warning").is_none_or(Value::is_null) { + m.insert("warning".into(), w.clone()); + } + m.insert("previewWarning".into(), w); + } + r +} + impl Session { /// `spec`'s `enabled` with `ids` selected instead of the selection, which is then put back. fn enabled_with_selection(&mut self, spec: &CommandSpec, ids: Vec<NodeId>) -> std::result::Result<(), String> { @@ -54,7 +75,14 @@ impl Session { self.finish_tool_edit_later()?; } let outer = std::mem::replace(&mut self.reading, !spec.journal || JOURNALED_READS.contains(&id)); - let r = self.execute_spec(spec, id, params); + // A preview that a top-level command applied first (a drag with Real-time Drawing off, kept + // before Undo) reports its warning in the command's result. + let r = if self.depth == 0 { + let (r, settled) = self.collect_settled_warnings(|s| s.execute_spec(spec, id, params)); + r.map(|v| with_settled_warnings(v, &settled)) + } else { + self.execute_spec(spec, id, params) + }; self.reading = outer; r } @@ -82,7 +110,13 @@ impl Session { && params.get("ids").is_none_or(Value::is_null) && params.get("id").and_then(Value::as_str).is_some_and(|e| !e.starts_with('$')); if cmd::params::id_stands_for_ids(spec.params) && !effect_named && self.active().is_some() { - cmd::given_objects(self, params, id)?; + // `effect.refreshDeferred` looks its objects up itself: they can also be in the art of + // a symbol, pattern, brush or opacity mask. + if id == "effect.refreshDeferred" { + cmd::given_object_ids(params, id)?; + } else { + cmd::given_nodes(self, params, id, TAKES_GUIDE_IDS.contains(&id))?; + } } if SELECTS_GIVEN_IDS.contains(&id) { self.check_given_ids(id, params)?; @@ -100,7 +134,8 @@ impl Session { // whichever tool is chosen. let given = given_ids(spec.params, params); // The guide commands take ruler guides by index; an object command given one's id is refused. - if let (Some(ids), Some(st)) = (&given, self.active()) + if !TAKES_GUIDE_IDS.contains(&id) + && let (Some(ids), Some(st)) = (&given, self.active()) && let Some(guide) = ids.iter().find(|i| st.doc.node(**i).is_some_and(|n| n.is_ruler_guide())) { let value = guide.0; @@ -162,6 +197,10 @@ impl Session { let (doc, journal, grouped) = (self.active().map(|d| d.uid), self.journal.len(), self.undo_group_docs()); let open = (self.depth == 0).then(|| self.docs.iter().map(|d| d.uid).collect::<Vec<_>>()); let r = if self.depth == 0 { self.run_guarded(id, run) } else { self.run_nested(run) }; + // Colors are drawn and converted through the profiles of the document in front now, also + // after an undone or redone Assign Profile, a failed or panicked command's documents put + // back, and a batch step, before the next step converts through them. + self.sync_front_profiles(); if r.is_err() && self.depth == 0 { self.batch_paint_docs.clear(); // A failed or panicked command's documents are put back: type is drawn in their @@ -358,3 +397,25 @@ impl Session { r } } + +#[cfg(test)] +mod tests { + use serde_json::json; + + use super::with_settled_warnings; + + /// The command's own warning stays the one the status bar shows, and the settled preview's is + /// kept beside it; a null result holds the preview's; other results are left as they are. + #[test] + fn settled_warnings_join_the_result() { + let settled = ["a".to_string(), "b".to_string()]; + assert_eq!( + with_settled_warnings(json!({"ran": 1, "warning": "own"}), &settled), + json!({"ran": 1, "warning": "own", "previewWarning": "a; b"}) + ); + assert_eq!(with_settled_warnings(json!({"warning": null}), &settled), json!({"warning": "a; b", "previewWarning": "a; b"})); + assert_eq!(with_settled_warnings(json!(null), &settled[..1]), json!({"warning": "a", "previewWarning": "a"})); + assert_eq!(with_settled_warnings(json!([1]), &settled), json!([1])); + assert_eq!(with_settled_warnings(json!({"ran": 1}), &[]), json!({"ran": 1})); + } +} diff --git a/crates/engine/src/session/undo.rs b/crates/engine/src/session/undo.rs index d06934926c..3af4cafe5f 100644 --- a/crates/engine/src/session/undo.rs +++ b/crates/engine/src/session/undo.rs @@ -164,6 +164,10 @@ impl Session { if self.depth == 0 { self.trim_histories(); } + // A canceled group's Assign Profile is undone with it. + if cancel { + self.sync_front_profiles(); + } } /// When journal entry `n` is a `command.batch` with `steps` noted in canceled undo groups and @@ -280,5 +284,7 @@ impl Session { g.journal.retain(|&(n, _)| n < scope.journal); g.steps.retain(|&(n, _)| n < scope.journal); } + // A canceled scope's Assign Profile is undone with it. + self.sync_front_profiles(); } } diff --git a/crates/engine/src/store.rs b/crates/engine/src/store.rs index 9a96f96212..8a18ce9824 100644 --- a/crates/engine/src/store.rs +++ b/crates/engine/src/store.rs @@ -39,6 +39,7 @@ use std::sync::{Arc, Mutex, MutexGuard}; use std::time::SystemTime; use vectorcraft_pdf::{PdfPreset, builtin_preset}; +use vectorcraft_plugins::permissions::GrantToken; use vectorcraft_plugins::safe_mode; use vectorcraft_plugins::storage::{self, Meter, Storage, StorageError}; @@ -88,6 +89,24 @@ static PLUGIN_DATA_LOCK: Mutex<()> = Mutex::new(()); /// The state of each plug-in folder's storage, shared by every storage made for the folder until /// the plug-in is removed, which closes it and drops it. static PLUGIN_DATA_OPEN: Mutex<BTreeMap<PathBuf, Arc<PluginData>>> = Mutex::new(BTreeMap::new()); +/// The grants of plug-in stores that the sessions of the process don't count, and when each was +/// last written ([`IgnoredGrants`]). Another process reads `grants.json` as it is. +static IGNORED_PLUGIN_GRANTS: Mutex<IgnoredGrants> = Mutex::new(IgnoredGrants { ignored: BTreeSet::new(), written: BTreeMap::new(), writes: 0 }); +/// How many of the latest grant writes [`IgnoredGrants`] keeps. +const MAX_GRANT_WRITES_KEPT: usize = 256; + +/// Grants of plug-in stores, by the store's folder ([`plugin_store_key`]) and the plug-in id. +struct IgnoredGrants { + /// The grants that should be gone but could not be removed: no session in the process counts + /// them ([`Session::ignore_stored_grant`]) until one writes the store's grants for the id + /// ([`Session::store_grant`]). + ignored: BTreeSet<(PathBuf, String)>, + /// The latest grant writes of the process, at most [`MAX_GRANT_WRITES_KEPT`], each with the + /// count of writes it made ([`IgnoredGrants::writes`]). + written: BTreeMap<(PathBuf, String), u64>, + /// How many grant writes the sessions of the process have made ([`Session::grant_writes`]). + writes: u64, +} /// The file name (without extension) a stored item called `name` gets: its name made safe for any /// file system, then a hash of the name, so that names that differ only in characters a file name @@ -99,6 +118,37 @@ pub(crate) fn file_stem(name: &str) -> String { format!("{}-{hash:016x}", safe.trim()) } +/// The folder `dir` spelled one way for every path to it, so that sessions attached to it by +/// different paths share [`IGNORED_PLUGIN_GRANTS`]: the canonical path when the folder exists, else +/// the canonical path of its nearest folder that exists followed by the rest of the path, with `.` +/// and `..` taken out by name. The path as given when it has no absolute form (the current folder +/// can't be read). +pub(crate) fn plugin_store_key(dir: &Path) -> PathBuf { + if let Ok(path) = std::fs::canonicalize(dir) { + return path; + } + let Ok(absolute) = std::path::absolute(dir) else { return dir.to_path_buf() }; + let mut parts: Vec<std::path::Component> = Vec::new(); + for part in absolute.components() { + match part { + std::path::Component::CurDir => {} + std::path::Component::ParentDir => { + if matches!(parts.last(), Some(std::path::Component::Normal(_))) { + parts.pop(); + } + } + _ => parts.push(part), + } + } + for kept in (1..=parts.len()).rev() { + let base: PathBuf = parts[..kept].iter().collect(); + if let Ok(found) = std::fs::canonicalize(&base) { + return parts[kept..].iter().fold(found, |path, part| path.join(part)); + } + } + parts.iter().collect() +} + /// The regular files of `dir` with the extension `ext` (any case), by file name, at most /// [`MAX_STORE_FILES`]; none when the folder can't be read. fn list_files(dir: &Path, ext: &str) -> Vec<PathBuf> { @@ -190,6 +240,12 @@ fn lock_disabled(_: &Path) -> Option<std::fs::File> { thread_local! { /// Tests: [`Session::put_back_plugin`] fails on this thread, as on a full volume. pub(crate) static PUT_BACK_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; + /// Tests: removing [`GRANTS_FILE`] fails on this thread while the file still reads, as when + /// another program holds it open. + pub(crate) static GRANTS_DELETE_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; + /// Tests: [`Session::put_back_plugin`] writes the old module back on this thread and then + /// reports a failure, as when the last flush of a copy fails. + pub(crate) static PUT_BACK_FAILS_AFTER_WRITE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; /// Tests: moving a plug-in's settings and cache back from `<folder>.removed` ([`move_back`]) /// fails on this thread, as when another program holds a file in the folder. pub(crate) static MOVE_BACK_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; @@ -201,7 +257,15 @@ thread_local! { /// Remove `dir/file` → whether it is gone; a file that isn't there is what was wanted. fn take(dir: &Path, file: &str) -> bool { let path = dir.join(file); - match std::fs::remove_file(&path) { + #[cfg(test)] + let removed = if file == GRANTS_FILE && GRANTS_DELETE_FAILS.get() { + Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied)) + } else { + std::fs::remove_file(&path) + }; + #[cfg(not(test))] + let removed = std::fs::remove_file(&path); + match removed { Err(e) if e.kind() != std::io::ErrorKind::NotFound => { log::warn!("can't remove {}: {e}", path.display()); false @@ -340,9 +404,6 @@ impl Session { let disabled = read_capped(&dir.join(DISABLED_FILE), safe_mode::MAX_DISABLED_FILE_BYTES).map(|b| safe_mode::parse_disabled_file(&b)).unwrap_or_default(); safe_mode::set_disabled(disabled); - if self.plugin_dir.as_ref() != Some(&dir) { - self.ignored_plugin_grants.lock().unwrap_or_else(|e| e.into_inner()).clear(); - } self.plugin_dir = Some(dir); self.load_stored_plugins(); } @@ -353,12 +414,15 @@ impl Session { /// there don't grant that very module ([`grant_covers`]), is skipped with a log record, and /// stays in the folder with its grant. A grant for an id whose stored module lists no /// permissions is forgotten; one that can't be removed from the grants file doesn't count for - /// the rest of the session ([`Session::plugin_approver`]). + /// any session in the process attached to the folder until the file can be written for the id + /// ([`Session::ignore_stored_grant`]). pub fn load_stored_plugins(&mut self) { let Some(dir) = self.plugin_dir.clone() else { return }; if safe_mode::active() { return; } + // A `plugin.install` in another session writes the store before this reads it. + let _held = crate::cmd::plugin::hold_plugin_changes(); let grants = self.counted_grants(&dir); let limits = vectorcraft_plugins::Limits::default(); let mut left = MAX_PLUGIN_STORE; @@ -389,9 +453,11 @@ impl Session { match grants.get(&m.id).filter(|g| grant_covers(g, &plugin)) { Some(g) => { asks_nothing.remove(&m.id); - vectorcraft_plugins::registry::grant(g.clone()); + vectorcraft_plugins::registry::grant(GrantToken::from_engine_grants_file(g.clone())); vectorcraft_plugins::registry::set_storage(&m.id, plugin_storage(Some(&dir), &m.id)); - vectorcraft_plugins::registry::install(plugin.with_source(path.display().to_string())); + if let Err(e) = vectorcraft_plugins::registry::install(plugin.with_source(path.display().to_string())) { + log::warn!("skipping the stored plug-in {}: {e}", path.display()); + } } None => { log::warn!("skipping the stored plug-in {}: the user hasn't granted this module the permissions it lists", path.display()) @@ -401,7 +467,9 @@ impl Session { Ok(plugin) => { asks_nothing.insert(plugin.id().to_string()); vectorcraft_plugins::registry::set_storage(plugin.id(), plugin_storage(Some(&dir), plugin.id())); - vectorcraft_plugins::registry::install(plugin.with_source(path.display().to_string())); + if let Err(e) = vectorcraft_plugins::registry::install(plugin.with_source(path.display().to_string())) { + log::warn!("skipping the stored plug-in {}: {e}", path.display()); + } } Err(e) => log::warn!("skipping the stored plug-in {}: {e}", path.display()), } @@ -413,8 +481,11 @@ impl Session { Ok(file) => file.names(id), Err(e) => e.unread, }; - if named && !self.store_grant(id, None) && self.holds_plugin_grant(id) { - self.ignore_stored_grant(id); + if named { + let writes = self.grant_writes(); + if !self.store_grant(id, None) && self.holds_plugin_grant(id) { + self.ignore_stored_grant(id, writes); + } } } } @@ -475,12 +546,37 @@ impl Session { } } - /// The grants kept in the plug-in store `dir` ([`stored_grants`]) without those this session - /// doesn't count ([`Session::ignore_stored_grant`]). + /// [`Session::plugin_approver`] for a folder load: a module the store's grants approve gets + /// that grant recorded for the process too, since the registry installs only a module that a + /// recorded grant covers ([`vectorcraft_plugins::registry::install`]). + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn plugin_folder_approver(&self) -> impl Fn(&vectorcraft_plugins::Plugin) -> bool + use<> { + let grants = self.plugin_dir.as_deref().map(|dir| self.counted_grants(dir)); + move |plugin| { + let m = plugin.manifest(); + match &grants { + Some(grants) if m.asks_permissions() => match grants.get(&m.id).filter(|g| grant_covers(g, plugin)) { + Some(g) => { + vectorcraft_plugins::registry::grant(GrantToken::from_engine_grants_file(g.clone())); + true + } + None => false, + }, + _ => vectorcraft_plugins::registry::approved(plugin), + } + } + } + + /// The grants kept in the plug-in store `dir` ([`stored_grants`]) without those the process + /// doesn't count for that folder ([`Session::ignore_stored_grant`]). The folder's key is worked + /// out on each call, so a path whose link now leads elsewhere is matched with where it leads. fn counted_grants(&self, dir: &Path) -> BTreeMap<String, vectorcraft_plugins::permissions::Grant> { - let ignored = self.ignored_plugin_grants.lock().unwrap_or_else(|e| e.into_inner()); + let key = plugin_store_key(dir); let mut grants = stored_grants(dir); - grants.retain(|id, _| !ignored.contains(id)); + let shared = IGNORED_PLUGIN_GRANTS.lock().unwrap_or_else(|e| e.into_inner()); + for (_, id) in shared.ignored.range((key.clone(), String::new())..).take_while(|(folder, _)| *folder == key) { + grants.remove(id); + } grants } @@ -504,16 +600,21 @@ impl Session { /// Return the store's module for the plug-in `id` to `previous`, the bytes it held before a /// write ([`Session::stored_plugin_bytes`]): with `None`, the file is removed. → whether the - /// store now holds `previous`. + /// write reported success; a write that reports a failure may still have put `previous` back. pub(crate) fn put_back_plugin(&self, id: &str, previous: Option<&[u8]>) -> bool { #[cfg(test)] if PUT_BACK_FAILS.get() { return false; } - match previous { + let back = match previous { Some(bytes) => self.store_plugin(id, bytes), None => self.unstore_plugin(id), + }; + #[cfg(test)] + if PUT_BACK_FAILS_AFTER_WRITE.get() { + return false; } + back } /// The file the plug-in `id` is stored in, spelled as [`Session::load_stored_plugins`] names it @@ -528,20 +629,53 @@ impl Session { /// be read or doesn't hold a list is left as it is, with a log record, and nothing is recorded; /// so is one whose new content would be larger than `MAX_GRANTS_FILE`. → whether the store now /// holds what was asked (`false` without a folder). When it does, the grant kept for `id` counts - /// again ([`Session::ignore_stored_grant`]). + /// again, for every session in the process attached to the store ([`Session::ignore_stored_grant`]). pub(crate) fn store_grant(&self, id: &str, grant: Option<vectorcraft_plugins::permissions::Grant>) -> bool { let done = self.write_grant(id, grant); - if done { - self.ignored_plugin_grants.lock().unwrap_or_else(|e| e.into_inner()).remove(id); + if done && let Some(key) = self.plugin_dir.as_deref().map(plugin_store_key) { + let mut shared = IGNORED_PLUGIN_GRANTS.lock().unwrap_or_else(|e| e.into_inner()); + let entry = (key, id.to_string()); + shared.ignored.remove(&entry); + shared.writes = shared.writes.saturating_add(1); + let writes = shared.writes; + shared.written.insert(entry, writes); + if shared.written.len() > MAX_GRANT_WRITES_KEPT + && let Some(oldest) = shared.written.iter().min_by_key(|(_, at)| **at).map(|(entry, _)| entry.clone()) + { + shared.written.remove(&oldest); + } } done } - /// Stop counting the store's grant for the plug-in `id` until [`Session::store_grant`] next - /// succeeds for it or another store is attached: for a grant that should be gone and could not - /// be removed, which would otherwise approve the bytes it covers. - pub(crate) fn ignore_stored_grant(&self, id: &str) { - self.ignored_plugin_grants.lock().unwrap_or_else(|e| e.into_inner()).insert(id.to_string()); + /// How many grant writes the sessions of the process have made ([`Session::store_grant`]). + /// Taken before a write that may fail, for [`Session::ignore_stored_grant`]. + pub(crate) fn grant_writes(&self) -> u64 { + IGNORED_PLUGIN_GRANTS.lock().unwrap_or_else(|e| e.into_inner()).writes + } + + /// How many grant writes the process keeps ([`IgnoredGrants::written`]). + #[cfg(test)] + pub(crate) fn grant_writes_kept() -> usize { + IGNORED_PLUGIN_GRANTS.lock().unwrap_or_else(|e| e.into_inner()).written.len() + } + + /// Stop counting the attached store's grant for the plug-in `id`, in every session in the + /// process attached to the same folder, until [`Session::store_grant`] next succeeds for it in + /// one of them: for a grant that should be gone and could not be removed, which would otherwise + /// approve the bytes it covers. `writes` is [`Session::grant_writes`] from before the failed + /// write: when a session has written the store's grants for `id` since, the file holds what that + /// write asked for, and the grant keeps counting. A write no longer among the latest + /// [`MAX_GRANT_WRITES_KEPT`] is not seen, and the grant stops counting. Another process on the + /// folder reads `grants.json` as it is. + pub(crate) fn ignore_stored_grant(&self, id: &str, writes: u64) { + if let Some(key) = self.plugin_dir.as_deref().map(plugin_store_key) { + let mut shared = IGNORED_PLUGIN_GRANTS.lock().unwrap_or_else(|e| e.into_inner()); + let entry = (key, id.to_string()); + if shared.written.get(&entry).is_none_or(|at| *at <= writes) { + shared.ignored.insert(entry); + } + } } fn write_grant(&self, id: &str, grant: Option<vectorcraft_plugins::permissions::Grant>) -> bool { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 2620a0fdbd..c260b42d90 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -9,6 +9,7 @@ pub(super) mod adjust; mod ai_open_path; mod appearance; mod areafit; +mod arrowheads; mod assets; mod assets_3d; mod attributes; @@ -20,6 +21,7 @@ mod brushlib; mod brushsym; mod build; mod cancel; +mod caret_kerning; mod charstroke; pub(super) mod clip; mod clipboard; @@ -42,8 +44,10 @@ mod containers; mod css; mod cut; mod dashalign; +mod dcs; mod distort; mod docsetup; +mod document_close; mod document_move; mod draw2; mod dynamic_symbols; @@ -133,6 +137,7 @@ mod placed_document; mod plugins; mod prefs; mod prefs_file; +mod prefs_roots; mod previewbounds; mod print; mod printadvanced; @@ -155,11 +160,13 @@ mod scalestrokes; mod script_console; mod script_dialogs; mod script_dollar; +mod script_engines; mod script_folder; mod script_include; mod script_io; mod script_run; mod scripts; +mod select_effects; mod select_ids_first; mod shaper; mod shapetools; @@ -170,6 +177,7 @@ mod smartguides; mod smooth_path; mod spelling; mod store; +mod stored_path; mod strokegeom; mod strokegradient; mod strokereach; @@ -202,6 +210,7 @@ mod typescale; mod typeundo; mod units; mod variables; +mod warp_images; mod webexport; mod widthpoints; mod widthprofiles; @@ -4025,6 +4034,38 @@ fn snap_to_pixel_rounds_drawing_and_moves() { assert_eq!((b.x0, b.y0), (17.0, 16.0)); } +/// Pixel Snapping Options (`view.snapToPixel.options`): with While Drawing off a rectangle drawn +/// with Snap to Pixel on keeps its fractional corners while a move still lands on whole pixels, and +/// with While Moving off a move keeps its fractional offset while drawing snaps again. +#[test] +fn pixel_snapping_options_choose_the_edits_snap_to_pixel_rounds() { + let mut s = session(); + let v = ViewInfo { snap_to_pixel: true, smart_guides: false, snap_to_point: false, ..Default::default() }; + let drag = |s: &mut Session, tool: &str, from: (f64, f64), to: (f64, f64)| { + s.select_tool(tool, v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, from.0, from.1), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, to.0, to.1), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, to.0, to.1), v).unwrap(); + }; + let bounds = |s: &Session, id| { + let b = s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap(); + (b.x0, b.y0, b.x1, b.y1) + }; + s.execute("view.snapToPixel.options", &json!({"drawing": false})).unwrap(); + drag(&mut s, "rectangle", (10.25, 10.5), (60.5, 40.25)); + let id = s.doc().unwrap().selection.objects[0]; + assert_eq!(bounds(&s, id), (10.25, 10.5, 60.5, 40.25), "drawing does not snap"); + drag(&mut s, "selection", (30.0, 30.0), (37.5, 34.75)); + assert_eq!(bounds(&s, id).0, 18.0, "moving still snaps the left edge"); + assert_eq!(bounds(&s, id).1, 15.0, "moving still snaps the top edge"); + s.execute("view.snapToPixel.options", &json!({"drawing": true, "moving": false})).unwrap(); + drag(&mut s, "selection", (40.0, 30.0), (45.25, 33.5)); + assert_eq!((bounds(&s, id).0, bounds(&s, id).1), (23.25, 18.5), "moving does not snap"); + drag(&mut s, "rectangle", (100.25, 100.5), (140.5, 130.75)); + let drawn = s.doc().unwrap().selection.objects[0]; + assert_eq!(bounds(&s, drawn), (100.0, 101.0, 141.0, 131.0), "drawing snaps again"); +} + #[test] fn shaper_turns_rough_strokes_into_live_shapes_and_scribbles_punch_fills() { let mut s = session(); @@ -4246,8 +4287,8 @@ fn given_targets_are_used_as_given_and_range_style_takes_the_selected_type() { /// #785: commands whose `ids` or `id` the shared check doesn't read (it reads `id` where it stands /// for `ids` of one) refuse one that isn't an object id. They don't act on the selection, the -/// current layer or a new object instead, and the document, the selection and the undo history -/// stay as they are. +/// current layer or a new object instead, and the document, the selection, the undo history, +/// isolation mode and the shown opacity mask stay as they are. #[test] fn malformed_ids_are_refused_by_commands_that_default_to_the_selection() { let mut s = session(); @@ -4295,17 +4336,19 @@ fn malformed_ids_are_refused_by_commands_that_default_to_the_selection() { if let Some(p) = p.as_object_mut() { p.insert(key.into(), bad.clone()); } - let (doc, selection, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().selection.clone(), s.doc().unwrap().history.undo.len()); + let st = s.doc().unwrap(); + let (doc, selection, undo, modes) = (st.doc.clone(), st.selection.clone(), st.history.undo.len(), (st.isolation, st.mask_view)); let r = s.execute(cmd, &p); let named = |e: &str| e.contains("object id") || e.contains("step reference") || e.contains(&format!("`{key}` must be")); let refused = r.as_ref().err().map(|e| e.to_string()).is_some_and(|e| named(&e)); - let same = s.doc().unwrap().doc == doc && s.doc().unwrap().selection == selection && s.doc().unwrap().history.undo.len() == undo; + let st = s.doc().unwrap(); + let same = st.doc == doc && st.selection == selection && st.history.undo.len() == undo && (st.isolation, st.mask_view) == modes; if !(refused && same) { wrong.push(format!("{cmd} {p}: {r:?}, document unchanged: {same}")); } if !same { let st = s.doc_mut().unwrap(); - (st.doc, st.selection) = (doc, selection); + (st.doc, st.selection, (st.isolation, st.mask_view)) = (doc, selection, modes); st.history.undo.truncate(undo); } } diff --git a/crates/engine/src/tests/appearance.rs b/crates/engine/src/tests/appearance.rs index 8d12c83719..53cbb42ca9 100644 --- a/crates/engine/src/tests/appearance.rs +++ b/crates/engine/src/tests/appearance.rs @@ -3,7 +3,7 @@ use serde_json::{Value, json}; use vectorcraft_color::{BlendMode, Color, GradientKind, Paint}; -use vectorcraft_doc::{AppearanceItem, FillLayer, Node}; +use vectorcraft_doc::{AppearanceItem, FillLayer, LineJoin, Node}; use crate::*; @@ -185,6 +185,48 @@ fn group_rows_are_the_groups_own_stack() { assert_eq!(fill_paint(&node(&s, b), 0).color().unwrap().to_hex(), "#00ff00"); } +/// #6739: `stroke.set` without an item on a group with a stroke row of its own edits that row; +/// its members, which have no stroke (as paths a PDF import brings in), are left alone instead of +/// each getting a black 1 pt stroke. Options alone never make a stroke visible: a row created for +/// a join has no paint, while a weight still gives the usual black stroke. +#[test] +fn stroke_options_on_a_group_with_its_own_stroke_edit_that_stroke() { + let mut s = session(); + let (a, b) = (rect(&mut s, 100.0), rect(&mut s, 250.0)); + for id in [a, b] { + run(&mut s, "appearance.removeItem", json!({"ids": [id.0], "index": 1})); + assert!(node(&s, id).appearance.stroke().is_none(), "the member has no stroke row"); + } + let g = NodeId(run(&mut s, "object.group", json!({"ids": [a.0, b.0]}))["id"].as_u64().unwrap()); + run(&mut s, "appearance.addStroke", json!({"ids": [g.0]})); + run(&mut s, "appearance.setItem", json!({"ids": [g.0], "index": 0, "color": "#ffffff", "weight": 2})); + let r = run(&mut s, "stroke.set", json!({"ids": [g.0], "join": "round"})); + assert_eq!(r["objects"], 1, "{r}"); + let gs = node(&s, g).appearance.stroke().unwrap().clone(); + assert_eq!((gs.join, gs.width, gs.paint.color().map(|c| c.to_hex())), (LineJoin::Round, 2.0, Some("#ffffff".to_string()))); + for id in [a, b] { + assert!(node(&s, id).appearance.stroke().is_none(), "a member keeps no stroke"); + } + // A group without a stroke of its own still reaches its members; for a join alone the row + // made on each has no paint, so nothing becomes visible. + let (c, d) = (rect(&mut s, 400.0), rect(&mut s, 550.0)); + for id in [c, d] { + run(&mut s, "appearance.removeItem", json!({"ids": [id.0], "index": 1})); + } + let h = NodeId(run(&mut s, "object.group", json!({"ids": [c.0, d.0]}))["id"].as_u64().unwrap()); + run(&mut s, "stroke.set", json!({"ids": [h.0], "join": "bevel"})); + for id in [c, d] { + let st = node(&s, id).appearance.stroke().cloned().expect("a stroke row for the join"); + assert_eq!((st.paint, st.join), (Paint::None, LineJoin::Bevel), "no paint for a join alone"); + } + // A weight is a visible stroke: an object without one gets the black stroke, as before. + let e = rect(&mut s, 700.0); + run(&mut s, "appearance.removeItem", json!({"ids": [e.0], "index": 1})); + run(&mut s, "stroke.set", json!({"ids": [e.0], "weight": 3})); + let st = node(&s, e).appearance.stroke().cloned().unwrap(); + assert_eq!((st.paint, st.width), (Paint::solid(Color::BLACK), 3.0)); +} + #[test] fn text_items_take_item_paint() { let mut s = session(); diff --git a/crates/engine/src/tests/areafit.rs b/crates/engine/src/tests/areafit.rs index b6d6883430..7d8f759cf5 100644 --- a/crates/engine/src/tests/areafit.rs +++ b/crates/engine/src/tests/areafit.rs @@ -485,7 +485,7 @@ fn making_and_restyling_type_reports_its_overflow() { } /// The formats whose exports draw type. -const DRAWING_FORMATS: [&str; 8] = ["pdf", "eps", "svg", "png", "jpg", "tiff", "emf", "wmf"]; +const DRAWING_FORMATS: [&str; 9] = ["pdf", "eps", "svg", "png", "jpg", "tiff", "emf", "wmf", "hpgl"]; /// The warnings of `document.export {format, …options}` about type that doesn't fit its frame. fn export_overflow(s: &mut Session, format: &str, options: Value) -> Vec<String> { diff --git a/crates/engine/src/tests/arrowheads.rs b/crates/engine/src/tests/arrowheads.rs new file mode 100644 index 0000000000..0cdc3312ff --- /dev/null +++ b/crates/engine/src/tests/arrowheads.rs @@ -0,0 +1,446 @@ +//! Custom arrowheads (`cmd/arrowheads.rs`): heads read from the arrowheads file's symbols, listed, +//! set with `stroke.set`, reloaded when the file is saved, and kept with the documents that use +//! them. + +use std::sync::Arc; + +use serde_json::json; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Arrowhead, Document, Node, StrokeLayer, Symbol, SymbolRegistration}; +use vectorcraft_geom::{PathData, Point, SubPath}; + +use crate::cmd::arrowheads::{self, heads_of}; +use crate::*; + +fn polygon(pts: &[(f64, f64)], ap: Appearance) -> Node { + let pts: Vec<Point> = pts.iter().map(|&(x, y)| Point::new(x, y)).collect(); + Node::path(NodeId(0), PathData::single(SubPath::polyline(&pts, true)), ap) +} + +fn add_symbol(d: &mut Document, name: &str, art: Node) { + let art = d.reid(&art); + d.symbols.push(Symbol { name: name.into(), art: Arc::new(art), dynamic: false }); +} + +fn filled() -> Appearance { + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 1.0) +} + +/// A folder of its own for test `name`, emptied. +fn folder(name: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("vectorcraft-arrowheads-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +fn session_with_line() -> (Session, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let r = s.execute("shape.line", &json!({"x1": 10, "y1": 100, "x2": 150, "y2": 100})).unwrap(); + (s, NodeId(r["id"].as_u64().unwrap())) +} + +fn stroke(s: &Session, id: NodeId) -> StrokeLayer { + s.doc().unwrap().doc.node(id).unwrap().appearance.stroke().unwrap().clone() +} + +#[test] +fn each_symbol_is_a_head_pointing_right_with_its_tip_at_the_registration_point() { + let mut d = Document::new(100.0, 100.0); + // 20 high, so a unit is 5 pt: tip on the right edge's middle. + add_symbol(&mut d, "Wedge", polygon(&[(0.0, -10.0), (20.0, 0.0), (0.0, 10.0)], filled())); + d.set_symbol_registration("Wedge", SymbolRegistration(5)); + // A stroke alone paints its outline: a 10 × 4 band, tip at its centre (the default). + let mut line = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 4.0); + line.stroke_mut().unwrap().cap = vectorcraft_doc::LineCap::Butt; + let band = Node::path(NodeId(0), PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0)], false)), line); + add_symbol(&mut d, "Band", band); + // Neither filled nor stroked: no head. + add_symbol(&mut d, "Ghost", polygon(&[(0.0, 0.0), (5.0, 0.0), (5.0, 5.0)], Appearance::default())); + // Far longer than wide. + add_symbol(&mut d, "Needle", polygon(&[(0.0, 0.0), (1000.0, 0.5), (0.0, 1.0)], filled())); + // A fill at 0 % opacity paints nothing. + let mut clear = filled(); + if let Some(vectorcraft_doc::AppearanceItem::Fill(f)) = clear.items.first_mut() { + f.opacity = 0.0; + } + add_symbol(&mut d, "Clear", polygon(&[(0.0, 0.0), (5.0, 0.0), (5.0, 5.0)], clear)); + // More anchors than a symbol's art may have: skipped before its shapes are united. + let dense: Vec<(f64, f64)> = (0..=arrowheads::MAX_ART_ANCHORS).map(|i| ((i as f64).cos(), (i as f64).sin())).collect(); + add_symbol(&mut d, "Dense", polygon(&dense, filled())); + // A 20 × 4 bar clipped to a 4 × 4 square: a 4 × 4 head. + let mut mask = polygon(&[(0.0, 0.0), (4.0, 0.0), (4.0, 4.0), (0.0, 4.0)], Appearance::default()); + if let NodeKind::Path { clipping, .. } = &mut mask.kind { + *clipping = true; + } + let bar = polygon(&[(0.0, 0.0), (20.0, 0.0), (20.0, 4.0), (0.0, 4.0)], filled()); + add_symbol(&mut d, "Clipped", Node::new(NodeId(0), NodeKind::Group { children: vec![Arc::new(mask), Arc::new(bar)], clip: true })); + // An 8 × 4 bar grown by 2 pt on every side (Offset Path): 12 × 8, so 6 units long. + let mut grown = filled(); + grown.effects.push(vectorcraft_doc::Effect { id: "path.offsetPath".into(), params: json!({"offset": 2}), visible: true }); + add_symbol(&mut d, "Grown", polygon(&[(0.0, 0.0), (8.0, 0.0), (8.0, 4.0), (0.0, 4.0)], grown)); + // The same effect on the fill alone. + let mut fill_grown = filled(); + fill_grown.items[0].effects_mut().push(vectorcraft_doc::Effect { id: "path.offsetPath".into(), params: json!({"offset": 2}), visible: true }); + add_symbol(&mut d, "Fill Grown", polygon(&[(0.0, 0.0), (8.0, 0.0), (8.0, 4.0), (0.0, 4.0)], fill_grown)); + // And on a group holding the bar. + let mut group = Node::group(NodeId(0), vec![Arc::new(polygon(&[(0.0, 0.0), (8.0, 0.0), (8.0, 4.0), (0.0, 4.0)], filled()))]); + group.appearance.effects.push(vectorcraft_doc::Effect { id: "path.offsetPath".into(), params: json!({"offset": 2}), visible: true }); + add_symbol(&mut d, "Group Grown", group); + // A clipping path stroked 2 pt: its stroke paints unclipped and does not widen the clip. + let mut frame = polygon(&[(0.0, 0.0), (4.0, 0.0), (4.0, 4.0), (0.0, 4.0)], Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 2.0)); + if let NodeKind::Path { clipping, .. } = &mut frame.kind { + *clipping = true; + } + let bar = polygon(&[(0.0, 0.0), (20.0, 0.0), (20.0, 4.0), (0.0, 4.0)], filled()); + add_symbol(&mut d, "Framed", Node::new(NodeId(0), NodeKind::Group { children: vec![Arc::new(frame), Arc::new(bar)], clip: true })); + // A group's own fill paints its unpainted 8 × 4 member. + let mut painted_group = Node::group(NodeId(0), vec![Arc::new(polygon(&[(0.0, 0.0), (8.0, 0.0), (8.0, 4.0), (0.0, 4.0)], Appearance::default()))]); + painted_group.appearance = filled().into(); + add_symbol(&mut d, "Group Fill", painted_group); + // A 10 × 4 band stroked with a gradient along it. + let gradient = Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(vectorcraft_color::Gradient::default()))); + let mut along = Appearance::basic(Paint::None, gradient, 4.0); + if let Some(st) = along.stroke_mut() { + (st.cap, st.gradient_mode) = (vectorcraft_doc::LineCap::Butt, vectorcraft_doc::StrokeGradientMode::Along); + } + let band = Node::path(NodeId(0), PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0)], false)), along); + add_symbol(&mut d, "Gradient Band", band); + // An 8 × 4 mesh of two patches whose right one is fully transparent: a 4 × 4 head. + let corners = vectorcraft_doc::live::grid_points(vectorcraft_geom::Rect::new(0.0, 0.0, 8.0, 4.0), 1, 2); + let points = corners + .iter() + .map(|&p| vectorcraft_doc::MeshPoint { p, color: Color::BLACK, opacity: if p.x > 1.0 { 0.0 } else { 1.0 }, handles: Default::default() }) + .collect(); + let mesh = vectorcraft_doc::GradientMesh { rows: 1, cols: 2, points }; + add_symbol(&mut d, "Half Mesh", Node::new(NodeId(0), NodeKind::Mesh(mesh))); + // An effect on the file's layer is not part of any symbol. + Arc::make_mut(&mut d.layers[0]).appearance.effects.push(vectorcraft_doc::Effect { + id: "path.offsetPath".into(), + params: json!({"offset": 5}), + visible: true, + }); + let read = heads_of(&d); + let names: Vec<&str> = read.heads.iter().map(|h| h.name.as_str()).collect(); + assert_eq!(names, ["Wedge", "Band", "Clipped", "Grown", "Fill Grown", "Group Grown", "Framed", "Group Fill", "Gradient Band", "Half Mesh"]); + let b = read.heads[9].path.bounds().unwrap(); + assert!((b.width() - 4.0).abs() < 1e-3 && (b.height() - 4.0).abs() < 1e-3, "the mesh's painted patch: {b:?}"); + let b = read.heads[7].path.bounds().unwrap(); + assert!((b.width() - 8.0).abs() < 1e-3 && (b.height() - 4.0).abs() < 1e-3, "the group's fill: {b:?}"); + let (g, plain) = (read.heads[8].path.bounds().unwrap(), read.heads[1].path.bounds().unwrap()); + let near = |a: f64, b: f64| (a - b).abs() < 1e-3; + assert!(near(g.x0, plain.x0) && near(g.x1, plain.x1) && near(g.y0, plain.y0) && near(g.y1, plain.y1), "the gradient stroke's outline: {g:?}"); + let framed = read.heads[6].path.to_bezpath(); + let b = vectorcraft_geom::Shape::bounding_box(&framed); + assert!((b.width() - 4.0).abs() < 1e-3 && (b.height() - 4.0).abs() < 1e-3, "6 × 6 with the stroke: {b:?}"); + assert_ne!(vectorcraft_geom::Shape::winding(&framed, Point::new(0.1, 0.1)), 0, "the clipped bar fills the middle"); + for h in &read.heads[3..6] { + let b = h.path.bounds().unwrap(); + assert!((b.width() - 6.0).abs() < 1e-3 && (b.height() - 4.0).abs() < 1e-3, "{}: the effect's outline: {b:?}", h.name); + } + let skipped: Vec<&str> = read.skipped.iter().map(|(n, _)| n.as_str()).collect(); + assert_eq!(skipped, ["Ghost", "Needle", "Clear", "Dense"], "{:?}", read.skipped); + let b = read.heads[2].path.bounds().unwrap(); + assert!((b.width() - 4.0).abs() < 1e-3 && (b.height() - 4.0).abs() < 1e-3, "clipped to the square: {b:?}"); + let b = read.heads[0].path.bounds().unwrap(); + assert!(b.x0.abs() < 1e-6 && (b.x1 - 4.0).abs() < 1e-6 && (b.y0 + 2.0).abs() < 1e-6 && (b.y1 - 2.0).abs() < 1e-6, "{b:?}"); + assert!((read.heads[0].reach() - 4.0f64.hypot(2.0)).abs() < 1e-6); + let b = read.heads[1].path.bounds().unwrap(); + assert!((b.x0 + 5.0).abs() < 1e-3 && (b.x1 - 5.0).abs() < 1e-3 && (b.y0 + 2.0).abs() < 1e-3 && (b.y1 - 2.0).abs() < 1e-3, "{b:?}"); +} + +#[test] +fn the_arrowheads_file_is_made_opened_and_reloaded_when_saved() { + let dir = folder("edit"); + let file = dir.join(arrowheads::FILE_NAME).to_string_lossy().to_string(); + let (mut s, id) = session_with_line(); + s.attach_arrowheads_file(file.clone()); + let list = s.execute("stroke.arrowheads.list", &json!({})).unwrap(); + assert_eq!((list["arrowheads"].as_array().unwrap().len(), list["file"].as_str()), (0, Some(file.as_str()))); + assert!(s.execute("stroke.set", &json!({"endArrow": {"custom": "Example Arrowhead"}})).is_err(), "no such head yet"); + let line_doc = s.doc().unwrap().uid; + let r = s.execute("stroke.arrowheads.edit", &json!({})).unwrap(); + assert_eq!(r["created"], true); + assert_eq!(s.doc().unwrap().path.as_deref(), Some(file.as_str()), "the file is the active document"); + let list = s.execute("stroke.arrowheads.list", &json!({})).unwrap(); + assert_eq!(list["arrowheads"][0]["name"], "Example Arrowhead"); + // A second head drawn in the file is listed once the file is saved. + let st = s.doc_mut().unwrap(); + let d = Arc::make_mut(&mut st.doc); + add_symbol(d, "Square", polygon(&[(0.0, 0.0), (4.0, 0.0), (4.0, 4.0), (0.0, 4.0)], filled())); + assert_eq!(s.execute("stroke.arrowheads.list", &json!({})).unwrap()["arrowheads"].as_array().unwrap().len(), 1); + s.execute("document.save", &json!({})).unwrap(); + let list = s.execute("stroke.arrowheads.list", &json!({})).unwrap(); + let names: Vec<&str> = list["arrowheads"].as_array().unwrap().iter().filter_map(|h| h["name"].as_str()).collect(); + assert_eq!(names, ["Example Arrowhead", "Square"]); + // Editing again from the line's document brings the open file to the front, without making + // it anew or opening it twice. + s.execute("document.activate", &json!({"index": 0})).unwrap(); + assert_eq!(s.doc().unwrap().uid, line_doc); + assert_eq!(s.execute("stroke.arrowheads.edit", &json!({})).unwrap()["created"], false); + assert_eq!((s.documents().len(), s.doc().unwrap().path.as_deref()), (2, Some(file.as_str()))); + // The line takes the head with its art. + s.execute("document.activate", &json!({"index": 0})).unwrap(); + s.execute("stroke.set", &json!({"ids": [id.0], "endArrow": {"custom": "Square"}})).unwrap(); + let Some(Arrowhead::Custom(c)) = stroke(&s, id).end_arrow else { panic!("a custom head") }; + assert_eq!(c.name, "Square"); + assert!(s.execute("stroke.set", &json!({"endArrow": {"custom": 3}})).is_err()); + assert!(s.execute("stroke.set", &json!({"endArrow": {"custom": "Circle"}})).is_err()); + // A head given with its art is refused when the art could not be drawn. + let mut far = serde_json::to_value(Arrowhead::Custom(c.clone())).unwrap(); + far["Custom"]["path"] = serde_json::to_value(PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(1e6, 1.0)], true))).unwrap(); + assert!(s.execute("stroke.set", &json!({"ids": [id.0], "endArrow": far})).is_err()); + let mut empty = serde_json::to_value(Arrowhead::Custom(c)).unwrap(); + empty["Custom"]["path"] = json!({"subpaths": []}); + assert!(s.execute("stroke.set", &json!({"ids": [id.0], "endArrow": empty})).is_err()); + // One anchor, or anchors on one line, fill nothing. + for pts in [vec![Point::new(1.0, 1.0)], vec![Point::new(0.0, 0.0), Point::new(2.0, 0.0), Point::new(4.0, 0.0)]] { + let mut flat = + serde_json::to_value(Arrowhead::Custom(Arc::new(vectorcraft_doc::CustomArrowhead::new("Flat".into(), PathData::default())))).unwrap(); + flat["Custom"]["path"] = serde_json::to_value(PathData::single(SubPath::polyline(&pts, false))).unwrap(); + assert!(s.execute("stroke.set", &json!({"ids": [id.0], "endArrow": flat})).is_err(), "{pts:?}"); + } + // A lone anchor draws no segment, whatever its handles. + let mut lone = vectorcraft_geom::Anchor::corner(Point::new(1.0, 0.0)); + (lone.h_in, lone.h_out) = (Point::new(0.0, 1.0), Point::new(2.0, -1.0)); + let mut handles = + serde_json::to_value(Arrowhead::Custom(Arc::new(vectorcraft_doc::CustomArrowhead::new("Lone".into(), PathData::default())))).unwrap(); + handles["Custom"]["path"] = serde_json::to_value(PathData::single(SubPath::new(vec![lone], true))).unwrap(); + assert!(s.execute("stroke.set", &json!({"ids": [id.0], "endArrow": handles.clone()})).is_err(), "a lone anchor"); + // Two equal squares winding opposite ways cancel out. + let sq = [Point::new(0.0, -1.0), Point::new(2.0, -1.0), Point::new(2.0, 1.0), Point::new(0.0, 1.0)]; + let back: Vec<Point> = sq.iter().rev().copied().collect(); + let cancel = PathData::new(vec![SubPath::polyline(&sq, true), SubPath::polyline(&back, true)]); + handles["Custom"]["path"] = serde_json::to_value(cancel).unwrap(); + assert!(s.execute("stroke.set", &json!({"ids": [id.0], "endArrow": handles})).is_err(), "opposite squares"); + // A bow tie's lobes wind opposite ways, so its signed area is 0, and it still fills both. + let tie = [Point::new(0.0, -1.0), Point::new(2.0, 1.0), Point::new(2.0, -1.0), Point::new(0.0, 1.0)]; + let mut bow = + serde_json::to_value(Arrowhead::Custom(Arc::new(vectorcraft_doc::CustomArrowhead::new("Bow".into(), PathData::default())))).unwrap(); + bow["Custom"]["path"] = serde_json::to_value(PathData::single(SubPath::polyline(&tie, true))).unwrap(); + assert!(matches!(stroke(&s, id).end_arrow, Some(Arrowhead::Custom(h)) if h.name == "Square"), "the head stays as it was"); + s.execute("stroke.set", &json!({"ids": [id.0], "endArrow": bow.clone()})).unwrap(); + assert!(matches!(stroke(&s, id).end_arrow, Some(Arrowhead::Custom(h)) if h.name == "Bow")); + // So does a very thin bar. + let bar = [Point::new(0.0, 0.0), Point::new(4.0, 0.0), Point::new(4.0, 0.001), Point::new(0.0, 0.001)]; + bow["Custom"]["path"] = serde_json::to_value(PathData::single(SubPath::polyline(&bar, true))).unwrap(); + s.execute("stroke.set", &json!({"ids": [id.0], "endArrow": bow})).unwrap(); + let Some(Arrowhead::Custom(h)) = stroke(&s, id).end_arrow else { panic!("a custom head") }; + assert_eq!(h.path.anchor_count(), 4, "the thin bar"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_document_keeps_its_custom_heads_without_the_arrowheads_file() { + let (mut s, id) = session_with_line(); + let mut d = Document::new(100.0, 100.0); + add_symbol(&mut d, "Wedge", polygon(&[(0.0, -10.0), (20.0, 0.0), (0.0, 10.0)], filled())); + let head = Arrowhead::Custom(Arc::new(heads_of(&d).heads.remove(0))); + // As document.inspect reports it, so it reads back unchanged. + s.execute("stroke.set", &json!({"startArrow": head, "endArrow": "Triangle"})).unwrap(); + assert_eq!(stroke(&s, id).start_arrow, Some(head.clone())); + let inspect = s.execute("document.inspect", &json!({})).unwrap().to_string(); + assert!(inspect.contains("\"Wedge\""), "inspect names the head"); + let ink = |s: &Session| { + vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 200, 200, vectorcraft_geom::Affine::IDENTITY, &Default::default()) + }; + let with_head = ink(&s); + // Saved and opened in a session that has no arrowheads file: the head is drawn the same. + let saved = s.execute("document.export", &json!({"format": "vectorcraft"})).unwrap()["dataBase64"].clone(); + let mut o = Session::new(); + o.execute("document.open", &json!({"name": "a.vectorcraft", "dataBase64": saved})).unwrap(); + assert_eq!(stroke(&o, id).start_arrow, Some(head)); + assert_eq!(ink(&o).pixels, with_head.pixels); + // SVG and PDF write it as they write the built-in heads. + let svg = |s: &mut Session| s.execute("document.export", &json!({"format": "svg"})).unwrap()["dataBase64"].as_str().unwrap().len(); + let headed = svg(&mut o); + o.execute("stroke.set", &json!({"ids": [id.0], "startArrow": null})).unwrap(); + assert!(headed > svg(&mut o), "the head is in the SVG"); + // Undo puts it back. + o.execute("edit.undo", &json!({})).unwrap(); + assert!(matches!(stroke(&o, id).start_arrow, Some(Arrowhead::Custom(_)))); +} + +#[test] +fn an_unreadable_arrowheads_file_lists_no_heads_and_says_why() { + let dir = folder("bad"); + let file = dir.join(arrowheads::FILE_NAME); + std::fs::write(&file, b"not a drawing").unwrap(); + let mut s = Session::new(); + s.attach_arrowheads_file(file.to_string_lossy().to_string()); + let list = s.execute("stroke.arrowheads.list", &json!({})).unwrap(); + assert!(list["arrowheads"].as_array().unwrap().is_empty()); + assert!(list["error"].is_string(), "{list}"); + assert!(s.execute("stroke.arrowheads.reload", &json!({})).is_err()); + // A folder in its place is not read either. + std::fs::remove_file(&file).unwrap(); + std::fs::create_dir(&file).unwrap(); + assert!(s.execute("stroke.arrowheads.reload", &json!({})).is_err()); + let _ = std::fs::remove_dir_all(&dir); + // Without a file (the web, runs without preferences) there is nothing to edit. + let mut bare = Session::new(); + assert!(bare.execute("stroke.arrowheads.edit", &json!({})).is_err()); + assert_eq!(bare.execute("stroke.arrowheads.list", &json!({})).unwrap()["file"], serde_json::Value::Null); +} + +/// Automation roots that grant reading `read` alone. +fn read_roots(read: &[&std::path::Path]) -> Arc<crate::file_access::AutomationRoots> { + crate::file_access::AutomationRoots::new(read, &[]).unwrap().unwrap() +} + +#[test] +fn an_agent_outside_the_arrowheads_files_folder_sees_its_file_name_alone_and_cannot_reload_it() { + let dir = folder("roots-list"); + let (prefs, other) = (dir.join("prefs"), dir.join("other")); + std::fs::create_dir_all(&prefs).unwrap(); + std::fs::create_dir_all(&other).unwrap(); + let file = prefs.join(arrowheads::FILE_NAME); + std::fs::write(&file, b"not a drawing").unwrap(); + let (file, prefs_text) = (file.to_string_lossy().to_string(), prefs.to_string_lossy().to_string()); + let mut s = Session::new(); + s.attach_arrowheads_file(file.clone()); + let (outside, inside) = (read_roots(&[&other]), read_roots(&[&prefs])); + let list = crate::file_access::confine(Some(&outside), || s.execute("stroke.arrowheads.list", &json!({}))).unwrap(); + assert_eq!(list["file"], serde_json::Value::Null, "{list}"); + let error = list["error"].as_str().unwrap(); + assert!(error.starts_with(arrowheads::FILE_NAME) && !error.contains(&prefs_text), "{error}"); + let list = crate::file_access::confine(Some(&inside), || s.execute("stroke.arrowheads.list", &json!({}))).unwrap(); + assert_eq!(list["file"].as_str(), Some(file.as_str())); + assert!(list["error"].as_str().unwrap().starts_with(&file), "{list}"); + // A good file now: an agent outside the folder cannot have it read. + std::fs::write(&file, vectorcraft_format::save_file(&arrowheads::starter())).unwrap(); + let e = crate::file_access::confine(Some(&outside), || s.execute("stroke.arrowheads.reload", &json!({}))).unwrap_err().to_string(); + assert!(e.contains("outside the read root") && e.ends_with(arrowheads::FILE_NAME) && !e.contains(&prefs_text), "{e}"); + let list = s.execute("stroke.arrowheads.list", &json!({})).unwrap(); + assert!(list["arrowheads"].as_array().unwrap().is_empty() && list["error"].is_string(), "not read again: {list}"); + let r = crate::file_access::confine(Some(&inside), || s.execute("stroke.arrowheads.reload", &json!({}))).unwrap(); + assert_eq!(r["count"], 1); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn an_agent_edits_the_arrowheads_file_only_inside_its_read_roots() { + let dir = folder("roots-edit"); + let (prefs, other) = (dir.join("prefs"), dir.join("other")); + std::fs::create_dir_all(&other).unwrap(); + let file = prefs.join(arrowheads::FILE_NAME).to_string_lossy().to_string(); + let prefs_text = prefs.to_string_lossy().to_string(); + let (mut s, _) = session_with_line(); + s.attach_arrowheads_file(file.clone()); + let line_doc = s.doc().unwrap().uid; + let outside = read_roots(&[&other]); + let edit = |s: &mut Session, roots: &Arc<crate::file_access::AutomationRoots>| { + crate::file_access::confine(Some(roots), || s.execute("stroke.arrowheads.edit", &json!({}))) + }; + // Refused before the folder or the file is made, or anything is opened. + let e = edit(&mut s, &outside).unwrap_err().to_string(); + assert!(e.ends_with(arrowheads::FILE_NAME) && !e.contains(&prefs_text), "{e}"); + assert!(!prefs.exists(), "no folder made"); + assert_eq!((s.documents().len(), s.doc().unwrap().uid), (1, line_doc)); + // From the Stroke panel menu (no roots), the file is made and opened. + assert_eq!(s.execute("stroke.arrowheads.edit", &json!({})).unwrap()["created"], true); + assert_eq!(s.documents().len(), 2); + // Open already: still not brought to the front for an agent outside the folder. + s.execute("document.activate", &json!({"index": 0})).unwrap(); + assert!(edit(&mut s, &outside).is_err()); + assert_eq!((s.documents().len(), s.doc().unwrap().uid), (2, line_doc)); + // Inside the read roots: opened under them, with its path. + let inside = read_roots(&[&prefs]); + let mut agent = Session::new(); + agent.attach_arrowheads_file(file.clone()); + let r = edit(&mut agent, &inside).unwrap(); + assert_eq!((r["path"].as_str(), &r["created"]), (Some(file.as_str()), &json!(false))); + let st = agent.doc().unwrap(); + assert_eq!(st.path.as_deref(), Some(file.as_str())); + assert!(st.opened_by.as_ref().is_some_and(|r| Arc::ptr_eq(r, &inside)), "opened under the agent's roots"); + // A missing file inside the roots is still made first. + let fresh = dir.join("fresh").join(arrowheads::FILE_NAME).to_string_lossy().to_string(); + let mut agent = Session::new(); + agent.attach_arrowheads_file(fresh.clone()); + let r = edit(&mut agent, &read_roots(&[&dir])).unwrap(); + assert_eq!(r["created"], true); + assert!(std::path::Path::new(&fresh).is_file()); + assert_eq!(agent.doc().unwrap().path.as_deref(), Some(fresh.as_str())); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn the_heads_listed_after_a_save_are_read_from_the_file_and_editing_keeps_it() { + let dir = folder("saved"); + let file = dir.join(arrowheads::FILE_NAME).to_string_lossy().to_string(); + let (mut s, _) = session_with_line(); + s.attach_arrowheads_file(file.clone()); + assert_eq!(s.execute("stroke.arrowheads.edit", &json!({})).unwrap()["created"], true); + // A speck that saving rounds to a point is a head only before the save. + let st = s.doc_mut().unwrap(); + add_symbol(Arc::make_mut(&mut st.doc), "Speck", polygon(&[(0.0, 0.0), (0.3, 0.1), (0.0, 0.2)], filled())); + assert!(heads_of(&s.doc().unwrap().doc).heads.iter().any(|h| h.name == "Speck"), "a head before rounding"); + s.execute("document.save", &json!({"precision": 0})).unwrap(); + let list = s.execute("stroke.arrowheads.list", &json!({})).unwrap(); + let names: Vec<&str> = list["arrowheads"].as_array().unwrap().iter().filter_map(|h| h["name"].as_str()).collect(); + assert_eq!(names, ["Example Arrowhead"]); + assert_eq!(list["skipped"][0]["name"], "Speck", "{list}"); + // Editing again leaves the file as it is. + let saved = std::fs::read(&file).unwrap(); + s.execute("document.activate", &json!({"index": 0})).unwrap(); + assert_eq!(s.execute("stroke.arrowheads.edit", &json!({})).unwrap()["created"], false); + assert_eq!(std::fs::read(&file).unwrap(), saved, "the file is left as it was"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn an_arrowheads_file_that_unpacks_past_the_size_limit_is_not_read() { + let dir = folder("unpacked"); + let file = dir.join(arrowheads::FILE_NAME); + let mut d = arrowheads::starter(); + d.title = "a".repeat(arrowheads::MAX_FILE_BYTES as usize); + let bytes = vectorcraft_format::save_with(&d, &vectorcraft_format::SaveOptions { compress: true, ..Default::default() }).unwrap(); + assert!((bytes.len() as u64) < arrowheads::MAX_FILE_BYTES / 16, "compressed small: {}", bytes.len()); + std::fs::write(&file, &bytes).unwrap(); + let mut s = Session::new(); + s.attach_arrowheads_file(file.to_string_lossy().to_string()); + let list = s.execute("stroke.arrowheads.list", &json!({})).unwrap(); + assert!(list["arrowheads"].as_array().unwrap().is_empty(), "{}", list["arrowheads"]); + assert!(list["error"].is_string(), "{}", list["error"]); + // The same head in a file of an ordinary size is read. + std::fs::write(&file, vectorcraft_format::save_file(&arrowheads::starter())).unwrap(); + assert_eq!(s.execute("stroke.arrowheads.reload", &json!({})).unwrap()["count"], 1); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_symbol_whose_shapes_cannot_be_combined_is_skipped() { + let wedge = || Arc::new(polygon(&[(0.0, -10.0), (20.0, 0.0), (0.0, 10.0)], filled())); + // Too far out for the shape operations to measure: the union would leave it out. + let far = || Arc::new(polygon(&[(0.0, 0.0), (1e200, 0.0), (0.0, 1e200)], filled())); + let mut d = Document::new(100.0, 100.0); + add_symbol(&mut d, "Wedge", (*wedge()).clone()); + add_symbol(&mut d, "Broken", Node::group(NodeId(0), vec![wedge(), far()])); + // The same as clipped art. + let mut mask = polygon(&[(0.0, -10.0), (20.0, -10.0), (20.0, 10.0), (0.0, 10.0)], Appearance::default()); + if let NodeKind::Path { clipping, .. } = &mut mask.kind { + *clipping = true; + } + add_symbol(&mut d, "Broken Clip", Node::new(NodeId(0), NodeKind::Group { children: vec![Arc::new(mask), wedge(), far()], clip: true })); + let read = heads_of(&d); + let names: Vec<&str> = read.heads.iter().map(|h| h.name.as_str()).collect(); + assert_eq!(names, ["Wedge"]); + let skipped: Vec<&str> = read.skipped.iter().map(|(n, _)| n.as_str()).collect(); + assert_eq!(skipped, ["Broken", "Broken Clip"], "{:?}", read.skipped); +} + +#[test] +fn a_group_used_as_the_clipping_path_adds_none_of_its_own_fills() { + // A group holding a filled 20 × 4 bar clips a filled 4 × 4 square: the group paints nothing as + // the clipping path, so the head is the square alone. + let bar = polygon(&[(0.0, 0.0), (20.0, 0.0), (20.0, 4.0), (0.0, 4.0)], filled()); + let mask = Node::group(NodeId(0), vec![Arc::new(bar)]); + let square = polygon(&[(0.0, 0.0), (4.0, 0.0), (4.0, 4.0), (0.0, 4.0)], filled()); + let mut d = Document::new(100.0, 100.0); + add_symbol(&mut d, "Group Clip", Node::new(NodeId(0), NodeKind::Group { children: vec![Arc::new(mask), Arc::new(square)], clip: true })); + let read = heads_of(&d); + assert_eq!(read.heads.len(), 1, "{:?}", read.skipped); + let b = read.heads[0].path.bounds().unwrap(); + assert!((b.width() - 4.0).abs() < 1e-3 && (b.height() - 4.0).abs() < 1e-3, "the square alone: {b:?}"); +} diff --git a/crates/engine/src/tests/attributes.rs b/crates/engine/src/tests/attributes.rs index 4dea459409..d3edf2615b 100644 --- a/crates/engine/src/tests/attributes.rs +++ b/crates/engine/src/tests/attributes.rs @@ -1,4 +1,5 @@ -//! Window → Attributes (`attributes.set`, `attributes.info`, `path.setFillRule`, `path.reverse`), +//! Window → Attributes (`attributes.set`, `attributes.info`, `path.setFillRule`, `path.reverse`, +//! and `select.byNote`, which selects objects by their note), //! the links SVG export writes for objects with a URL, and what objects keep for other software //! (their `data-*` attributes and their attributes in other applications' namespaces). @@ -216,6 +217,140 @@ fn object_data_is_set_saved_and_written_to_svg() { assert_eq!(back.node(a).unwrap().extras().attrs, s.doc().unwrap().doc.node(a).unwrap().extras().attrs); } +/// The selected objects after `select.byNote` with `p`, or its error. +fn by_note(s: &mut Session, p: Value) -> std::result::Result<Vec<u64>, String> { + s.execute("select.byNote", &p).map_err(|e| e.to_string())?; + Ok(s.doc().unwrap().selection.objects.iter().map(|id| id.0).collect()) +} + +fn note(s: &mut Session, id: NodeId, note: &str) { + run(s, "attributes.set", json!({"ids": [id.0], "note": note})); +} + +/// Select by Note finds a note anywhere and in any letter case by default, replaces the selection +/// with every object it finds, in paint order, and is not an undo step. Case Sensitive and Whole +/// Word narrow it; Reselect repeats it. +#[test] +fn select_by_note_matches_part_of_a_note_in_any_case_unless_asked() { + let mut s = session(); + let [a, b, c, d] = [0.0, 20.0, 40.0, 60.0].map(|x| rect(&mut s, x)); + note(&mut s, a, "Logo front"); + note(&mut s, b, "logo"); + note(&mut s, c, "Logotype"); + note(&mut s, d, "back"); + run(&mut s, "select.set", json!({"ids": [d.0]})); + let undo = s.doc().unwrap().history.undo.len(); + assert_eq!(by_note(&mut s, json!({"note": " LOGO "})), Ok(vec![a.0, b.0, c.0]), "outer spaces are left out"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step"); + assert_eq!(by_note(&mut s, json!({"note": "logo", "caseSensitive": true})), Ok(vec![b.0])); + assert_eq!(by_note(&mut s, json!({"note": "logo", "wholeWord": true})), Ok(vec![a.0, b.0])); + assert_eq!(by_note(&mut s, json!({"note": "Logo", "caseSensitive": true, "wholeWord": true})), Ok(vec![a.0])); + assert_eq!(by_note(&mut s, json!({"note": "o f"})), Ok(vec![a.0]), "spaces inside the note count"); + run(&mut s, "select.none", json!({})); + run(&mut s, "select.reselect", json!({})); + assert_eq!(s.doc().unwrap().selection.objects, [a]); +} + +/// Whole Word looks at every place the text occurs, also places that overlap. +#[test] +fn select_by_note_whole_word_matches_overlapping_places_and_other_scripts() { + let mut s = session(); + let a = rect(&mut s, 0.0); + let matches = |s: &mut Session, text: &str, p: Value| { + note(s, a, text); + by_note(s, p).is_ok() + }; + assert!(matches(&mut s, "a aa a a", json!({"note": "a a", "wholeWord": true}))); + assert!(!matches(&mut s, "aa_a", json!({"note": "a", "wholeWord": true}))); + assert!(matches(&mut s, "x-ray, x", json!({"note": "x", "wholeWord": true}))); + assert!(matches(&mut s, "ÉTIQUETTE", json!({"note": "étiquette"}))); + assert!(!matches(&mut s, "ÉTIQUETTE", json!({"note": "étiquette", "caseSensitive": true}))); + assert!(matches(&mut s, "标签 一", json!({"note": "一", "wholeWord": true}))); + assert!(!matches(&mut s, "", json!({"note": "a"}))); +} + +/// Letter case is compared one character at a time: a final Σ, whose lowercase is ς, matches Σ +/// and σ. Whole Word looks at the characters of the note itself, so a letter whose lowercase +/// takes two characters (İ) neither ends a word early nor matches half of itself. +#[test] +fn select_by_note_compares_letter_case_per_character() { + let mut s = session(); + let a = rect(&mut s, 0.0); + let matches = |s: &mut Session, text: &str, p: Value| { + note(s, a, text); + by_note(s, p).is_ok() + }; + assert!(matches(&mut s, "ΟΣ", json!({"note": "Σ"}))); + assert!(matches(&mut s, "ΟΣ", json!({"note": "σ"}))); + assert!(matches(&mut s, "ΟΣ", json!({"note": "ος", "wholeWord": true}))); + assert!(!matches(&mut s, "ΟΣ", json!({"note": "σ", "caseSensitive": true}))); + assert!(!matches(&mut s, "İx", json!({"note": "i", "wholeWord": true}))); + assert!(matches(&mut s, "İ x", json!({"note": "İ", "wholeWord": true}))); + assert!(!matches(&mut s, "İ x", json!({"note": "i", "wholeWord": true}))); +} + +/// Select by Note leaves out hidden and locked objects, selects a group whose note matches without +/// its members and a member whose note matches on its own, keeps to the isolated group, and leaves +/// the selection as it was when it finds nothing. Bad params are errors that change nothing. +#[test] +fn select_by_note_takes_only_objects_that_can_be_selected() { + let mut s = session(); + let [a, b, c, d, e] = [0.0, 10.0, 20.0, 30.0, 40.0].map(|x| rect(&mut s, x)); + for id in [a, b, c, d, e] { + note(&mut s, id, "tag"); + } + run(&mut s, "select.set", json!({"ids": [a.0]})); + run(&mut s, "object.hide", json!({})); + run(&mut s, "select.set", json!({"ids": [b.0]})); + run(&mut s, "object.lock", json!({})); + run(&mut s, "select.set", json!({"ids": [c.0, d.0]})); + let g = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap()); + note(&mut s, g, "tag group"); + assert_eq!(by_note(&mut s, json!({"note": "tag"})), Ok(vec![g.0, e.0]), "the group, not its members"); + note(&mut s, g, "box"); + assert_eq!(by_note(&mut s, json!({"note": "tag"})), Ok(vec![c.0, d.0, e.0])); + run(&mut s, "object.isolate", json!({"id": g.0})); + assert_eq!(by_note(&mut s, json!({"note": "tag"})), Ok(vec![c.0, d.0]), "inside the isolated group only"); + run(&mut s, "select.set", json!({"ids": [c.0]})); + let missing = by_note(&mut s, json!({"note": "nothing"})).unwrap_err(); + assert!(missing.contains("no object that can be selected has a note matching “nothing”"), "{missing}"); + assert_eq!(s.doc().unwrap().selection.objects, [c], "the selection stays"); + for bad in [ + json!({}), + json!({"note": " "}), + json!({"note": 5}), + json!({"note": "x".repeat(1025)}), + json!({"note": "tag", "caseSensitive": "yes"}), + json!({"note": "tag", "wholeWord": 1}), + ] { + assert!(s.execute("select.byNote", &bad).is_err(), "{bad}"); + assert_eq!(s.doc().unwrap().selection.objects, [c], "{bad}"); + } + assert!(by_note(&mut s, json!({"note": "x".repeat(1024)})).is_err_and(|e| e.contains("no object")), "1,024 bytes is allowed"); +} + +/// Under Lock Guides a guide whose note matches is not a match, and a search that finds only such +/// guides leaves the selection and the Puppet Warp pins on it as they were. +#[test] +fn select_by_note_leaves_locked_guides_out_before_changing_the_selection() { + let mut s = session(); + let a = rect(&mut s, 10.0); + let g = rect(&mut s, 50.0); + note(&mut s, g, "edge"); + run(&mut s, "select.set", json!({"ids": [g.0]})); + run(&mut s, "view.guides.make", json!({})); + run(&mut s, "view.guides.lock", json!({"locked": true})); + run(&mut s, "select.set", json!({"ids": [a.0]})); + run(&mut s, "object.puppetWarp", json!({"id": a.0, "rest": true, "pins": [[25, 25]], "moved": [[25, 25]]})); + run(&mut s, "select.set", json!({"ids": [a.0]})); + assert!(s.doc().unwrap().doc.puppet.is_some(), "a pin on the rectangle"); + let missing = by_note(&mut s, json!({"note": "edge"})).unwrap_err(); + assert!(missing.contains("no object that can be selected"), "{missing}"); + let st = s.doc().unwrap(); + assert_eq!(st.selection.objects, [a], "the selection stays"); + assert!(st.doc.puppet.is_some(), "the pins stay"); +} + /// An object's attributes in other applications' XML namespaces are its own, as its `data-*` /// attributes are: a pasted copy and a duplicate keep them, deleting the object takes them with /// it, and the native file and SVG export keep them. diff --git a/crates/engine/src/tests/bboxrotate.rs b/crates/engine/src/tests/bboxrotate.rs index 1893f8c186..8907b21cc0 100644 --- a/crates/engine/src/tests/bboxrotate.rs +++ b/crates/engine/src/tests/bboxrotate.rs @@ -104,6 +104,92 @@ fn handles_turn_with_the_object_and_scale_along_its_axes() { assert!(near(selection_box(&s).rect.width(), 100.0)); } +/// Presses, drags and lets go with the current tool along `pts`, holding `mods`. +fn drag_with(s: &mut Session, pts: &[Point], mods: Mods) { + let v = ViewInfo::default(); + let kinds = std::iter::once(PointerKind::Down).chain(std::iter::repeat_n(PointerKind::Drag, pts.len().saturating_sub(2))); + for (kind, p) in kinds.chain([PointerKind::Up]).zip(pts) { + s.pointer(&PointerEvent::new(kind, p.x, p.y).with_mods(mods), v).unwrap(); + } +} + +/// The anchors of path `id`, on the page. +fn anchors(s: &Session, id: NodeId) -> Vec<Point> { + s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().anchors().map(|(_, _, an)| an.p).collect() +} + +fn has_point(pts: &[Point], p: Point) -> bool { + pts.iter().any(|q| q.distance(p) < 1e-6) +} + +#[test] +fn free_transform_handles_turn_with_the_object_and_scale_along_its_axes() { + let mut s = session(); + let a = turned_rect(&mut s); + let b = selection_box(&s); + // The Right handle of the turned box, dragged 50 pt further out along the object's own x axis. + let right = b.to_doc() * Handle::Right.pos(b.rect); + let to = b.to_doc() * (Handle::Right.pos(b.rect) + vectorcraft_geom::Vec2::new(50.0, 0.0)); + let n = undo_len(&s); + s.select_tool("freeTransform", ViewInfo::default()).unwrap(); + drag_with(&mut s, &[right, to, to], Mods::default()); + assert_eq!(undo_len(&s), n + 1); + assert_eq!(s.doc().unwrap().history.undo.last().map(|e| e.label.as_str()), Some("Scale")); + // 150 × 50 along its own axes, still at exactly 45°, the left side where it was. + assert_eq!(angle(&s, a), b.angle); + let nb = selection_box(&s); + assert!(near(nb.rect.width(), 150.0) && near(nb.rect.height(), 50.0), "{nb:?}"); + let left = |b: &OrientedBox| b.to_doc() * Handle::Left.pos(b.rect); + assert!(left(&nb).distance(left(&b)) < 1e-6); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(near(selection_box(&s).rect.width(), 100.0)); +} + +#[test] +fn free_transform_shears_along_the_turned_side() { + let mut s = session(); + let a = turned_rect(&mut s); + let b = selection_box(&s); + let [tl, tr, br, bl] = b.corners(); + // Dragging the Top handle 20 pt along the object's own top side with Cmd held once the drag + // started (a Cmd press is the temporary Selection tool) slides that side along itself; the + // bottom side stays. + let top = b.to_doc() * Handle::Top.pos(b.rect); + let along = b.to_doc() * (Handle::Top.pos(b.rect) + vectorcraft_geom::Vec2::new(20.0, 0.0)); + let shift = along - top; + let v = ViewInfo::default(); + s.select_tool("freeTransform", v).unwrap(); + let cmd = Mods { cmd: true, ..Default::default() }; + for (kind, p, m) in [(PointerKind::Down, top, Mods::default()), (PointerKind::Drag, along, cmd), (PointerKind::Up, along, cmd)] { + s.pointer(&PointerEvent::new(kind, p.x, p.y).with_mods(m), v).unwrap(); + } + assert_eq!(s.doc().unwrap().history.undo.last().map(|e| e.label.as_str()), Some("Shear")); + let pts = anchors(&s, a); + for p in [tl + shift, tr + shift, br, bl] { + assert!(has_point(&pts, p), "{p:?} not in {pts:?}"); + } +} + +#[test] +fn free_transform_distort_starts_from_the_turned_box() { + let mut s = session(); + let a = turned_rect(&mut s); + let b = selection_box(&s); + let [tl, tr, br, bl] = b.corners(); + s.select_tool("freeTransform", ViewInfo::default()).unwrap(); + s.set_tool_option("mode", &json!("distort")); + let to = br + vectorcraft_geom::Vec2::new(10.0, 20.0); + let n = undo_len(&s); + drag_with(&mut s, &[br, to, to], Mods::default()); + assert_eq!(undo_len(&s), n + 1); + assert_eq!(s.journal.last().map(|j| j.0.as_str()), Some("object.distort")); + // The dragged corner of the turned box lands under the pointer; the other three stay. + let pts = anchors(&s, a); + for p in [tl, tr, to, bl] { + assert!(has_point(&pts, p), "{p:?} not in {pts:?}"); + } +} + #[test] fn transform_panel_sizes_follow_the_turned_box() { let mut s = session(); @@ -375,3 +461,72 @@ fn the_selection_tool_reports_a_transforming_drag() { assert!(s.tool_busy() && !s.tool_transforming()); s.pointer(&ev(PointerKind::Up, 550.0, 450.0), v).unwrap(); } + +/// With General › Show Bounding Box While Moving and Drawing on, a move drag's bounding box is the +/// box measured once, at the drag's start, offset by each step's move: with Real-time Drawing on +/// and off, the later steps do not measure the selection again. Off, only the Selection tool with +/// Real-time Drawing off gives a box (the art waits for the release). +#[test] +fn a_move_drag_measures_the_bounding_box_once() { + for (real_time, while_moving) in [(true, true), (false, true), (true, false), (false, false)] { + let what = format!("real time {real_time}, box while moving {while_moving}"); + let mut s = session(); + let id = rect(&mut s, 100.0, 100.0, 100.0, 50.0); + sel(&mut s, &[id]); + s.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": real_time})).unwrap(); + s.execute("prefs.set", &json!({"key": "boundingBoxWhileMovingAndDrawing", "value": while_moving})).unwrap(); + let v = ViewInfo::default(); + s.select_tool("selection", v).unwrap(); + let ev = |kind, x: f64, y: f64| PointerEvent::new(kind, x, y).with_mods(Mods::default()); + s.pointer(&ev(PointerKind::Down, 150.0, 125.0), v).unwrap(); + assert_eq!(s.move_drag_box(), None, "{what}: not before the drag begins"); + s.pointer(&ev(PointerKind::Drag, 170.0, 135.0), v).unwrap(); + if real_time && !while_moving { + assert_eq!(s.move_drag_box(), None, "{what}: no box during the move"); + s.pointer(&ev(PointerKind::Up, 170.0, 135.0), v).unwrap(); + continue; + } + assert_eq!(s.move_drag_box(), Some(OrientedBox::aligned(Rect::new(120.0, 110.0, 220.0, 160.0))), "{what}"); + // The measurement made at the drag's start is the one each step offsets: replaced by a + // stand-in, the next step's box is the stand-in moved. + let it = s.doc_mut().unwrap().interaction.as_mut().unwrap(); + assert_eq!(it.move_box.get(), Some(&Some(OrientedBox::aligned(Rect::new(100.0, 100.0, 200.0, 150.0)))), "{what}: measured at the start"); + it.move_box = std::sync::OnceLock::from(Some(OrientedBox::aligned(Rect::new(0.0, 0.0, 10.0, 10.0)))); + s.pointer(&ev(PointerKind::Drag, 200.0, 165.0), v).unwrap(); + assert_eq!(s.move_drag_box(), Some(OrientedBox::aligned(Rect::new(50.0, 40.0, 60.0, 50.0))), "{what}: not measured again"); + s.pointer(&ev(PointerKind::Up, 200.0, 165.0), v).unwrap(); + assert_eq!(s.move_drag_box(), None, "{what}: none after the release"); + assert_eq!(selection_box(&s), OrientedBox::aligned(Rect::new(150.0, 140.0, 250.0, 190.0)), "{what}: moved"); + } +} + +/// A shape being drawn has no preview applied after a step that failed (with Real-time Drawing on, +/// also when the failed command left a document other than the interaction's snapshot), and with +/// Real-time Drawing off, where the document stays at the snapshot. A successful step with Real-time +/// Drawing on applies it. +#[test] +fn a_shape_being_drawn_reports_whether_a_preview_is_applied() { + for real_time in [true, false] { + let what = format!("real time {real_time}"); + let mut s = session(); + s.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": real_time})).unwrap(); + let v = ViewInfo::default(); + s.select_tool("rectangle", v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 160.0, 140.0), v).unwrap(); + assert_eq!(s.interaction_unapplied(), !real_time, "{what}: after a step that succeeded"); + assert!(s.preview("shape.rectangle", &json!({"x": "left"})).is_err(), "{what}: the preview fails"); + assert!(s.interaction_unapplied(), "{what}: after a step that failed"); + if real_time { + // A failed command that copied the document on write leaves another document than the + // snapshot; no preview is applied all the same. + let st = s.doc_mut().unwrap(); + st.doc = std::sync::Arc::new((*st.doc).clone()); + assert!(s.interaction_unapplied(), "{what}: a failed step with a copied document"); + } + s.pointer(&PointerEvent::new(PointerKind::Drag, 180.0, 150.0), v).unwrap(); + assert_eq!(s.interaction_unapplied(), !real_time, "{what}: the next step succeeded"); + s.pointer(&PointerEvent::new(PointerKind::Up, 180.0, 150.0), v).unwrap(); + assert!(!s.interaction_unapplied(), "{what}: no interaction after the release"); + } +} diff --git a/crates/engine/src/tests/blendopts.rs b/crates/engine/src/tests/blendopts.rs index 059357ddb3..05fbf1a72e 100644 --- a/crates/engine/src/tests/blendopts.rs +++ b/crates/engine/src/tests/blendopts.rs @@ -405,6 +405,184 @@ fn a_document_with_bad_blend_easing_numbers_opens_clamped_while_commands_refuse( } } +/// `object.blend.setEasing` sets one blend's easing and color shift, records no undo step when +/// nothing changes, and refuses bad values, a blend whose steps follow no spine (easing only), a +/// hidden or locked blend and a target that is not a blend, leaving the blend and the history alone. +#[test] +fn set_easing_edits_one_blend_and_refuses_what_it_cannot_set() { + let mut s = session(); + let (a, b) = (rect(&mut s, 0.0, 0.0, 40.0), rect(&mut s, 200.0, 0.0, 40.0)); + sel(&mut s, &[a, b]); + let g = id_of(&s.execute("object.blend.make", &json!({"steps": 3})).unwrap()); + let depth = |s: &Session| s.doc().unwrap().history.undo.len(); + let d0 = depth(&s); + // Align to Page along the straight lines between the keys: the steps follow no spine. + for bad in [json!({"ramp": 30}), json!({"easingType": "easeOut"})] { + let e = s.execute("object.blend.setEasing", &bad).unwrap_err().to_string(); + assert!(e.contains("the blend has no spine"), "{e}"); + } + assert_eq!(depth(&s), d0); + let r = s.execute("object.blend.setEasing", &json!({"colorShift": 25})).unwrap(); + assert_eq!(r, json!({"id": g.0, "easingType": "easeIn", "ramp": 0.0, "colorShift": 25.0, "changed": true})); + assert_eq!((spec(&s, g).1.color_shift, depth(&s)), (25.0, d0 + 1)); + let r = s.execute("object.blend.setEasing", &json!({"colorShift": 25})).unwrap(); + assert_eq!((&r["changed"], depth(&s)), (&json!(false), d0 + 1), "an unchanged value records no undo step"); + // Along the spine each of the four types keeps its kind through a ramp change and its undo. + s.execute("object.blend.options", &json!({"orientation": "path"})).unwrap(); + for kind in ["easeIn", "easeOut", "easeInOut", "easeOutIn"] { + s.execute("object.blend.setEasing", &json!({"easingType": kind, "ramp": 60})).unwrap(); + let r = s.execute("object.blend.setEasing", &json!({"ramp": 20})).unwrap(); + assert_eq!((&r["easingType"], &r["ramp"], &r["colorShift"]), (&json!(kind), &json!(20.0), &json!(25.0))); + s.execute("edit.undo", &json!({})).unwrap(); + let sp = spec(&s, g).1; + assert_eq!((sp.ease.kind.id(), sp.ease.ramp, sp.color_shift), (kind, 0.6, 25.0)); + } + let before = spec(&s, g).1; + let d1 = depth(&s); + for bad in [ + json!({"ramp": 101}), + json!({"ramp": -1}), + json!({"ramp": "x"}), + json!({"colorShift": 1e308}), + json!({"colorShift": -101}), + json!({"easingType": "sideways"}), + json!({"id": "abc", "ramp": 10}), + json!({"id": a.0, "ramp": 10}), + ] { + assert!(s.execute("object.blend.setEasing", &bad).is_err(), "{bad}"); + assert_eq!((spec(&s, g).1, depth(&s)), (before.clone(), d1), "{bad}"); + } + // An explicit id works with nothing selected; nothing selected and no id is an error. + s.execute("select.none", &json!({})).unwrap(); + assert!(s.execute("object.blend.setEasing", &json!({"ramp": 10})).is_err()); + s.execute("object.blend.setEasing", &json!({"id": g.0, "ramp": 10})).unwrap(); + assert_eq!(spec(&s, g).1.ease.ramp, 0.1); + // A hidden or locked blend is refused. + for hide in [true, false] { + s.edit("state", |d, _| { + let n = d.node_mut(g).unwrap(); + (n.visible, n.locked) = (!hide, !hide); + Ok(()) + }) + .unwrap(); + let (before, d2) = (spec(&s, g).1, depth(&s)); + let e = s.execute("object.blend.setEasing", &json!({"id": g.0, "colorShift": 5})).unwrap_err().to_string(); + assert!(e.contains("the object is hidden or locked"), "{e}"); + assert_eq!((spec(&s, g).1, depth(&s)), (before, d2)); + } + // A blend made without a spine takes no easing, Align to Path included; its color shift still + // changes. + let (c, d) = (rect(&mut s, 0.0, 300.0, 40.0), rect(&mut s, 200.0, 300.0, 40.0)); + sel(&mut s, &[c, d]); + let n = id_of(&s.execute("object.blend.make", &json!({"createSpine": "never", "orientation": "path"})).unwrap()); + let d3 = depth(&s); + let e = s.execute("object.blend.setEasing", &json!({"id": n.0, "ramp": 30})).unwrap_err().to_string(); + assert!(e.contains("the blend has no spine"), "{e}"); + assert_eq!(depth(&s), d3); + s.execute("object.blend.setEasing", &json!({"id": n.0, "colorShift": 10})).unwrap(); + assert_eq!(spec(&s, n).1.color_shift, 10.0); + // Replace Spine gives it a spine, and it takes easing from then on. + let path = id_of(&s.execute("path.create", &json!({"d": "M0 320 L200 320"})).unwrap()); + sel(&mut s, &[n, path]); + s.execute("object.blend.replaceSpine", &json!({})).unwrap(); + let r = s.execute("object.blend.setEasing", &json!({"id": n.0, "easingType": "easeOut", "ramp": 30})).unwrap(); + assert_eq!((&r["easingType"], &r["ramp"], &r["changed"]), (&json!("easeOut"), &json!(30.0), &json!(true))); +} + +/// Dragging a blend widget with the Selection tool or the Blend tool is one undo step; a click, a +/// drag that ends at its starting value and a drag canceled with Escape record none, and Escape +/// puts the value back. +#[test] +fn dragging_a_blend_widget_is_one_undo_step_and_a_click_or_escape_none() { + let mut s = session(); + let (a, b) = (rect(&mut s, 0.0, 0.0, 40.0), rect(&mut s, 200.0, 0.0, 40.0)); + sel(&mut s, &[a, b]); + let g = id_of(&s.execute("object.blend.make", &json!({"steps": 3, "orientation": "path", "easingType": "easeOut"})).unwrap()); + let v = ViewInfo::default(); + let depth = |s: &Session| s.doc().unwrap().history.undo.len(); + let ptr = |s: &mut Session, kind: PointerKind, x: f64, y: f64| { + s.pointer(&PointerEvent::new(kind, x, y), ViewInfo::default()).unwrap(); + }; + s.select_tool("selection", v).unwrap(); + sel(&mut s, &[g]); + let d0 = depth(&s); + // The Easing widget sits 16 px below the spine's halfway point (120, 20). + ptr(&mut s, PointerKind::Down, 120.0, 36.0); + ptr(&mut s, PointerKind::Drag, 135.0, 36.0); + ptr(&mut s, PointerKind::Drag, 150.0, 36.0); + ptr(&mut s, PointerKind::Up, 150.0, 36.0); + let sp = spec(&s, g).1; + assert_eq!((sp.ease.kind.id(), sp.ease.ramp, sp.color_shift, depth(&s)), ("easeOut", 0.3, 0.0, d0 + 1)); + assert_eq!(s.doc().unwrap().selection.objects, vec![g], "the blend stays selected"); + // A click, and a drag back to where it started. + ptr(&mut s, PointerKind::Down, 120.0, 36.0); + ptr(&mut s, PointerKind::Up, 120.0, 36.0); + ptr(&mut s, PointerKind::Down, 120.0, 36.0); + ptr(&mut s, PointerKind::Drag, 160.0, 36.0); + ptr(&mut s, PointerKind::Drag, 120.0, 36.0); + ptr(&mut s, PointerKind::Up, 120.0, 36.0); + assert_eq!((spec(&s, g).1.ease.ramp, depth(&s)), (0.3, d0 + 1)); + // Escape during a drag puts the value back. + ptr(&mut s, PointerKind::Down, 120.0, 36.0); + ptr(&mut s, PointerKind::Drag, 170.0, 36.0); + assert_eq!(spec(&s, g).1.ease.ramp, 0.8, "the drag previews"); + s.tool_key(ToolKey::Escape, Mods::default(), v).unwrap(); + ptr(&mut s, PointerKind::Up, 170.0, 36.0); + assert_eq!((spec(&s, g).1.ease.ramp, depth(&s)), (0.3, d0 + 1)); + // The Blend tool drags the Appearance widget, 16 px above: the color shift alone. + s.select_tool("blend", v).unwrap(); + sel(&mut s, &[g]); + ptr(&mut s, PointerKind::Down, 120.0, 4.0); + ptr(&mut s, PointerKind::Drag, 100.0, 4.0); + ptr(&mut s, PointerKind::Up, 100.0, 4.0); + let sp = spec(&s, g).1; + assert_eq!((sp.ease.kind.id(), sp.ease.ramp, sp.color_shift, depth(&s)), ("easeOut", 0.3, -20.0, d0 + 2)); + assert_eq!(s.doc().unwrap().selection.objects, vec![g]); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(spec(&s, g).1.color_shift, 0.0); +} + +/// A blend made without a spine has the Appearance widget alone: a drag of it with the Selection +/// tool or the Blend tool changes the color shift in one undo step, and there is no Easing widget +/// to drag. +#[test] +fn dragging_the_appearance_widget_of_a_blend_without_a_spine_is_one_undo_step() { + let mut s = session(); + let (a, b) = (rect(&mut s, 0.0, 0.0, 40.0), rect(&mut s, 200.0, 0.0, 40.0)); + sel(&mut s, &[a, b]); + let g = id_of(&s.execute("object.blend.make", &json!({"steps": 3, "createSpine": "never", "orientation": "path"})).unwrap()); + assert!(spec(&s, g).1.no_spine); + let v = ViewInfo::default(); + let depth = |s: &Session| s.doc().unwrap().history.undo.len(); + let ptr = |s: &mut Session, kind: PointerKind, x: f64, y: f64| { + s.pointer(&PointerEvent::new(kind, x, y), ViewInfo::default()).unwrap(); + }; + for (n, tool) in [(1.0, "selection"), (2.0, "blend")] { + s.select_tool(tool, v).unwrap(); + sel(&mut s, &[g]); + let d0 = depth(&s); + // The Appearance widget sits 16 px above the halfway point (120, 20) of the line between + // the key centers. + ptr(&mut s, PointerKind::Down, 120.0, 4.0); + ptr(&mut s, PointerKind::Drag, 135.0, 4.0); + ptr(&mut s, PointerKind::Up, 135.0, 4.0); + let sp = spec(&s, g).1; + assert_eq!((sp.color_shift, sp.ease.ramp, depth(&s)), (15.0 * n, 0.0, d0 + 1), "{tool}"); + assert_eq!(s.doc().unwrap().selection.objects, vec![g], "{tool}: the blend stays selected"); + } + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(spec(&s, g).1.color_shift, 15.0, "each drag is its own undo step"); + // 16 px below there is no widget: a drag there leaves the easing and the color shift alone. + s.select_tool("selection", v).unwrap(); + sel(&mut s, &[g]); + let before = spec(&s, g).1; + ptr(&mut s, PointerKind::Down, 120.0, 36.0); + ptr(&mut s, PointerKind::Drag, 150.0, 36.0); + ptr(&mut s, PointerKind::Up, 150.0, 36.0); + let after = spec(&s, g).1; + assert_eq!((after.ease, after.color_shift), (before.ease, before.color_shift), "no Easing widget"); +} + #[test] fn native_blend_easing_values_clamp_and_non_finite_become_default() { for (bad, ramp, shift) in [ @@ -418,3 +596,179 @@ fn native_blend_easing_values_clamp_and_non_finite_become_default() { assert_eq!((spec.ease.ramp, spec.color_shift), (ramp, shift), "{bad}"); } } + +fn create_spine(s: &mut Session, p: Value) -> Value { + s.execute("object.blend.createSpine", &p).unwrap()["mode"].clone() +} + +/// Two squares 100 pt apart blended with `p`; the blend. +fn make(s: &mut Session, y: f64, p: Value) -> NodeId { + let (a, b) = (rect(s, 0.0, y, 10.0), rect(s, 100.0, y, 10.0)); + let mut p = p; + p["ids"] = json!([a.0, b.0]); + p["steps"] = json!(3); + id_of(&s.execute("object.blend.make", &p).unwrap()) +} + +#[test] +fn create_spine_sets_whether_new_blends_get_a_spine() { + let mut s = session(); + assert_eq!(create_spine(&mut s, json!({})), "auto", "Auto until one is chosen"); + let spined = make(&mut s, 0.0, json!({})); + assert!(!spec(&s, spined).1.no_spine); + let depth = s.doc().unwrap().history.undo.len(); + assert_eq!(create_spine(&mut s, json!({"mode": "never"})), "never"); + assert_eq!(s.doc().unwrap().history.undo.len(), depth, "a tool setting, not an undo step"); + assert_eq!(create_spine(&mut s, json!({})), "never"); + // The Blend Options set with nothing selected keep it, and it keeps them. + s.execute("select.none", &json!({})).unwrap(); + s.execute("object.blend.options", &json!({"steps": 7})).unwrap(); + assert_eq!(create_spine(&mut s, json!({})), "never"); + assert_eq!(s.prefs.blend_options.unwrap().spacing, BlendSpacing::Steps(7)); + // A new blend has no spine; the blend made before keeps its own. + let bare = make(&mut s, 50.0, json!({})); + assert!(spec(&s, bare).1.no_spine); + assert!(!spec(&s, spined).1.no_spine, "blends already made keep their spine"); + sel(&mut s, &[bare]); + let info = s.execute("object.blend.info", &json!({})).unwrap(); + assert_eq!(info["hasSpine"], json!(false)); + assert!(info.get("spine").is_none(), "{info}"); + sel(&mut s, &[spined]); + assert_eq!(s.execute("object.blend.info", &json!({})).unwrap()["hasSpine"], json!(true)); + // `createSpine` on Make chooses for that blend only. + let forced = make(&mut s, 100.0, json!({"createSpine": "always"})); + assert!(!spec(&s, forced).1.no_spine); + assert_eq!(create_spine(&mut s, json!({})), "never"); + assert_eq!(create_spine(&mut s, json!({"mode": "always"})), "always"); + let always = make(&mut s, 150.0, json!({})); + assert!(!spec(&s, always).1.no_spine); + assert!(spec(&s, bare).1.no_spine, "blends already made keep having no spine"); + let none = make(&mut s, 200.0, json!({"createSpine": "never"})); + assert!(spec(&s, none).1.no_spine); + // The setting survives a round trip through the preferences file; Auto is not written. + let back: Prefs = serde_json::from_value(s.prefs.to_json()).unwrap(); + assert_eq!(back.blend_options.unwrap().create_spine, vectorcraft_doc::live::BlendSpineMode::Always); + assert_eq!(s.prefs.to_json()["blendOptions"]["createSpine"], json!("always")); + create_spine(&mut s, json!({"mode": "auto"})); + assert!(s.prefs.to_json()["blendOptions"].get("createSpine").is_none()); + let mut odd = s.prefs.to_json(); + odd["blendOptions"]["createSpine"] = json!("sometimes"); + let unknown: Prefs = serde_json::from_value(odd).unwrap(); + assert_eq!(unknown.blend_options.unwrap().create_spine, vectorcraft_doc::live::BlendSpineMode::Auto, "an unknown value reads as Auto"); +} + +#[test] +fn create_spine_refuses_bad_values_and_changes_nothing() { + let mut s = session(); + create_spine(&mut s, json!({"mode": "never"})); + let prefs = s.prefs.blend_options; + for bad in [json!({"mode": "sometimes"}), json!({"mode": 1}), json!({"mode": true}), json!({"mode": ["never"]}), json!({"mode": "Never"})] { + let e = s.execute("object.blend.createSpine", &bad).unwrap_err().to_string(); + assert!(e.contains("`mode` must be one of auto, always, never"), "{bad}: {e}"); + assert_eq!(s.prefs.blend_options, prefs, "{bad}"); + } + let (a, b) = (rect(&mut s, 0.0, 0.0, 10.0), rect(&mut s, 100.0, 0.0, 10.0)); + let depth = s.doc().unwrap().history.undo.len(); + for bad in [json!({"createSpine": "x"}), json!({"createSpine": 0}), json!({"createSpine": "never", "easingType": "easeIn"}), json!({"ramp": 30})] + { + let mut p = bad.clone(); + p["ids"] = json!([a.0, b.0]); + assert!(s.execute("object.blend.make", &p).is_err(), "{bad}"); + assert_eq!(s.doc().unwrap().history.undo.len(), depth, "{bad}: nothing made"); + } + assert!(s.execute("object.blend.createSpine", &json!({"spine": "never"})).is_err(), "an unknown key"); +} + +#[test] +fn a_blend_without_a_spine_has_none_to_edit_reverse_ease_or_release() { + let mut s = session(); + let g = make(&mut s, 0.0, json!({"createSpine": "never"})); + sel(&mut s, &[g]); + let before = node(&s, g); + let depth = s.doc().unwrap().history.undo.len(); + // Reverse Spine, easing and the spine point commands refuse it and change nothing. + let refused = [ + ("object.blend.reverseSpine", json!({})), + ("object.blend.options", json!({"easingType": "easeOut"})), + ("object.blend.options", json!({"ramp": 40})), + ("object.blend.spine.addAnchor", json!({"x": 50, "y": 5})), + ("object.blend.spine.moveAnchor", json!({"anchor": 0, "x": 0, "y": 50})), + ]; + for (cmd, p) in refused { + let e = s.execute(cmd, &p).unwrap_err().to_string(); + assert!(e.contains("the blend has no spine"), "{cmd}: {e}"); + assert_eq!((node(&s, g), s.doc().unwrap().history.undo.len()), (before.clone(), depth), "{cmd}"); + } + // Spacing, Orientation and Shift still apply; Align to Path makes no spine. + s.execute("object.blend.options", &json!({"steps": 2, "orientation": "path", "colorShift": 20})).unwrap(); + let sp = spec(&s, g).1; + assert_eq!((sp.spacing, sp.orientation, sp.color_shift, sp.no_spine), (BlendSpacing::Steps(2), BlendOrientation::AlignToPath, 20.0, true)); + assert!(s.execute("object.blend.info", &json!({})).unwrap().get("spine").is_none()); + // Taking in another key keeps it without a spine, whatever Create Spine says. + let c = rect(&mut s, 200.0, 0.0, 10.0); + sel(&mut s, &[g, c]); + create_spine(&mut s, json!({"mode": "always"})); + let g = id_of(&s.execute("object.blend.make", &json!({})).unwrap()); + assert_eq!(spec(&s, g).0.len(), 3); + assert!(spec(&s, g).1.no_spine && spec(&s, g).1.spine.is_none()); + // Release gives back the keys and no spine path. + sel(&mut s, &[g]); + let r = s.execute("object.blend.release", &json!({})).unwrap(); + assert_eq!((r["ids"].as_array().map(Vec::len), &r["spines"]), (Some(3), &json!([]))); + s.execute("edit.undo", &json!({})).unwrap(); + // Replace Spine gives it one: then it reverses and eases like any other. + let line = id_of(&s.execute("path.create", &json!({"d": "M0 100 L200 150"})).unwrap()); + sel(&mut s, &[g, line]); + s.execute("object.blend.replaceSpine", &json!({})).unwrap(); + let sp = spec(&s, g).1; + assert!(!sp.no_spine && sp.spine.is_some()); + let info = s.execute("object.blend.info", &json!({})).unwrap(); + assert_eq!((&info["hasSpine"], &info["spine"]["explicit"]), (&json!(true), &json!(true))); + s.execute("object.blend.reverseSpine", &json!({})).unwrap(); + s.execute("object.blend.options", &json!({"easingType": "easeOut", "ramp": 40})).unwrap(); + assert_eq!(spec(&s, g).1.ease.ramp, 0.4); +} + +#[test] +fn a_blend_without_a_spine_draws_its_steps_where_one_with_a_spine_does() { + let mut s = session(); + for orientation in ["page", "path"] { + let spined = make(&mut s, 0.0, json!({"orientation": orientation})); + let bare = make(&mut s, 0.0, json!({"orientation": orientation, "createSpine": "never"})); + let boxes = |g: NodeId| -> Vec<_> { vectorcraft_doc::live::expand_live(&node(&s, g)).iter().map(|n| n.geometric_bounds()).collect() }; + assert_eq!(boxes(bare), boxes(spined), "{orientation}"); + assert!(boxes(bare).len() >= 3, "the three steps at least"); + } + // Easing stored on a blend without a spine (a hand-edited file) leaves its steps evenly spaced. + let bare = make(&mut s, 300.0, json!({"orientation": "path", "createSpine": "never"})); + let even = vectorcraft_doc::live::expand_live(&node(&s, bare)); + let mut eased = node(&s, bare); + if let NodeKind::Blend { spec, .. } = &mut eased.kind { + spec.ease = vectorcraft_doc::live::BlendEase { kind: vectorcraft_doc::live::BlendEaseType::In, ramp: 1.0 }; + } + let boxes = |v: &[Node]| -> Vec<_> { v.iter().map(|n| n.geometric_bounds()).collect() }; + assert_eq!(boxes(&vectorcraft_doc::live::expand_live(&eased)), boxes(&even)); +} + +#[test] +fn whether_a_blend_has_a_spine_is_saved_and_old_blends_have_one() { + let mut s = session(); + let bare = make(&mut s, 0.0, json!({"createSpine": "never"})); + let spined = make(&mut s, 50.0, json!({})); + let d = &s.doc().unwrap().doc; + let back = vectorcraft_format::load(&vectorcraft_format::save(d, false)).unwrap(); + assert_eq!(&back.layers, &d.layers); + let saved = |g: NodeId| match &back.node(g).unwrap().kind { + NodeKind::Blend { spec, .. } => spec.no_spine, + _ => panic!("not a blend"), + }; + assert!(saved(bare) && !saved(spined)); + assert_eq!(serde_json::to_value(spec(&s, bare).1).unwrap()["noSpine"], json!(true)); + assert!(serde_json::to_value(spec(&s, spined).1).unwrap().get("noSpine").is_none(), "a spine is not written"); + let old: BlendSpec = serde_json::from_value(json!({"spacing": {"steps": 4}})).unwrap(); + assert!(!old.no_spine, "a blend saved before Create Spine has a spine"); + for odd in [json!("yes"), json!(1), json!(null)] { + let v: BlendSpec = serde_json::from_value(json!({"noSpine": odd.clone()})).unwrap_or_else(|e| panic!("{odd}: {e}")); + assert!(!v.no_spine, "{odd}"); + } +} diff --git a/crates/engine/src/tests/brushlib.rs b/crates/engine/src/tests/brushlib.rs index 491a471088..2d363d18cf 100644 --- a/crates/engine/src/tests/brushlib.rs +++ b/crates/engine/src/tests/brushlib.rs @@ -104,7 +104,20 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { let list = run(&mut s, "brush.libraries", json!({})); let libs = list["libraries"].as_array().unwrap(); let ids: Vec<&str> = libs.iter().map(|l| l["id"].as_str().unwrap()).collect(); - assert_eq!(ids, ["art-ribbons", "calligraphic-nibs", "pattern-borders", "scatter-shapes", "game-trails", "energy-beams"]); + assert_eq!( + ids, + [ + "art-ribbons", + "ink-and-wash", + "calligraphic-nibs", + "bristle-brushes", + "pattern-borders", + "scatter-shapes", + "game-trails", + "energy-beams", + "dry-media" + ] + ); assert!(libs.iter().all(|l| l["category"] == "builtIn")); let lib = run(&mut s, "brush.library", json!({"library": "art ribbons"})); assert_eq!( @@ -117,29 +130,40 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { trails["brushes"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap()).collect::<Vec<_>>(), ["Speed Line", "Dash Trail", "Burst Ray", "Zigzag"] ); - assert_eq!(libs[4]["count"].as_u64(), Some(4)); + assert_eq!(libs[6]["count"].as_u64(), Some(4)); let beams = run(&mut s, "brush.library", json!({"library": "energy-beams"})); assert_eq!( beams["brushes"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap()).collect::<Vec<_>>(), ["Laser Bolt", "Plasma Arc", "Charge Wave", "Spark Trail"] ); - assert_eq!(libs[5]["count"].as_u64(), Some(4)); + assert_eq!(libs[7]["count"].as_u64(), Some(4)); + let dry = run(&mut s, "brush.library", json!({"library": "Dry Media"})); + assert_eq!( + dry["brushes"].as_array().unwrap().iter().map(|b| (b["name"].as_str().unwrap(), b["type"].as_str().unwrap())).collect::<Vec<_>>(), + [("Chalk Grain", "art"), ("Graphite Pencil", "art"), ("Wax Crayon", "art"), ("Charcoal Dust", "art")] + ); + assert_eq!((libs[8]["name"].as_str(), libs[8]["count"].as_u64()), (Some("Dry Media"), Some(4))); run(&mut s, "file.new", json!({"width": 200, "height": 200})); let id = run(&mut s, "shape.rectangle", json!({"x": 10, "y": 20, "width": 40, "height": 8}))["id"].as_u64().unwrap(); let added = run(&mut s, "brush.addFromLibrary", json!({"library": "energy-beams", "name": "Laser Bolt", "apply": true, "ids": [id]})); assert_eq!(strs(&added["added"]), ["Laser Bolt"]); - // One kind of brush per library, every brush drawing something. + // One kind of brush per library (Ink and Wash: art brushes and a calligraphic one), every + // brush drawing something. for (id, kind) in [ ("art-ribbons", "art"), + ("ink-and-wash", "art"), ("calligraphic-nibs", "calligraphic"), + ("bristle-brushes", "bristle"), ("pattern-borders", "pattern"), ("scatter-shapes", "scatter"), ("game-trails", "art"), ("energy-beams", "art"), + ("dry-media", "art"), ] { let (_, lib) = cmd::brushlib::library(&s, id).unwrap(); assert!(lib.len() >= 4, "{id}"); for b in &lib.brushes { + let kind = if b.name == "Brush Pen" { "calligraphic" } else { kind }; assert_eq!(b.kind.type_id(), kind, "{}", b.name); let mut line = vectorcraft_geom::BezPath::new(); line.move_to((0.0, 0.0)); @@ -165,6 +189,355 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { assert!(s.execute("brush.library", &json!({"library": "nope"})).is_err()); } +/// Every path of brush art `n`: (anchors, opacity). +fn art_paths(n: &vectorcraft_doc::Node) -> Vec<(usize, f32)> { + let mut out = vec![]; + n.walk(&mut |c| { + if let Some(p) = c.path_data() { + out.push((p.anchor_count(), c.opacity)); + } + }); + out +} + +/// The Ink and Wash library, made once. +fn inks(s: &Session) -> std::sync::Arc<cmd::brushlib::BrushLibrary> { + cmd::brushlib::library(s, "ink-and-wash").unwrap().1 +} + +/// A straight line from the origin to (`x`, 0). +fn line_to(x: f64) -> vectorcraft_geom::BezPath { + let mut line = vectorcraft_geom::BezPath::new(); + line.move_to((0.0, 0.0)); + line.line_to((x, 0.0)); + line +} + +fn black_stroke() -> vectorcraft_doc::StrokeLayer { + vectorcraft_doc::StrokeLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), 1.0) +} + +/// Ink and Wash: a tapered ink art brush, a brush pen whose size follows the pen pressure and two +/// translucent washes, with names of their own and a few paths of art each. +#[test] +fn the_ink_and_wash_library_has_tapered_ink_a_brush_pen_and_two_washes() { + let mut s = session(); + let lib = run(&mut s, "brush.library", json!({"library": "ink-and-wash"})); + assert_eq!((lib["name"].as_str(), lib["category"].as_str()), (Some("Ink and Wash"), Some("builtIn"))); + let listed: Vec<(&str, &str)> = + lib["brushes"].as_array().unwrap().iter().map(|b| (b["name"].as_str().unwrap(), b["type"].as_str().unwrap())).collect(); + assert_eq!(listed, [("Tapered Ink", "art"), ("Brush Pen", "calligraphic"), ("Soft Wash", "art"), ("Pooling Wash", "art")]); + assert_eq!(run(&mut s, "brush.library", json!({"library": "Ink and Wash"}))["id"], "ink-and-wash"); + let inks = inks(&s); + // Names no other built-in library uses. + for b in cmd::brushlib::BUILTIN.iter().filter(|b| b.id != "ink-and-wash") { + let (_, other) = cmd::brushlib::library(&s, b.id).unwrap(); + assert!(inks.brushes.iter().all(|x| other.brush(&x.name).is_none()), "{}", b.id); + } + // The art: within its 100 pt length, a few paths each, opaque ink and translucent washes. + let mut anchors = 0; + for name in ["Tapered Ink", "Soft Wash", "Pooling Wash"] { + let BrushKind::Art(a) = &inks.brush(name).unwrap().kind else { panic!("{name} is not an art brush") }; + assert_eq!((a.scale, a.colorization), (vectorcraft_brush::ArtScale::Stretch, vectorcraft_brush::Colorization::Tints), "{name}"); + let b = a.art.geometric_bounds().unwrap(); + assert!([b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()), "{name}"); + assert!(b.x0 >= 0.0 && b.x1 <= 100.0 && b.x1 - b.x0 > 99.0, "{name}: {b:?}"); + assert!(b.y0 >= -8.0 && b.y1 <= 8.0 && b.y1 - b.y0 > 5.0, "{name}: {b:?}"); + let paths = art_paths(&a.art); + let count: usize = paths.iter().map(|p| p.0).sum(); + assert!(paths.len() <= 80 && count <= 500, "{name}: {} paths, {count} anchors", paths.len()); + anchors += count; + let opacities: Vec<f32> = paths.iter().map(|p| p.1).collect(); + if name == "Tapered Ink" { + assert_eq!(opacities, [1.0], "opaque ink"); + } else { + assert!(paths.len() >= 3, "{name}: a wash of several layers"); + assert!(opacities.iter().all(|o| (0.15..=0.55).contains(o)), "{name}: {opacities:?}"); + } + } + assert!(anchors <= 1200, "{anchors} anchors"); + let BrushKind::Calligraphic(pen) = &inks.brush("Brush Pen").unwrap().kind else { panic!("Brush Pen is not calligraphic") }; + use vectorcraft_brush::Variation::{Fixed, Pressure}; + assert_eq!((pen.size, pen.modes(), pen.variation), (5.0, [Fixed, Fixed, Pressure], [0.0, 0.0, 2.5]), "no random variation"); +} + +/// Every Ink and Wash brush draws along straight, curved, short and tight paths within finite +/// bounds, and Tapered Ink is broad near its start and fine at its end. +#[test] +fn ink_and_wash_brushes_draw_along_straight_curved_short_and_tight_paths() { + let inks = inks(&Session::new()); + let mut curve = vectorcraft_geom::BezPath::new(); + curve.move_to((0.0, 0.0)); + curve.curve_to((60.0, -40.0), (140.0, 40.0), (200.0, 0.0)); + let tight = vectorcraft_geom::shapes::ellipse(vectorcraft_geom::Rect::new(0.0, 0.0, 6.0, 6.0)).to_bezpath(); + let paths = [line_to(200.0), line_to(3.0), curve, tight]; + for b in &inks.brushes { + for line in &paths { + let pieces = vectorcraft_brush::stroke_pieces(&inks.doc, b, line, &black_stroke()); + assert!(!pieces.is_empty(), "{} draws nothing", b.name); + let bounds: Vec<_> = pieces.iter().map(|p| p.geometric_bounds()).collect(); + assert!(bounds.iter().all(|r| r.is_some_and(|r| [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()))), "{}", b.name); + } + } + let pieces = vectorcraft_brush::stroke_pieces(&inks.doc, inks.brush("Tapered Ink").unwrap(), &line_to(100.0), &black_stroke()); + let widest = |from: f64, to: f64| { + pieces + .iter() + .filter_map(|n| n.path_data()) + .flat_map(|p| p.anchors().map(|(_, _, a)| a.p).collect::<Vec<_>>()) + .filter(|p| p.x >= from && p.x <= to) + .map(|p| p.y.abs()) + .fold(0.0, f64::max) + }; + assert!(widest(15.0, 30.0) > 4.0 * widest(95.0, 100.0), "broad start, fine tip"); +} + +/// Ink and Wash brushes are added and applied in one step, undone and redone, not added twice, +/// and kept with the brushed stroke by a saved and reopened document. +#[test] +fn ink_and_wash_brushes_add_apply_undo_and_survive_a_saved_document() { + let mut s = session(); + let inks = inks(&s); + let path = run(&mut s, "shape.line", json!({"x1": 10, "y1": 10, "x2": 150, "y2": 60}))["id"].as_u64().unwrap(); + let (defaults, before) = (brushes(&s), undo_len(&s)); + let names = ["Tapered Ink", "Brush Pen", "Soft Wash", "Pooling Wash"]; + let r = run(&mut s, "brush.addFromLibrary", json!({"library": "ink-and-wash", "name": "Soft Wash", "apply": true, "ids": [path]})); + assert_eq!((strs(&r["added"]), r["applied"].clone(), undo_len(&s)), (vec!["Soft Wash"], json!([path]), before + 1)); + let stroke_brush = |s: &Session| doc(s).node(NodeId(path)).unwrap().appearance.stroke().and_then(|st| st.brush.clone()); + assert_eq!(stroke_brush(&s).as_deref(), Some("Soft Wash")); + run(&mut s, "edit.undo", json!({})); + assert_eq!((brushes(&s), stroke_brush(&s)), (defaults.clone(), None)); + run(&mut s, "edit.redo", json!({})); + assert_eq!(stroke_brush(&s).as_deref(), Some("Soft Wash")); + let r = run(&mut s, "brush.addFromLibrary", json!({"library": "ink-and-wash"})); + assert_eq!( + (strs(&r["names"]), strs(&r["existing"]), strs(&r["added"])), + (names.to_vec(), vec!["Soft Wash"], vec!["Tapered Ink", "Brush Pen", "Pooling Wash"]) + ); + let before = undo_len(&s); + let r = run(&mut s, "brush.addFromLibrary", json!({"library": "ink-and-wash"})); + assert_eq!((strs(&r["existing"]), undo_len(&s)), (names.to_vec(), before)); + assert_eq!(brushes(&s).len(), defaults.len() + 4); + for n in names { + assert_eq!(&brush(&s, n), inks.brush(n).unwrap(), "{n}"); + } + + // Saved and opened again, the document keeps the definitions and the brushed stroke. + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let reopened = vectorcraft_format::load(&vectorcraft_format::base64_decode(&b64).unwrap()).unwrap(); + for n in names { + assert_eq!(vectorcraft_brush::find(&reopened, n).as_ref(), inks.brush(n), "{n}"); + } + let n = reopened.node(NodeId(path)).unwrap(); + assert_eq!(n.appearance.stroke().and_then(|st| st.brush.clone()).as_deref(), Some("Soft Wash")); + assert_eq!( + vectorcraft_brush::node_pieces(&reopened, n).map(|p| p.len()), + vectorcraft_brush::node_pieces(doc(&s), doc(&s).node(NodeId(path)).unwrap()).map(|p| p.len()) + ); +} + +/// Whether `p` lies inside the polygon through `pts` (even-odd ray cast). +fn inside(p: vectorcraft_geom::Point, pts: &[vectorcraft_geom::Point]) -> bool { + let mut odd = false; + for (i, a) in pts.iter().enumerate() { + let b = pts[(i + 1) % pts.len()]; + if (a.y > p.y) != (b.y > p.y) && p.x < a.x + (p.y - a.y) * (b.x - a.x) / (b.y - a.y) { + odd = !odd; + } + } + odd +} + +/// Every anchor of the paths in `nodes` and their descendants. +fn anchors(nodes: &[&vectorcraft_doc::Node]) -> Vec<vectorcraft_geom::Point> { + let mut out = vec![]; + for n in nodes { + n.walk(&mut |c| out.extend(c.path_data().into_iter().flat_map(|p| p.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p))))); + } + out +} + +/// Dry Media: four art brushes of grainy dry marks (chalk, pencil, crayon, charcoal) with names +/// of their own. Each one's art is a bounded set of filled vector paths 100 pt long that takes the +/// stroke color as tints, with real even-odd gaps in the chalk and the crayon; it draws finite art +/// on curved and short paths, is the same every time it is made, and goes into a document in one +/// undo step, once, applied, and through a saved library unchanged. +#[test] +fn the_dry_media_library_holds_grainy_art_brushes_with_bounded_art() { + use vectorcraft_brush::{ArtScale, Colorization}; + use vectorcraft_geom::FillRule; + let mut s = session(); + let (info, lib) = cmd::brushlib::library(&s, "dry-media").unwrap(); + assert_eq!((info.name.as_str(), info.category, lib.name.as_str()), ("Dry Media", "builtIn", "Dry Media")); + let names: Vec<String> = lib.brushes.iter().map(|b| b.name.clone()).collect(); + assert_eq!(names, ["Chalk Grain", "Graphite Pencil", "Wax Crayon", "Charcoal Dust"]); + let mut total = 0; + for (b, (height, gaps)) in lib.brushes.iter().zip([(8.0, true), (2.5, false), (6.0, true), (7.0, false)]) { + let BrushKind::Art(a) = &b.kind else { panic!("{} is not an art brush", b.name) }; + assert_eq!((a.colorization, a.scale, a.width), (Colorization::Tints, ArtScale::Stretch, 100.0), "{}", b.name); + let (mut paths, mut holes) = (0, 0); + a.art.walk(&mut |n| match &n.kind { + NodeKind::Path { path, .. } => { + paths += 1; + assert!(path.subpaths.iter().all(|sp| sp.closed && sp.anchors.len() >= 4), "{}", b.name); + } + NodeKind::Compound { children, rule } => { + assert_eq!(*rule, FillRule::EvenOdd, "{}", b.name); + // The gaps lie inside the band and apart from each other, so each one is a hole. + let body = anchors(&[&*children[0]]); + let boxes: Vec<vectorcraft_geom::Rect> = children[1..].iter().map(|c| c.path_data().unwrap().bounds().unwrap()).collect(); + for (i, c) in children[1..].iter().enumerate() { + assert!(anchors(&[&**c]).iter().all(|p| inside(*p, &body)), "{}: gap {i} leaves the band", b.name); + let r = boxes[i]; + assert!(boxes[..i].iter().all(|o| r.x0 >= o.x1 || o.x0 >= r.x1 || r.y0 >= o.y1 || o.y0 >= r.y1), "{}: gap {i} overlaps", b.name); + } + holes += children.len() - 1; + } + NodeKind::Group { .. } => {} + other => panic!("{}: unexpected {other:?}", b.name), + }); + let pts = anchors(&[&a.art]); + assert!(pts.iter().all(|p| p.x.is_finite() && p.y.is_finite())); + assert!(paths <= 80 && pts.len() <= 500, "{}: {paths} paths, {} anchors", b.name, pts.len()); + assert_eq!(holes > 0, gaps, "{}: {holes} gaps", b.name); + let r = vectorcraft_geom::Rect::from_points(pts[0], pts[0]); + let r = pts.iter().fold(r, |r, p| r.union_pt(*p)); + assert!(r.x0 >= 0.0 && r.x0 < 0.5 && r.x1 <= 100.0 && r.x1 > 99.5, "{}: {r:?}", b.name); + assert!((r.height() - height).abs() <= height * 0.25 && r.y0 < 0.0 && r.y1 > 0.0, "{}: {r:?}", b.name); + total += pts.len(); + // Finite art on a curve and on a 2 pt path. + for (line, width) in [(vec![(0.0, 0.0), (60.0, -40.0), (140.0, 40.0), (200.0, 0.0)], 1.0), (vec![(0.0, 0.0), (2.0, 0.0)], 3.0)] { + let mut bp = vectorcraft_geom::BezPath::new(); + bp.move_to(line[0]); + if line.len() == 4 { + bp.curve_to(line[1], line[2], line[3]); + } else { + bp.line_to(line[1]); + } + let stroke = vectorcraft_doc::StrokeLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), width); + let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &bp, &stroke); + let drawn = anchors(&pieces.iter().collect::<Vec<_>>()); + assert!(!drawn.is_empty() && drawn.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{} on {line:?}", b.name); + } + } + assert!(total <= 1200, "{total} anchors"); + // Made again, the same bytes; the checksum pins them across runs and platforms. + let bytes = serde_json::to_string(&cmd::brushlib::dry_media().brushes).unwrap(); + assert_eq!(bytes, serde_json::to_string(&lib.brushes).unwrap()); + let fnv = bytes.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |h, b| (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3)); + assert_eq!(fnv, 12_859_086_488_513_909_464, "the Dry Media art changed"); + // Names of their own: no default brush's, no other built-in library's. + let defaults: Vec<&str> = vectorcraft_brush::defaults().iter().map(|b| b.name.as_str()).collect(); + let others: Vec<String> = cmd::brushlib::BUILTIN + .iter() + .filter(|b| b.id != "dry-media") + .flat_map(|b| cmd::brushlib::library(&s, b.id).unwrap().1.brushes.iter().map(|x| x.name.clone()).collect::<Vec<_>>()) + .collect(); + assert!(names.iter().all(|n| !defaults.contains(&n.as_str()) && !others.contains(n)), "{names:?}"); + + // Added and applied to a path in one undo step, which undo takes back. + let path = run(&mut s, "shape.line", json!({"x1": 10, "y1": 10, "x2": 150, "y2": 60}))["id"].as_u64().unwrap(); + let stroke_brush = |s: &Session| doc(s).node(NodeId(path)).unwrap().appearance.stroke().and_then(|st| st.brush.clone()); + let before = (undo_len(&s), brushes(&s)); + let r = run(&mut s, "brush.addFromLibrary", json!({"library": "Dry Media", "name": "Wax Crayon", "apply": true, "ids": [path]})); + assert_eq!((strs(&r["added"]), r["applied"].clone()), (vec!["Wax Crayon"], json!([path]))); + assert_eq!((undo_len(&s), stroke_brush(&s).as_deref()), (before.0 + 1, Some("Wax Crayon"))); + assert_eq!(&brush(&s, "Wax Crayon"), lib.brush("Wax Crayon").unwrap()); + run(&mut s, "edit.undo", json!({})); + assert_eq!((brushes(&s), stroke_brush(&s)), (before.1.clone(), None)); + run(&mut s, "edit.redo", json!({})); + // The rest in one more step; then nothing new to add. + let r = run(&mut s, "brush.addFromLibrary", json!({"library": "dry-media"})); + assert_eq!((strs(&r["added"]), strs(&r["existing"])), (vec!["Chalk Grain", "Graphite Pencil", "Charcoal Dust"], vec!["Wax Crayon"])); + assert_eq!(undo_len(&s), before.0 + 2); + assert_eq!( + brushes(&s), + [before.1.clone(), vec!["Wax Crayon".into(), "Chalk Grain".into(), "Graphite Pencil".into(), "Charcoal Dust".into()]].concat() + ); + let r = run(&mut s, "brush.addFromLibrary", json!({"library": "dry-media"})); + assert_eq!((strs(&r["added"]).len(), undo_len(&s)), (0, before.0 + 2)); + // Saved as a library and loaded back: the same brushes, in the document's order. + let saved = run(&mut s, "brush.saveLibrary", json!({ "names": names, "name": "Dry" })); + let b64 = saved["dataBase64"].as_str().unwrap().to_string(); + let r = run(&mut s, "brush.loadLibrary", json!({"dataBase64": b64, "name": "Dry.vectorcraft"})); + let (_, reopened) = cmd::brushlib::library(&s, r["library"].as_str().unwrap()).unwrap(); + assert_eq!(reopened.len(), lib.len()); + for b in &lib.brushes { + assert_eq!(reopened.brush(&b.name), Some(b), "{}", b.name); + } +} + +/// Bristle Brushes: one brush per tip shape, every value inside the range the brush keeps (a value +/// outside would be clamped without notice), names no other library or default brush uses; added +/// in one step, not twice, and saved as a library they reopen unchanged. +#[test] +fn the_bristle_brushes_library_covers_every_tip_shape_within_the_bristle_ranges() { + use vectorcraft_brush::{Bristle, BristleShape}; + let mut s = session(); + let (_, lib) = cmd::brushlib::library(&s, "bristle-brushes").unwrap(); + assert_eq!(lib.name, "Bristle Brushes"); + let names: Vec<String> = lib.brushes.iter().map(|b| b.name.clone()).collect(); + assert!((8..=10).contains(&names.len()), "{names:?}"); + let within = |v: f64, (lo, hi): (f64, f64)| (lo..=hi).contains(&v); + let mut shapes = vec![]; + for b in &lib.brushes { + let BrushKind::Bristle(x) = &b.kind else { panic!("{} is not a bristle brush", b.name) }; + assert!(within(x.size, Bristle::SIZE_RANGE) && within(x.length, Bristle::LENGTH_RANGE), "{}", b.name); + for v in [x.density, x.thickness, x.opacity, x.stiffness] { + assert!(within(v, Bristle::PERCENT_RANGE), "{}: {v}", b.name); + } + let mut kept = b.clone(); + kept.sanitize(); + assert_eq!(&kept, b, "sanitizing changes {}", b.name); + assert!(b.name.chars().count() <= Bristle::MAX_NAME_CHARS, "{}", b.name); + if !shapes.contains(&x.shape) { + shapes.push(x.shape); + } + } + let every = [ + BristleShape::RoundPoint, + BristleShape::FlatPoint, + BristleShape::RoundBlunt, + BristleShape::FlatBlunt, + BristleShape::RoundCurve, + BristleShape::FlatCurve, + BristleShape::RoundAngle, + BristleShape::FlatAngle, + BristleShape::RoundFan, + BristleShape::FlatFan, + ]; + assert!(every.iter().all(|x| shapes.contains(x)), "{shapes:?}"); + // Names of its own: no default brush's, no other built-in library's, none twice. + let defaults: Vec<&str> = vectorcraft_brush::defaults().iter().map(|b| b.name.as_str()).collect(); + let others: Vec<String> = cmd::brushlib::BUILTIN + .iter() + .filter(|b| b.id != "bristle-brushes") + .flat_map(|b| cmd::brushlib::library(&s, b.id).unwrap().1.brushes.iter().map(|x| x.name.clone()).collect::<Vec<_>>()) + .collect(); + for (i, n) in names.iter().enumerate() { + assert!(!defaults.contains(&n.as_str()) && !others.contains(n) && !names[..i].contains(n), "{n}"); + } + + // Added to a document in one undo step; adding them again adds nothing. + let before = (undo_len(&s), brushes(&s)); + let r = run(&mut s, "brush.addFromLibrary", json!({"library": "Bristle Brushes"})); + assert_eq!(strs(&r["added"]), names.iter().map(String::as_str).collect::<Vec<_>>()); + assert_eq!(undo_len(&s), before.0 + 1); + assert_eq!(brushes(&s), [before.1.clone(), names.clone()].concat()); + for b in &lib.brushes { + assert_eq!(&brush(&s, &b.name), b); + } + let again = undo_len(&s); + let r = run(&mut s, "brush.addFromLibrary", json!({"library": "bristle-brushes"})); + assert_eq!((strs(&r["added"]).len(), strs(&r["existing"]).len(), undo_len(&s)), (0, names.len(), again)); + // Saved as a library and loaded back: the same brushes, in the same order. + let saved = run(&mut s, "brush.saveLibrary", json!({ "names": names, "name": "Bristles" })); + let b64 = saved["dataBase64"].as_str().unwrap().to_string(); + let r = run(&mut s, "brush.loadLibrary", json!({"dataBase64": b64, "name": "Bristles.vectorcraft"})); + let (_, reopened) = cmd::brushlib::library(&s, r["library"].as_str().unwrap()).unwrap(); + assert_eq!(reopened.brushes, lib.brushes); +} + #[test] fn a_saved_library_reopens_and_its_brushes_join_another_document_in_one_step() { let dir = folder("user"); diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index fd1ac70476..1a1fcd87b5 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -253,6 +253,367 @@ fn selection_art_is_the_art_new_brush_takes() { assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "only brush.new is an undo step"); } +fn undo_steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn selected(s: &Session) -> Vec<NodeId> { + s.doc().unwrap().selection.objects.clone() +} + +/// The JSON of object `id`, as `brush.options` params take art. +fn art_json(s: &mut Session, id: NodeId) -> Value { + s.execute("brush.selectionArt", &json!({"ids": [id.0]})).unwrap()["art"].clone() +} + +/// `brush.placeArt` places a copy of an art or scatter brush's art centered where it is dropped +/// (by default on the first artboard's center), selected, in one undo step; brushes without art, +/// unknown brushes and a position that is not a number are refused. +#[test] +fn place_art_puts_a_copy_of_the_brush_art_where_it_is_dropped() { + let mut s = session(); + let r = rect(&mut s, 10.0, 20.0, 40.0, 8.0); + s.execute("brush.new", &json!({"type": "art", "name": "Bar", "ids": [r.0]})).unwrap(); + let steps = undo_steps(&s); + let id = NodeId(s.execute("brush.placeArt", &json!({"name": "Bar", "x": 100, "y": 80})).unwrap()["id"].as_u64().unwrap()); + assert_eq!(undo_steps(&s), steps + 1); + assert_eq!(selected(&s), vec![id]); + assert_ne!(id, r, "a copy, not the art the brush was made from"); + assert!(close(bounds(&s, id), Rect::new(80.0, 76.0, 120.0, 84.0), 1e-6), "{:?}", bounds(&s, id)); + // Without a position: the first artboard's center (the document is 400 × 300). + let scatter = NodeId(s.execute("brush.placeArt", &json!({"name": "Dots"})).unwrap()["id"].as_u64().unwrap()); + let c = bounds(&s, scatter).center(); + assert!((c.x - 200.0).abs() < 1e-6 && (c.y - 150.0).abs() < 1e-6, "{c:?}"); + let steps = undo_steps(&s); + for (p, msg) in [ + (json!({"name": "3 pt. Round"}), "`3 pt. Round` has no art (only scatter, art and pattern brushes do)"), + (json!({"name": "Bristle Round"}), "`Bristle Round` has no art (only scatter, art and pattern brushes do)"), + (json!({"name": "Nope"}), "no brush named `Nope`"), + ] { + let e = s.execute("brush.placeArt", &p).unwrap_err(); + assert!(e.to_string().contains(msg), "{p}: {e}"); + } + assert!(s.execute("brush.placeArt", &json!({"name": "Bar", "x": "100"})).is_err()); + assert_eq!(undo_steps(&s), steps, "a refused call adds no undo step"); +} + +/// Brush art holding an instance of a symbol whose art lies away from the symbol's origin (as +/// imported symbols can) is centered by that art, not by the box an instance has without its +/// document. +#[test] +fn placed_art_with_a_symbol_instance_is_centered_by_the_symbols_art() { + let mut s = session(); + let r = rect(&mut s, 300.0, 10.0, 100.0, 40.0); + let art = node(&s, r); + s.execute("edit.clear", &json!({"ids": [r.0]})).unwrap(); + let st = s.doc_mut().unwrap(); + let d = std::sync::Arc::make_mut(&mut st.doc); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Off".into(), art: std::sync::Arc::new(art) }); + let layer = d.layers[0].id; + let inst = d.alloc_id(); + let xf = vectorcraft_geom::Affine::translate((50.0, 50.0)); + d.insert(Some(layer), usize::MAX, Node::new(inst, NodeKind::SymbolInstance { symbol: "Off".into(), xf })).unwrap(); + let inst = inst.0; + s.execute("brush.new", &json!({"type": "art", "name": "Stamp", "ids": [inst]})).unwrap(); + let id = NodeId(s.execute("brush.placeArt", &json!({"name": "Stamp", "x": 200, "y": 150})).unwrap()["id"].as_u64().unwrap()); + let st = s.doc().unwrap(); + let b = st.doc.bounds_of(&[id], false).unwrap(); + assert!((b.center().x - 200.0).abs() < 1e-6 && (b.center().y - 150.0).abs() < 1e-6, "{b:?}"); + assert!((b.width() - 100.0).abs() < 1e-6, "{b:?}"); +} + +/// A pattern brush with side, outer corner and start tiles, the side tile with a repeat frame +/// wider than its art: → its name. +fn framed_pattern_brush(s: &mut Session) -> String { + let side = rect(s, 0.0, 0.0, 20.0, 10.0); + let corner = rect(s, 0.0, 40.0, 10.0, 10.0); + let start = rect(s, 0.0, 80.0, 6.0, 10.0); + let name = s.execute("brush.new", &json!({"type": "pattern", "name": "Rail", "ids": [side.0]})).unwrap()["name"].as_str().unwrap().to_string(); + let params = json!({ + "side": art_json(s, side), + "side_frame": Rect::new(-2.0, 0.0, 22.0, 10.0), + "outer_corner": art_json(s, corner), + "start": art_json(s, start), + }); + s.execute("brush.options", &json!({"name": name, "params": params})).unwrap(); + name +} + +/// `brush.placeArt` lays a pattern brush's tiles out left to right, each in a group named for its +/// tile, with an unpainted rectangle at the back of a tile with a repeat frame marking that frame. +#[test] +fn pattern_brushes_place_their_tiles_in_a_row() { + let mut s = session(); + let name = framed_pattern_brush(&mut s); + let id = NodeId(s.execute("brush.placeArt", &json!({"name": name, "x": 200, "y": 150})).unwrap()["id"].as_u64().unwrap()); + let placed = node(&s, id); + let tiles: Vec<Node> = placed.children().unwrap().iter().map(|c| (**c).clone()).collect(); + let names: Vec<&str> = tiles.iter().map(|t| t.name.as_deref().unwrap_or("")).collect(); + assert_eq!(names, ["Side Tile", "Outer Corner Tile", "Start Tile"]); + let boxes: Vec<Rect> = tiles.iter().map(|t| t.geometric_bounds().unwrap()).collect(); + assert!(boxes.windows(2).all(|w| (w[1].x0 - w[0].x1 - 10.0).abs() < 1e-6), "10 pt apart, left to right: {boxes:?}"); + // The side tile: the frame's rectangle, unpainted, behind the art. + let side = tiles[0].children().unwrap(); + assert_eq!(side.len(), 2); + let marker = &side[0]; + assert!(marker.appearance.items.iter().all(|i| match i { + vectorcraft_doc::AppearanceItem::Fill(f) => f.paint.is_none(), + vectorcraft_doc::AppearanceItem::Stroke(st) => st.paint.is_none(), + })); + let frame = marker.geometric_bounds().unwrap(); + assert!((frame.width() - 24.0).abs() < 1e-6 && (frame.height() - 10.0).abs() < 1e-6, "{frame:?}"); + assert_eq!(tiles[1].children().unwrap().len(), 1, "no frame, no rectangle"); +} + +/// `brush.replaceArt` reads the tiles `brush.placeArt` places back tile by tile, frames included: +/// every tile and the frame keep their sizes, and the frame keeps its place around the art. +#[test] +fn placed_pattern_tiles_go_back_into_the_brush_tile_by_tile() { + let mut s = session(); + let name = framed_pattern_brush(&mut s); + let before = s.execute("brush.get", &json!({"name": name})).unwrap(); + let id = NodeId(s.execute("brush.placeArt", &json!({"name": name, "x": 200, "y": 150})).unwrap()["id"].as_u64().unwrap()); + let steps = undo_steps(&s); + s.execute("brush.replaceArt", &json!({"name": name, "ids": [id.0]})).unwrap(); + assert_eq!(undo_steps(&s), steps + 1); + let after = s.execute("brush.get", &json!({"name": name})).unwrap(); + let size = |v: &Value| { + let n: Node = serde_json::from_value(v.clone()).unwrap(); + let b = n.geometric_bounds().unwrap(); + (b.width(), b.height()) + }; + for key in ["side", "outer_corner", "start"] { + let (a, b) = (size(&before[key]), size(&after[key])); + assert!((a.0 - b.0).abs() < 1e-6 && (a.1 - b.1).abs() < 1e-6, "{key}: {a:?} → {b:?}"); + } + assert!(after.get("end").is_none_or(Value::is_null) && after.get("inner_corner").is_none_or(Value::is_null)); + let frame: Rect = serde_json::from_value(after["side_frame"].clone()).unwrap(); + let art: Node = serde_json::from_value(after["side"].clone()).unwrap(); + let art = art.geometric_bounds().unwrap(); + assert!((frame.width() - 24.0).abs() < 1e-6 && (art.x0 - frame.x0 - 2.0).abs() < 1e-6, "{frame:?} around {art:?}"); + assert!(after["outer_corner_frame"].is_null() || after.get("outer_corner_frame").is_none()); +} + +/// Art that is not the tiles `brush.placeArt` places becomes a pattern brush's side tile, and the +/// other tiles stay; one tile group alone replaces only that tile. +#[test] +fn other_art_replaces_the_side_tile_of_a_pattern_brush() { + let mut s = session(); + let name = framed_pattern_brush(&mut s); + let before = s.execute("brush.get", &json!({"name": name})).unwrap(); + let r = rect(&mut s, 100.0, 100.0, 30.0, 12.0); + s.execute("brush.replaceArt", &json!({"name": name, "ids": [r.0]})).unwrap(); + let after = s.execute("brush.get", &json!({"name": name})).unwrap(); + let side: Node = serde_json::from_value(after["side"].clone()).unwrap(); + assert!(close(side.geometric_bounds().unwrap(), Rect::new(100.0, 100.0, 130.0, 112.0), 1e-6)); + assert!(after.get("side_frame").is_none_or(Value::is_null), "the old frame goes with the old art"); + assert_eq!((&after["outer_corner"], &after["start"]), (&before["outer_corner"], &before["start"])); + // One placed tile, its group dragged back alone: only the start tile changes. + let id = NodeId(s.execute("brush.placeArt", &json!({"name": name})).unwrap()["id"].as_u64().unwrap()); + let start = node(&s, id).children().unwrap()[2].clone(); + assert_eq!(start.name.as_deref(), Some("Start Tile")); + s.execute("brush.replaceArt", &json!({"name": name, "ids": [start.id.0]})).unwrap(); + let last = s.execute("brush.get", &json!({"name": name})).unwrap(); + assert_eq!((&last["side"], &last["outer_corner"]), (&after["side"], &after["outer_corner"])); + let art: Node = serde_json::from_value(last["start"].clone()).unwrap(); + assert!(close(art.geometric_bounds().unwrap(), start.geometric_bounds().unwrap(), 1e-6), "the start tile is the placed one"); + assert!(art.name.is_none(), "the tile's name stays on the canvas"); +} + +/// `brush.replaceArt` gives a brush new art in one undo step: strokes that use it redraw with it, +/// or with `applyToStrokes: false` keep the brush as it was while a copy with the new art becomes +/// the current brush. A brush no stroke uses changes in place either way. +#[test] +fn replace_art_applies_to_strokes_or_leaves_them_on_the_old_brush() { + let mut s = session(); + let r = rect(&mut s, 10.0, 200.0, 40.0, 8.0); + s.execute("brush.new", &json!({"type": "art", "name": "Bar", "ids": [r.0]})).unwrap(); + let path = line(&mut s); + s.execute("brush.apply", &json!({"name": "Bar", "ids": [path.0]})).unwrap(); + let thin = brushed_bounds(&s, path).height(); + // A path painted with a brush made from the taller art: what the stroke should draw. + let tall = rect(&mut s, 10.0, 220.0, 40.0, 20.0); + s.execute("brush.new", &json!({"type": "art", "name": "Tall", "ids": [tall.0]})).unwrap(); + let reference = line(&mut s); + s.execute("brush.apply", &json!({"name": "Tall", "ids": [reference.0]})).unwrap(); + let want = brushed_bounds(&s, reference).height(); + assert!(want > thin * 2.0, "{want} against {thin}"); + // Apply to Strokes: the stroke redraws with the taller art. + let steps = undo_steps(&s); + let r = s.execute("brush.replaceArt", &json!({"name": "Bar", "ids": [tall.0]})).unwrap(); + assert_eq!(r["name"], "Bar"); + assert_eq!(undo_steps(&s), steps + 1); + assert!((brushed_bounds(&s, path).height() - want).abs() < 1e-6); + s.execute("edit.undo", &json!({})).unwrap(); + assert!((brushed_bounds(&s, path).height() - thin).abs() < 1e-9, "undo puts the old art back"); + s.execute("edit.redo", &json!({})).unwrap(); + // Leave Strokes: the stroke keeps Bar as it was; Bar copy has the new art, after Bar, current. + let short = rect(&mut s, 10.0, 260.0, 40.0, 4.0); + let bar = s.execute("brush.get", &json!({"name": "Bar"})).unwrap(); + let r = s.execute("brush.replaceArt", &json!({"name": "Bar", "ids": [short.0], "applyToStrokes": false})).unwrap(); + assert_eq!(r["name"], "Bar copy"); + assert_eq!(brush_of(&s, path).as_deref(), Some("Bar")); + assert_eq!(s.execute("brush.get", &json!({"name": "Bar"})).unwrap(), bar); + assert!((brushed_bounds(&s, path).height() - want).abs() < 1e-6); + let copy: Node = serde_json::from_value(s.execute("brush.get", &json!({"name": "Bar copy"})).unwrap()["art"].clone()).unwrap(); + assert!((copy.geometric_bounds().unwrap().height() - 4.0).abs() < 1e-6); + let list = s.execute("brush.list", &json!({})).unwrap(); + assert_eq!(list["current"], "Bar copy"); + let names: Vec<&str> = list["brushes"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap()).collect(); + let at = names.iter().position(|n| *n == "Bar").unwrap(); + assert_eq!(names.get(at + 1), Some(&"Bar copy")); + // No stroke uses Bar copy: its art changes in place, with or without applying. + s.execute("brush.replaceArt", &json!({"name": "Bar copy", "ids": [tall.0], "applyToStrokes": false})).unwrap(); + assert!(s.execute("brush.get", &json!({"name": "Bar copy 2"})).is_err()); +} + +/// `brush.replaceArt` refuses a brush without art, an unknown brush, an empty selection, art with no +/// width and an `applyToStrokes` that is not a boolean, and changes nothing then. +#[test] +fn replace_art_refuses_what_it_cannot_take() { + let mut s = session(); + let r = rect(&mut s, 10.0, 20.0, 40.0, 8.0); + let flat = s.execute("shape.line", &json!({"x1": 50, "y1": 100, "x2": 50, "y2": 160})).unwrap()["id"].as_u64().unwrap(); + let lib = s.execute("brush.list", &json!({})).unwrap(); + let steps = undo_steps(&s); + for (p, msg) in [ + (json!({"name": "3 pt. Round", "ids": [r.0]}), "`3 pt. Round` has no art (only scatter, art and pattern brushes do)"), + (json!({"name": "Bristle Round", "ids": [r.0]}), "`Bristle Round` has no art (only scatter, art and pattern brushes do)"), + (json!({"name": "Nope", "ids": [r.0]}), "no brush named `Nope`"), + (json!({"name": "Arrow", "ids": [flat]}), "the selected art has no width"), + (json!({"name": "Chain", "ids": [flat]}), "the selected art has no width"), + (json!({"name": "Arrow", "ids": [r.0], "applyToStrokes": "no"}), "`applyToStrokes` must be true or false"), + ] { + let e = s.execute("brush.replaceArt", &p).unwrap_err(); + assert!(e.to_string().contains(msg), "{p}: {e}"); + } + s.select(|_, sel| sel.clear()).unwrap(); + let e = s.execute("brush.replaceArt", &json!({"name": "Arrow"})).unwrap_err(); + assert!(e.to_string().contains("nothing selected"), "{e}"); + assert_eq!(undo_steps(&s), steps); + assert_eq!(s.execute("brush.list", &json!({})).unwrap(), lib); +} + +/// An instance of a symbol whose art has no width is art with no width for `brush.new` and +/// `brush.replaceArt`, although an instance's box without its document has width. +#[test] +fn a_symbol_whose_art_has_no_width_makes_no_brush_art() { + let mut s = session(); + let flat = NodeId(s.execute("shape.line", &json!({"x1": 50, "y1": 100, "x2": 50, "y2": 160})).unwrap()["id"].as_u64().unwrap()); + let art = node(&s, flat); + s.execute("edit.clear", &json!({"ids": [flat.0]})).unwrap(); + let st = s.doc_mut().unwrap(); + let d = std::sync::Arc::make_mut(&mut st.doc); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Flat".into(), art: std::sync::Arc::new(art) }); + let layer = d.layers[0].id; + let inst = d.alloc_id(); + d.insert(Some(layer), usize::MAX, Node::new(inst, NodeKind::SymbolInstance { symbol: "Flat".into(), xf: vectorcraft_geom::Affine::IDENTITY })) + .unwrap(); + assert!(node(&s, inst).geometric_bounds().is_some_and(|b| b.width() > 1.0), "the box an instance has without its document"); + for (cmd, p) in [("brush.new", json!({"type": "art", "ids": [inst.0]})), ("brush.replaceArt", json!({"name": "Arrow", "ids": [inst.0]}))] { + let e = s.execute(cmd, &p).unwrap_err(); + assert!(e.to_string().contains("the selected art has no width"), "{cmd}: {e}"); + } +} + +/// `brush.replaceArt` checks only the art it is given: a tile the pattern brush already has that +/// has no width does not stop another tile from being replaced. +#[test] +fn replace_art_checks_only_the_tiles_it_is_given() { + let mut s = session(); + let flat = NodeId(s.execute("shape.line", &json!({"x1": 50, "y1": 100, "x2": 50, "y2": 160})).unwrap()["id"].as_u64().unwrap()); + let end = art_json(&mut s, flat); + s.execute("brush.options", &json!({"name": "Chain", "params": {"end": end}})).unwrap(); + let r = rect(&mut s, 10.0, 20.0, 40.0, 8.0); + s.execute("brush.replaceArt", &json!({"name": "Chain", "ids": [r.0]})).unwrap(); + let side: Node = serde_json::from_value(s.execute("brush.get", &json!({"name": "Chain"})).unwrap()["side"].clone()).unwrap(); + assert!(close(side.geometric_bounds().unwrap(), bounds(&s, r), 1e-6)); +} + +/// Tile `key` (`side`, `start`…) of pattern brush `name`. +fn tile_art(s: &mut Session, name: &str, key: &str) -> Node { + serde_json::from_value(s.execute("brush.get", &json!({"name": name})).unwrap()[key].clone()).unwrap() +} + +/// A pattern brush tile placed with `brush.placeArt` and given back with `brush.replaceArt` is the +/// art it was, not that art inside the tile's group, however many times it goes out and back. +#[test] +fn pattern_tiles_go_out_and_back_without_gaining_a_group() { + let mut s = session(); + let name = framed_pattern_brush(&mut s); + let size = |n: &Node| { + let b = n.geometric_bounds().unwrap(); + (b.width(), b.height()) + }; + let first = tile_art(&mut s, &name, "side"); + assert!(matches!(first.kind, NodeKind::Path { .. }), "{:?}", first.kind); + for round in 1..=2 { + let id = s.execute("brush.placeArt", &json!({"name": name})).unwrap()["id"].as_u64().unwrap(); + s.execute("brush.replaceArt", &json!({"name": name, "ids": [id]})).unwrap(); + let side = tile_art(&mut s, &name, "side"); + assert!(matches!(side.kind, NodeKind::Path { .. }), "round {round}: {:?}", side.kind); + let (a, b) = (size(&first), size(&side)); + assert!((a.0 - b.0).abs() < 1e-6 && (a.1 - b.1).abs() < 1e-6, "round {round}: {a:?} → {b:?}"); + } +} + +/// A tile group whose art was deleted, leaving only the rectangle that marks its frame, is art with +/// no width: the brush keeps its tile. +#[test] +fn a_tile_group_holding_only_its_frame_is_refused() { + let mut s = session(); + let name = framed_pattern_brush(&mut s); + let before = s.execute("brush.get", &json!({"name": name})).unwrap(); + let id = NodeId(s.execute("brush.placeArt", &json!({"name": name})).unwrap()["id"].as_u64().unwrap()); + let side = node(&s, id).children().unwrap()[0].clone(); + assert_eq!(side.name.as_deref(), Some("Side Tile")); + let art = side.children().unwrap()[1].id; + s.execute("edit.clear", &json!({"ids": [art.0]})).unwrap(); + let steps = undo_steps(&s); + let e = s.execute("brush.replaceArt", &json!({"name": name, "ids": [side.id.0]})).unwrap_err(); + assert!(e.to_string().contains("the selected art has no width"), "{e}"); + assert_eq!(undo_steps(&s), steps); + assert_eq!(s.execute("brush.get", &json!({"name": name})).unwrap(), before); +} + +/// Two groups named for the same tile: the frontmost one is the tile's art. +#[test] +fn the_frontmost_group_named_for_a_tile_is_that_tile() { + let mut s = session(); + let name = framed_pattern_brush(&mut s); + let back = rect(&mut s, 10.0, 10.0, 20.0, 10.0); + let front = rect(&mut s, 10.0, 40.0, 30.0, 10.0); + let (back, front) = (node(&s, back), node(&s, front)); + s.execute("edit.clear", &json!({"ids": [back.id.0, front.id.0]})).unwrap(); + let st = s.doc_mut().unwrap(); + let d = std::sync::Arc::make_mut(&mut st.doc); + let tile = |d: &mut Document, n: Node| { + let mut g = Node::group(d.alloc_id(), vec![std::sync::Arc::new(n)]); + g.name = Some("Start Tile".into()); + std::sync::Arc::new(g) + }; + let tiles = vec![tile(d, back), tile(d, front)]; + let both = Node::group(d.alloc_id(), tiles); + let both_id = both.id; + let layer = d.layers[0].id; + d.insert(Some(layer), usize::MAX, both).unwrap(); + s.execute("brush.replaceArt", &json!({"name": name, "ids": [both_id.0]})).unwrap(); + let start = tile_art(&mut s, &name, "start"); + assert!((start.geometric_bounds().unwrap().width() - 30.0).abs() < 1e-6, "{:?}", start.geometric_bounds()); +} + +/// Type is art for `brush.replaceArt` as it is for `brush.new`: taken as it is. +#[test] +fn replace_art_takes_type_as_brush_new_does() { + let mut s = session(); + let t = s.execute("text.create", &json!({"x": 20, "y": 60, "text": "Hi", "size": 24})).unwrap()["id"].as_u64().unwrap(); + let want = art_json(&mut s, NodeId(t)); + s.execute("brush.replaceArt", &json!({"name": "Arrow", "ids": [t]})).unwrap(); + assert_eq!(s.execute("brush.get", &json!({"name": "Arrow"})).unwrap()["art"], want); + let made = s.execute("brush.new", &json!({"type": "art", "ids": [t]})).unwrap()["name"].as_str().unwrap().to_string(); + assert_eq!(s.execute("brush.get", &json!({"name": made})).unwrap()["art"], want); +} + #[test] fn brush_options_rename_duplicate_and_delete_update_strokes() { let mut s = session(); diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 3ed51e3c38..6eeace1073 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -793,8 +793,9 @@ fn shape_builder_applies_a_merge_before_what_comes_next() { let labels: Vec<&str> = s.doc().unwrap().history.undo.iter().rev().take(2).map(|e| e.label.as_str()).collect(); assert_eq!(labels, ["Move", "Shape Builder"]); }), - // The proof views redraw every document (a new revision); they are left off, as the - // other tests of the process-wide proof view expect. + // The proof views apply the merge first by command id (`WAIT_FOR_TOOL_EDIT`), also when + // the view does not change and no document gets a new revision. They are left off, as + // the other tests of the process-wide proof view expect. ("Separations Preview", |s, _, _| { s.execute("view.separationsPreview", &json!({"on": false})).unwrap(); }), @@ -807,6 +808,13 @@ fn shape_builder_applies_a_merge_before_what_comes_next() { ("Proof Setup", |s, _, _| { s.execute("view.proofSetup", &json!({})).unwrap(); }), + ("a proof view that changes", |s, _, _| { + let _v = crate::tests_colormgmt::DefaultView::new(); + s.execute("view.proofColors", &json!({"on": true})).unwrap(); + let on = s.doc().unwrap().revision; + s.execute("view.proofColors", &json!({"on": false})).unwrap(); + assert!(s.doc().unwrap().revision > on, "the view changes and the documents get new revisions"); + }), ("a preference", |s, _, _| { let every = s.prefs.gridline_every; s.execute("prefs.set", &json!({"key": "gridlineEvery", "value": every + 10.0})).unwrap(); @@ -832,7 +840,7 @@ fn shape_builder_applies_a_merge_before_what_comes_next() { }), ]; let _proof = crate::tests_colormgmt::GLOBAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - let dir = vectorcraft_testkit::temp_dir("shape-builder-merge-first"); + let dir = vectorcraft_testkit::TempDir::new("shape-builder-merge-first"); for (what, then) in next { let mut s = session(); if what == "Select All Instances" { @@ -2945,6 +2953,120 @@ fn merged_live_paint_groups_keep_the_bottom_groups_gap_options() { assert_eq!(merged(off, json!({"detect": false})), GapOptions { detect: false, size: GapSize::Custom(12.0), color: blue }); } +#[test] +fn live_paint_bucket_drag_fills_multiple_faces() { + let mut s = session(); + let g = live(&mut s); + let v = ViewInfo::default(); + s.select_tool("livePaintBucket", v).unwrap(); + s.paint.fill = Paint::solid(Color::rgb(0.0, 1.0, 1.0)); + let before = s.doc().unwrap().doc.clone(); + s.pointer(&PointerEvent::new(PointerKind::Down, 25.0, 50.0), v).unwrap(); + // Skip the middle face between pointer events, as can happen in a fast drag. + s.pointer(&PointerEvent::new(PointerKind::Drag, 125.0, 50.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 125.0, 50.0), v).unwrap(); + let gn = node(&s, g); + for x in [25.0, 75.0, 125.0] { + let f = vectorcraft_tools::builder::face_at(&gn, Point::new(x, 50.0)).unwrap(); + assert_eq!(f.appearance.fill_paint(), s.paint.fill, "dragged face at {x}"); + } + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, before, "one Undo restores every face"); + s.pointer(&PointerEvent::new(PointerKind::Move, 125.0, 50.0), v).unwrap(); + assert!(!s.overlays(v).is_empty(), "hover still highlights a face"); + assert_eq!(s.doc().unwrap().doc, before, "hover does not paint"); +} + +#[test] +fn live_paint_bucket_drag_crosses_thin_grid_cells_and_can_cancel() { + for (deferred, cancel) in [(false, false), (false, true), (true, false)] { + let mut s = session(); + let ids = [rect(&mut s, 0.0, 0.0, 150.0, 100.0), line(&mut s, (50.0, 0.0), (50.0, 100.0)), line(&mut s, (50.25, 0.0), (50.25, 100.0))]; + s.execute("select.set", &json!({"ids": ids.map(|i| i.0)})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let v = ViewInfo::default(); + s.select_tool("livePaintBucket", v).unwrap(); + s.prefs.real_time_drawing = !deferred; + s.paint.fill = Paint::solid(Color::rgb(0.0, 1.0, 1.0)); + s.pointer(&PointerEvent::new(PointerKind::Down, 25.0, 50.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 125.0, 50.0), v).unwrap(); + if cancel { + assert!(s.tool_busy()); + assert!(s.tool_claims_key(ToolKey::Escape, v)); + s.tool_key(ToolKey::Escape, Mods::default(), v).unwrap(); + assert!(!s.tool_busy()); + assert!(!s.tool_claims_key(ToolKey::Escape, v)); + } + s.pointer(&PointerEvent::new(PointerKind::Up, 125.0, 50.0), v).unwrap(); + if !cancel { + let g = s.doc().unwrap().selection.objects[0]; + let gn = node(&s, g); + for x in [25.0, 50.125, 125.0] { + let f = vectorcraft_tools::builder::face_at(&gn, Point::new(x, 50.0)).unwrap(); + assert_eq!(f.appearance.fill_paint(), s.paint.fill, "deferred={deferred}, x={x}"); + } + s.execute("edit.undo", &json!({})).unwrap(); + } + assert!(s.doc().unwrap().doc == before, "deferred={deferred}, cancel={cancel}: original paths and selection art must be restored"); + } +} + +#[test] +fn live_paint_bucket_long_drag_keeps_late_turns_and_release_as_one_undo() { + for cancel in [false, true] { + let mut s = session(); + let ids = [rect(&mut s, 0.0, 0.0, 150.0, 100.0), line(&mut s, (50.0, 0.0), (50.0, 100.0)), line(&mut s, (100.0, 0.0), (100.0, 100.0))]; + s.execute("select.set", &json!({"ids": ids.map(|id| id.0)})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let v = ViewInfo::default(); + s.select_tool("livePaintBucket", v).unwrap(); + s.prefs.real_time_drawing = false; + s.paint.fill = Paint::solid(Color::rgb(0.0, 1.0, 1.0)); + s.pointer(&PointerEvent::new(PointerKind::Down, 25.0, 50.0), v).unwrap(); + for i in 1..4096 { + s.pointer(&PointerEvent::new(PointerKind::Drag, 25.0 + f64::from(i) / 10000.0, 50.0), v).unwrap(); + } + // Turn around the middle face after the chunk limit, then enter the right face on Up. + for (x, y) in [(25.0, 150.0), (125.0, 150.0)] { + s.pointer(&PointerEvent::new(PointerKind::Drag, x, y), v).unwrap(); + } + if cancel { + s.tool_key(ToolKey::Escape, Mods::default(), v).unwrap(); + } + s.pointer(&PointerEvent::new(PointerKind::Up, 125.0, 50.0), v).unwrap(); + if !cancel { + let g = s.doc().unwrap().selection.objects[0]; + let gn = node(&s, g); + for x in [25.0, 125.0] { + assert_eq!(vectorcraft_tools::builder::face_at(&gn, Point::new(x, 50.0)).unwrap().appearance.fill_paint(), s.paint.fill); + } + assert_eq!(vectorcraft_tools::builder::face_at(&gn, Point::new(75.0, 50.0)).unwrap().appearance.fill_paint(), Paint::solid(Color::WHITE)); + s.execute("edit.undo", &json!({})).unwrap(); + } + assert!(s.doc().unwrap().doc == before, "long drag is one cancellable undo step"); + } +} + +#[test] +fn live_paint_bucket_drag_rejects_invalid_points_atomically() { + let mut s = session(); + let g = live(&mut s); + let before = s.doc().unwrap().doc.clone(); + for points in + [json!([]), json!([[26.0, 50.0]]), json!([[25.0, 50.0], [null, 0]]), json!([[25.0, 50.0], [1e30, 0]]), json!(vec![[25.0, 50.0]; 4097])] + { + assert!(s.execute("livePaint.fill", &json!({"group": g.0, "point": [25.0, 50.0], "points": points})).is_err()); + assert_eq!(s.doc().unwrap().doc, before); + } + for continuation in [json!(null), json!([[[26.0, 50.0], [125.0, 50.0]]]), json!([vec![[25.0, 50.0]; 4097]])] { + assert!( + s.execute("livePaint.fill", &json!({"group": g.0, "point": [25.0, 50.0], "points": [[25.0, 50.0]], "continuation": continuation})) + .is_err() + ); + assert_eq!(s.doc().unwrap().doc, before); + } +} + #[test] fn live_paint_bucket_tool_fills_face() { let mut s = session(); @@ -3666,6 +3788,103 @@ fn a_trace_run_needs_the_library_colours_it_traced_with() { assert!(!run.current(&s), "{name} changed"); } +/// `image_doc`'s image with its disc 20 px to the left: the same size, other pixels. +fn moved_disc_png() -> Vec<u8> { + vectorcraft_trace::Raster::from_fn(100, 100, |x, y| { + let (dx, dy) = (x as f64 + 0.5 - 30.0, y as f64 + 0.5 - 50.0); + if dx * dx + dy * dy <= 900.0 { [0, 0, 0, 255] } else { [255, 255, 255, 255] } + }) + .encode_png() +} + +/// Puts `bytes` under the image key `key`, or takes the key's image data away (`None`). +fn set_image_data(s: &mut Session, key: &str, bytes: Option<Vec<u8>>) { + s.edit("image data", |d, _| { + match bytes { + Some(b) => d.images.insert(key.into(), ImageBlob::new("image/png", b)), + None => d.images.remove(key), + }; + Ok(()) + }) + .unwrap(); +} + +/// The middle of the first traced path of the Image Trace object the reply `r` names, in x. +fn traced_center_x(s: &Session, r: &Value) -> f64 { + outline(&traced_paths(&node(s, NodeId(r["id"].as_u64().unwrap())))[0]).0.bounds().unwrap().center().x +} + +/// A trace made away from its command no longer applies once the pixels under its image's key +/// change, though the object, its image record and the settings stay as they were; both commands +/// then trace the pixels there now. The same bytes in another allocation still apply. +#[test] +fn a_trace_run_needs_the_pixels_it_traced() { + let p = json!({"params": {"ignoreWhite": true}}); + for command in ["imageTrace.make", "imageTrace.makeAndExpand"] { + let mut s = session(); + image_doc(&mut s); + let run = cmd::TraceRun::prepare(&s, command, &p).unwrap(); + let traced = run.run(&|_, _| true).unwrap(); + // The same bytes, allocated anew: still current. + let same = s.doc().unwrap().doc.images["img1"].bytes.to_vec(); + set_image_data(&mut s, "img1", Some(same)); + assert!(run.current(&s), "{command}: equal bytes"); + // Other pixels under the same key: no longer current, and the hand-off is dropped. + set_image_data(&mut s, "img1", Some(moved_disc_png())); + assert!(!run.current(&s), "{command}: other pixels"); + traced.hand_in(&mut s); + let r = s.execute(command, run.params()).unwrap(); + assert!(s.trace_hand_off.is_none(), "{command}: dropped"); + // The disc is now at image x 30, which the ×2 placement at 50 puts at 110. + let x = traced_center_x(&s, &r); + assert!((x - 110.0).abs() < 1.5, "{command}: traced the pixels there now, at {x}"); + } +} + +/// Image data that is missing or empty: a run made before it went no longer applies, the run's +/// command gives the error it gives without a run, and nothing panics. +#[test] +fn a_trace_run_of_missing_or_empty_image_data() { + let p = json!({"params": {"ignoreWhite": true}}); + let mut s = session(); + image_doc(&mut s); + let run = cmd::TraceRun::prepare(&s, "imageTrace.make", &p).unwrap(); + let traced = run.run(&|_, _| true).unwrap(); + set_image_data(&mut s, "img1", None); + assert!(!run.current(&s), "missing"); + traced.hand_in(&mut s); + let e = s.execute(run.command(), run.params()).unwrap_err().to_string(); + assert!(e.contains("image data `img1` is missing"), "{e}"); + set_image_data(&mut s, "img1", Some(vec![])); + assert!(!run.current(&s), "empty"); + let empty = cmd::TraceRun::prepare(&s, "imageTrace.make", &p).unwrap(); + assert!(empty.current(&s), "two empty blobs are equal"); + assert!(matches!(empty.run(&|_, _| true), Err(EngineError::Other(_)))); + assert!(matches!(s.execute(run.command(), run.params()), Err(EngineError::Other(_)))); +} + +/// Tracing an Image Trace object again follows the same rule: once the pixels of the image it +/// holds change, a run made before no longer applies, and the command traces the pixels there now. +#[test] +fn a_trace_run_of_an_image_trace_object_needs_its_pixels() { + let p = json!({"params": {"ignoreWhite": true}}); + let mut s = session(); + image_doc(&mut s); + let g = s.execute("imageTrace.make", &p).unwrap()["id"].as_u64().unwrap(); + let again = json!({"id": g, "params": {"ignoreWhite": true}}); + let run = cmd::TraceRun::prepare(&s, "imageTrace.make", &again).unwrap(); + assert_eq!(run.target(), NodeId(g)); + let traced = run.run(&|_, _| true).unwrap(); + assert!(run.current(&s)); + set_image_data(&mut s, "img1", Some(moved_disc_png())); + assert!(!run.current(&s)); + traced.hand_in(&mut s); + let r = s.execute(run.command(), run.params()).unwrap(); + assert!(s.trace_hand_off.is_none(), "dropped"); + let x = traced_center_x(&s, &r); + assert!((x - 110.0).abs() < 1.5, "traced the pixels there now, at {x}"); +} + /// Shapes: the disc of the test image comes out as a live ellipse where the image lies, the same /// circle as its traced path; without the option it is a plain path. #[test] diff --git a/crates/engine/src/tests/cancel.rs b/crates/engine/src/tests/cancel.rs index 8237707a10..9a044ead89 100644 --- a/crates/engine/src/tests/cancel.rs +++ b/crates/engine/src/tests/cancel.rs @@ -22,7 +22,8 @@ fn revision(s: &Session) -> u64 { #[test] fn a_pdf_export_cancelled_between_pages_stops_writes_nothing_and_changes_nothing() { - let path = vectorcraft_testkit::temp_dir("cancel-pdf").join("out.pdf"); + let dir = vectorcraft_testkit::TempDir::new("cancel-pdf"); + let path = dir.join("out.pdf"); std::fs::remove_file(&path).ok(); let mut s = session(5); let before = (revision(&s), s.doc().unwrap().history.undo.len()); @@ -66,7 +67,7 @@ fn a_cancelled_flattening_export_stops_before_the_pages() { #[test] fn raster_exports_and_svg_stop_when_cancelled_too() { - let dir = vectorcraft_testkit::temp_dir("cancel-formats"); + let dir = vectorcraft_testkit::TempDir::new("cancel-formats"); let mut s = session(3); let token = CancelToken::new(); token.cancel(); diff --git a/crates/engine/src/tests/caret_kerning.rs b/crates/engine/src/tests/caret_kerning.rs new file mode 100644 index 0000000000..dca3519cb1 --- /dev/null +++ b/crates/engine/src/tests/caret_kerning.rs @@ -0,0 +1,183 @@ +//! Kerning at the Type tool's caret at the start of a line (#5111): with no character on the line +//! before the caret, `type.step`, `type.resetTracking` and the Kerning field set the space before +//! the character after it (`kerningBefore`), as one undo step, and the character moves. + +use serde_json::json; +use vectorcraft_doc::{CharStyle, NodeId, NodeKind, TextObject}; +use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; + +use crate::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s +} + +fn text(s: &mut Session, t: &str) -> NodeId { + NodeId(s.execute("text.create", &json!({"x": 100, "y": 100, "text": t, "size": 20})).unwrap()["id"].as_u64().unwrap()) +} + +fn obj(s: &Session, id: NodeId) -> TextObject { + let Some(NodeKind::Text(t)) = s.doc().unwrap().doc.node(id).map(|n| &n.kind) else { panic!("not text") }; + (**t).clone() +} + +fn style_at(s: &Session, id: NodeId, byte: usize) -> CharStyle { + vectorcraft_text::edit::style_at(&obj(s, id).runs, byte + 1) +} + +/// Where glyph `byte` is drawn along its line, in text space. +fn drawn_x(s: &Session, id: NodeId, byte: usize) -> f64 { + let l = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &obj(s, id)); + l.glyphs.iter().find(|g| g.byte == byte).unwrap().xf.as_coeffs()[4] +} + +/// The Type tool editing `id` (made by [`text`]) with its caret at byte `caret`. +fn caret_in(s: &mut Session, id: NodeId, caret: usize) -> ViewInfo { + let v = ViewInfo::default(); + s.select_tool("type", v).unwrap(); + for k in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(k, 102.0, 95.0), v).unwrap(); + } + assert_eq!(s.tool_options()["editing"], json!(id.0), "editing the text"); + s.set_tool_option("select", &json!({"start": caret, "end": caret})); + v +} + +fn step_at(s: &mut Session, id: NodeId, caret: usize, by: i32) -> serde_json::Value { + s.execute("type.step", &json!({"id": id.0, "start": caret, "end": caret, "attribute": "kerning", "by": by})).unwrap() +} + +#[test] +fn a_step_at_the_start_of_the_text_moves_the_first_character() { + let mut s = session(); + let id = text(&mut s, "AV"); + let inc = s.prefs.tracking_increment; + let (a, v) = (drawn_x(&s, id, 0), drawn_x(&s, id, 1)); + assert_eq!(step_at(&mut s, id, 0, 1)["ids"], json!([id.0])); + let st = style_at(&s, id, 0); + assert_eq!((st.kerning_before, st.kerning), (inc, None), "the space before A, not after it"); + // A step of `inc` thousandths of the 20 pt em moves both letters along the line. + let moved = inc / 1000.0 * 20.0; + assert!((drawn_x(&s, id, 0) - a - moved).abs() < 1e-6 && (drawn_x(&s, id, 1) - v - moved).abs() < 1e-6); + // A negative step goes back towards the line's start, past it. + step_at(&mut s, id, 0, -3); + assert_eq!(style_at(&s, id, 0).kerning_before, -2.0 * inc); + assert!((drawn_x(&s, id, 0) - a + 2.0 * moved).abs() < 1e-6); + // One undo step each. + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(style_at(&s, id, 0).kerning_before, inc); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(style_at(&s, id, 0).kerning_before, 0.0); + assert!((drawn_x(&s, id, 0) - a).abs() < 1e-6); +} + +#[test] +fn inside_a_line_a_step_still_kerns_the_character_before_the_caret() { + let mut s = session(); + let id = text(&mut s, "AV"); + step_at(&mut s, id, 1, 1); + let (a, v) = (style_at(&s, id, 0), style_at(&s, id, 1)); + assert_eq!((a.kerning_before, v.kerning_before, v.kerning), (0.0, 0.0, None)); + assert!(a.kerning.is_some(), "the pair after A"); +} + +#[test] +fn the_start_of_a_paragraph_or_after_a_forced_line_break_kerns_the_character_after_it() { + let mut s = session(); + let inc = s.prefs.tracking_increment; + let id = text(&mut s, "One\nTwo"); + let t = drawn_x(&s, id, 4); + step_at(&mut s, id, 4, 1); + assert_eq!((style_at(&s, id, 3).kerning, style_at(&s, id, 4).kerning_before), (None, inc), "not the line break's kerning"); + assert!(drawn_x(&s, id, 4) > t, "T moves"); + let forced = text(&mut s, "One\u{2028}Two"); + let after = "One\u{2028}".len(); + step_at(&mut s, forced, after, 1); + assert_eq!((style_at(&s, forced, 3).kerning, style_at(&s, forced, after).kerning_before), (None, inc)); +} + +#[test] +fn an_empty_line_has_nothing_to_kern() { + let mut s = session(); + let id = text(&mut s, "One\n\nTwo"); + let before = obj(&s, id).runs; + assert_eq!(step_at(&mut s, id, 4, 1)["ids"], json!([])); + assert_eq!(obj(&s, id).runs, before); + // Nor does the end of text after a line break. + let end = text(&mut s, "One\n"); + assert_eq!(step_at(&mut s, end, 4, 1)["ids"], json!([])); +} + +#[test] +fn reset_at_the_start_of_a_line_clears_the_space_before_and_a_full_reset_clears_it_too() { + let mut s = session(); + let id = text(&mut s, "AV"); + s.execute("text.setRangeStyle", &json!({"id": id.0, "kerning": -40, "tracking": 100})).unwrap(); + step_at(&mut s, id, 0, 2); + assert_ne!(style_at(&s, id, 0).kerning_before, 0.0); + // At the caret before A only the space before A goes; A keeps its kerning after it. + caret_in(&mut s, id, 0); + s.execute("type.resetTracking", &json!({})).unwrap(); + let st = style_at(&s, id, 0); + assert_eq!((st.kerning_before, st.kerning, st.tracking), (0.0, Some(-40.0), 100.0)); + step_at(&mut s, id, 0, 2); + s.execute("type.resetTracking", &json!({"ids": [id.0]})).unwrap(); + let st = style_at(&s, id, 0); + assert_eq!((st.kerning_before, st.kerning, st.tracking), (0.0, None, 0.0), "all manual kerning"); +} + +#[test] +fn set_range_style_sets_the_space_before() { + let mut s = session(); + let id = text(&mut s, "AV"); + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 0, "end": 1, "kerningBefore": 50})).unwrap(); + assert_eq!(style_at(&s, id, 0).kerning_before, 50.0); + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 0, "end": 1, "kerningBefore": 20000})).unwrap(); + assert_eq!(style_at(&s, id, 0).kerning_before, 10000.0, "kerning's limits"); + assert!(s.execute("text.setRangeStyle", &json!({"id": id.0, "kerningBefore": "auto"})).is_err()); +} + +/// The Type tool: Alt+← at the caret before the first character kerns it, and Alt+→ back. +#[test] +fn alt_arrows_at_the_caret_before_the_first_character_kern_it() { + let mut s = session(); + let inc = s.prefs.tracking_increment; + let id = text(&mut s, "Hello"); + let v = caret_in(&mut s, id, 0); + let alt = Mods { alt: true, ..Mods::default() }; + s.tool_key(ToolKey::Left, alt, v).unwrap(); + assert_eq!((style_at(&s, id, 0).kerning_before, style_at(&s, id, 0).kerning), (-inc, None)); + s.tool_key(ToolKey::Right, alt, v).unwrap(); + s.tool_key(ToolKey::Right, alt, v).unwrap(); + assert_eq!(style_at(&s, id, 0).kerning_before, inc); +} + +/// The Eyedropper copies how type looks, not where a line starts: a sample from a first character +/// with a space before it leaves the target's first character where it was. +#[test] +fn the_eyedropper_keeps_the_targets_space_before() { + let mut s = session(); + let src = text(&mut s, "Source"); + s.execute("text.setRangeStyle", &json!({"id": src.0, "start": 0, "end": 1, "kerningBefore": 300, "tracking": 50})).unwrap(); + let dst = text(&mut s, "Target"); + s.execute("appearance.copyFrom", &json!({"source": src.0})).unwrap(); + let st = style_at(&s, dst, 0); + assert_eq!((st.tracking, st.kerning_before), (50.0, 0.0), "the tracking goes, the space before doesn't"); +} + +/// A character style captured from a line's first character leaves its space before out, and a +/// style can't be given one: it would space the first character of every paragraph set in it. +#[test] +fn a_character_style_leaves_the_space_before_out() { + let mut s = session(); + let id = text(&mut s, "Source"); + s.execute("text.setRangeStyle", &json!({"id": id.0, "kerningBefore": 300, "tracking": 50})).unwrap(); + s.execute("charStyle.new", &json!({"name": "Body", "id": id.0})).unwrap(); + let attrs = s.doc().unwrap().doc.char_styles[0].attrs.clone(); + assert_eq!(attrs.get("tracking"), Some(&json!(50.0))); + assert!(!attrs.contains_key("kerningBefore"), "{attrs:?}"); + let err = s.execute("charStyle.new", &json!({"name": "Spaced", "attrs": {"kerningBefore": 100}})).unwrap_err(); + assert!(err.to_string().contains("kerningBefore"), "{err}"); +} diff --git a/crates/engine/src/tests/clipboard.rs b/crates/engine/src/tests/clipboard.rs index b5ebf080ea..d0e003ec49 100644 --- a/crates/engine/src/tests/clipboard.rs +++ b/crates/engine/src/tests/clipboard.rs @@ -492,6 +492,222 @@ fn pasting_again_reuses_what_an_earlier_paste_added() { assert!(doc(&s).swatch("Brand 3").is_none() && doc(&s).char_styles.len() == 1); } +/// The active document, to edit its definitions directly. +fn doc_mut(s: &mut Session) -> &mut Document { + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc) +} + +/// The pattern a paint paints with. +fn pattern_of(p: &Paint) -> Option<&str> { + match p { + Paint::Pattern { pattern, .. } => Some(pattern), + _ => None, + } +} + +/// The pattern the fill of the active document's character style `name` paints with. +fn style_pattern(s: &Session, name: &str) -> Option<String> { + let attrs = &doc(s).char_styles.iter().find(|x| x.name == name)?.attrs; + pattern_of(&serde_json::from_value::<Paint>(attrs.get("fill")?.clone()).ok()?).map(str::to_string) +} + +/// A pattern "Dots" made from a `size` square of `color` in the active document. +fn dots(s: &mut Session, size: f64, color: &str) { + let square = rect(s, 300.0, 200.0, size, size); + s.execute("paint.setFill", &json!({"ids": [square.0], "color": color})).unwrap(); + s.execute("object.pattern.make", &json!({"name": "Dots", "edit": false, "ids": [square.0]})).unwrap(); +} + +/// Type "Hi" filled with the pattern "Dots" (a small red square), set in a character style +/// "Patterned" whose fill is that pattern. +fn patterned_type(s: &mut Session) -> NodeId { + dots(s, 10.0, "#ff0000"); + let t = id_of(&s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Hi"})).unwrap()); + s.execute("paint.setFill", &json!({"ids": [t.0], "swatch": "Dots"})).unwrap(); + s.execute("charStyle.new", &json!({"name": "Patterned", "id": t.0})).unwrap(); + s.execute("charStyle.apply", &json!({"name": "Patterned", "id": t.0})).unwrap(); + t +} + +/// The character style name of a type object's first run, and the pattern that run paints with. +fn type_links(s: &Session, id: NodeId) -> (Option<String>, Option<String>) { + let NodeKind::Text(tx) = node(s, id).kind else { panic!("not type") }; + (tx.runs[0].style.style_name.clone(), pattern_of(&tx.runs[0].style.fill).map(str::to_string)) +} + +/// Type set in a style that paints with a pattern, pasted into a document with another pattern of +/// that name: the pattern comes in as "Dots 2", and the style paints with "Dots 2" too, so applying +/// it later paints with the pasted pattern. Pasting again adds nothing. +#[test] +fn pasted_styles_paint_with_the_renamed_pattern_they_use() { + let mut s = session(); + let t = patterned_type(&mut s); + copy(&mut s, &[t]); + new_doc(&mut s); + dots(&mut s, 30.0, "#0000ff"); + let v = s.execute("edit.paste", &json!({})).unwrap(); + assert!(doc(&s).pattern("Dots 2").is_some(), "{v}"); + assert_eq!(style_pattern(&s, "Patterned").as_deref(), Some("Dots 2"), "{v}"); + let named = |n: &str| Some(n.to_string()); + assert_eq!(type_links(&s, ids_of(&v)[0]), (named("Patterned"), named("Dots 2"))); + let other = id_of(&s.execute("text.create", &json!({"x": 10, "y": 150, "text": "Yo"})).unwrap()); + s.execute("charStyle.apply", &json!({"name": "Patterned", "id": other.0})).unwrap(); + assert_eq!(type_links(&s, other).1.as_deref(), Some("Dots 2"), "the applied style paints with the pasted pattern"); + let counts = |s: &Session| (doc(s).patterns.len(), doc(s).char_styles.len()); + let before = counts(&s); + let v = s.execute("edit.paste", &json!({})).unwrap(); + assert_eq!(v["added"], 0, "{v}"); + assert_eq!(counts(&s), before); + assert_eq!(type_links(&s, ids_of(&v)[0]), (named("Patterned"), named("Dots 2"))); +} + +/// A document whose "Patterned" style has the pasted style's attributes but whose "Dots" is +/// another pattern: that style paints with the document's "Dots", so the pasted one comes in as +/// "Patterned 2", painting with "Dots 2", and the document's own is left as it was. Pasting again +/// uses the numbered copies. +#[test] +fn pasted_styles_are_not_matched_to_styles_that_paint_with_another_pattern() { + let mut s = session(); + let t = patterned_type(&mut s); + let style = doc(&s).char_styles.iter().find(|x| x.name == "Patterned").unwrap().clone(); + copy(&mut s, &[t]); + new_doc(&mut s); + dots(&mut s, 30.0, "#0000ff"); + doc_mut(&mut s).char_styles.push(style); + let own = (doc(&s).char_styles.clone(), doc(&s).pattern("Dots").cloned()); + let v = s.execute("edit.paste", &json!({})).unwrap(); + assert_eq!(style_pattern(&s, "Patterned 2").as_deref(), Some("Dots 2"), "{v}"); + let d = doc(&s); + assert_eq!((&d.char_styles[..own.0.len()], d.pattern("Dots")), (&own.0[..], own.1.as_ref()), "the document's own are unchanged"); + let named = |n: &str| Some(n.to_string()); + let links = (named("Patterned 2"), named("Dots 2")); + assert_eq!(type_links(&s, ids_of(&v)[0]), links); + let counts = |s: &Session| (doc(s).patterns.len(), doc(s).char_styles.len()); + let before = counts(&s); + let v = s.execute("edit.paste", &json!({})).unwrap(); + assert_eq!(v["added"], 0, "{v}"); + assert_eq!(counts(&s), before); + assert_eq!(type_links(&s, ids_of(&v)[0]), links); +} + +/// A style that paints with a pattern whose tile sets type in that same style is pasted with the +/// pattern: when the pattern comes in as "Dots 2", the style paints with "Dots 2", and the tile's +/// type is set in the style. Pasting again adds nothing. The commands do not make that loop, so the +/// source is a document edited directly. +#[test] +fn a_pasted_style_and_the_pattern_whose_tile_uses_it_come_in_together() { + let mut s = session(); + let t = id_of(&s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Tile"})).unwrap()); + s.execute("charStyle.new", &json!({"name": "Accent", "attrs": {"kerning": 40}})).unwrap(); + s.execute("charStyle.apply", &json!({"name": "Accent", "id": t.0})).unwrap(); + s.execute("object.pattern.make", &json!({"name": "Dots", "edit": false, "ids": [t.0]})).unwrap(); + let other = id_of(&s.execute("text.create", &json!({"x": 10, "y": 90, "text": "B"})).unwrap()); + s.execute("charStyle.apply", &json!({"name": "Accent", "id": other.0})).unwrap(); + s.execute("paint.setFill", &json!({"swatch": "Dots", "ids": [other.0]})).unwrap(); + s.execute("charStyle.new", &json!({"name": "Painted", "id": other.0})).unwrap(); + let d = doc_mut(&mut s); + let painted = d.char_styles.iter().find(|x| x.name == "Painted").unwrap().attrs.clone(); + d.char_styles.retain(|x| x.name != "Painted"); + d.char_styles.iter_mut().find(|x| x.name == "Accent").unwrap().attrs = painted; + assert_eq!(style_pattern(&s, "Accent").as_deref(), Some("Dots")); + copy(&mut s, &[other]); + new_doc(&mut s); + dots(&mut s, 30.0, "#0000ff"); + let v = s.execute("edit.paste", &json!({})).unwrap(); + assert!(doc(&s).pattern("Dots 2").is_some(), "{v}"); + assert_eq!(style_pattern(&s, "Accent").as_deref(), Some("Dots 2"), "{v}"); + let NodeKind::Text(tile) = &doc(&s).pattern("Dots 2").unwrap().art[0].kind else { panic!("the tile is type") }; + assert_eq!(tile.runs[0].style.style_name.as_deref(), Some("Accent")); + let after = doc(&s).clone(); + let v = s.execute("edit.paste", &json!({})).unwrap(); + assert_eq!(v["added"], 0, "{v}"); + assert!(doc(&s).patterns == after.patterns && doc(&s).char_styles == after.char_styles, "nothing is added"); + // Back in the source document, the loop is the document's own. + s.execute("document.activate", &json!({"index": 0})).unwrap(); + let v = s.execute("edit.paste", &json!({})).unwrap(); + assert_eq!((v["added"].as_u64(), v["renamed"].as_array().map(Vec::len)), (Some(0), Some(0)), "{v}"); +} + +/// A symbol whose art paints with a pattern is not matched to the document's symbol of that name +/// and art when the document's pattern of that name is another one: it comes in as "Mark 2", +/// painting with "Dots 2". +#[test] +fn pasted_symbols_are_not_matched_to_symbols_that_paint_with_another_pattern() { + let mut s = session(); + dots(&mut s, 10.0, "#ff0000"); + let r = rect(&mut s, 20.0, 20.0, 50.0, 50.0); + s.execute("paint.setFill", &json!({"ids": [r.0], "swatch": "Dots"})).unwrap(); + sel(&mut s, &[r]); + let mark = id_of(&s.execute("symbol.new", &json!({"name": "Mark"})).unwrap()); + copy(&mut s, &[mark]); + // The document gets "Mark" and "Dots" from a first paste; then its "Dots" gets another tile. + new_doc(&mut s); + let v = s.execute("edit.paste", &json!({})).unwrap(); + assert_eq!(v["renamed"], json!([]), "{v}"); + let tile = &mut doc_mut(&mut s).patterns.iter_mut().find(|p| p.name == "Dots").unwrap().tile; + *tile = Rect::new(tile.x0, tile.y0, tile.x1 + 30.0, tile.y1 + 30.0); + let v = s.execute("edit.paste", &json!({})).unwrap(); + assert!(renamed(&v).contains(&("symbol".to_string(), "Mark".to_string(), "Mark 2".to_string())), "{v}"); + let art = |s: &Session, name: &str| fill_of(&doc(s).symbols.iter().find(|x| x.name == name).unwrap().art); + assert_eq!((art(&s, "Mark").as_deref(), art(&s, "Mark 2").as_deref()), (Some("Dots"), Some("Dots 2"))); + assert!(matches!(node(&s, ids_of(&v)[0]).kind, NodeKind::SymbolInstance { ref symbol, .. } if symbol == "Mark 2")); + let v = s.execute("edit.paste", &json!({})).unwrap(); + assert_eq!(v["added"], 0, "{v}"); +} + +/// The pattern the first filled object in `n` paints with. +fn fill_of(n: &Node) -> Option<String> { + let mut found = None; + n.walk(&mut |m| { + if found.is_none() { + found = pattern_of(&m.appearance.fill_paint()).map(str::to_string); + } + }); + found +} + +/// A brush whose art sets type in a character style is not matched to the document's brush of +/// that name and art when the document's style of that name is another one: the style comes in as +/// "Accent 2", and the brush as a copy whose type is set in "Accent 2". +#[test] +fn pasted_brushes_are_not_matched_to_brushes_that_use_another_style() { + let mut s = session(); + let t = id_of(&s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Ink"})).unwrap()); + s.execute("charStyle.new", &json!({"name": "Accent", "attrs": {"kerning": 40}})).unwrap(); + s.execute("charStyle.apply", &json!({"name": "Accent", "id": t.0})).unwrap(); + let name = s.execute("brush.new", &json!({"type": "art", "name": "Lettering", "ids": [t.0]})).unwrap()["name"].as_str().unwrap().to_string(); + let path = rect(&mut s, 200.0, 200.0, 40.0, 10.0); + s.execute("brush.apply", &json!({"name": name, "ids": [path.0]})).unwrap(); + let brush = vectorcraft_brush::find(doc(&s), &name).unwrap(); + copy(&mut s, &[path]); + new_doc(&mut s); + s.execute("charStyle.new", &json!({"name": "Accent", "attrs": {"kerning": 10}})).unwrap(); + let d = doc_mut(&mut s); + let mut lib = vectorcraft_brush::library(d); + lib.push(brush); + vectorcraft_brush::store(d, &lib); + let v = s.execute("edit.paste", &json!({})).unwrap(); + let names = renamed(&v); + let copied = names.iter().find(|(k, from, _)| k == "brush" && *from == name).map(|(_, _, to)| to.clone()); + assert!(names.contains(&("charStyle".to_string(), "Accent".to_string(), "Accent 2".to_string())), "{v}"); + let copied = copied.unwrap_or_else(|| panic!("the brush is added under a free name: {v}")); + let style_of = |s: &Session, b: &str| { + let b = vectorcraft_brush::find(doc(s), b).unwrap(); + let mut found = None; + for a in b.art() { + a.walk(&mut |m| { + if let NodeKind::Text(tx) = &m.kind { + found = found.take().or_else(|| tx.runs[0].style.style_name.clone()); + } + }); + } + found + }; + assert_eq!((style_of(&s, &name).as_deref(), style_of(&s, &copied).as_deref()), (Some("Accent"), Some("Accent 2"))); + let v = s.execute("edit.paste", &json!({})).unwrap(); + assert_eq!(v["added"], 0, "{v}"); +} + #[test] fn brushes_travel_with_their_strokes() { let mut s = session(); @@ -878,7 +1094,8 @@ fn paste_remembers_layers_restores_the_source_layers() { let art = id_of(&s.execute("layer.new", &json!({"name": "Art"})).unwrap()); let b = rect(&mut s, 20.0, 0.0, 10.0, 10.0); copy(&mut s, &[a, b]); - assert_eq!(s.clipboard.source_layers, [Some("Layer 1".to_string()), Some("Art".to_string())]); + let names: Vec<_> = s.clipboard.source_layers.iter().map(|l| l.as_ref().map(|l| l.names.clone())).collect(); + assert_eq!(names, [Some(vec!["Layer 1".to_string()]), Some(vec!["Art".to_string()])]); let other = id_of(&s.execute("layer.new", &json!({"name": "Other"})).unwrap()); assert_eq!(s.execute("layer.pasteRemembersLayers", &json!({})).unwrap()["on"], true); assert!(doc(&s).paste_remembers_layers); @@ -905,6 +1122,157 @@ fn paste_remembers_layers_restores_the_source_layers() { assert!(ids.iter().all(|id| doc(&s).parent_of(*id) == Some(other))); } +/// A sublayer `name` made inside `parent`; it becomes the current layer. +fn sublayer(s: &mut Session, parent: NodeId, name: &str) -> NodeId { + id_of(&s.execute("layer.newSublayer", &json!({"parent": parent.0, "name": name})).unwrap()) +} + +/// The names of the layers around `id`, the top-level layer first. +fn layer_path(s: &Session, id: NodeId) -> Vec<String> { + let d = doc(s); + d.ancestry(id).unwrap().iter().filter_map(|a| d.node(*a).filter(|n| n.is_layer())).map(|l| l.name.clone().unwrap()).collect() +} + +/// Art from two sublayers of the same name in different layers pastes back into each one; in +/// another document a missing sublayer is made inside its layer, and a missing layer on top with +/// the sublayer inside, in the paste's one undo step. +#[test] +fn paste_remembers_layers_keeps_same_named_sublayers_apart() { + let mut s = session(); + let first = doc(&s).layers[0].id; + let sub1 = sublayer(&mut s, first, "Sub"); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let second = id_of(&s.execute("layer.new", &json!({"name": "Layer 2", "top": true})).unwrap()); + let sub2 = sublayer(&mut s, second, "Sub"); + let b = rect(&mut s, 20.0, 0.0, 10.0, 10.0); + copy(&mut s, &[a, b]); + s.execute("layer.pasteRemembersLayers", &json!({"on": true})).unwrap(); + s.execute("layer.setCurrent", &json!({"id": first.0})).unwrap(); + let ids = ids_of(&s.execute("edit.paste", &json!({})).unwrap()); + let parents: Vec<_> = ids.iter().map(|id| doc(&s).parent_of(*id)).collect(); + assert_eq!(parents, [Some(sub1), Some(sub2)]); + new_doc(&mut s); + s.execute("layer.pasteRemembersLayers", &json!({"on": true})).unwrap(); + let before = doc(&s).clone(); + let ids = ids_of(&s.execute("edit.paste", &json!({})).unwrap()); + let paths: Vec<_> = ids.iter().map(|id| layer_path(&s, *id)).collect(); + assert_eq!(paths, [["Layer 1", "Sub"], ["Layer 2", "Sub"]]); + assert_eq!(doc(&s).layers.len(), 2, "Layer 1 is kept; Layer 2 is new"); + assert_eq!(doc(&s).layers[0].children().unwrap().len(), 1, "Sub is made inside Layer 1"); + let after = doc(&s).clone(); + // Pasting again finds the layers made. + let again = ids_of(&s.execute("edit.paste", &json!({})).unwrap()); + let parents: Vec<_> = again.iter().map(|id| doc(&s).parent_of(*id)).collect(); + assert_eq!(parents, ids.iter().map(|id| doc(&s).parent_of(*id)).collect::<Vec<_>>()); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(*doc(&s), after); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(*doc(&s), before, "one undo step takes the art and the layers made for it"); +} + +/// Art whose sublayer was deleted after the copy pastes into a new sublayer of that name inside +/// the same layer, not into a sublayer of that name in another layer. +#[test] +fn paste_remembers_layers_makes_a_deleted_sublayer_again_inside_its_layer() { + let mut s = session(); + let first = doc(&s).layers[0].id; + let sub = sublayer(&mut s, first, "Sub"); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let second = id_of(&s.execute("layer.new", &json!({"name": "Layer 2", "top": true})).unwrap()); + let elsewhere = sublayer(&mut s, second, "Sub"); + copy(&mut s, &[a]); + s.execute("layer.delete", &json!({"id": sub.0})).unwrap(); + s.execute("layer.pasteRemembersLayers", &json!({"on": true})).unwrap(); + let ids = ids_of(&s.execute("edit.paste", &json!({})).unwrap()); + let made = doc(&s).parent_of(ids[0]).unwrap(); + assert_ne!(made, elsewhere); + assert_eq!(doc(&s).parent_of(made), Some(first)); + assert_eq!(layer_path(&s, ids[0]), ["Layer 1", "Sub"]); +} + +/// Art whose sublayer was moved into another layer after the copy pastes into that sublayer where +/// it is now; no sublayer is made where it was. +#[test] +fn paste_remembers_layers_follows_a_moved_sublayer() { + let mut s = session(); + let first = doc(&s).layers[0].id; + let sub = sublayer(&mut s, first, "Sub"); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let second = id_of(&s.execute("layer.new", &json!({"name": "Layer 2", "top": true})).unwrap()); + copy(&mut s, &[a]); + s.execute("layer.move", &json!({"id": sub.0, "target": second.0})).unwrap(); + s.execute("layer.pasteRemembersLayers", &json!({"on": true})).unwrap(); + let ids = ids_of(&s.execute("edit.paste", &json!({})).unwrap()); + assert_eq!(doc(&s).parent_of(ids[0]), Some(sub)); + assert_eq!(layer_path(&s, ids[0]), ["Layer 2", "Sub"]); + assert!(node(&s, first).children().unwrap().is_empty(), "no Sub is made in Layer 1"); +} + +/// In another document with layers of the same names, art goes into the topmost chain of layers +/// that matches the most names, a shown and unlocked one before a hidden or locked one. +#[test] +fn paste_remembers_layers_takes_the_topmost_open_match_of_repeated_names() { + let mut s = session(); + let first = doc(&s).layers[0].id; + sublayer(&mut s, first, "Sub"); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + copy(&mut s, &[a]); + new_doc(&mut s); + s.execute("layer.pasteRemembersLayers", &json!({"on": true})).unwrap(); + let lower = doc(&s).layers[0].id; + let lower_sub = sublayer(&mut s, lower, "Sub"); + s.execute("layer.new", &json!({"name": "Sub", "top": true})).unwrap(); + let upper = id_of(&s.execute("layer.new", &json!({"name": "Layer 1", "top": true})).unwrap()); + // The upper Layer 1 has no Sub, and a top-level Sub is not inside a Layer 1: the lower chain + // matches both names. + let ids = ids_of(&s.execute("edit.paste", &json!({})).unwrap()); + assert_eq!(doc(&s).parent_of(ids[0]), Some(lower_sub)); + let upper_sub = sublayer(&mut s, upper, "Sub"); + let ids = ids_of(&s.execute("edit.paste", &json!({})).unwrap()); + assert_eq!(doc(&s).parent_of(ids[0]), Some(upper_sub), "the topmost of two full matches"); + s.execute("layer.setProps", &json!({"id": upper_sub.0, "locked": true})).unwrap(); + let ids = ids_of(&s.execute("edit.paste", &json!({})).unwrap()); + assert_eq!(doc(&s).parent_of(ids[0]), Some(lower_sub), "an unlocked match before a locked one"); +} + +/// A remembered layer or sublayer that is hidden or locked, or inside a layer that is, refuses the +/// whole paste: the document, the selection and the undo history stay as they were. +#[test] +fn paste_remembers_layers_refuses_a_hidden_or_locked_layer() { + let (locked, hidden) = (json!({"locked": true}), json!({"visible": false})); + for (on_sub, props) in [(true, &locked), (true, &hidden), (false, &locked), (false, &hidden)] { + let mut s = session(); + let first = doc(&s).layers[0].id; + let sub = sublayer(&mut s, first, "Sub"); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let other = id_of(&s.execute("layer.new", &json!({"name": "Other", "top": true})).unwrap()); + let b = rect(&mut s, 20.0, 0.0, 10.0, 10.0); + copy(&mut s, &[b, a]); + s.execute("layer.pasteRemembersLayers", &json!({"on": true})).unwrap(); + let mut p = props.clone(); + p["id"] = json!(if on_sub { sub.0 } else { first.0 }); + s.execute("layer.setProps", &p).unwrap(); + s.execute("layer.setCurrent", &json!({"id": other.0})).unwrap(); + let before = s.doc().unwrap().clone(); + assert!(s.execute("edit.paste", &json!({})).is_err(), "{p}"); + assert_eq!(s.doc().unwrap().doc, before.doc, "{p}"); + assert_eq!(s.doc().unwrap().selection, before.selection, "{p}"); + assert_eq!(s.doc().unwrap().history.undo.len(), before.history.undo.len(), "{p}"); + } + // In another document, a locked layer of the copied layer's name is refused too. + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + copy(&mut s, &[a]); + new_doc(&mut s); + s.execute("layer.pasteRemembersLayers", &json!({"on": true})).unwrap(); + let locked = doc(&s).layers[0].id; + id_of(&s.execute("layer.new", &json!({"name": "Flyer"})).unwrap()); + s.execute("layer.setProps", &json!({"id": locked.0, "locked": true})).unwrap(); + let before = doc(&s).clone(); + assert!(s.execute("edit.paste", &json!({})).is_err()); + assert_eq!(*doc(&s), before, "no second Layer 1 is made"); +} + #[test] fn paste_remembers_layers_survives_save_and_old_files_load_without_it() { let mut s = session(); diff --git a/crates/engine/src/tests/colorize.rs b/crates/engine/src/tests/colorize.rs index c71014eb1c..e281b3ee04 100644 --- a/crates/engine/src/tests/colorize.rs +++ b/crates/engine/src/tests/colorize.rs @@ -462,6 +462,49 @@ fn a_colorized_missing_link_placeholder_is_not_flattened() { assert_eq!(colorize(&s, id), Some(Paint::solid(Color::rgb8(255, 0, 0))), "the image keeps its paint"); } +/// A fill color on a colorized image that shows the missing-link placeholder recolors the image, +/// as the Fill proxy shows its colorize paint, and adds no fill item. +#[test] +fn a_fill_color_recolors_a_colorized_missing_link_placeholder() { + let mut s = session(); + let bytes = std::sync::Arc::new(vectorcraft_doc::links::missing_placeholder().unwrap()); + let id = image(&mut s, "pic", ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) }); + s.edit("Colorize", |d, _| { + d.node_mut(id).unwrap().extras_mut().colorize = Some(Box::new(Paint::solid(Color::rgb8(255, 0, 0)))); + Ok(()) + }) + .unwrap(); + let appearance = s.doc().unwrap().doc.node(id).unwrap().appearance.clone(); + s.execute("paint.setFill", &json!({"color": "#0000ff", "ids": [id.0]})).unwrap(); + assert_eq!(colorize(&s, id).and_then(|p| p.color()).map(|c| c.to_hex()), Some("#0000ff".into())); + assert_eq!(s.doc().unwrap().doc.node(id).unwrap().appearance, appearance, "no fill item"); + assert_eq!(s.proxy_paints().0.color().map(|c| c.to_hex()), Some("#0000ff".into())); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(colorize(&s, id), Some(Paint::solid(Color::rgb8(255, 0, 0)))); +} + +/// The pixels behind the placeholder may have an alpha channel, so a missing-link image colorized +/// with a spot color takes another spot color, black or white, and refuses a process color. +#[test] +fn a_colorized_missing_link_placeholder_in_a_spot_color_refuses_a_process_color() { + let mut s = session(); + let bytes = std::sync::Arc::new(vectorcraft_doc::links::missing_placeholder().unwrap()); + let id = image(&mut s, "pic", ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) }); + s.execute("swatch.new", &json!({"name": "Ink 2", "color": {"c": 100, "m": 0, "y": 0, "k": 0}, "spot": true})).unwrap(); + s.edit("Colorize", |d, _| { + let ink = Paint::Solid { color: Color::rgb8(255, 0, 0), swatch: Some("Ink".into()), tint: 1.0 }; + d.node_mut(id).unwrap().extras_mut().colorize = Some(Box::new(ink)); + Ok(()) + }) + .unwrap(); + let before = colorize(&s, id); + let e = s.execute("paint.setFill", &json!({"color": "#0000ff", "ids": [id.0]})).unwrap_err().to_string(); + assert!(e.contains("a process color can't colorize a grayscale image with transparency"), "{e}"); + assert_eq!(colorize(&s, id), before); + s.execute("paint.setFill", &json!({"swatch": "Ink 2", "ids": [id.0]})).unwrap(); + assert!(matches!(colorize(&s, id), Some(Paint::Solid { swatch: Some(w), .. }) if w == "Ink 2"), "{:?}", colorize(&s, id)); +} + #[test] fn flattened_colorized_image_shows_the_art_under_white_pixels() { let mut s = session(); diff --git a/crates/engine/src/tests/colormgmt.rs b/crates/engine/src/tests/colormgmt.rs index d0901f30a0..493f569805 100644 --- a/crates/engine/src/tests/colormgmt.rs +++ b/crates/engine/src/tests/colormgmt.rs @@ -308,6 +308,23 @@ fn assign_profile_is_stored_and_undoable() { assert_eq!(cmd::colormgmt::doc_profiles(&s.doc().unwrap().doc), (None, None)); } +/// Assigning the working profiles leaves the active color settings and the other documents' +/// revisions unchanged. +#[test] +fn assigning_the_working_profiles_keeps_the_active_color_settings() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut s = session(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let working = cms::active_settings(); + let active = cms::active(); + let other = s.documents()[0].revision; + let r = s.execute("edit.assignProfile", &json!({"rgb": working.rgb, "cmyk": working.cmyk})).unwrap(); + assert_eq!((r["rgb"].as_str(), r["cmyk"].as_str()), (Some(working.rgb.as_str()), Some(working.cmyk.as_str()))); + assert_eq!(cmd::colormgmt::doc_profiles(&s.doc().unwrap().doc), (Some(working.rgb.clone()), Some(working.cmyk.clone()))); + assert!(std::sync::Arc::ptr_eq(&active, &cms::active()), "the active color settings were replaced"); + assert_eq!(s.documents()[0].revision, other, "the other document's revision changed"); +} + #[test] fn proof_colors_simulate_press_on_screen() { let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); @@ -438,6 +455,7 @@ fn overprint_black_multiplies_in_preview() { #[test] fn view_toggles_redraw_without_dirtying() { let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let _v = DefaultView::new(); let mut s = session(); let rev = s.doc().unwrap().revision; let r = s.execute("view.proofColors", &json!({"on": true})).unwrap(); @@ -458,6 +476,101 @@ fn view_toggles_redraw_without_dirtying() { s.execute("view.overprintPreview", &json!({"on": false})).unwrap(); } +/// Sets the default proof view when made and again when dropped, also after a failed assertion, +/// so the next test starts from the default view. +pub(crate) struct DefaultView; + +impl DefaultView { + pub(crate) fn new() -> Self { + vectorcraft_render::proof::set_view(Default::default()); + DefaultView + } +} + +impl Drop for DefaultView { + fn drop(&mut self) { + vectorcraft_render::proof::set_view(Default::default()); + } +} + +/// Runs `cmd` with `p` twice from the default proof view: the first run changes the view and +/// redraws, and the second asks for the view that is already showing and leaves the revision alone. +fn repeat_keeps_revision(cmd: &str, p: Value) { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let _v = DefaultView::new(); + let mut s = session(); + let rev = s.doc().unwrap().revision; + s.execute(cmd, &p).unwrap(); + let changed = s.doc().unwrap().revision; + assert!(changed > rev, "{cmd} {p}: the first run changes the view"); + s.execute(cmd, &p).unwrap(); + assert_eq!(s.doc().unwrap().revision, changed, "{cmd} {p}: the same view again"); +} + +/// Runs `cmd` with `p` once from the default proof view, which `p` leaves as it is. +fn default_view_keeps_revision(cmd: &str, p: Value) { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let _v = DefaultView::new(); + let mut s = session(); + let rev = s.doc().unwrap().revision; + s.execute(cmd, &p).unwrap(); + assert_eq!(s.doc().unwrap().revision, rev, "{cmd} {p}"); + assert_eq!(vectorcraft_render::proof::view(), Default::default(), "{cmd} {p}"); +} + +#[test] +fn proof_setup_with_nothing_changed_keeps_the_revision() { + repeat_keeps_revision("view.proofSetup", json!({"target": "deuteranopia"})); + repeat_keeps_revision("view.proofSetup", json!({"simulatePaper": true, "proof": true})); + default_view_keeps_revision("view.proofSetup", json!({})); + default_view_keeps_revision("view.proofSetup", json!({"target": "workingCmyk", "proof": false})); +} + +#[test] +fn proof_colors_with_nothing_changed_keeps_the_revision() { + repeat_keeps_revision("view.proofColors", json!({"on": true})); + default_view_keeps_revision("view.proofColors", json!({"on": false})); +} + +#[test] +fn overprint_preview_with_nothing_changed_keeps_the_revision() { + repeat_keeps_revision("view.overprintPreview", json!({"on": true})); + default_view_keeps_revision("view.overprintPreview", json!({"on": false})); +} + +#[test] +fn separations_preview_with_nothing_changed_keeps_the_revision() { + repeat_keeps_revision("view.separationsPreview", json!({"on": true})); + repeat_keeps_revision("view.separationsPreview", json!({"only": "Cyan"})); + repeat_keeps_revision("view.separationsPreview", json!({"plates": ["Magenta", "Black"]})); + default_view_keeps_revision("view.separationsPreview", json!({"on": false})); +} + +/// Separations Preview's visible plates are a set: the same plates in another order, or with one +/// named twice, leave the revision alone, and a plate named twice hides with one `toggle`. +#[test] +fn separations_preview_compares_the_visible_plates_as_a_set() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let _v = DefaultView::new(); + let mut s = session(); + let sep = |s: &mut Session, p: Value| { + s.execute("view.separationsPreview", &p).unwrap(); + s.doc().unwrap().revision + }; + let shown = sep(&mut s, json!({"plates": ["Magenta", "Black"]})); + assert_eq!(sep(&mut s, json!({"plates": ["Black", "Magenta"]})), shown, "another order"); + assert_eq!(sep(&mut s, json!({"plates": ["Magenta", "Black", "Black"]})), shown, "a plate named twice"); + // Cyan hidden and shown again goes to the end of the list; every plate is shown. + sep(&mut s, json!({"on": false})); + sep(&mut s, json!({"on": true})); + sep(&mut s, json!({"toggle": "Cyan"})); + let all = sep(&mut s, json!({"toggle": "Cyan"})); + assert_eq!(sep(&mut s, json!({"plates": ["Cyan", "Magenta", "Yellow", "Black"]})), all, "every plate in plate order"); + sep(&mut s, json!({"plates": ["Cyan", "Cyan"]})); + let r = s.execute("view.separationsPreview", &json!({"toggle": "Cyan"})).unwrap(); + assert!(r["plates"].as_array().unwrap().iter().all(|p| p["visible"] == false), "{r}"); +} + #[test] fn proof_setup_simulates_tritanopia() { let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); diff --git a/crates/engine/src/tests/compare.rs b/crates/engine/src/tests/compare.rs index 3bd4446d61..3a6c66e2f5 100644 --- a/crates/engine/src/tests/compare.rs +++ b/crates/engine/src/tests/compare.rs @@ -36,7 +36,7 @@ fn error(s: &mut Session, p: Value) -> String { #[test] fn an_export_compares_equal_and_a_moved_square_counts_the_pixels_it_changed() { - let dir = vectorcraft_testkit::temp_dir("compare-moved"); + let dir = vectorcraft_testkit::TempDir::new("compare-moved"); let png = path_in(&dir, "art.png"); let (mut s, id) = session(); export(&mut s, &png); @@ -54,12 +54,11 @@ fn an_export_compares_equal_and_a_moved_square_counts_the_pixels_it_changed() { assert_eq!(r["rmse"].as_f64(), Some(rmse), "{r}"); // Above every difference, nothing is over. assert_eq!(compare(&mut s, json!({"path": png, "threshold": 1}))["over"], json!(0)); - let _ = std::fs::remove_dir_all(dir); } #[test] fn the_image_and_the_render_are_flattened_on_the_background() { - let dir = vectorcraft_testkit::temp_dir("compare-background"); + let dir = vectorcraft_testkit::TempDir::new("compare-background"); let png = path_in(&dir, "clear.png"); // Transparent everywhere, with red in the color channels that the alpha hides. image::RgbaImage::from_pixel(80, 40, image::Rgba([255, 0, 0, 0])).save(&png).unwrap(); @@ -81,12 +80,11 @@ fn the_image_and_the_render_are_flattened_on_the_background() { assert_eq!((r["rmse"].as_f64(), r["over"].as_u64()), (Some(rmse(255.0)), Some(1600)), "{r}"); // A threshold just above 128/255 leaves the gray differences out. assert_eq!(compare(&mut s, json!({"path": png, "background": "#808080", "threshold": 0.51}))["over"], json!(0)); - let _ = std::fs::remove_dir_all(dir); } #[test] fn an_image_of_other_proportions_is_refused_and_one_pixel_is_allowed() { - let dir = vectorcraft_testkit::temp_dir("compare-size"); + let dir = vectorcraft_testkit::TempDir::new("compare-size"); let (mut s, _) = session(); let square = path_in(&dir, "square.png"); image::RgbaImage::from_pixel(30, 30, image::Rgba([255; 4])).save(&square).unwrap(); @@ -96,12 +94,11 @@ fn an_image_of_other_proportions_is_refused_and_one_pixel_is_allowed() { image::RgbaImage::from_pixel(80, 41, image::Rgba([255; 4])).save(&taller).unwrap(); let r = compare(&mut s, json!({"path": taller})); assert_eq!((r["width"].as_u64(), r["height"].as_u64(), r["total"].as_u64()), (Some(80), Some(41), Some(3280)), "{r}"); - let _ = std::fs::remove_dir_all(dir); } #[test] fn an_export_whose_height_was_rounded_compares_equal() { - let dir = vectorcraft_testkit::temp_dir("compare-rounded"); + let dir = vectorcraft_testkit::TempDir::new("compare-rounded"); let png = path_in(&dir, "art.png"); // 20.25 pt at 2 pixels a point is 40.5 rows, which the export rounds to 41. let mut s = Session::new(); @@ -112,7 +109,6 @@ fn an_export_whose_height_was_rounded_compares_equal() { export(&mut s, &png); let r = compare(&mut s, json!({"path": png})); assert_eq!(r, json!({"width": 80, "height": 41, "rmse": 0.0, "over": 0, "total": 3280, "threshold": 0.08})); - let _ = std::fs::remove_dir_all(dir); } #[test] @@ -151,7 +147,7 @@ fn a_linked_image_is_drawn_from_its_file_as_a_png_export_draws_it() { #[test] fn an_image_that_cannot_be_decoded_and_a_missing_font_warn_as_a_png_export_does() { - let dir = vectorcraft_testkit::temp_dir("compare-warnings"); + let dir = vectorcraft_testkit::TempDir::new("compare-warnings"); let png = path_in(&dir, "art.png"); let (mut s, _) = session(); export(&mut s, &png); @@ -167,12 +163,11 @@ fn an_image_that_cannot_be_decoded_and_a_missing_font_warn_as_a_png_export_does( assert!(warnings.iter().any(|w| w == "an image couldn't be decoded and is missing from the picture"), "{r}"); assert!(warnings.iter().any(|w| w.as_str().unwrap().contains("Nonexistent Sans Probe")), "{r}"); assert!(warnings.iter().any(|w| w.as_str().unwrap().contains("doesn't fit its frame")), "{r}"); - let _ = std::fs::remove_dir_all(dir); } #[test] fn diff_path_writes_each_pixels_differences() { - let dir = vectorcraft_testkit::temp_dir("compare-diff"); + let dir = vectorcraft_testkit::TempDir::new("compare-diff"); let png = path_in(&dir, "art.png"); let diff = path_in(&dir, "diff.png"); let (mut s, id) = session(); @@ -188,12 +183,11 @@ fn diff_path_writes_each_pixels_differences() { } let changed = img.pixels().filter(|p| p.0[0] != 0).count(); assert_eq!(changed as u64, r["over"].as_u64().unwrap()); - let _ = std::fs::remove_dir_all(dir); } #[test] fn missing_unreadable_and_malformed_inputs_are_errors() { - let dir = vectorcraft_testkit::temp_dir("compare-errors"); + let dir = vectorcraft_testkit::TempDir::new("compare-errors"); let (mut s, _) = session(); let png = path_in(&dir, "art.png"); export(&mut s, &png); @@ -216,14 +210,13 @@ fn missing_unreadable_and_malformed_inputs_are_errors() { let e = error(&mut s, p.clone()); assert!(e.contains(want), "{p}: {e}"); } - let _ = std::fs::remove_dir_all(dir); } /// A planar TIFF whose header claims more strips than the decoder can count (2^31 + 1 rows a strip /// each, times 5 planes) is refused as too large to draw, without a panic. #[test] fn a_tiff_with_more_strips_than_can_be_counted_is_too_large() { - let dir = vectorcraft_testkit::temp_dir("compare-strips"); + let dir = vectorcraft_testkit::TempDir::new("compare-strips"); let (mut s, _) = session(); let plane = |v: u16| vec![v; 6]; let channels = [plane(200), plane(40), plane(10), plane(0), plane(90)]; @@ -247,12 +240,11 @@ fn a_tiff_with_more_strips_than_can_be_counted_is_too_large() { std::fs::write(&tif, &file).unwrap(); let e = error(&mut s, json!({"path": tif})); assert_eq!(e, "invalid parameters for `document.compare`: an image of 3 × 2147483649 pixels is too large to draw"); - let _ = std::fs::remove_dir_all(dir); } #[test] fn the_image_and_the_difference_image_stay_inside_the_automation_roots() { - let dir = vectorcraft_testkit::temp_dir("compare-roots"); + let dir = vectorcraft_testkit::TempDir::new("compare-roots"); for d in ["in", "out", "elsewhere"] { std::fs::create_dir_all(dir.join(d)).unwrap(); } @@ -272,5 +264,4 @@ fn the_image_and_the_difference_image_stay_inside_the_automation_roots() { assert!(!std::path::Path::new(&stray).exists()); let kept = path_in(&dir.join("out"), "diff.png"); assert_eq!(run(json!({"path": inside, "diffPath": kept})).unwrap()["diffPath"], json!(kept)); - let _ = std::fs::remove_dir_all(dir); } diff --git a/crates/engine/src/tests/constrain_tools.rs b/crates/engine/src/tests/constrain_tools.rs index a93965eb0b..41acc54172 100644 --- a/crates/engine/src/tests/constrain_tools.rs +++ b/crates/engine/src/tests/constrain_tools.rs @@ -115,6 +115,9 @@ fn constrain_angle_draws_boxes_along_the_turned_axes() { let mut s = new_doc(); set_pref(&mut s, "constrainAngle", json!(90)); for tool in ["rectangle", "ellipse"] { + // The shape drawn before stays selected, and a press on its box's corner handle would + // scale it instead of drawing. + s.execute("select.none", &json!({})).unwrap(); s.select_tool(tool, ViewInfo::default()).unwrap(); // 60 right and 20 down on the page: along axes turned 90°, 20 wide and 60 high. gesture(&mut s, Mods::default(), &[(Down, 100.0, 100.0), (Drag, 130.0, 110.0), (Drag, 160.0, 120.0), (Up, 160.0, 120.0)]); diff --git a/crates/engine/src/tests/containers.rs b/crates/engine/src/tests/containers.rs index dd32135c18..42cebea2ad 100644 --- a/crates/engine/src/tests/containers.rs +++ b/crates/engine/src/tests/containers.rs @@ -256,6 +256,122 @@ fn an_images_stroke_with_outline_object_draws_exports_and_expands_along_its_fram assert!(kids[0].appearance.fill_paint().is_none()); } +/// A 100×100 PNG, transparent but for an opaque red disc of radius 30 in its middle. +fn disc_png() -> Vec<u8> { + let mut png = vec![]; + image::RgbaImage::from_fn(100, 100, |x, y| { + let r = (f64::from(x) + 0.5 - 50.0).hypot(f64::from(y) + 0.5 - 50.0); + image::Rgba([255, 0, 0, if r <= 30.0 { 255 } else { 0 }]) + }) + .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .unwrap(); + png +} + +#[test] +fn an_images_stroke_with_outline_object_follows_its_opaque_area() { + let mut s = session(); + // The frame runs from 50 to 150, the disc from 70 to 130. + let r = run(&mut s, "file.place", json!({"name": "disc.png", "dataBase64": vectorcraft_format::base64_encode(&disc_png()), "at": [100, 100]})); + let im = NodeId(r["ids"][0].as_u64().unwrap()); + run(&mut s, "appearance.addStroke", json!({})); + run(&mut s, "appearance.setItem", json!({"index": 0, "weight": 8, "color": "#000000"})); + run(&mut s, "effect.apply", json!({"effect": "path.outlineObject", "item": 0})); + // Under the image, the stroke's outer 4 pt shows around the disc, from 66 to 70; nothing runs + // along the frame. + let shade = |s: &Session, x: u32, y: u32| match pixel(s, x, y) { + p if p == RED => "red", + [r, g, b, _] if r.max(g).max(b) < 40 => "black", + [r, g, b, _] if r.min(g).min(b) > 215 => "white", + p => panic!("({x}, {y}) is {p:?}"), + }; + assert_eq!([shade(&s, 64, 100), shade(&s, 67, 100), shade(&s, 100, 100), shade(&s, 100, 132)], ["white", "black", "red", "black"]); + assert_eq!([shade(&s, 49, 100), shade(&s, 52, 100)], ["white", "white"]); + // SVG and PDF hold the disc's outline stroked 8 pt. + let doc = s.doc().unwrap().doc.clone(); + let disc = |b: vectorcraft_geom::Rect| [b.x0 - 70.0, b.y0 - 70.0, b.x1 - 130.0, b.y1 - 130.0].iter().all(|d| d.abs() < 0.5); + let svg = vectorcraft_svg::export(&doc, &Default::default()); + assert!(svg.contains("<image") && svg.contains("stroke-width=\"8\""), "{svg}"); + let back = vectorcraft_pdf::import(&vectorcraft_pdf::export(&doc, &Default::default()).unwrap()).unwrap(); + let mut outlines = 0; + for l in &back.layers { + l.walk(&mut |n| { + let stroked = (n.appearance.stroke_width() - 8.0).abs() < 0.01; + outlines += usize::from(matches!(n.kind, NodeKind::Path { .. }) && stroked && n.geometric_bounds().is_some_and(disc)); + }); + } + assert_eq!(outlines, 1); + // Expand Appearance leaves the disc's outline below the image. + run(&mut s, "effect.expandAppearance", json!({})); + let n = node(&s, im); + let kids = n.children().unwrap(); + assert!(kids.len() == 2 && matches!(kids[1].kind, NodeKind::Image(_)), "{n:?}"); + assert!(disc(kids[0].geometric_bounds().unwrap()), "{:?}", kids[0].geometric_bounds()); + run(&mut s, "edit.undo", json!({})); + // An Offset Path of 3 pt after Outline Object moves the stroke 3 pt out: it shows from 63 to 70. + run(&mut s, "effect.apply", json!({"effect": "path.offsetPath", "params": {"offset": 3}, "item": 0})); + assert_eq!([shade(&s, 61, 100), shade(&s, 64, 100)], ["white", "black"]); + // Relinked to an opaque image, the stroke follows the frame 3 pt out: it shows from 43 to 50. + let dir = vectorcraft_testkit::TempDir::new("outline-object-relink"); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("opaque.png"); + let mut png = vec![]; + image::RgbaImage::from_pixel(100, 100, image::Rgba([255, 0, 0, 255])) + .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .unwrap(); + std::fs::write(&path, png).unwrap(); + run(&mut s, "links.relink", json!({"ids": [im.0], "path": path})); + assert_eq!([shade(&s, 41, 100), shade(&s, 45, 100), shade(&s, 64, 100)], ["white", "black", "red"]); +} + +#[test] +fn an_images_outline_object_stroke_exports_selects_and_measures_along_its_opaque_area() { + let mut s = session(); + // The frame runs from 50 to 150, the disc from 70 to 130. + let r = run(&mut s, "file.place", json!({"name": "disc.png", "dataBase64": vectorcraft_format::base64_encode(&disc_png()), "at": [100, 100]})); + let im = NodeId(r["ids"][0].as_u64().unwrap()); + run(&mut s, "appearance.addStroke", json!({})); + run(&mut s, "appearance.setItem", json!({"index": 0, "weight": 20, "color": "#000000"})); + run(&mut s, "effect.apply", json!({"effect": "path.outlineObject", "item": 0})); + // EPS and the PDF-compatible .ai draw the disc's outline stroked 20 pt, 20 pt inside the + // image's frame on each side (EPS moves the art to its bounding box). + let disc_outlines = |d: &vectorcraft_doc::Document| { + let mut frame = None; + d.walk(|c| { + if matches!(c.kind, NodeKind::Image(_)) { + frame = c.geometric_bounds(); + } + }); + let f = frame.unwrap(); + let mut n = 0; + d.walk(|c| { + let disc = |b: vectorcraft_geom::Rect| { + [b.x0 - f.x0 - 20.0, b.y0 - f.y0 - 20.0, f.x1 - b.x1 - 20.0, f.y1 - b.y1 - 20.0].iter().all(|d| d.abs() < 0.6) + }; + let stroked = (c.appearance.stroke_width() - 20.0).abs() < 0.01; + n += usize::from(matches!(c.kind, NodeKind::Path { .. }) && stroked && c.geometric_bounds().is_some_and(disc)); + }); + n + }; + let saved = |s: &mut Session, p: Value| vectorcraft_format::base64_decode(run(s, "file.saveCopy", p)["dataBase64"].as_str().unwrap()).unwrap(); + let eps = saved(&mut s, json!({"format": "eps", "previewFormat": "none", "thumbnails": false})); + assert_eq!(disc_outlines(&vectorcraft_eps::import_with(&eps, false).unwrap().document), 1); + let ai = saved(&mut s, json!({"format": "ai"})); + assert_eq!(disc_outlines(&crate::cmd::fileio::page_document(&ai, 0, &Default::default()).unwrap().0), 1); + // An Offset Path of 30 pt after Outline Object: the stroke runs round a circle of radius 60, + // from 30 to 50 on the left, where along the frame it would run from 10 to 30. + run(&mut s, "effect.apply", json!({"effect": "path.offsetPath", "params": {"offset": 30}, "item": 0})); + assert_eq!((pixel(&s, 35, 100), pixel(&s, 15, 100)), ([0, 0, 0, 255], [255; 4])); + run(&mut s, "select.none", json!({})); + assert_eq!(click(&mut s, 35.0, 100.0), [im]); + run(&mut s, "select.none", json!({})); + assert!(click(&mut s, 15.0, 100.0).is_empty()); + // Use Preview Bounds measures the stroke round the circle. + s.prefs.use_preview_bounds = true; + let b = s.transform_bounds(&[im]).unwrap(); + assert!([b.x0 - 30.0, b.y0 - 30.0, b.x1 - 170.0, b.y1 - 170.0].iter().all(|d| d.abs() < 1.0), "{b:?}"); +} + /// Click with the Selection tool at (x, y) on a 100% view: what is selected afterwards. fn click(s: &mut Session, x: f64, y: f64) -> Vec<NodeId> { let v = ViewInfo::default(); diff --git a/crates/engine/src/tests/css.rs b/crates/engine/src/tests/css.rs index 764990b100..39fb6a5bc2 100644 --- a/crates/engine/src/tests/css.rs +++ b/crates/engine/src/tests/css.rs @@ -57,6 +57,28 @@ fn type_gives_font_properties_and_gradients_css_gradients() { assert!(text.contains("background-image: linear-gradient(90deg, "), "{text}"); } +/// CSS gradients mix linearly: a gradient mixed around the hue wheel is written through the stops +/// on its way around the wheel, so red to blue lists green one way and magenta the other. +#[test] +fn gradients_mixed_around_the_hue_wheel_give_css_the_stops_on_their_way() { + let mut s = session(); + run(&mut s, "shape.rectangle", json!({"x": 0, "y": 100, "width": 100, "height": 50})); + let stops = json!([{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]); + let gradient = |s: &mut Session, method: &str| { + run(s, "paint.setFill", json!({"gradient": {"kind": "linear", "method": method, "stops": stops}})); + let text = css(&run(s, "css.selection", json!({}))).to_string(); + text.lines().find(|l| l.contains("linear-gradient(")).unwrap_or_else(|| panic!("a gradient in {text}")).to_string() + }; + let classic = gradient(&mut s, "classic"); + assert_eq!(classic.matches('%').count(), 2, "{classic}"); + for (method, middle, other) in [("hue-counterclockwise", "#00ff00 50%", "#ff00ff"), ("hue-clockwise", "#ff00ff 50%", "#00ff00")] { + let line = gradient(&mut s, method); + assert!(line.matches('%').count() > 2, "{method}: {line}"); + assert!(line.contains("#ff0000 0%") && line.contains("#0000ff 100%"), "{method}: {line}"); + assert!(line.contains(middle) && !line.contains(other), "{method}: {line}"); + } +} + #[test] fn generate_covers_the_document_and_an_empty_selection_has_none() { let mut s = session(); @@ -98,6 +120,69 @@ fn export_writes_the_sheet_and_rasterized_art() { assert!(s.execute("css.export", &json!({})).is_err(), "nothing selected: nothing to export"); } +#[test] +fn export_refuses_a_scope_or_path_that_is_not_a_string() { + let mut s = session(); + run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40})); + run(&mut s, "shape.ellipse", json!({"x": 60, "y": 0, "width": 40, "height": 40})); + let refused = |s: &mut Session, p: Value, key: &str| { + let e = s.execute("css.export", &p).expect_err(&p.to_string()).to_string(); + assert_eq!(e, format!("invalid parameters for `css.export`: `{key}` must be a string"), "{p}"); + }; + for scope in [json!(5), json!(true), json!(["all"]), Value::Null] { + refused(&mut s, json!({"scope": scope}), "scope"); + } + for path in [json!(5), Value::Null] { + refused(&mut s, json!({"path": path}), "path"); + refused(&mut s, json!({"path": path, "scope": "all"}), "path"); + } + // Left out, each keeps its default: the selection (the ellipse), and the CSS as data. + let r = run(&mut s, "css.export", json!({})); + assert_eq!((r["rules"].clone(), r["data"].is_string()), (json!(1), true), "{r}"); + assert_eq!(run(&mut s, "css.export", json!({"scope": "all"}))["rules"], json!(2)); + let e = s.execute("css.export", &json!({"scope": "page"})).unwrap_err().to_string(); + assert!(e.contains("scope must be selection or all (got page)"), "{e}"); +} + +#[test] +fn every_object_refuses_malformed_ids_it_does_not_use() { + let mut s = session(); + let rect = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].as_u64().unwrap(); + run(&mut s, "shape.ellipse", json!({"x": 60, "y": 0, "width": 40, "height": 40})); + for (cmd, base) in [("css.generate", json!({})), ("css.export", json!({"scope": "all"}))] { + for (key, value, says) in [ + ("ids", json!("abc"), "`ids` must be an array of object ids, not \"abc\""), + ("ids", json!([1.5]), "object ids are non-negative integers, not 1.5"), + ("id", json!(-1), "object ids are non-negative integers, not -1"), + ("id", json!("$step"), "`id` is the step reference \"$step\""), + ] { + let mut p = base.clone(); + p[key] = value; + let e = s.execute(cmd, &p).expect_err(&format!("{cmd} {p}")).to_string(); + assert!(e.contains(says), "{cmd} {p}: {e}"); + } + // Well-formed ids are still not used: every object. + let mut p = base.clone(); + p["ids"] = json!([rect]); + let rules = run(&mut s, cmd, p)["rules"].clone(); + let count = rules.as_array().map_or(rules.as_u64(), |r| Some(r.len() as u64)); + assert_eq!(count, Some(2), "{cmd}: {rules}"); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn export_with_a_scope_that_is_not_a_string_writes_nothing() { + let mut s = session(); + run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40})); + let dir = std::env::temp_dir().join(format!("vc-css-scope-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("site.css"); + assert!(s.execute("css.export", &json!({"path": path.to_string_lossy(), "scope": 5})).is_err()); + assert!(!path.exists(), "no file for a refused scope"); + std::fs::remove_dir_all(&dir).ok(); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn export_to_a_path_puts_the_pictures_next_to_the_sheet() { diff --git a/crates/engine/src/tests/dcs.rs b/crates/engine/src/tests/dcs.rs new file mode 100644 index 0000000000..b780f14c09 --- /dev/null +++ b/crates/engine/src/tests/dcs.rs @@ -0,0 +1,915 @@ +//! DCS files placed with Link (`file.place`): one linked image of their plates, their spot plates +//! as spot swatches, clipped by their composite's clipping path, never opened or embedded; and +//! the Links panel's Show DCS Transparency Interactions (`links.list` with `dcsTransparency`). +//! The files are made from scratch as http://www.telegraphics.net/doc/DCS.txt describes them. + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Node, NodeKind}; + +use crate::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s +} + +/// A fresh scratch folder for one test, removed when dropped. +fn temp_dir(name: &str) -> vectorcraft_testkit::TempDir { + vectorcraft_testkit::TempDir::new(&format!("dcs-{name}")) +} + +/// A plate program: one 2 × 2 grayscale image (`gray`, row by row) on a 20 × 10 pt page. +fn plate_eps(gray: [u8; 4]) -> String { + let hex: String = gray.iter().map(|g| format!("{g:02x}")).collect(); + format!( + "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 20 10\n%%EndComments\n20 10 scale\n2 2 8 [2 0 0 -2 0 2] <{hex}> image\nshowpage\n%%Trailer\n%%EOF\n" + ) +} + +/// A single-file DCS 2.0 file of `plates` (name, plate program), with the header lines `extra`; its +/// composite is drawn through a clipping path, the left half of the page. +fn single_file(plates: &[(&str, String)], extra: &str) -> Vec<u8> { + let header = |offsets: &[usize]| { + let mut s = String::from("%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 20 10\n"); + s.push_str(extra); + for ((name, eps), at) in plates.iter().zip(offsets) { + s.push_str(&format!("%%PlateFile: ({name}) EPS #{at:010} {:010}\n", eps.len())); + } + s.push_str("%%EndComments\ngsave newpath 0 0 moveto 10 0 lineto 10 10 lineto 0 10 lineto closepath clip newpath\n"); + s.push_str("20 10 scale 2 2 8 [2 0 0 -2 0 2] <808080808080808080808080> false 3 colorimage grestore showpage\n%%EOF\n"); + s + }; + let main = header(&vec![0; plates.len()]).len(); + let mut offsets = vec![]; + let mut at = main; + for (_, eps) in plates { + offsets.push(at); + at += eps.len(); + } + let mut out = header(&offsets).into_bytes(); + for (_, eps) in plates { + out.extend(eps.as_bytes()); + } + out +} + +/// Cyan solid on the top row, PANTONE 185 C at 50% on the left column. +fn two_plates() -> Vec<u8> { + single_file( + &[("Cyan", plate_eps([0, 0, 255, 255])), ("PANTONE 185 C", plate_eps([127, 255, 127, 255]))], + "%%DocumentCustomColors: (PANTONE 185 C)\n%%CMYKCustomColor: 0 .91 .76 0 (PANTONE 185 C)\n", + ) +} + +fn write(dir: &std::path::Path, name: &str, bytes: &[u8]) -> String { + let p = dir.join(name); + std::fs::write(&p, bytes).unwrap(); + p.to_string_lossy().into_owned() +} + +/// The image inside placed object `id` (itself, or the image of its clipping group). +fn image_of(s: &Session, id: &Value) -> Node { + let n = s.doc().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap().clone(); + let mut found = None; + n.walk(&mut |c: &Node| { + if found.is_none() && matches!(c.kind, NodeKind::Image(_)) { + found = Some(c.clone()); + } + }); + found.expect("an image") +} + +fn error(s: &mut Session, cmd: &str, p: Value) -> String { + s.execute(cmd, &p).unwrap_err().to_string() +} + +#[test] +fn a_dcs_file_places_as_one_linked_image_of_its_plates() { + let dir = temp_dir("place"); + let path = write(&dir, "pic.eps", &two_plates()); + let mut s = session(); + let r = s.execute("file.place", &json!({ "path": path, "at": [100, 100] })).unwrap(); + assert_eq!(r["linked"], true); + assert_eq!(r["warnings"], json!([])); + let id = &r["ids"][0]; + let placed = s.doc().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap().clone(); + let NodeKind::Group { children, clip: true } = &placed.kind else { panic!("a clipping group: {:?}", placed.kind) }; + assert!(matches!(children[0].kind, NodeKind::Path { clipping: true, .. }), "the composite's clipping path"); + assert_eq!(children[0].geometric_bounds().map(|b| b.width().round()), Some(10.0)); + assert_eq!(r["width"].as_f64().map(f64::round), Some(10.0), "clipped to the left half of its 20 pt page"); + let image = image_of(&s, id); + let NodeKind::Image(im) = &image.kind else { not_an_image() }; + assert!(im.link.as_ref().is_some_and(|l| l.path.ends_with("pic.eps"))); + let doc = &s.doc().unwrap().doc; + let plates = doc.images[&im.key].separated().expect("its plates are kept"); + assert_eq!(plates.plates.iter().map(|p| p.name.as_str()).collect::<Vec<_>>(), ["Cyan", "PANTONE 185 C"]); + assert_eq!(plates.plates[1].data, [128, 0, 128, 0]); + let sw = doc.swatch("PANTONE 185 C").expect("a spot swatch for the spot plate"); + assert!(sw.spot); + assert_eq!(sw.paint, Paint::solid(Color::cmyk(0.0, 0.91, 0.76, 0.0))); + assert!(!doc.swatches_iter().any(|w| w.spot && w.name == "Cyan"), "process plates add no spot swatch"); + let list = s.execute("links.list", &json!({})).unwrap(); + assert_eq!(list["links"][0]["format"], "DCS"); + assert_eq!(list["links"][0]["status"], "ok"); + let info = s.execute("file.place.info", &json!({ "path": path })).unwrap(); + assert_eq!(info["plates"], json!(["Cyan", "PANTONE 185 C"])); + assert_eq!(info["colorMode"], "CMYK"); + assert_eq!(info["pixelWidth"], 2); + // One undo step takes the swatch away too. + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.swatch("PANTONE 185 C").is_none()); +} + +fn not_an_image() -> ! { + panic!("an image") +} + +#[test] +fn a_dcs_file_is_never_opened_or_embedded() { + let dir = temp_dir("refused"); + let bytes = two_plates(); + let path = write(&dir, "pic.eps", &bytes); + let mut s = session(); + let only = "DCS files can only be placed linked"; + assert!(error(&mut s, "file.place", json!({ "path": path, "link": false })).contains(only)); + let data = json!({ "name": "pic.eps", "dataBase64": vectorcraft_format::base64_encode(&bytes) }); + assert!(error(&mut s, "file.place", data).contains(only), "bytes alone can't be linked"); + assert!(error(&mut s, "document.open", json!({ "path": path })).contains(only)); + let r = s.execute("file.place", &json!({ "path": path })).unwrap(); + let image = image_of(&s, &r["ids"][0]); + let e = error(&mut s, "links.embed", json!({ "ids": [image.id.0] })); + assert!(e.contains(only), "{e}"); + let NodeKind::Image(im) = &image_of(&s, &r["ids"][0]).kind else { not_an_image() }; + assert!(im.link.is_some(), "still linked"); +} + +#[test] +fn a_swatch_of_the_same_name_is_kept_with_a_warning() { + let dir = temp_dir("swatch"); + let path = write(&dir, "pic.eps", &two_plates()); + let mut s = session(); + s.execute("swatch.new", &json!({"name": "PANTONE 185 C", "color": {"c": 0.0, "m": 1.0, "y": 1.0, "k": 0.0}, "spot": true})).unwrap(); + let r = s.execute("file.place", &json!({ "path": path })).unwrap(); + assert_eq!(r["warnings"], json!(["the document's swatch `PANTONE 185 C` is kept: it is a different color"])); + let sw = s.doc().unwrap().doc.swatch("PANTONE 185 C").unwrap().clone(); + assert_eq!(sw.paint.color(), Some(Color::cmyk(0.0, 1.0, 1.0, 0.0))); +} + +#[test] +fn plate_files_of_their_own_are_read_from_the_dcs_files_folder() { + let dir = temp_dir("files"); + write(&dir, "pic.C", plate_eps([0, 255, 255, 255]).as_bytes()); + write(&dir, "pic.K", plate_eps([255, 255, 255, 0]).as_bytes()); + let main = "%!PS-Adobe-2.0 EPSF-1.2\n%%BoundingBox: 0 0 20 10\n%%CyanPlate: OldDisk:Scans:pic.C\n%%BlackPlate: pic.K\n%%EndComments\nshowpage\n"; + let path = write(&dir, "pic.eps", main.as_bytes()); + let mut s = session(); + let r = s.execute("file.place", &json!({ "path": path })).unwrap(); + let image = image_of(&s, &r["ids"][0]); + assert!(matches!(image.kind, NodeKind::Image(_)), "no clipping path without a composite"); + let NodeKind::Image(im) = &image.kind else { not_an_image() }; + let plates = s.doc().unwrap().doc.images[&im.key].separated().unwrap(); + assert_eq!(plates.plates[0].data, [255, 0, 0, 0], "the plate file found by its name in the folder"); + assert_eq!(plates.plates[1].data, [0, 0, 0, 255]); + std::fs::remove_file(dir.join("pic.K")).unwrap(); + let e = error(&mut s, "file.place", json!({ "path": path })); + assert!(e.contains("the Black plate can't be read") && e.contains("`pic.K` is not in the DCS file's folder"), "{e}"); +} + +#[test] +fn update_link_reads_the_plates_again() { + let dir = temp_dir("update"); + let path = write(&dir, "pic.eps", &two_plates()); + let mut s = session(); + let r = s.execute("file.place", &json!({ "path": path })).unwrap(); + let id = image_of(&s, &r["ids"][0]).id; + let changed = single_file(&[("Cyan", plate_eps([0, 0, 0, 0])), ("Varnish", plate_eps([255; 4]))], "%%CMYKCustomColor: 0 0 .2 0 (Varnish)\n"); + std::fs::write(&path, &changed).unwrap(); + let u = s.execute("links.update", &json!({ "ids": [id.0] })).unwrap(); + assert_eq!(u["updated"], json!([id.0])); + let NodeKind::Image(im) = &s.doc().unwrap().doc.node(id).unwrap().kind else { not_an_image() }; + let plates = s.doc().unwrap().doc.images[&im.key].separated().unwrap(); + assert_eq!(plates.plates.len(), 2); + assert_eq!(plates.plates[0].data, [255; 4]); + let sw = s.doc().unwrap().doc.swatch("Varnish").expect("a spot swatch for the plate the file gained"); + assert!(sw.spot); + assert_eq!(sw.paint, Paint::solid(Color::cmyk(0.0, 0.0, 0.2, 0.0))); +} + +#[test] +fn update_link_takes_the_files_new_clipping_path() { + let dir = temp_dir("update-clip"); + let path = write(&dir, "pic.eps", &two_plates()); + let mut s = session(); + let r = s.execute("file.place", &json!({ "path": path, "at": [100, 100] })).unwrap(); + let group = NodeId(r["ids"][0].as_u64().unwrap()); + let id = image_of(&s, &r["ids"][0]).id; + let clip_width = |s: &Session| { + let NodeKind::Group { children, .. } = &s.doc().unwrap().doc.node(group).unwrap().kind else { panic!("a clipping group") }; + children[0].geometric_bounds().map(|b| b.width()) + }; + let before = clip_width(&s).unwrap(); + // The same file, its composite now drawn through the left quarter of the page (same length, + // so the plates stay where the header says). + let text = String::from_utf8(two_plates()).unwrap().replacen("10 0 lineto 10 10 lineto", " 5 0 lineto 5 10 lineto", 1); + std::fs::write(&path, text.as_bytes()).unwrap(); + let u = s.execute("links.update", &json!({ "ids": [id.0] })).unwrap(); + assert_eq!(u["updated"], json!([id.0])); + let after = clip_width(&s).unwrap(); + assert!((after - before / 2.0).abs() < 1e-6, "the clipping path follows the file: {before} → {after}"); +} + +#[test] +fn update_link_clips_an_image_whose_file_gained_a_clipping_path() { + let dir = temp_dir("update-gained-clip"); + // The composite drawn without its clipping path (same length). + let unclipped = String::from_utf8(two_plates()).unwrap().replacen("closepath clip newpath", "closepath newpath ", 1); + let path = write(&dir, "pic.eps", unclipped.as_bytes()); + let mut s = session(); + let r = s.execute("file.place", &json!({ "path": path })).unwrap(); + let id = NodeId(r["ids"][0].as_u64().unwrap()); + assert!(matches!(s.doc().unwrap().doc.node(id).unwrap().kind, NodeKind::Image(_)), "no clipping path, no group"); + std::fs::write(&path, two_plates()).unwrap(); + s.execute("links.update", &json!({ "ids": [id.0] })).unwrap(); + let doc = &s.doc().unwrap().doc; + let group = doc.node(doc.parent_of(id).expect("a parent")).unwrap(); + let NodeKind::Group { children, clip: true } = &group.kind else { panic!("a clipping group: {:?}", group.kind) }; + assert_eq!(children[0].geometric_bounds().map(|b| b.width().round()), Some(10.0), "the left half of the page"); +} + +#[test] +fn a_changed_plate_file_marks_the_link_modified() { + let dir = temp_dir("plate-changed"); + write(&dir, "pic.C", plate_eps([0, 255, 255, 255]).as_bytes()); + let main = "%!PS-Adobe-2.0 EPSF-1.2\n%%BoundingBox: 0 0 20 10\n%%CyanPlate: pic.C\n%%EndComments\nshowpage\n"; + let path = write(&dir, "pic.eps", main.as_bytes()); + let mut s = session(); + let r = s.execute("file.place", &json!({ "path": path })).unwrap(); + let id = image_of(&s, &r["ids"][0]).id; + assert_eq!(s.execute("links.list", &json!({})).unwrap()["links"][0]["status"], "ok"); + // Only the plate file changes (a size of its own, so the change shows whatever the clock). + write(&dir, "pic.C", format!("{}% more\n", plate_eps([255, 255, 255, 0])).as_bytes()); + assert_eq!(s.execute("links.list", &json!({})).unwrap()["links"][0]["status"], "modified"); + let u = s.execute("links.update", &json!({})).unwrap(); + assert_eq!(u["updated"], json!([id.0])); + let NodeKind::Image(im) = &s.doc().unwrap().doc.node(id).unwrap().kind else { not_an_image() }; + assert_eq!(s.doc().unwrap().doc.images[&im.key].separated().unwrap().plates[0].data, [0, 0, 0, 255]); + assert_eq!(s.execute("links.list", &json!({})).unwrap()["links"][0]["status"], "ok"); + std::fs::remove_file(dir.join("pic.C")).unwrap(); + assert_eq!(s.execute("links.list", &json!({})).unwrap()["links"][0]["status"], "modified", "a plate file that is gone"); +} + +#[test] +fn the_link_watch_reads_the_link_again_when_only_a_plate_file_changes() { + let dir = temp_dir("plate-watch"); + write(&dir, "pic.C", plate_eps([0, 255, 255, 255]).as_bytes()); + let main = "%!PS-Adobe-2.0 EPSF-1.2\n%%BoundingBox: 0 0 20 10\n%%CyanPlate: pic.C\n%%EndComments\nshowpage\n"; + let path = write(&dir, "pic.eps", main.as_bytes()); + let mut s = session(); + let r = s.execute("file.place", &json!({ "path": path })).unwrap(); + let id = image_of(&s, &r["ids"][0]).id; + let files: Vec<String> = crate::link_watch::linked_files(&s.doc().unwrap().doc).into_iter().map(|(p, _)| p).collect(); + assert!(files.iter().any(|p| p.ends_with("pic.C")), "the plate file is watched too: {files:?}"); + // The first look only remembers the files. + assert_eq!(s.execute("links.updateChanged", &json!({})).unwrap()["updated"], json!([])); + write(&dir, "pic.C", format!("{}% more\n", plate_eps([255, 255, 255, 0])).as_bytes()); + assert_eq!(s.execute("links.updateChanged", &json!({})).unwrap()["updated"], json!([id.0])); + let NodeKind::Image(im) = &s.doc().unwrap().doc.node(id).unwrap().kind else { not_an_image() }; + assert_eq!(s.doc().unwrap().doc.images[&im.key].separated().unwrap().plates[0].data, [0, 0, 0, 255]); +} + +/// The width of the clipping path of the clip group holding the image in the art of symbol +/// `name`; `None` when no clip group holds it. +fn symbol_clip_width(s: &Session, name: &str) -> Option<f64> { + fn find(n: &Node) -> Option<Option<f64>> { + if let NodeKind::Group { children, clip: true } = &n.kind + && let [c, im] = &children[..] + && matches!(im.kind, NodeKind::Image(_)) + { + return Some(c.geometric_bounds().map(|b| b.width())); + } + if matches!(n.kind, NodeKind::Image(_)) { + return Some(None); + } + n.children().and_then(|ch| ch.iter().find_map(|c| find(c))) + } + let doc = &s.doc().unwrap().doc; + find(&doc.symbols.iter().find(|w| w.name == name).expect("the symbol").art).expect("an image in the symbol") +} + +#[test] +fn update_link_takes_the_files_clipping_path_into_symbols_too() { + let dir = temp_dir("update-symbol-clip"); + let path = write(&dir, "pic.eps", &two_plates()); + let mut s = session(); + let r = s.execute("file.place", &json!({ "path": path, "at": [100, 100] })).unwrap(); + let id = image_of(&s, &r["ids"][0]).id; + let other = s.execute("file.place", &json!({ "path": path, "at": [200, 100] })).unwrap(); + s.execute("symbol.new", &json!({ "name": "Pic", "ids": [other["ids"][0]] })).unwrap(); + let before = symbol_clip_width(&s, "Pic").expect("the file's clipping path"); + // The composite now drawn through the left quarter of the page (same length). + let text = String::from_utf8(two_plates()).unwrap().replacen("10 0 lineto 10 10 lineto", " 5 0 lineto 5 10 lineto", 1); + std::fs::write(&path, text.as_bytes()).unwrap(); + s.execute("links.update", &json!({ "ids": [id.0] })).unwrap(); + let after = symbol_clip_width(&s, "Pic").expect("still clipped"); + assert!((after - before / 2.0).abs() < 1e-6, "the symbol's clipping path follows the file: {before} → {after}"); + // The file without a clipping path (same length): the symbol's image is no longer clipped. + let unclipped = text.replacen("closepath clip newpath", "closepath newpath ", 1); + std::fs::write(&path, unclipped.as_bytes()).unwrap(); + s.execute("links.update", &json!({ "ids": [id.0] })).unwrap(); + assert_eq!(symbol_clip_width(&s, "Pic"), None); +} + +#[test] +fn update_and_relink_by_id_keep_the_clipping_path_of_a_dcs_image_in_a_symbol() { + let dir = temp_dir("symbol-clip-by-id"); + let path = write(&dir, "pic.eps", &two_plates()); + let mut s = session(); + let r = s.execute("file.place", &json!({ "path": path, "at": [100, 100] })).unwrap(); + s.execute("symbol.new", &json!({ "name": "Pic", "ids": [r["ids"][0]] })).unwrap(); + let list = s.execute("links.list", &json!({})).unwrap(); + let row = list["links"].as_array().unwrap().iter().find(|r| r["owner"]["kind"] == "symbol").cloned().expect("the symbol's image is listed"); + let id = row["id"].as_u64().unwrap(); + assert_eq!(row["format"], "DCS", "{list}"); + let before = symbol_clip_width(&s, "Pic").expect("the file's clipping path"); + // The composite now drawn through the left quarter of the page (same length). + let text = String::from_utf8(two_plates()).unwrap().replacen("10 0 lineto 10 10 lineto", " 5 0 lineto 5 10 lineto", 1); + std::fs::write(&path, text.as_bytes()).unwrap(); + assert_eq!(s.execute("links.update", &json!({ "ids": [id] })).unwrap()["updated"], json!([id])); + let after = symbol_clip_width(&s, "Pic").expect("still clipped"); + assert!((after - before / 2.0).abs() < 1e-6, "the symbol's clipping path follows the file: {before} → {after}"); + // Relinked by its id to a plain image: the DCS file's clipping path goes. + let png = dir.join("plain.png"); + image::RgbImage::from_pixel(2, 2, image::Rgb([9, 9, 9])).save(&png).unwrap(); + s.execute("links.relink", &json!({ "ids": [id], "path": png.to_string_lossy() })).unwrap(); + assert_eq!(symbol_clip_width(&s, "Pic"), None); +} + +#[test] +fn a_file_that_lost_its_clipping_path_unclips_the_image() { + let dir = temp_dir("update-lost-clip"); + let path = write(&dir, "pic.eps", &two_plates()); + let mut s = session(); + let r = s.execute("file.place", &json!({ "path": path })).unwrap(); + let id = image_of(&s, &r["ids"][0]).id; + let unclipped = String::from_utf8(two_plates()).unwrap().replacen("closepath clip newpath", "closepath newpath ", 1); + std::fs::write(&path, unclipped.as_bytes()).unwrap(); + s.execute("links.update", &json!({ "ids": [id.0] })).unwrap(); + let doc = &s.doc().unwrap().doc; + let placed = NodeId(r["ids"][0].as_u64().unwrap()); + assert_eq!(doc.node(placed).and_then(plain_group_of_image), Some((false, true)), "the placed group stays, without the clip"); + let parent = doc.parent_of(id).expect("a parent"); + assert!(!matches!(doc.node(parent).unwrap().kind, NodeKind::Group { clip: true, .. }), "the image is not clipped"); + // Relinked to a plain image: no clip group either. + let png = dir.join("plain.png"); + image::RgbImage::from_pixel(2, 2, image::Rgb([9, 9, 9])).save(&png).unwrap(); + std::fs::write(&path, two_plates()).unwrap(); + s.execute("links.update", &json!({ "ids": [id.0] })).unwrap(); + assert!( + s.doc().unwrap().doc.parent_of(id).is_some_and(|p| matches!(s.doc().unwrap().doc.node(p).unwrap().kind, NodeKind::Group { clip: true, .. })) + ); + s.execute("links.relink", &json!({ "ids": [id.0], "path": png.to_string_lossy() })).unwrap(); + let doc = &s.doc().unwrap().doc; + assert!( + !matches!(doc.node(doc.parent_of(id).unwrap()).unwrap().kind, NodeKind::Group { clip: true, .. }), + "a plain image isn't clipped by the DCS file's path" + ); +} + +#[test] +fn a_file_that_gains_its_clipping_path_again_clips_the_group_that_stayed() { + let dir = temp_dir("update-regained-clip"); + let path = write(&dir, "pic.eps", &two_plates()); + let mut s = session(); + let r = s.execute("file.place", &json!({ "path": path, "at": [100, 100] })).unwrap(); + let placed = NodeId(r["ids"][0].as_u64().unwrap()); + let id = image_of(&s, &r["ids"][0]).id; + let other = s.execute("file.place", &json!({ "path": path, "at": [200, 100] })).unwrap(); + s.execute("symbol.new", &json!({ "name": "Pic", "ids": [other["ids"][0]] })).unwrap(); + let unclipped = String::from_utf8(two_plates()).unwrap().replacen("closepath clip newpath", "closepath newpath ", 1); + // The symbol's art: how deep the image is. + let depth = |s: &Session| { + fn find(n: &Node, at: usize) -> Option<usize> { + if matches!(n.kind, NodeKind::Image(_)) { + return Some(at); + } + n.children().and_then(|ch| ch.iter().find_map(|c| find(c, at + 1))) + } + find(&s.doc().unwrap().doc.symbols.iter().find(|w| w.name == "Pic").expect("the symbol").art, 0) + }; + let clipped_depth = depth(&s); + for _ in 0..2 { + std::fs::write(&path, unclipped.as_bytes()).unwrap(); + s.execute("links.update", &json!({ "ids": [id.0] })).unwrap(); + std::fs::write(&path, two_plates()).unwrap(); + s.execute("links.update", &json!({ "ids": [id.0] })).unwrap(); + let doc = &s.doc().unwrap().doc; + assert_eq!(doc.parent_of(id), Some(placed), "the placed group holds the image itself"); + let NodeKind::Group { children, clip: true } = &doc.node(placed).unwrap().kind else { panic!("a clip group again") }; + assert!(matches!(&children[..], [c, im] if matches!(c.kind, NodeKind::Path { clipping: true, .. }) && im.id == id)); + assert_eq!(depth(&s), clipped_depth, "the symbol's image is not nested deeper"); + assert!(symbol_clip_width(&s, "Pic").is_some(), "the symbol's image is clipped again"); + } +} + +/// The kind of group `g` is, as (clip, the kinds of its children are just one image). +fn plain_group_of_image(g: &Node) -> Option<(bool, bool)> { + match &g.kind { + NodeKind::Group { children, clip } => Some((*clip, matches!(&children[..], [c] if matches!(c.kind, NodeKind::Image(_))))), + _ => None, + } +} + +#[test] +fn a_hidden_or_transparent_clip_group_loses_the_files_old_clipping_path() { + let dir = temp_dir("lost-clip-kept-group"); + let path = write(&dir, "pic.eps", &two_plates()); + let mut s = session(); + let place = |s: &mut Session, x: f64| s.execute("file.place", &json!({ "path": path, "at": [x, 100] })).unwrap(); + let (faded, hidden, in_symbol) = (place(&mut s, 100.0), place(&mut s, 200.0), place(&mut s, 300.0)); + let (faded, hidden) = (NodeId(faded["ids"][0].as_u64().unwrap()), NodeId(hidden["ids"][0].as_u64().unwrap())); + let image = image_of(&s, &json!(faded.0)).id; + s.execute("transparency.set", &json!({"ids": [faded.0, in_symbol["ids"][0]], "opacity": 50})).unwrap(); + s.edit("hide", |d, _| { + if let Some(n) = d.node_mut(hidden) { + n.visible = false; + } + Ok(()) + }) + .unwrap(); + s.execute("symbol.new", &json!({ "name": "Pic", "ids": [in_symbol["ids"][0]] })).unwrap(); + let unclipped = String::from_utf8(two_plates()).unwrap().replacen("closepath clip newpath", "closepath newpath ", 1); + std::fs::write(&path, unclipped.as_bytes()).unwrap(); + let hidden_image = image_of(&s, &json!(hidden.0)).id; + s.execute("links.update", &json!({ "ids": [image.0, hidden_image.0] })).unwrap(); + let doc = &s.doc().unwrap().doc; + for (g, why) in [(faded, "the transparent group"), (hidden, "the hidden group")] { + let n = doc.node(g).unwrap_or_else(|| panic!("{why} stays")); + assert_eq!(plain_group_of_image(n), Some((false, true)), "{why} holds the image alone, unclipped"); + } + assert!((doc.node(faded).unwrap().opacity - 0.5).abs() < 1e-6, "its transparency kept"); + assert!(!doc.node(hidden).unwrap().visible, "still hidden"); + // In a symbol's art too. + let art = &doc.symbols.iter().find(|w| w.name == "Pic").expect("the symbol").art; + let mut found = None; + art.walk(&mut |n: &Node| { + if found.is_none() && n.children().is_some_and(|ch| ch.iter().any(|c| matches!(c.kind, NodeKind::Image(_)))) { + found = plain_group_of_image(n); + } + }); + assert_eq!(found, Some((false, true)), "the symbol's transparent group holds the image alone, unclipped"); +} + +#[test] +fn a_clipping_mask_of_ones_own_stays_when_the_link_is_updated() { + let dir = temp_dir("own-mask"); + let unclipped = String::from_utf8(two_plates()).unwrap().replacen("closepath clip newpath", "closepath newpath ", 1); + let path = write(&dir, "pic.eps", unclipped.as_bytes()); + let mut s = session(); + let r = s.execute("file.place", &json!({ "path": path, "at": [100, 100] })).unwrap(); + let id = NodeId(r["ids"][0].as_u64().unwrap()); + let rect = s.execute("shape.rectangle", &json!({"x": 95, "y": 95, "width": 4, "height": 4})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({ "ids": [id.0, rect] })).unwrap(); + let g = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("links.update", &json!({ "ids": [id.0] })).unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(g), "the clipping mask made in the document stays"); + let mask_width = |s: &Session| { + let NodeKind::Group { children, .. } = &s.doc().unwrap().doc.node(g).unwrap().kind else { panic!("the mask's group") }; + children[0].geometric_bounds().map(|b| b.width().round()) + }; + assert_eq!(mask_width(&s), Some(4.0)); + // The file gains a clipping path: its clip group goes inside the mask, which keeps its path. + std::fs::write(&path, two_plates()).unwrap(); + s.execute("links.update", &json!({ "ids": [id.0] })).unwrap(); + let doc = &s.doc().unwrap().doc; + let inner = doc.parent_of(id).expect("a parent"); + assert_ne!(inner, g); + assert!(matches!(doc.node(inner).unwrap().kind, NodeKind::Group { clip: true, .. }), "the file's clip group"); + assert_eq!(doc.parent_of(inner), Some(g)); + assert_eq!(mask_width(&s), Some(4.0), "the mask's path is kept"); +} + +#[test] +fn a_dcs_file_takes_the_place_parameters_an_eps_file_takes() { + let dir = temp_dir("params"); + let path = write(&dir, "pic.eps", &two_plates()); + let mut s = session(); + assert!(error(&mut s, "file.place", json!({ "path": path, "page": 0 })).contains("page")); + assert!(error(&mut s, "file.place", json!({ "path": path, "crop": "trim" })).contains("crop")); +} + +#[test] +fn a_clipped_placement_answers_its_image_for_the_links_commands() { + let dir = temp_dir("image-id"); + let path = write(&dir, "pic.eps", &two_plates()); + let mut s = session(); + let r = s.execute("file.place", &json!({ "path": path })).unwrap(); + assert_eq!(r["image"], json!(image_of(&s, &r["ids"][0]).id.0)); + let info = s.execute("links.info", &json!({ "id": r["image"] })).unwrap(); + assert_eq!(info["format"], "DCS"); + let unclipped = String::from_utf8(two_plates()).unwrap().replacen("closepath clip newpath", "closepath newpath ", 1); + let plain = write(&dir, "plain.eps", unclipped.as_bytes()); + assert!(s.execute("file.place", &json!({ "path": plain })).unwrap().get("image").is_none(), "an image placed alone is its own id"); +} + +#[test] +fn update_and_relink_warn_of_a_swatch_kept_for_a_new_spot_plate() { + let dir = temp_dir("update-swatch"); + let path = write(&dir, "pic.eps", &two_plates()); + let mut s = session(); + let r = s.execute("file.place", &json!({ "path": path })).unwrap(); + let id = image_of(&s, &r["ids"][0]).id; + s.execute("swatch.new", &json!({"name": "Varnish", "color": {"c": 1.0, "m": 0.0, "y": 0.0, "k": 0.0}})).unwrap(); + let changed = single_file(&[("Cyan", plate_eps([0, 0, 0, 0])), ("Varnish", plate_eps([255; 4]))], "%%CMYKCustomColor: 0 0 .2 0 (Varnish)\n"); + std::fs::write(&path, &changed).unwrap(); + let u = s.execute("links.update", &json!({ "ids": [id.0] })).unwrap(); + let kept = "the document's swatch `Varnish` is kept: it is a process color, so the plate prints as process inks"; + assert_eq!(u["warnings"], json!([kept])); + let other = write(&dir, "other.eps", &changed); + let r = s.execute("links.relink", &json!({ "ids": [id.0], "path": other })).unwrap(); + assert_eq!(r["warnings"], json!([kept])); + assert!(s.execute("links.update", &json!({ "ids": [id.0] })).unwrap().get("warnings").is_some(), "every read warns"); +} + +#[test] +fn a_deleted_dcs_image_leaves_its_spot_swatch_unused() { + let dir = temp_dir("unused"); + let path = write(&dir, "pic.eps", &two_plates()); + let mut s = session(); + let r = s.execute("file.place", &json!({ "path": path })).unwrap(); + let unused = |s: &mut Session| s.execute("swatch.unused", &json!({})).unwrap()["names"].as_array().unwrap().iter().any(|n| n == "PANTONE 185 C"); + assert!(!unused(&mut s), "in use while the image shows it"); + s.execute("select.set", &json!({ "ids": [r["ids"][0]] })).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + assert!(unused(&mut s), "unused once the image is deleted"); +} + +#[test] +fn a_process_swatch_giving_a_dcs_plate_its_color_is_used() { + let dir = temp_dir("unused-process"); + let path = write(&dir, "pic.eps", &two_plates()); + let mut s = session(); + s.execute("swatch.new", &json!({"name": "PANTONE 185 C", "color": {"c": 1.0, "m": 0.0, "y": 0.0, "k": 0.0}})).unwrap(); + let unused = |s: &mut Session| s.execute("swatch.unused", &json!({})).unwrap()["names"].as_array().unwrap().iter().any(|n| n == "PANTONE 185 C"); + assert!(unused(&mut s), "nothing uses it yet"); + s.execute("file.place", &json!({ "path": path })).unwrap(); + assert!(!unused(&mut s), "the plate of its name prints as its process inks"); +} + +#[test] +fn an_opened_clipping_path_is_not_the_files_and_stays() { + let dir = temp_dir("opened-clip"); + let path = write(&dir, "pic.eps", &two_plates()); + let mut s = session(); + let r = s.execute("file.place", &json!({ "path": path })).unwrap(); + let group = NodeId(r["ids"][0].as_u64().unwrap()); + let id = image_of(&s, &r["ids"][0]).id; + // The clipping path opened, its anchors where they were. + s.edit("open", |d, _| { + let clip = d.node(group).and_then(|g| g.children()).map(|ch| ch[0].id).unwrap(); + if let Some(Node { kind: NodeKind::Path { path, .. }, .. }) = d.node_mut(clip) { + path.subpaths[0].closed = false; + } + Ok(()) + }) + .unwrap(); + let unclipped = String::from_utf8(two_plates()).unwrap().replacen("closepath clip newpath", "closepath newpath ", 1); + std::fs::write(&path, unclipped.as_bytes()).unwrap(); + s.execute("links.update", &json!({ "ids": [id.0] })).unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(group), "a clipping path edited in the document stays"); +} + +#[test] +fn a_clipping_path_given_another_fill_rule_is_not_the_files_and_stays() { + let dir = temp_dir("rule-clip"); + let path = write(&dir, "pic.eps", &two_plates()); + let mut s = session(); + let r = s.execute("file.place", &json!({ "path": path })).unwrap(); + let group = NodeId(r["ids"][0].as_u64().unwrap()); + let id = image_of(&s, &r["ids"][0]).id; + // The clipping path's fill rule changed, its anchors where they were. + s.edit("rule", |d, _| { + let clip = d.node(group).and_then(|g| g.children()).map(|ch| ch[0].id).unwrap(); + if let Some(Node { kind: NodeKind::Path { rule, .. }, .. }) = d.node_mut(clip) { + *rule = vectorcraft_geom::FillRule::EvenOdd; + } + Ok(()) + }) + .unwrap(); + let unclipped = String::from_utf8(two_plates()).unwrap().replacen("closepath clip newpath", "closepath newpath ", 1); + std::fs::write(&path, unclipped.as_bytes()).unwrap(); + s.execute("links.update", &json!({ "ids": [id.0] })).unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(group), "a clipping path whose fill rule was changed stays"); +} + +#[test] +fn an_even_odd_clipping_path_is_placed_and_matched_under_the_nonzero_rule() { + let dir = temp_dir("eo-clip"); + // The same length, so the plates' offsets hold. + let eo = String::from_utf8(two_plates()).unwrap().replacen("gsave newpath 0 0 moveto", "gsave 0 0 moveto ", 1); + let eo = eo.replacen("closepath clip newpath", "closepath eoclip newpath", 1); + assert_eq!(eo.len(), two_plates().len()); + let path = write(&dir, "pic.eps", eo.as_bytes()); + let mut s = session(); + let r = s.execute("file.place", &json!({ "path": path })).unwrap(); + let group = NodeId(r["ids"][0].as_u64().unwrap()); + let id = image_of(&s, &r["ids"][0]).id; + let doc = &s.doc().unwrap().doc; + let clip = &doc.node(group).and_then(|g| g.children()).expect("the file's clip group")[0]; + assert!(matches!(clip.kind, NodeKind::Path { rule: vectorcraft_geom::FillRule::NonZero, clipping: true, .. }), "{:?}", clip.kind); + // The file without its clipping path: the group's clipping path is the file's, and goes. + let unclipped = String::from_utf8(two_plates()).unwrap().replacen("closepath clip newpath", "closepath newpath ", 1); + std::fs::write(&path, unclipped.as_bytes()).unwrap(); + s.execute("links.update", &json!({ "ids": [id.0] })).unwrap(); + assert_eq!(s.doc().unwrap().doc.node(group).and_then(plain_group_of_image), Some((false, true)), "the file's clipping path is gone"); +} + +#[test] +fn files_updated_together_warn_when_they_add_one_ink_in_two_colors() { + let dir = temp_dir("update-two-inks"); + let (a, b) = (write(&dir, "a.eps", &two_plates()), write(&dir, "b.eps", &two_plates())); + let mut s = session(); + s.execute("file.place", &json!({ "path": a })).unwrap(); + s.execute("file.place", &json!({ "path": b })).unwrap(); + let varnish = + |c: &str| single_file(&[("Cyan", plate_eps([0; 4])), ("Varnish", plate_eps([255; 4]))], &format!("%%CMYKCustomColor: {c} (Varnish)\n")); + std::fs::write(&a, varnish("0 0 .2 0")).unwrap(); + std::fs::write(&b, varnish("1 0 0 0")).unwrap(); + let u = s.execute("links.update", &json!({})).unwrap(); + assert_eq!(u["updated"].as_array().map(Vec::len), Some(2), "{u}"); + assert_eq!(u["warnings"], json!(["the document's swatch `Varnish` is kept: it is a different color"])); +} + +#[test] +fn relink_with_copy_refuses_a_dcs_file_with_plate_files() { + let dir = temp_dir("copy"); + write(&dir, "pic.C", plate_eps([0, 255, 255, 255]).as_bytes()); + let main = "%!PS-Adobe-2.0 EPSF-1.2\n%%BoundingBox: 0 0 20 10\n%%CyanPlate: pic.C\n%%EndComments\nshowpage\n"; + let path = write(&dir, "pic.eps", main.as_bytes()); + let docs = dir.join("docs"); + std::fs::create_dir_all(&docs).unwrap(); + let mut s = session(); + s.execute("document.save", &json!({ "path": docs.join("doc.vectorcraft").to_string_lossy() })).unwrap(); + let png = dir.join("plain.png"); + image::RgbImage::from_pixel(2, 2, image::Rgb([9, 9, 9])).save(&png).unwrap(); + let r = s.execute("file.place", &json!({ "path": png.to_string_lossy() })).unwrap(); + let id = r["ids"][0].clone(); + let e = error(&mut s, "links.relink", json!({ "ids": [id], "path": path, "copy": true })); + assert!(e.contains("plate files"), "{e}"); + assert!(!docs.join("pic.eps").exists(), "nothing is copied"); + // A single-file DCS file has its plates inside it: it is copied. + let single = write(&dir, "single.eps", &two_plates()); + s.execute("links.relink", &json!({ "ids": [id], "path": single, "copy": true })).unwrap(); + assert!(docs.join("single.eps").exists()); +} + +#[test] +fn a_saved_document_reads_the_plates_again_and_prints_the_spot_ink() { + let dir = temp_dir("saved"); + let path = write(&dir, "pic.eps", &two_plates()); + let saved = dir.join("doc.vectorcraft").to_string_lossy().into_owned(); + let mut s = session(); + s.execute("file.place", &json!({ "path": path })).unwrap(); + let unused = s.execute("swatch.unused", &json!({})).unwrap(); + assert!(!unused["names"].as_array().unwrap().iter().any(|n| n == "PANTONE 185 C"), "the plate's swatch is in use: {unused}"); + s.execute("document.save", &json!({ "path": saved })).unwrap(); + let mut s = Session::new(); + s.execute("document.open", &json!({ "path": saved })).unwrap(); + let list = s.execute("links.list", &json!({})).unwrap(); + assert_eq!(list["links"][0]["format"], "DCS"); + assert_eq!(list["links"][0]["status"], "ok"); + let id = NodeId(list["links"][0]["id"].as_u64().unwrap()); + let NodeKind::Image(im) = &s.doc().unwrap().doc.node(id).unwrap().kind else { not_an_image() }; + let plates = s.doc().unwrap().doc.images[&im.key].separated().expect("the plates, read from the file again"); + assert_eq!(plates.plates[1].data, [128, 0, 128, 0]); + let v = s.execute("print.preview", &json!({"settings": {"output": {"mode": "separations"}}})).unwrap(); + let inks: Vec<&str> = v["sheets"].as_array().unwrap().iter().filter_map(|p| p["ink"].as_str()).collect(); + assert_eq!(inks, ["Cyan", "Magenta", "Yellow", "Black", "PANTONE 185 C"]); +} + +#[test] +fn a_saved_document_reads_the_plates_again_with_the_low_resolution_eps_proxy() { + let dir = temp_dir("saved-proxy"); + // Plates wider than a preview, so the saved document keeps a preview of the image. + let wide = |gray: u8| { + let hex = format!("{gray:02x}").repeat(300); + format!( + "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 20 10\n%%EndComments\n20 10 scale\n300 1 8 [300 0 0 -1 0 1] <{hex}> image\nshowpage\n%%Trailer\n%%EOF\n" + ) + }; + let file = single_file(&[("Cyan", wide(0)), ("PANTONE 185 C", wide(128))], "%%CMYKCustomColor: 0 .91 .76 0 (PANTONE 185 C)\n"); + let path = write(&dir, "pic.eps", &file); + let saved = dir.join("doc.vectorcraft").to_string_lossy().into_owned(); + let mut s = session(); + s.execute("file.place", &json!({ "path": path })).unwrap(); + s.execute("document.save", &json!({ "path": saved })).unwrap(); + let mut s = Session::new(); + s.execute("prefs.set", &json!({"key": "lowResProxyEps", "value": true})).unwrap(); + s.execute("document.open", &json!({ "path": saved })).unwrap(); + let list = s.execute("links.list", &json!({})).unwrap(); + assert_eq!(list["links"][0]["format"], "DCS", "{list}"); + let id = NodeId(list["links"][0]["id"].as_u64().unwrap()); + let NodeKind::Image(im) = &s.doc().unwrap().doc.node(id).unwrap().kind else { not_an_image() }; + assert!(s.doc().unwrap().doc.images[&im.key].separated().is_some(), "the plates, read from the file again"); +} + +#[test] +fn a_dcs_header_is_found_at_the_start_of_a_file_or_behind_a_binary_eps_header() { + use crate::cmd::place::dcs::{HEAD_BYTES, head_is_dcs, is_dcs}; + // A whole file, as `is_dcs` reads it. + let whole = |b: &[u8]| { + let is = head_is_dcs(b, b.len() as u64); + assert_eq!(is, Some(is_dcs(b))); + is + }; + let ps = two_plates(); + assert_eq!(whole(&ps), Some(true)); + assert_eq!(whole(b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 20 10\n%%EndComments\n"), Some(false)); + let binary = |start: u32| { + let mut b = vec![0xC5, 0xD0, 0xD3, 0xC6]; + b.extend(start.to_le_bytes()); + b.extend((ps.len() as u32).to_le_bytes()); + b.resize(start as usize, 0); + b.extend(&ps); + b + }; + assert_eq!(whole(&binary(30)), Some(true)); + // A binary header whose PostScript or TIFF preview ends past the end of the file names none. + let mut cut = binary(30); + cut[8..12].copy_from_slice(&(64u32 << 20).to_le_bytes()); + assert_eq!(whole(&cut), Some(false)); + let mut tiff = binary(30); + tiff[20..24].copy_from_slice(&30u32.to_le_bytes()); + tiff[24..28].copy_from_slice(&(64u32 << 20).to_le_bytes()); + assert_eq!(whole(&tiff), Some(false)); + // A file longer than the bytes read, its PostScript running past them: its header is read from + // the part there is, unless the header puts the PostScript or the preview past the file's end. + let mut big = binary(30); + big.resize(HEAD_BYTES, b' '); + big[8..12].copy_from_slice(&(64u32 << 20).to_le_bytes()); + assert_eq!(head_is_dcs(&big, 30 + (64 << 20)), Some(true)); + assert_eq!(head_is_dcs(&big, 30 + (64 << 20) - 1), Some(false)); + big[20..24].copy_from_slice(&30u32.to_le_bytes()); + big[24..28].copy_from_slice(&(65u32 << 20).to_le_bytes()); + assert_eq!(head_is_dcs(&big, 30 + (64 << 20)), Some(false)); + // PostScript that starts past the bytes read: the whole file is needed. + let far = binary(HEAD_BYTES as u32 + 10); + assert_eq!(head_is_dcs(&far[..HEAD_BYTES], far.len() as u64), None); + // A header that goes on past the bytes read may name its plates further on. + let mut long = b"%!PS-Adobe-3.0 EPSF-3.0\n".to_vec(); + while long.len() < HEAD_BYTES { + long.extend(format!("%%Title: {}\n", "x".repeat(190)).as_bytes()); + } + long.truncate(HEAD_BYTES); + assert_eq!(head_is_dcs(&long, HEAD_BYTES as u64 + 1), None); + // One that ended within them names none. + long[30..45].copy_from_slice(b"\n%%EndComments\n"); + assert_eq!(head_is_dcs(&long, HEAD_BYTES as u64 + 1), Some(false)); +} + +#[test] +fn dcs_transparency_marks_transparent_and_overlapped_dcs_images() { + let dir = temp_dir("transparency"); + let path = write(&dir, "pic.eps", &two_plates()); + let mut s = session(); + let r = s.execute("file.place", &json!({ "path": path, "at": [100, 100] })).unwrap(); + let image = image_of(&s, &r["ids"][0]).id; + let marked = |s: &mut Session| s.execute("links.list", &json!({ "dcsTransparency": true })).unwrap()["links"][0]["dcsTransparency"] == true; + assert!(!marked(&mut s), "nothing transparent"); + assert!(s.execute("links.list", &json!({})).unwrap()["links"][0].get("dcsTransparency").is_none()); + // A half-transparent square away from it, then over it. + let far = s.execute("shape.rectangle", &json!({"x": 300, "y": 200, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("transparency.set", &json!({"ids": [far], "opacity": 50})).unwrap(); + assert!(!marked(&mut s), "a transparent object elsewhere"); + s.execute("shape.rectangle", &json!({"x": 90, "y": 90, "width": 20, "height": 20})).unwrap(); + let over = s.execute("shape.rectangle", &json!({"x": 92, "y": 92, "width": 4, "height": 4})).unwrap()["id"].as_u64().unwrap(); + assert!(!marked(&mut s), "opaque objects over it"); + s.execute("transparency.set", &json!({"ids": [over], "blend": "multiply"})).unwrap(); + assert!(marked(&mut s), "a blend mode over it"); + s.execute("transparency.set", &json!({"ids": [over], "blend": "normal"})).unwrap(); + s.execute("transparency.set", &json!({"ids": [image.0], "opacity": 80})).unwrap(); + assert!(marked(&mut s), "the image itself"); + assert!(error(&mut s, "links.list", json!({ "dcsTransparency": "yes" })).contains("dcsTransparency"), "a flag that isn't true or false"); +} + +#[test] +fn dcs_transparency_looks_only_at_the_part_of_an_image_its_clipping_path_shows() { + let dir = temp_dir("transparency-clipped"); + let path = write(&dir, "pic.eps", &two_plates()); + let mut s = session(); + let r = s.execute("file.place", &json!({ "path": path, "at": [100, 100] })).unwrap(); + let group = NodeId(r["ids"][0].as_u64().unwrap()); + let image = image_of(&s, &r["ids"][0]).id; + let (clip, all) = { + let doc = &s.doc().unwrap().doc; + let NodeKind::Group { children, clip: true } = &doc.node(group).unwrap().kind else { panic!("a clipping group") }; + (children[0].geometric_bounds().unwrap(), doc.node(image).unwrap().geometric_bounds().unwrap()) + }; + assert!(all.x1 - clip.x1 > 2.0, "the file's clipping path shows the left half: {clip:?} of {all:?}"); + // A half-transparent square over the part of the image the clipping path hides. + let x = (clip.x1 + all.x1) / 2.0 - 1.0; + let over = s.execute("shape.rectangle", &json!({"x": x, "y": all.y0, "width": 2, "height": 2})).unwrap()["id"].as_u64().unwrap(); + s.execute("transparency.set", &json!({"ids": [over], "opacity": 50})).unwrap(); + let marked = |s: &mut Session| s.execute("links.list", &json!({ "dcsTransparency": true })).unwrap()["links"][0]["dcsTransparency"] == true; + assert!(!marked(&mut s), "the square is over the hidden part only"); + s.execute("transparency.set", &json!({"ids": [over], "opacity": 100})).unwrap(); + let shown = s.execute("shape.rectangle", &json!({"x": clip.x0, "y": all.y0, "width": 2, "height": 2})).unwrap()["id"].as_u64().unwrap(); + s.execute("transparency.set", &json!({"ids": [shown], "opacity": 50})).unwrap(); + assert!(marked(&mut s), "a square over the part that shows"); +} + +#[test] +fn dcs_transparency_skips_a_transparent_object_its_own_clipping_paths_hide() { + let dir = temp_dir("transparency-clipped-over"); + let path = write(&dir, "pic.eps", &two_plates()); + // A session with the file placed, and the top-left corner of the image, inside the part its + // clipping path shows. + let placed = || { + let mut s = session(); + let r = s.execute("file.place", &json!({ "path": path, "at": [100, 100] })).unwrap(); + let b = image_of(&s, &r["ids"][0]).geometric_bounds().unwrap(); + (s, b.x0, b.y0) + }; + let rect = |s: &mut Session, x: f64, y: f64, width: f64| { + s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": width, "height": 2})).unwrap()["id"].as_u64().unwrap() + }; + let make = |s: &mut Session, ids: [u64; 2]| { + s.execute("select.set", &json!({ "ids": ids })).unwrap(); + s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap() + }; + let marked = |s: &mut Session| s.execute("links.list", &json!({ "dcsTransparency": true })).unwrap()["links"][0]["dcsTransparency"] == true; + // A half-transparent square over the part of the image that shows. + let square = |s: &mut Session, x: f64, y: f64| { + let id = rect(s, x, y, 2.0); + s.execute("transparency.set", &json!({"ids": [id], "opacity": 50})).unwrap(); + assert!(marked(s), "the square over the image"); + id + }; + + // Its own clip group's clipping path is beside it. + let (mut s, x, y) = placed(); + let over = square(&mut s, x, y); + let beside = rect(&mut s, x + 5.0, y, 2.0); + make(&mut s, [over, beside]); + assert!(!marked(&mut s), "a clip group that hides the square"); + + // Its layer's clipping path is beside it. + let (mut s, x, y) = placed(); + s.execute("layer.new", &json!({})).unwrap(); + square(&mut s, x, y); + rect(&mut s, x + 5.0, y, 2.0); + s.execute("select.none", &json!({})).unwrap(); + assert!(s.execute("layer.clippingMask.toggle", &json!({})).unwrap()["clip"].as_bool().unwrap()); + assert!(!marked(&mut s), "a clipping layer that hides the square"); + + // Each of two nested clipping paths shows part of the inner group, and only the inner one + // covers the square. + let (mut s, x, y) = placed(); + let over = square(&mut s, x, y); + let inner = rect(&mut s, x, y, 40.0); + let group = make(&mut s, [over, inner]); + assert!(marked(&mut s), "the inner clipping path shows the square"); + let outer = rect(&mut s, x + 10.0, y, 20.0); + make(&mut s, [group, outer]); + assert!(!marked(&mut s), "the two clipping paths together hide the square"); +} + +#[test] +fn dcs_transparency_counts_a_transparent_dcs_image_over_another() { + let dir = temp_dir("transparency-two"); + let path = write(&dir, "pic.eps", &two_plates()); + let mut s = session(); + let a = s.execute("file.place", &json!({ "path": path, "at": [100, 100] })).unwrap(); + let b = s.execute("file.place", &json!({ "path": path, "at": [103, 100] })).unwrap(); + let (a, b) = (image_of(&s, &a["ids"][0]).id, image_of(&s, &b["ids"][0]).id); + s.execute("transparency.set", &json!({"ids": [a.0], "opacity": 80})).unwrap(); + let list = s.execute("links.list", &json!({ "dcsTransparency": true })).unwrap(); + let marked = |id: NodeId| list["links"].as_array().unwrap().iter().any(|r| r["id"] == id.0 && r["dcsTransparency"] == true); + assert!(marked(a), "the transparent image"); + assert!(marked(b), "the opaque image it overlaps"); +} + +#[test] +fn dcs_transparency_counts_characters_with_a_transparent_gradient() { + use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let dir = temp_dir("transparency-text"); + let path = write(&dir, "pic.eps", &two_plates()); + let mut s = session(); + s.execute("file.place", &json!({ "path": path, "at": [100, 100] })).unwrap(); + let t = NodeId(s.execute("text.create", &json!({"x": 96, "y": 104, "text": "Hi", "size": 12})).unwrap()["id"].as_u64().unwrap()); + let marked = |s: &mut Session| s.execute("links.list", &json!({ "dcsTransparency": true })).unwrap()["links"][0]["dcsTransparency"] == true; + assert!(!marked(&mut s), "opaque characters over it"); + let mut 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))]; + stops[1].opacity = 0.5; + let gradient = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))); + s.edit("t", |d, _| { + if let Some(Node { kind: NodeKind::Text(text), .. }) = d.node_mut(t) { + text.runs[0].style.fill = gradient.clone(); + } + Ok(()) + }) + .unwrap(); + assert!(marked(&mut s), "characters filled with a gradient that has a transparent stop"); + assert!(s.doc().unwrap().doc.node(t).unwrap().shows_transparency()); +} diff --git a/crates/engine/src/tests/document_close.rs b/crates/engine/src/tests/document_close.rs new file mode 100644 index 0000000000..a1b106d365 --- /dev/null +++ b/crates/engine/src/tests/document_close.rs @@ -0,0 +1,91 @@ +//! `file.close {index}`: closing a document tab other than the current one keeps the current +//! document current, and closing the current one makes its neighbor current. + +use serde_json::json; + +use crate::*; + +/// A session with documents A, B, C and D, in that order, D current. +fn four() -> Session { + let mut s = Session::new(); + for name in ["A", "B", "C", "D"] { + s.execute("file.new", &json!({"name": name, "created": null})).unwrap(); + } + s +} + +fn order(s: &Session) -> String { + s.documents().iter().map(DocState::title).collect::<Vec<_>>().join("") +} + +fn current(s: &Session) -> String { + s.active().map(DocState::title).unwrap_or_default() +} + +fn close(s: &mut Session, index: usize) { + s.execute("file.close", &json!({"index": index})).unwrap_or_else(|e| panic!("file.close {index}: {e}")); +} + +#[test] +fn closing_a_tab_before_the_current_one_keeps_the_current_document() { + let mut s = four(); + close(&mut s, 0); + assert_eq!((order(&s), current(&s)), ("BCD".into(), "D".into())); + assert_eq!(s.active_index(), Some(2)); + assert!(s.set_active(1)); + close(&mut s, 0); + assert_eq!((order(&s), current(&s)), ("CD".into(), "C".into())); + assert_eq!(s.active_index(), Some(0)); +} + +#[test] +fn closing_a_tab_after_the_current_one_keeps_the_current_document() { + let mut s = four(); + assert!(s.set_active(1)); + close(&mut s, 3); + assert_eq!((order(&s), current(&s)), ("ABC".into(), "B".into())); + close(&mut s, 2); + assert_eq!((order(&s), current(&s)), ("AB".into(), "B".into())); + assert_eq!(s.active_index(), Some(1)); +} + +#[test] +fn closing_the_current_tab_makes_its_neighbor_current() { + let mut s = four(); + assert!(s.set_active(1)); + close(&mut s, 1); + assert_eq!((order(&s), current(&s)), ("ACD".into(), "C".into()), "the tab that took its place"); + assert!(s.set_active(2)); + close(&mut s, 2); + assert_eq!((order(&s), current(&s)), ("AC".into(), "C".into()), "the last tab: the one before it"); + s.execute("file.close", &json!({})).unwrap(); + assert_eq!((order(&s), current(&s)), ("A".into(), "A".into()), "without an index, the current one closes"); + close(&mut s, 0); + assert!(s.active().is_none()); + assert!(s.execute("file.close", &json!({"index": 0})).is_err(), "no document left"); +} + +#[test] +fn closing_another_tab_keeps_the_tool_and_the_documents_edits() { + let mut s = four(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let resets = s.tool_resets; + let nodes = s.doc().unwrap().doc.node_count(); + let history = super::history(&s); + close(&mut s, 1); + assert_eq!(s.tool_resets, resets, "no document was switched to, so the tool is not reset"); + assert_eq!(super::history(&s), history); + assert_eq!(s.doc().unwrap().doc.node_count(), nodes); + assert!(s.doc().unwrap().is_dirty(), "the document keeps its unsaved edit"); + close(&mut s, 2); + assert_ne!(s.tool_resets, resets, "closing the current document resets the tool"); +} + +#[test] +fn a_bad_index_closes_nothing() { + let mut s = four(); + assert!(s.set_active(2)); + assert!(s.execute("file.close", &json!({"index": 4})).is_err()); + assert!(!s.close_document(4)); + assert_eq!((order(&s), current(&s)), ("ABCD".into(), "C".into())); +} diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index ea10df64b5..f29df7ff23 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -1367,6 +1367,59 @@ fn smooth_tool_reduces_jagged_path() { assert_eq!(p.subpaths[0].anchors[0].p, Point::new(100.0, 200.0)); } +/// A drag of the Smooth tool along a line jagged by up to 6 pt leaves no corner between a curve and +/// a line: every anchor between the path's ends turns by at most 1°. +#[test] +fn smooth_tool_leaves_no_corner_where_a_curve_meets_a_line() { + let mut s = session(); + let mut seed = 7u64; + let anchors: Vec<_> = (0..=60) + .map(|i| { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + let noise = ((seed >> 11) as f64 / (1u64 << 53) as f64) * 2.0 - 1.0; + json!({"x": 100.0 + f64::from(i) * 5.0, "y": 200.0 + 6.0 * noise}) + }) + .collect(); + let r = s.execute("path.create", &json!({"anchors": anchors})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + let drag_points: Vec<(f64, f64)> = (0..=64).map(|i| (90.0 + f64::from(i) * 5.0, 200.0)).collect(); + drag(&mut s, "smooth", &drag_points, Mods::default()); + let p = path(&s, id); + let sp = &p.subpaths[0]; + assert!(sp.anchors.len() < 61, "the path is smoothed: {}", sp.anchors.len()); + let dir = |v: kurbo::Vec2, w: kurbo::Vec2, chord: kurbo::Vec2| [v, w, chord].into_iter().find(|d| d.hypot() > 1e-9).unwrap_or(chord); + for i in 1..sp.segment_count() { + let (prev, next) = (sp.segment(i - 1), sp.segment(i)); + let arrive = dir(prev.p3 - prev.p2, prev.p3 - prev.p1, prev.p3 - prev.p0); + let leave = dir(next.p1 - next.p0, next.p2 - next.p0, next.p3 - next.p0); + let turn = arrive.cross(leave).atan2(arrive.dot(leave)).abs().to_degrees(); + let kinds = (sp.segment_is_line(i - 1), sp.segment_is_line(i)); + assert!(turn <= 1.0, "anchor {i} turns {turn}° (lines before and after: {kinds:?}): {:?}", sp.anchors[i]); + } +} + +/// Smoothing a path with direct-selected anchors leaves the path selected whole: the selection no +/// longer names anchors by indices into the anchors the smooth replaced. A selected path the drag +/// does not reach keeps its anchors selected, and undo brings the old selection back. +#[test] +fn smoothing_a_path_drops_its_direct_selected_anchors() { + let mut s = session(); + let anchors: Vec<_> = (0..=40).map(|i| json!({"x": 100.0 + i as f64 * 5.0, "y": 200.0 + if i % 2 == 0 { 0.0 } else { 1.5 }})).collect(); + let r = s.execute("path.create", &json!({"anchors": anchors})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + let other = line(&mut s, 100.0, 500.0, 300.0, 500.0); + s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 38]], "mode": "set"})).unwrap(); + s.execute("select.anchors", &json!({"id": other.0, "anchors": [[0, 1]], "mode": "add"})).unwrap(); + drag(&mut s, "smooth", &[(90.0, 200.0), (200.0, 200.0), (310.0, 200.0)], Mods::default()); + assert!(path(&s, id).anchor_count() < 20, "the path is smoothed"); + let sel = s.doc().unwrap().selection.clone(); + assert!(sel.contains(id) && sel.contains(other), "{sel:?}"); + assert!(!sel.anchors.contains_key(&id) && !sel.segments.contains_key(&id), "{sel:?}"); + assert_eq!(sel.anchors.get(&other), Some(&[(0, 1)].into()), "the path out of reach keeps its anchor"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().selection.anchors.get(&id), Some(&[(0, 38)].into())); +} + /// #1512: a short drag over a small bump smooths the stretch of path under it. The long straight /// sides next to the bump stay straight lines from their far ends, which keep their place. #[test] @@ -1390,6 +1443,169 @@ fn a_short_smooth_drag_leaves_the_rest_of_long_segments_alone() { } } +/// A selected path through `anchors` (x, y, and the in and out handles when given). +fn smooth_test_path(s: &mut Session, anchors: &[serde_json::Value], closed: bool) -> NodeId { + let r = s.execute("path.create", &json!({"anchors": anchors, "closed": closed})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + id +} + +/// `path.smoothRegion` along `drag` with the Smooth tool's reach (12 pt at 100%) and default Fidelity. +fn smooth_pass(s: &mut Session, drag: &[Point]) { + let pts: Vec<_> = drag.iter().map(|p| json!([p.x, p.y])).collect(); + s.execute("path.smoothRegion", &json!({"points": pts, "radius": 12, "fidelity": 2.5})).unwrap(); +} + +/// Points 1/32 of a segment apart along every segment of `p`. +fn smooth_test_samples(p: &PathData) -> Vec<Point> { + use kurbo::ParamCurve; + let mut v = vec![]; + for sp in &p.subpaths { + for i in 0..sp.segment_count() { + let c = sp.segment(i); + v.extend((0..32).map(|k| c.eval(f64::from(k) / 32.0))); + } + } + v +} + +/// How much `p` turns along its length, in radians: a wobbly path turns much more than a smooth one. +fn total_turning(p: &PathData) -> f64 { + let pts = smooth_test_samples(p); + pts.windows(3) + .map(|w| (w[1] - w[0], w[2] - w[1])) + .filter(|(u, v)| u.hypot() > 1e-9 && v.hypot() > 1e-9) + .map(|(u, v)| u.cross(v).atan2(u.dot(v)).abs()) + .sum() +} + +/// Deterministic noise in -1..1. +fn smooth_noise(seed: &mut u64) -> f64 { + *seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (*seed >> 11) as f64 / (1u64 << 53) as f64 * 2.0 - 1.0 +} + +/// A drag along y = `y` from x = `x0` to `x1`, one point every 5 pt. +fn smooth_drag_along(y: f64, x0: f64, x1: f64) -> Vec<Point> { + let n = ((x1 - x0) / 5.0).ceil() as usize; + (0..=n).map(|i| Point::new(x0 + (x1 - x0) * i as f64 / n as f64, y)).collect() +} + +/// Each drag of the Smooth tool smooths the path under it, and a second drag over the same place +/// smooths it further, as the help page describes +/// (https://helpx.adobe.com/illustrator/using/tool-techniques/smooth-tool.html): a curve that wobbles +/// 4 pt either side of its line every 12 pt, with an anchor at each crest, wobbles less after each drag. +#[test] +fn each_smooth_drag_smooths_a_wobble_larger_than_fidelity_further() { + let mut s = session(); + let anchors: Vec<_> = (0..=20) + .map(|k| { + let (x, y) = (100.0 + 12.0 * f64::from(k), if k % 2 == 0 { 196.0 } else { 204.0 }); + json!({"x": x, "y": y, "in": [x - 4.4, y], "out": [x + 4.4, y]}) + }) + .collect(); + let id = smooth_test_path(&mut s, &anchors, false); + let drag = smooth_drag_along(200.0, 90.0, 350.0); + let wobble = + |p: &PathData| smooth_test_samples(p).iter().filter(|q| (130.0..=310.0).contains(&q.x)).map(|q| (q.y - 200.0).abs()).fold(0.0, f64::max); + let mut before = path(&s, id); + for pass in 1..=2 { + smooth_pass(&mut s, &drag); + let after = path(&s, id); + assert_ne!(after, before, "pass {pass} changes the path"); + let (t0, t1) = (total_turning(&before), total_turning(&after)); + assert!(t1 < 0.9 * t0, "pass {pass}: turning {t0} -> {t1}"); + let (w0, w1) = (wobble(&before), wobble(&after)); + assert!(w1 < 0.8 * w0, "pass {pass}: wobble {w0} -> {w1}"); + let (a, b) = (before.subpaths[0].anchors[0].p, after.subpaths[0].anchors[0].p); + assert_eq!(a, b, "pass {pass}: the path keeps its start"); + before = after; + } +} + +/// Smoothing a line with up to 1 pt of noise again and again, over all of it or over its middle, +/// keeps it close to the line under the noise: each refit stays near the path it smooths. +#[test] +fn repeated_smooth_drags_stay_close_to_the_line_under_the_noise() { + let off = |p: &PathData| { + let d: Vec<f64> = smooth_test_samples(p).iter().map(|q| (q.y - 200.0).abs()).collect(); + (d.iter().sum::<f64>() / d.len() as f64, d.iter().copied().fold(0.0, f64::max)) + }; + for (x0, x1) in [(90.0, 410.0), (150.0, 350.0)] { + let mut s = session(); + let mut seed = 7u64; + let anchors: Vec<_> = (0..=60).map(|i| json!({"x": 100.0 + 5.0 * f64::from(i), "y": 200.0 + smooth_noise(&mut seed)})).collect(); + let id = smooth_test_path(&mut s, &anchors, false); + let drag = smooth_drag_along(200.0, x0, x1); + let (mean0, _) = off(&path(&s, id)); + for pass in 1..=5 { + smooth_pass(&mut s, &drag); + let (mean, max) = off(&path(&s, id)); + assert!( + mean <= 1.1 * mean0 && max <= 1.5, + "drag {x0}-{x1}, pass {pass}: {mean} on average and {max} at most from the line, {mean0} before" + ); + } + } +} + +/// A drag over the whole of a noisy closed path leaves no corner where the path starts. +#[test] +fn smoothing_a_whole_closed_path_leaves_no_kink_at_its_start() { + let mut s = session(); + let mut seed = 5u64; + let (c, r) = (Point::new(300.0, 300.0), 80.0); + let anchors: Vec<_> = (0..64) + .map(|i| { + let a = f64::from(i) / 64.0 * std::f64::consts::TAU; + let rr = r + 2.5 * smooth_noise(&mut seed); + json!({"x": c.x + rr * a.cos(), "y": c.y + rr * a.sin()}) + }) + .collect(); + let id = smooth_test_path(&mut s, &anchors, true); + let ring: Vec<Point> = (0..=128).map(|i| f64::from(i) / 128.0 * std::f64::consts::TAU).map(|a| c + r * kurbo::Vec2::from_angle(a)).collect(); + smooth_pass(&mut s, &ring); + let p = path(&s, id); + let sp = &p.subpaths[0]; + assert!(sp.closed && sp.anchors.len() < 64, "{} anchors", sp.anchors.len()); + let (last, first) = (sp.segment(sp.segment_count() - 1), sp.segment(0)); + let tin = if last.p3.distance(last.p2) > 1e-9 { last.p3 - last.p2 } else { last.p3 - last.p1 }; + let tout = if first.p1.distance(first.p0) > 1e-9 { first.p1 - first.p0 } else { first.p2 - first.p0 }; + let kink = tin.cross(tout).atan2(tin.dot(tout)).abs().to_degrees(); + assert!(kink <= 1.0, "a {kink}° corner at the start"); +} + +/// A drag over the whole of a closed path smooths a bump at its first anchor as much as the same +/// bump on the far side of it. +#[test] +fn smoothing_a_whole_closed_path_smooths_a_bump_at_its_start() { + let mut s = session(); + let (c, r) = (Point::new(300.0, 300.0), 80.0); + let anchors: Vec<_> = (0..64) + .map(|i| { + let a = f64::from(i) / 64.0 * std::f64::consts::TAU; + let rr = if i % 32 == 0 { r + 6.0 } else { r }; + json!({"x": c.x + rr * a.cos(), "y": c.y + rr * a.sin()}) + }) + .collect(); + let id = smooth_test_path(&mut s, &anchors, true); + let ring: Vec<Point> = (0..=128).map(|i| f64::from(i) / 128.0 * std::f64::consts::TAU).map(|a| c + r * kurbo::Vec2::from_angle(a)).collect(); + // A Fidelity of 0.5 pt, so the refit follows the smoothed path closely on both sides. + let pts: Vec<_> = ring.iter().map(|p| json!([p.x, p.y])).collect(); + s.execute("path.smoothRegion", &json!({"points": pts, "radius": 12, "fidelity": 0.5})).unwrap(); + let p = path(&s, id); + use std::f64::consts::{PI, TAU}; + // How far the path rises above the circle within 0.3 radians of the angle `near`. + let bump = |near: f64| { + let off = |q: &Point| (((q.y - c.y).atan2(q.x - c.x) - near + PI).rem_euclid(TAU) - PI).abs(); + smooth_test_samples(&p).iter().filter(|q| off(q) < 0.3).map(|q| q.distance(c) - r).fold(0.0, f64::max) + }; + let (start, far) = (bump(0.0), bump(PI)); + assert!(far < 5.0, "the far bump stays {far} pt high"); + assert!(start <= far + 0.5, "the bump at the start stays {start} pt high, the far one {far} pt"); +} + #[test] fn join_tool_joins_two_lines() { let mut s = session(); @@ -2533,6 +2749,49 @@ fn remove_anchor_points_selects_one_next_anchor_per_subpath_and_per_path() { assert_eq!(selected_anchors(&s, other), [(0, 0)]); } +#[test] +fn remove_anchor_points_on_many_paths_and_subpaths_matches_removing_one_at_a_time() { + // Many anchors over many subpaths and paths, curved and straight, open and closed: each + // subpath ends as removing its anchors one at a time, the last first, leaves it. Paths left + // with nothing go, the rest stay selected in order, and one undo step brings all back. + let mut s = session(); + let curvy = "M0 0 C10 20 30 20 40 0 C50 -20 70 -20 80 0 C90 20 110 20 120 0 C130 -20 150 -20 160 0 Z \ + M0 100 L40 120 C60 140 80 80 100 100 L140 90 L180 110 L220 100"; + let ids: Vec<NodeId> = (0..4).map(|i| path_from(&mut s, if i == 2 { "M0 0 L10 0 L20 5" } else { curvy })).collect(); + let picks: [&[(usize, usize)]; 4] = + [&[(0, 0), (0, 2), (0, 3), (1, 1), (1, 2), (1, 5)], &[(0, 1), (1, 0), (1, 6)], &[(0, 0), (0, 1)], &[(0, 3), (1, 3), (1, 4)]]; + for (k, (&id, &anchors)) in ids.iter().zip(&picks).enumerate() { + let mode = if k == 0 { "set" } else { "add" }; + s.execute("select.anchors", &json!({"id": id.0, "anchors": anchors, "mode": mode})).unwrap(); + } + let before: Vec<PathData> = ids.iter().map(|&id| path(&s, id)).collect(); + assert_eq!(s.execute("path.removeAnchors", &json!({})).unwrap()["removedObjects"], 1); + for (k, &id) in ids.iter().enumerate() { + let mut want = before[k].clone(); + let mut order = picks[k].to_vec(); + order.sort_unstable_by(|a, b| b.cmp(a)); + for (si, ai) in order { + vectorcraft_pathops::remove_anchor(&mut want.subpaths[si], ai); + } + want.subpaths.retain(|sp| sp.anchors.len() >= 2); + if want.subpaths.is_empty() { + assert!(s.doc().unwrap().doc.node(id).is_none(), "path {k} goes"); + } else { + assert_eq!(path(&s, id).subpaths, want.subpaths, "path {k}"); + } + } + let kept = [ids[0], ids[1], ids[3]]; + assert_eq!(s.doc().unwrap().selection.objects, kept); + s.execute("edit.undo", &json!({})).unwrap(); + for (k, &id) in ids.iter().enumerate() { + assert_eq!(path(&s, id), before[k]); + assert_eq!(selected_anchors(&s, id), picks[k]); + } + s.execute("edit.redo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.node(ids[2]).is_none()); + assert_eq!(s.doc().unwrap().selection.objects, kept); +} + #[test] fn remove_anchor_point_tool_and_delete_still_select_the_remainder_whole() { // Only Remove Anchor Points moves the selection on. The Delete Anchor Point tool leaves the @@ -3278,6 +3537,14 @@ fn close_path_places_the_first_anchors_handles() { s.execute("path.close", &json!({"id": id.0, "in": [60.0, 140.0], "out": [120.0, 60.0]})).unwrap(); let b = path(&s, id).subpaths[0].anchors[0]; assert_eq!((b.h_in, b.h_out, b.kind), (Point::new(60.0, 140.0), Point::new(120.0, 60.0), AnchorKind::Corner)); + // `at` moves the anchor, its handles with it, before `in` is placed. + s.execute("edit.undo", &json!({})).unwrap(); + refuses_with(&mut s, "path.close", &json!({"id": id.0, "at": "120, 90"}), "`at` must be [x, y]"); + s.execute("path.close", &json!({"id": id.0, "at": [120.0, 90.0], "in": [60.0, 140.0]})).unwrap(); + let b = path(&s, id).subpaths[0].anchors[0]; + assert_eq!((b.p, b.h_in, b.h_out), (Point::new(120.0, 90.0), Point::new(60.0, 140.0), Point::new(170.0, 90.0)), "{b:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(path(&s, id).subpaths[0].anchors[0], a, "one undo step"); } #[test] @@ -4450,6 +4717,12 @@ fn blob_anchors(s: &mut Session, fidelity: f64) -> usize { /// [`blob_anchors`] with the blob scaled by `scale`: drawn the same on screen zoomed in 1 / `scale` /// times. fn scaled_blob_anchors(s: &mut Session, fidelity: f64, scale: f64) -> usize { + blob_anchors_through(s, "path.freehand", &json!({}), Some(fidelity), scale) +} + +/// [`scaled_blob_anchors`] drawn with `command` and the params in `extra`, at `fidelity` (with none, +/// the command's default). +fn blob_anchors_through(s: &mut Session, command: &str, extra: &serde_json::Value, fidelity: Option<f64>, scale: f64) -> usize { let pts: Vec<_> = (0..1200) .map(|i| { let a = i as f64 / 1200.0 * std::f64::consts::TAU; @@ -4457,7 +4730,14 @@ fn scaled_blob_anchors(s: &mut Session, fidelity: f64, scale: f64) -> usize { json!([(400.0 + r * a.cos()) * scale, (300.0 + r * a.sin()) * scale]) }) .collect(); - let r = s.execute("path.freehand", &json!({"points": pts, "closed": true, "fidelity": fidelity, "keepSelected": false})).unwrap(); + let mut p = json!({"points": pts, "closed": true, "keepSelected": false}); + if let Some(f) = fidelity { + p["fidelity"] = json!(f); + } + if let (Some(p), Some(extra)) = (p.as_object_mut(), extra.as_object()) { + p.extend(extra.clone()); + } + let r = s.execute(command, &p).unwrap(); path(s, NodeId(r["id"].as_u64().unwrap())).subpaths.iter().map(|sp| sp.anchors.len()).sum() } @@ -4469,13 +4749,11 @@ fn pencil_fidelity_goes_down_to_a_hundredth_and_lower_keeps_more() { assert!(counts.windows(2).all(|w| w[0] <= w[1]), "{counts:?}"); // Below the old floor of 0.05 the stroke keeps more of itself. assert!(counts[4] > counts[2], "{counts:?}"); - // Below the floor, the lowest Fidelity (0.01 px) at the highest zoom (64000 %), is read as the - // floor (#5729). + // The floor is the lowest Fidelity (0.01 px) at the highest zoom (64000 %) (#5729); below it, + // `pencil_takes_fidelity_within_its_range_and_rejects_the_rest`. let floor = vectorcraft_tools::draw2::MIN_FIDELITY / 640.0; let at_floor = blob_anchors(&mut s, floor); assert!(at_floor >= counts[4], "{counts:?}"); - assert_eq!(blob_anchors(&mut s, floor / 10.0), at_floor); - assert_eq!(blob_anchors(&mut s, 0.0), at_floor); } /// #5729: the tools send Fidelity / zoom, so a stroke drawn the same on screen zoomed in keeps as @@ -4491,6 +4769,89 @@ fn pencil_fit_keeps_its_anchors_on_a_stroke_drawn_zoomed_in() { } } +/// The tools send Fidelity / zoom up to the highest Fidelity (100 px) at the lowest zoom (3.13 %): +/// a stroke drawn the same on screen zoomed out keeps as many anchors as at 100 %, as a Pencil or a +/// Paintbrush stroke and through `brush.freehand` with a brush. A tolerance above +/// `MAX_FIT_TOLERANCE` is an error, and a stroke given no Fidelity is fitted at 1.5 pt. +#[test] +fn pencil_fit_keeps_its_anchors_on_a_stroke_drawn_zoomed_out() { + let mut s = session(); + let max = vectorcraft_tools::draw2::MAX_FIT_TOLERANCE; + // The blob six times the size, so that 100 px still keeps some of its waves. + let big = 6.0; + for (command, extra) in [ + ("path.freehand", json!({})), + ("path.freehand", json!({"style": "brush"})), + ("brush.freehand", json!({"style": "brush", "brush": "3 pt. Round"})), + ] { + for fidelity in [20.0, 100.0] { + let want = blob_anchors_through(&mut s, command, &extra, Some(fidelity), big); + for zoom in [0.2, 0.0313] { + let got = blob_anchors_through(&mut s, command, &extra, Some(fidelity / zoom), big / zoom); + assert_eq!(got, want, "{command} {extra}: {fidelity} px at {zoom}x"); + // Fitted at 100 pt, the stroke on screen would keep the detail of a finer Fidelity. + if fidelity / zoom > 100.0 { + let at_100 = blob_anchors_through(&mut s, command, &extra, Some(100.0), big / zoom); + assert!(at_100 > want, "{command} {extra}: {fidelity} px at {zoom}x, 100 pt keeps {at_100} of {want}"); + } + } + } + let mut p = json!({"points": [[0, 0], [100, 50], [200, 0]], "fidelity": max * 10.0}); + if let (Some(p), Some(extra)) = (p.as_object_mut(), extra.as_object()) { + p.extend(extra.clone()); + } + let err = s.execute(command, &p).unwrap_err().to_string(); + assert!(err.contains("`fidelity` must be from"), "{command} {extra}: {err}"); + let default = blob_anchors_through(&mut s, command, &extra, None, 1.0); + assert_eq!(default, blob_anchors_through(&mut s, command, &extra, Some(1.5), 1.0), "{command} {extra}"); + } +} + +/// `path.freehand` and `brush.freehand` take a `fidelity` from `MIN_FIT_TOLERANCE` (the lowest +/// Fidelity at the highest zoom) to `MAX_FIT_TOLERANCE` (the highest at the lowest zoom), both ends +/// included, and reject a value just outside either end, a tenth of the lowest, 0, a negative one or +/// a huge one, leaving the document as it was. +#[test] +fn pencil_takes_fidelity_within_its_range_and_rejects_the_rest() { + let (lo, hi) = (vectorcraft_tools::draw2::MIN_FIT_TOLERANCE, vectorcraft_tools::draw2::MAX_FIT_TOLERANCE); + let points = json!([[0, 0], [100, 50], [200, 0], [300, 50]]); + for (command, extra) in [("path.freehand", json!({})), ("brush.freehand", json!({"style": "brush", "brush": "3 pt. Round"}))] { + let run = |s: &mut Session, fidelity: f64| { + let mut p = json!({"points": points, "fidelity": fidelity}); + if let (Some(p), Some(extra)) = (p.as_object_mut(), extra.as_object()) { + p.extend(extra.clone()); + } + s.execute(command, &p) + }; + let mut s = session(); + for fidelity in [100.0 / 0.0313, hi, lo, 0.01 / 640.0] { + let r = run(&mut s, fidelity); + assert!(r.as_ref().is_ok_and(|r| r["id"].is_u64()), "{command}: {fidelity} pt: {r:?}"); + } + let before = s.doc().unwrap().doc.clone(); + for fidelity in [f64::from_bits(hi.to_bits() + 1), f64::from_bits(lo.to_bits() - 1), lo / 10.0, 0.0, -1.5, 1e300] { + let err = run(&mut s, fidelity).unwrap_err().to_string(); + assert!(err.contains("`fidelity` must be from"), "{command}: {fidelity} pt: {err}"); + } + assert_eq!(s.doc().unwrap().doc, before, "{command}"); + } +} + +/// A stroke that continues an open path closes it when it ends within four Fidelities of the path's +/// other end, at most 400 pt away: at the coarsest Fidelity one ending 1000 pt away leaves it open, +/// and one ending 300 pt away closes it. +#[test] +fn pencil_extend_closes_within_400_pt_at_any_fidelity() { + let mut s = session(); + let max = vectorcraft_tools::draw2::MAX_FIT_TOLERANCE; + for (end, closed) in [([0, 1000], false), ([0, 300], true)] { + let l = line(&mut s, 0.0, 0.0, 2000.0, 0.0); + let points = json!([[2000, 0], [2000, 1000], [1000, 1500], end]); + s.execute("path.freehand", &json!({"points": points, "fidelity": max, "extend": {"id": l.0}, "keepSelected": false})).unwrap(); + assert_eq!(path(&s, l).subpaths[0].closed, closed, "ending at {end:?}"); + } +} + /// At Fidelity 0.01 short, one-point and repeated-point strokes still draw or are refused, never /// crash, and what they draw has finite anchors. #[test] diff --git a/crates/engine/src/tests/dynamic_symbols.rs b/crates/engine/src/tests/dynamic_symbols.rs index 278d979ef5..c5ef8a1949 100644 --- a/crates/engine/src/tests/dynamic_symbols.rs +++ b/crates/engine/src/tests/dynamic_symbols.rs @@ -432,6 +432,30 @@ fn redefining_the_symbol_keeps_the_changes_whose_objects_remain() { assert_eq!(overrides(&s, inst), 0); } +#[test] +fn redefining_the_symbol_drops_paints_its_new_objects_do_not_draw() { + let mut s = session(); + let inst = pair(&mut s, "dynamic"); + let p = json!({"id": inst.0, "path": [1], "fill": "#ff0000", "stroke": "#ff0000", "opacity": 50}); + s.execute("symbol.instance.setAppearance", &p).unwrap(); + // The second object is now an image, which draws no fill or stroke of its own. + let a = square(&mut s, 10.0); + place_image(&mut s); + let image = top(&s); + s.execute("symbol.update", &json!({"name": "Pair", "ids": [a.0, image.0]})).unwrap(); + let o = node(&s, inst).extras().symbol_overrides.clone(); + assert_eq!(o.len(), 1, "the opacity change stays: {o:?}"); + assert_eq!((&o[0].fill, &o[0].stroke, o[0].opacity), (&None, &None, Some(0.5))); + // A change of paint alone goes with its paint: the first object is now a blend. + s.execute("symbol.instance.setAppearance", &json!({"id": inst.0, "path": [0], "stroke": "#ff0000"})).unwrap(); + let (b, c) = (square(&mut s, 10.0), square(&mut s, 60.0)); + let blend = id(&s.execute("object.blend.make", &json!({"ids": [b.0, c.0], "steps": 1})).unwrap()); + let d = square(&mut s, 120.0); + s.execute("symbol.update", &json!({"name": "Pair", "ids": [blend.0, d.0]})).unwrap(); + let o = node(&s, inst).extras().symbol_overrides.clone(); + assert_eq!(o.iter().map(|o| o.path.clone()).collect::<Vec<_>>(), [vec![1]], "{o:?}"); +} + #[test] fn replace_symbol_drops_the_changes_made_for_the_old_symbol() { let mut s = session(); diff --git a/crates/engine/src/tests/dynamic_text.rs b/crates/engine/src/tests/dynamic_text.rs index 3512db9c59..8605a7e052 100644 --- a/crates/engine/src/tests/dynamic_text.rs +++ b/crates/engine/src/tests/dynamic_text.rs @@ -88,19 +88,17 @@ fn dynamic_text_refuses_bad_params_and_other_type() { assert!(err(s.execute("type.dynamicText", &json!({"on": 1}))).contains("on")); assert_eq!(undo_len(&s), before); assert!(!text(&s, id).dynamic_text); - // Point type alone: refused (area type takes Block, `typecmd::block_tests`). let point = s.execute("text.create", &json!({"x": 10, "y": 10, "text": "Point"})).unwrap()["id"].as_u64().unwrap(); - s.execute("select.set", &json!({"ids": [point]})).unwrap(); - assert!(err(s.execute("type.dynamicText", &json!({}))).contains("select type on a path or area type")); let empty = s.execute("shape.rectangle", &json!({"x": 300, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [empty]})).unwrap(); assert!(s.execute("type.dynamicText", &json!({})).is_err()); - // With point type selected too, only the type on a path changes. + // With point type selected too, both change in one undo step: the point type becomes area + // type with Block on (`typecmd::block_tests`). let before = undo_len(&s); s.execute("select.set", &json!({"ids": [point, id.0]})).unwrap(); let r = s.execute("type.dynamicText", &json!({"on": true})).unwrap(); - assert_eq!(r["ids"], json!([id.0])); - assert!(!text(&s, NodeId(point)).dynamic_text); + assert_eq!(r["ids"], json!([point, id.0])); + assert!(text(&s, NodeId(point)).dynamic_text && text(&s, id).dynamic_text); assert_eq!(undo_len(&s), before + 1); } @@ -234,6 +232,220 @@ fn svg_export_writes_the_drawn_size() { assert!(!sizes.iter().any(|v| (v - 12.0).abs() < 1e-3), "the stored size is not written: {sizes:?}"); } +#[test] +fn release_type_on_a_path_keeps_the_drawn_size() { + let mut s = session(); + let id = on_line(&mut s, "Release"); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + let size = 12.0 * fit(&s, id); + assert!(size > 24.0, "the text grows on the long line: {size}"); + let r = s.execute("addon.type.releasePath", &json!({"ids": [id.0], "mode": "text"})).unwrap(); + let released = NodeId(r["texts"][0].as_u64().unwrap()); + let t = text(&s, released); + assert!(!t.dynamic_text, "point type does not keep Dynamic Text"); + assert!((t.runs[0].style.size - size).abs() < 1e-9, "{} vs the drawn {size}", t.runs[0].style.size); + assert_eq!(fit(&s, released), 1.0); + // Type on a path without Dynamic Text keeps its stored size. + let plain = on_line(&mut s, "Plain"); + let r = s.execute("addon.type.releasePath", &json!({"ids": [plain.0], "mode": "text"})).unwrap(); + let t = text(&s, NodeId(r["texts"][0].as_u64().unwrap())); + assert!(!t.dynamic_text && t.runs[0].style.size == 12.0); +} + +/// 12 pt point type at (100, 100), selected, with its layout bounds. +fn point(s: &mut Session, content: &str) -> (NodeId, vectorcraft_geom::Rect) { + let r = s.execute("text.create", &json!({"x": 100, "y": 100, "text": content, "size": 12})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let b = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &text(s, id)).bounds; + (id, b) +} + +/// Type on a path's path, start bracket and end bracket. +fn on_path(t: &TextObject) -> (vectorcraft_geom::PathData, f64, Option<f64>) { + match &t.kind { + vectorcraft_doc::TextKind::OnPath { path, start, end } => (path.clone(), *start, *end), + k => panic!("not type on a path: {k:?}"), + } +} + +fn close(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-6 +} + +#[test] +fn presets_put_point_type_on_a_fitted_circle_arch_or_bow() { + let mut s = session(); + let (id, b) = point(&mut s, "Round and round"); + let w = b.width().max(b.height()); + let before = undo_len(&s); + let r = s.execute("type.dynamicTextPreset", &json!({"preset": "circle"})).unwrap(); + assert_eq!(r["ids"], json!([id.0])); + assert_eq!(undo_len(&s), before + 1); + assert_eq!(s.doc().unwrap().history.undo.last().unwrap().label, "Dynamic Text"); + let t = text(&s, id); + assert!(t.dynamic_text); + assert_eq!(t.path_align, vectorcraft_doc::PathAlign::Descender, "above by default"); + let (path, start, end) = on_path(&t); + assert!(path.is_closed()); + assert_eq!((start, end), (0.75, None)); + let pb = path.bounds().unwrap(); + assert!(close(pb.width(), w) && close(pb.height(), w), "{pb:?} vs {w}"); + assert!(close(pb.center().x, b.center().x) && close(pb.center().y, b.center().y), "{pb:?} vs {b:?}"); + // The start bracket, 3/4 of the way round, is the circle's bottom. + let bottom = path.subpaths[0].anchors[3].p; + assert!(close(bottom.y, pb.y1) && close(bottom.x, pb.center().x), "{bottom:?}"); + // Round a circle as wide as the text, the text grows to fill it and does not overflow. + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + assert!(lay.fit_scale > 2.0 && !lay.overflow, "{} {}", lay.fit_scale, lay.overflow); + assert_eq!(r["fitScale"], json!(lay.fit_scale)); + assert_eq!(t.cached_bounds, Some(lay.bounds)); + // Undo gives the point type back. + s.execute("edit.undo", &json!({})).unwrap(); + assert!(matches!(text(&s, id).kind, vectorcraft_doc::TextKind::Point) && !text(&s, id).dynamic_text); + + for (preset, up) in [("arch", true), ("bow", false)] { + s.execute("type.dynamicTextPreset", &json!({"preset": preset, "ids": [id.0]})).unwrap(); + let t = text(&s, id); + let (path, start, end) = on_path(&t); + assert!(!path.is_closed() && t.dynamic_text); + assert_eq!((start, end), (0.0, None)); + let a = &path.subpaths[0].anchors; + let (first, middle, last) = (a[0].p, a[1].p, a[a.len() - 1].p); + // Left to right, the chord as wide as the text, the arc rising (or falling) half its radius. + assert!(first.x < last.x && close(last.x - first.x, w) && close(first.y, last.y), "{preset}: {first:?} {last:?}"); + let pb = path.bounds().unwrap(); + assert!(close(pb.height(), w / 3f64.sqrt() / 2.0), "{preset}: {pb:?}"); + assert!(close(pb.center().y, b.center().y), "{preset}: {pb:?} vs {b:?}"); + assert_eq!(middle.y < first.y, up, "{preset}: {middle:?} {first:?}"); + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + assert!(lay.fit_scale > 1.0 && !lay.overflow, "{preset}: {}", lay.fit_scale); + s.execute("edit.undo", &json!({})).unwrap(); + } +} + +#[test] +fn preset_position_and_flip_set_align_to_path_and_direction() { + let mut s = session(); + let (id, _) = point(&mut s, "Over the hill"); + for (position, align) in [ + ("above", vectorcraft_doc::PathAlign::Descender), + ("center", vectorcraft_doc::PathAlign::Center), + ("below", vectorcraft_doc::PathAlign::Ascender), + ] { + s.execute("type.dynamicTextPreset", &json!({"preset": "arch", "position": position})).unwrap(); + assert_eq!(text(&s, id).path_align, align, "{position}"); + } + // Flipped, the arch runs right to left and the text stands on its other side. + s.execute("type.dynamicTextPreset", &json!({"preset": "arch", "flip": true})).unwrap(); + let t = text(&s, id); + let (path, start, end) = on_path(&t); + let a = &path.subpaths[0].anchors; + assert!(a[0].p.x > a[a.len() - 1].p.x, "{path:?}"); + assert_eq!((start, end), (0.0, None)); + assert_eq!(t.path_align, vectorcraft_doc::PathAlign::Descender); + assert!(!vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).overflow); + // A flipped circle runs the other way round from its bottom. + s.execute("type.dynamicTextPreset", &json!({"preset": "circle", "flip": true})).unwrap(); + let (path, start, end) = on_path(&text(&s, id)); + assert_eq!((start, end), (0.25, None)); + let at = path.subpaths[0].anchors[1].p; + assert!(close(at.y, path.bounds().unwrap().y1), "reversed, the bottom is a quarter of the way: {at:?}"); + // The effect and Spacing of Type on a Path Options stay. + s.execute("type.pathOptions", &json!({"effect": "skew", "spacing": 5})).unwrap(); + s.execute("type.dynamicTextPreset", &json!({"preset": "bow"})).unwrap(); + let t = text(&s, id); + assert_eq!((t.path_effect.id(), t.path_spacing), ("skew", 5.0)); +} + +#[test] +fn presets_fit_type_on_a_path_to_its_path_and_record_nothing_when_nothing_changes() { + let mut s = session(); + let id = on_line(&mut s, "Along the line"); + s.execute("type.dynamicTextPreset", &json!({"preset": "bow"})).unwrap(); + let (path, ..) = on_path(&text(&s, id)); + let a = &path.subpaths[0].anchors; + // The bow is as wide as the 400 pt line, centered where it was. + assert!(close(a[0].p.x, 100.0) && close(a[a.len() - 1].p.x, 500.0), "{a:?}"); + assert!(close(path.bounds().unwrap().center().y, 300.0)); + // The same preset again: nothing changes and no undo step is recorded. + let before = undo_len(&s); + let r = s.execute("type.dynamicTextPreset", &json!({"preset": "bow"})).unwrap(); + assert_eq!(r["ids"], json!([id.0])); + assert_eq!(undo_len(&s), before); + // Another position is a change. + s.execute("type.dynamicTextPreset", &json!({"preset": "bow", "position": "below"})).unwrap(); + assert_eq!(undo_len(&s), before + 1); + // The fit follows later edits to the text. + let f = fit(&s, id); + s.execute("text.setText", &json!({"ids": [id.0], "text": "Along the line and on past it"})).unwrap(); + assert!(fit(&s, id) < f * 0.8, "{} vs {f}", fit(&s, id)); + // On a rotated object the arch still bulges up the page, and on a squashed one the circle is + // round on the page. + let (turned, _) = point(&mut s, "Turned"); + s.execute("object.rotate", &json!({"ids": [turned.0], "angle": 45})).unwrap(); + s.execute("type.dynamicTextPreset", &json!({"preset": "arch", "ids": [turned.0]})).unwrap(); + let t = text(&s, turned); + let page = on_path(&t).0.transformed(t.xf); + let a = &page.subpaths[0].anchors; + assert!(close(a[0].p.y, a[2].p.y) && a[1].p.y < a[0].p.y && a[0].p.x < a[2].p.x, "{a:?}"); + // The same preset again leaves the rotated arch as it is. + let before = undo_len(&s); + s.execute("type.dynamicTextPreset", &json!({"preset": "arch", "ids": [turned.0]})).unwrap(); + assert_eq!(undo_len(&s), before); + let (squashed, _) = point(&mut s, "Squashed"); + s.execute("object.scale", &json!({"ids": [squashed.0], "sx": 200, "sy": 50})).unwrap(); + s.execute("type.dynamicTextPreset", &json!({"preset": "circle", "ids": [squashed.0]})).unwrap(); + let t = text(&s, squashed); + let pb = on_path(&t).0.transformed(t.xf).bounds().unwrap(); + assert!(close(pb.width(), pb.height()), "{pb:?}"); + // Empty 12 pt point type gets a circle four ems (48 pt) across. + let (empty, _) = point(&mut s, ""); + s.execute("type.dynamicTextPreset", &json!({"preset": "circle"})).unwrap(); + let (path, ..) = on_path(&text(&s, empty)); + let pb = path.bounds().unwrap(); + assert!(close(pb.width(), 48.0) && close(pb.height(), 48.0), "{pb:?}"); +} + +#[test] +fn presets_refuse_bad_params_area_type_and_threads() { + let mut s = session(); + let (id, _) = point(&mut s, "Point"); + let before = undo_len(&s); + for p in [ + json!({}), + json!({"preset": "square"}), + json!({"preset": 1}), + json!({"preset": "arch", "position": "top"}), + json!({"preset": "arch", "position": true}), + json!({"preset": "arch", "flip": "yes"}), + ] { + let e = err(s.execute("type.dynamicTextPreset", &p)); + let key = ["position", "flip"].into_iter().find(|k| p.get(k).is_some()).unwrap_or("preset"); + assert!(e.contains(key), "{p}: {e}"); + } + assert_eq!(undo_len(&s), before); + assert!(matches!(text(&s, id).kind, vectorcraft_doc::TextKind::Point)); + // Area type alone is refused; beside point type it is left as it is. + let area = + s.execute("text.create", &json!({"x": 10, "y": 300, "text": "Area", "area": {"width": 100, "height": 50}})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [area]})).unwrap(); + assert!(err(s.execute("type.dynamicTextPreset", &json!({"preset": "circle"}))).contains("select point type or type on a path")); + s.execute("select.set", &json!({"ids": [area, id.0]})).unwrap(); + let r = s.execute("type.dynamicTextPreset", &json!({"preset": "circle"})).unwrap(); + assert_eq!(r["ids"], json!([id.0])); + assert!(matches!(text(&s, NodeId(area)).kind, vectorcraft_doc::TextKind::Area { .. }) && !text(&s, NodeId(area)).dynamic_text); + // Type on a path in a thread is refused by id. + let threaded = on_line(&mut s, "Threaded story"); + let frame = s.execute("shape.rectangle", &json!({"x": 100, "y": 400, "width": 200, "height": 100})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [threaded.0, frame]})).unwrap(); + s.execute("text.thread.create", &json!({})).unwrap(); + let before = undo_len(&s); + let e = err(s.execute("type.dynamicTextPreset", &json!({"preset": "arch", "ids": [threaded.0, id.0]}))); + assert!(e.contains("in a thread") && e.contains(&threaded.0.to_string()), "{e}"); + assert_eq!(undo_len(&s), before); +} + /// The id of the first text object in `s`'s document. fn first_text(s: &Session) -> NodeId { let mut found = None; diff --git a/crates/engine/src/tests/editcolors.rs b/crates/engine/src/tests/editcolors.rs index 8f41ed3a73..e3aa59368a 100644 --- a/crates/engine/src/tests/editcolors.rs +++ b/crates/engine/src/tests/editcolors.rs @@ -77,10 +77,12 @@ fn saturate_needs_a_number_intensity() { let mut s = session(); let a = rect(&mut s, json!("#cc6666")); let undo = s.doc().unwrap().history.undo.len(); - for p in [json!({}), json!({"intensity": "40"}), json!({"intensity": null})] { + for p in [json!({}), json!({"intensity": null})] { let e = s.execute("edit.colors.saturate", &p).unwrap_err().to_string(); assert!(e.contains("missing number `intensity`"), "{p}: {e}"); } + let e = s.execute("edit.colors.saturate", &json!({"intensity": "40"})).unwrap_err().to_string(); + assert!(e.contains("`intensity` must be a number, not \"40\""), "{e}"); assert_eq!(fill_of(&s, a).to_hex(), "#cc6666"); assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step"); s.execute("edit.colors.saturate", &json!({"intensity": 100})).unwrap(); @@ -482,6 +484,250 @@ fn adjust_colors_converting_to_gray_stores_an_image_as_grayscale() { assert!(source(false).is_none(), "the colors keep their model"); } +/// Convert to Indexed Color stores an image as a palette PNG in one undo step; an image with few +/// enough colors keeps them, and converting it again changes nothing and adds no undo step. +#[test] +fn convert_to_indexed_stores_an_image_as_a_palette_png() { + let mut s = session(); + let id = image_node(&mut s); + let undo = s.doc().unwrap().history.undo.len(); + let r = s.execute("edit.colors.toIndexed", &json!({})).unwrap(); + assert_eq!(r["changed"], 1, "{r}"); + let key = image_key(&s, id); + assert!(s.doc().unwrap().doc.images[&key].indexed_png(), "an indexed PNG"); + assert_eq!(pixels(&s, id), [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [255, 255, 255, 255]], "half opaque becomes opaque"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + let again = s.execute("edit.colors.toIndexed", &json!({})).unwrap(); + assert_eq!(again["changed"], 0, "{again}"); + assert_eq!(image_key(&s, id), key); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "no undo step when nothing changes"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(pixels(&s, id)[3], [255, 255, 255, 128], "one undo step restores the image"); +} + +/// Pixels under half opacity become transparent; an indexed image converted to a palette it +/// already shows is left as it is, and one converted to a smaller palette changes. +#[test] +fn convert_to_indexed_keeps_transparency_and_reduces_an_indexed_image() { + let mut s = session(); + let id = image_of(&mut s, [[200, 30, 90, 255], [20, 40, 220, 255], [0, 0, 0, 100], [250, 250, 250, 255]]); + s.execute("edit.colors.toIndexed", &json!({"dither": "none"})).unwrap(); + assert_eq!(pixels(&s, id)[2][3], 0, "under half opacity: transparent"); + let r = s.execute("edit.colors.toIndexed", &json!({"reduction": "blackWhite", "dither": "none"})).unwrap(); + assert_eq!(r["changed"], 1, "{r}"); + let px = pixels(&s, id); + assert_eq!([px[0], px[1], px[3]], [[0, 0, 0, 255], [0, 0, 0, 255], [255, 255, 255, 255]]); + assert_eq!(px[2][3], 0); +} + +/// The uniform reduction takes evenly spaced levels of each channel, and the document reduction +/// the colors of the document's swatches. +#[test] +fn convert_to_indexed_uses_a_uniform_or_the_document_palette() { + let mut s = session(); + let id = image_of(&mut s, [[200, 30, 90, 255], [20, 40, 220, 255], [120, 130, 140, 255], [250, 250, 250, 255]]); + s.execute("edit.colors.toIndexed", &json!({"reduction": "uniform", "colors": 9, "dither": "none"})).unwrap(); + assert_eq!(pixels(&s, id), [[255, 0, 0, 255], [0, 0, 255, 255], [0, 255, 255, 255], [255, 255, 255, 255]]); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.colors.toIndexed", &json!({"reduction": "document"})).unwrap(); + let swatches: Vec<[u8; 3]> = crate::cmd::swatchlib::library_colors(&s, "document") + .unwrap() + .iter() + .map(|c| { + let [r, g, b, _] = c.to_rgba8(1.0); + [r, g, b] + }) + .collect(); + for p in pixels(&s, id) { + assert!(swatches.contains(&[p[0], p[1], p[2]]), "{p:?} is a swatch color"); + } +} + +/// The start of a PNG of `w` × `h` RGBA pixels: its header and a first image data chunk, without +/// the rest of the pixels. +fn png_header(w: u32, h: u32) -> Vec<u8> { + let crc = |data: &[u8]| { + let mut c = !0u32; + for &b in data { + c ^= u32::from(b); + for _ in 0..8 { + c = if c & 1 == 1 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 }; + } + } + !c + }; + let chunk = |ty: &[u8; 4], data: &[u8]| { + let body = [ty.as_slice(), data].concat(); + [(data.len() as u32).to_be_bytes().as_slice(), &body, &crc(&body).to_be_bytes()].concat() + }; + let ihdr = [w.to_be_bytes().as_slice(), &h.to_be_bytes(), &[8, 6, 0, 0, 0]].concat(); + [b"\x89PNG\r\n\x1a\n".as_slice(), &chunk(b"IHDR", &ihdr), &chunk(b"IDAT", &[0x78, 0x9c, 0x03, 0x00])].concat() +} + +/// An image larger than Convert to Indexed Color converts is refused by its size, read from the +/// file's header, before any pixel is decoded; nothing changes. +#[test] +fn convert_to_indexed_refuses_an_image_too_large_to_convert() { + let mut s = session(); + let id = image_node(&mut s); + assert_eq!(vectorcraft_doc::ImageBlob::png(png_header(30_000, 30_000)).pixel_size(), Some((30_000, 30_000))); + s.edit("Swap", |d, _| { + d.images.insert("pic".into(), vectorcraft_doc::ImageBlob::png(png_header(30_000, 30_000))); + Ok(()) + }) + .unwrap(); + let undo = s.doc().unwrap().history.undo.len(); + let e = s.execute("edit.colors.toIndexed", &json!({})).unwrap_err().to_string(); + assert!(e.contains("an image of 30000 × 30000 pixels is too large to convert"), "{e}"); + assert_eq!(image_key(&s, id), "pic"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo); +} + +/// Convert to Indexed Color refuses parameters it can't use, and leaves the image as it is. +#[test] +fn convert_to_indexed_refuses_bad_params() { + let mut s = session(); + let id = image_node(&mut s); + for (p, msg) in [ + (json!({"colors": 1}), "`colors` must be a whole number from 2 to 256"), + (json!({"colors": 257}), "`colors` must be a whole number from 2 to 256"), + (json!({"colors": "8"}), "`colors` must be a whole number from 2 to 256"), + (json!({"colors": 16.5}), "`colors` must be a whole number from 2 to 256"), + (json!({"reduction": "uniform", "colors": 8}), "`colors` must be at least 9 for the uniform reduction"), + (json!({"reduction": "document", "colors": 16}), "`colors` does not apply to the document reduction"), + (json!({"reduction": "blackWhite", "colors": 2}), "`colors` does not apply to the blackWhite reduction"), + (json!({"reduction": "posterize"}), "unknown reduction `posterize`"), + (json!({"dither": "random"}), "unknown dither `random`"), + (json!({"ditherAmount": 101}), "`ditherAmount` must be a number from 0 to 100"), + (json!({"ditherAmount": "50"}), "`ditherAmount` must be a number from 0 to 100"), + ] { + let e = s.execute("edit.colors.toIndexed", &p).unwrap_err().to_string(); + assert!(e.contains(msg), "{p}: {e}"); + } + assert_eq!(image_key(&s, id), "pic"); +} + +/// An embedded `w` × `h` image of the pixels `f(x, y)`, placed and selected. +fn placed(s: &mut Session, w: u32, h: u32, f: impl Fn(u32, u32) -> [u8; 4]) -> NodeId { + let mut png = Vec::new(); + image::RgbaImage::from_fn(w, h, |x, y| image::Rgba(f(x, y))).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let r = s.execute("file.place", &json!({"name": "art.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap(); + NodeId(r["ids"][0].as_u64().unwrap()) +} + +/// `ids` picks the images to convert; a linked image and a colorized image keep their pixels. +#[test] +fn convert_to_indexed_takes_ids_and_leaves_linked_and_colorized_images() { + let mut s = session(); + let a = placed(&mut s, 2, 1, |x, _| [200, 30 + x as u8, 90, 255]); + let b = placed(&mut s, 2, 1, |x, _| [20, 40, 200 + x as u8, 255]); + let (ka, kb) = (image_key(&s, a), image_key(&s, b)); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let r = s.execute("edit.colors.toIndexed", &json!({"ids": [b.0]})).unwrap(); + assert_eq!(r["changed"], 1, "{r}"); + assert_eq!(image_key(&s, a), ka, "not in `ids`"); + assert_ne!(image_key(&s, b), kb); + s.edit("Link", |d, _| { + let NodeKind::Image(im) = &mut d.node_mut(a).unwrap().kind else { panic!("not an image") }; + im.link = Some(vectorcraft_doc::LinkInfo::new("art.png")); + Ok(()) + }) + .unwrap(); + let undo = s.doc().unwrap().history.undo.len(); + let r = s.execute("edit.colors.toIndexed", &json!({"ids": [a.0]})).unwrap(); + assert_eq!(r["changed"], 0, "a linked image: {r}"); + assert_eq!(image_key(&s, a), ka); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step"); + let mut png = Vec::new(); + image::GrayImage::from_pixel(4, 4, image::Luma([90])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let r = s.execute("file.place", &json!({"name": "gray.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap(); + let gray = NodeId(r["ids"][0].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"ids": [gray.0], "color": "#ff0000"})).unwrap(); + assert!(s.doc().unwrap().doc.node(gray).unwrap().extras().colorize.is_some(), "the fill colorizes the image"); + let kg = image_key(&s, gray); + let r = s.execute("edit.colors.toIndexed", &json!({"ids": [gray.0]})).unwrap(); + assert_eq!(r["changed"], 0, "a colorized image: {r}"); + assert_eq!(image_key(&s, gray), kg); +} + +/// With the selection Select All makes, locked and hidden images are left out and counted in +/// `notChanged`; a left-out image too large to convert is counted without an error. +#[test] +fn convert_to_indexed_counts_left_out_images() { + let mut s = session(); + let a = placed(&mut s, 2, 1, |x, _| [200, 30 + x as u8, 90, 255]); + let locked = placed(&mut s, 2, 1, |x, _| [20, 40, 200 + x as u8, 255]); + let hidden = placed(&mut s, 2, 1, |x, _| [120, 140 + x as u8, 20, 255]); + s.edit("Huge", |d, _| { + let NodeKind::Image(im) = &mut d.node_mut(locked).unwrap().kind else { panic!("not an image") }; + im.key = "huge".into(); + d.images.insert("huge".into(), vectorcraft_doc::ImageBlob::png(png_header(30_000, 30_000))); + Ok(()) + }) + .unwrap(); + s.execute("object.lock", &json!({"ids": [locked.0]})).unwrap(); + s.execute("object.hide", &json!({"ids": [hidden.0]})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + let kh = image_key(&s, hidden); + let r = s.execute("edit.colors.toIndexed", &json!({})).unwrap(); + assert_eq!(r["changed"], 1, "{r}"); + assert_eq!(r["notChanged"], json!({"locked": 1, "hidden": 1}), "{r}"); + assert!(r["warning"].is_string(), "{r}"); + assert!(s.doc().unwrap().doc.images[&image_key(&s, a)].indexed_png()); + assert_eq!((image_key(&s, locked), image_key(&s, hidden)), ("huge".to_string(), kh)); +} + +/// The uniform reduction takes the most levels a channel whose cube leaves one entry for +/// transparency (3 for 64 colors, 6 for 256), and the document reduction takes 1 to 255 swatch +/// colors. +#[test] +fn convert_to_indexed_sizes_the_uniform_and_document_palettes() { + let mut s = session(); + let id = image_of(&mut s, [[200, 30, 90, 255], [20, 40, 220, 255], [120, 130, 140, 255], [250, 250, 250, 255]]); + s.execute("edit.colors.toIndexed", &json!({"reduction": "uniform", "colors": 64, "dither": "none"})).unwrap(); + assert_eq!(pixels(&s, id), [[255, 0, 127, 255], [0, 0, 255, 255], [127, 127, 127, 255], [255, 255, 255, 255]]); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.colors.toIndexed", &json!({"reduction": "uniform", "dither": "none"})).unwrap(); + assert_eq!(pixels(&s, id), [[204, 51, 102, 255], [0, 51, 204, 255], [102, 153, 153, 255], [255, 255, 255, 255]]); + s.execute("edit.undo", &json!({})).unwrap(); + s.edit("No swatches", |d, _| { + d.swatches.clear(); + d.swatch_groups.clear(); + Ok(()) + }) + .unwrap(); + let e = s.execute("edit.colors.toIndexed", &json!({"reduction": "document"})).unwrap_err().to_string(); + assert!(e.contains("the document has no color swatches"), "{e}"); + s.edit("Many swatches", |d, _| { + for i in 0..256u32 { + let paint = Paint::solid(Color::rgb8(i as u8, 7, 9)); + d.swatches.push(vectorcraft_color::swatch::Swatch { name: format!("c{i}"), paint, global: false, spot: false }); + } + Ok(()) + }) + .unwrap(); + let e = s.execute("edit.colors.toIndexed", &json!({"reduction": "document"})).unwrap_err().to_string(); + assert!(e.contains("the document's swatches hold 256 colors; the document reduction takes at most 255"), "{e}"); + assert_eq!(image_key(&s, id), "pic"); +} + +/// `dither` and `ditherAmount` reach the quantizer: a gray ramp reduced to black and white is +/// dithered by each method, and at an amount of 0 it comes out as with no dither. +#[test] +fn convert_to_indexed_dithers_by_the_amount_given() { + let ramp = |p: Value| { + let mut s = session(); + let id = placed(&mut s, 16, 4, |x, _| [(x * 17) as u8, (x * 17) as u8, (x * 17) as u8, 255]); + s.execute("edit.colors.toIndexed", &p).unwrap(); + pixels(&s, id) + }; + let none = ramp(json!({"reduction": "blackWhite", "dither": "none"})); + for d in ["diffusion", "pattern", "noise"] { + assert_eq!(ramp(json!({"reduction": "blackWhite", "dither": d, "ditherAmount": 0})), none, "{d} at 0"); + assert_ne!(ramp(json!({"reduction": "blackWhite", "dither": d})), none, "{d} at 100"); + } +} + /// A PDF of a CMYK document writes an image Convert to Grayscale made with one channel (#5632). #[test] fn a_converted_image_is_written_to_pdf_as_gray_in_a_cmyk_document() { diff --git a/crates/engine/src/tests/effectedit.rs b/crates/engine/src/tests/effectedit.rs index 2d10c3f5d9..34e01bf31e 100644 --- a/crates/engine/src/tests/effectedit.rs +++ b/crates/engine/src/tests/effectedit.rs @@ -147,3 +147,37 @@ fn show_all_hidden_attributes() { s.execute("edit.undo", &json!({})).unwrap(); assert!(node(&s, id).appearance.has_hidden()); } + +/// A Warp applied now takes its style's Bézier net (`version` 1) unless a map is given, an edit +/// keeps the map the effect has (one saved before the version existed keeps the earlier map), and +/// a map this build doesn't draw is refused. +#[test] +fn warps_keep_the_map_their_version_names() { + let (mut s, id) = session_with_rect(); + let version = |s: &Session| node(s, id).appearance.effects[0].params.get("version").cloned(); + run(&mut s, "effect.apply", json!({"effect": "warp.flag", "params": {"bend": 40}})); + assert_eq!(version(&s), Some(json!(vectorcraft_doc::live::WARP_NET))); + run(&mut s, "effect.setParams", json!({"index": 0, "params": {"bend": 20}, "warpStyle": "arc"})); + assert_eq!(version(&s), Some(json!(vectorcraft_doc::live::WARP_NET))); + // As a file saved before the version existed gives it. + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + if let Some(Value::Object(p)) = doc.node_mut(id).and_then(|n| n.appearance.effects.first_mut()).map(|e| &mut e.params) { + p.remove("version"); + } + run(&mut s, "effect.setParams", json!({"index": 0, "params": {"bend": 10, "horizontal": 20}})); + assert_eq!(version(&s), None); + run(&mut s, "effect.setParams", json!({"index": 0, "params": {"version": 1}})); + assert_eq!(version(&s), Some(json!(1))); + run(&mut s, "effect.apply", json!({"effect": "warp.arc", "params": {"version": 0}})); + assert_eq!(node(&s, id).appearance.effects[1].params["version"], json!(0)); + // A whole number given as a float is that version. + run(&mut s, "effect.setParams", json!({"index": 1, "params": {"version": 1.0}})); + assert_eq!(node(&s, id).appearance.effects[1].params["version"], json!(1)); + run(&mut s, "effect.setParams", json!({"index": 1, "params": {"version": 0.0}})); + assert_eq!(node(&s, id).appearance.effects[1].params["version"], json!(0)); + for bad in [json!(2), json!(-1), json!(0.5), json!("1")] { + assert!(s.execute("effect.apply", &json!({"effect": "warp.arc", "params": {"version": bad}})).is_err(), "{bad}"); + assert!(s.execute("effect.setParams", &json!({"index": 0, "params": {"version": bad}})).is_err(), "{bad}"); + } + assert_eq!(node(&s, id).appearance.effects.len(), 2); +} diff --git a/crates/engine/src/tests/envelope.rs b/crates/engine/src/tests/envelope.rs index e4d030d387..055cc62740 100644 --- a/crates/engine/src/tests/envelope.rs +++ b/crates/engine/src/tests/envelope.rs @@ -123,6 +123,74 @@ fn reset_with_warp_and_mesh_switch_the_kind_and_keep_the_content() { assert!(s.execute("object.envelope.resetWithMesh", &json!({})).is_err()); } +/// `object.mesh.addLine` at a point a mesh envelope already has (one stored without handles) adds +/// no line and records no undo step, with or without a `color`; a point between its lines adds +/// them as one step. +#[test] +fn mesh_envelope_add_line_at_a_mesh_point_records_no_undo_step() { + let mut s = session(); + let (_, e) = enveloped(&mut s, "object.envelope.makeWithMesh", json!({"rows": 2, "cols": 2})); + let before = kind(&s, e); + assert!(matches!(&before, EnvelopeKind::Mesh { handles, .. } if handles.is_empty()), "{before:?}"); + let undo_len = |s: &Session| s.doc().unwrap().history.undo.len(); + let n = undo_len(&s); + for (x, y) in [(100.0, 100.0), (300.0, 200.0), (200.0, 150.0), (300.0, 150.0)] { + s.execute("object.mesh.addLine", &json!({"id": e.0, "x": x, "y": y})).unwrap(); + assert_eq!((kind(&s, e), undo_len(&s)), (before.clone(), n), "({x}, {y}): nothing changed"); + } + // An envelope's points carry no color, so a color there changes nothing either. + s.execute("object.mesh.addLine", &json!({"id": e.0, "x": 200, "y": 150, "color": "#00ff00"})).unwrap(); + assert_eq!((kind(&s, e), undo_len(&s)), (before.clone(), n), "a color changes nothing"); + s.execute("object.mesh.addLine", &json!({"id": e.0, "x": 150, "y": 125})).unwrap(); + assert!(matches!(kind(&s, e), EnvelopeKind::Mesh { rows: 3, cols: 3, .. }), "{:?}", kind(&s, e)); + assert_eq!(undo_len(&s), n + 1); +} + +/// A new warp envelope bends with its style's Bézier net (`version` [`live::WARP_NET`]) and keeps +/// it through Reset with Warp. One saved before the version existed keeps the earlier map when its +/// warp or its options change. +#[test] +fn new_warp_envelopes_take_the_net_and_saved_ones_keep_their_map() { + // The surface point a quarter of the way along the top edge. + let quarter = |s: &Session, e| live::EnvelopeMap::of(&node(s, e)).unwrap().surface_mesh(4, 4, vectorcraft_color::Color::BLACK).points[1].p; + let at = |x, y| vectorcraft_geom::Point::new(x, y); + let mut s = session(); + let (_, e) = enveloped(&mut s, "object.envelope.makeWithWarp", json!({"style": "flag", "bend": 40})); + assert!(matches!(kind(&s, e), EnvelopeKind::Warp { version: live::WARP_NET, .. }), "{:?}", kind(&s, e)); + assert_eq!(s.execute("object.envelope.info", &json!({})).unwrap()["version"], json!(live::WARP_NET)); + // Flag moves the top edge 6 × bend × height × u(1 - u)(1 - 2u) down at u: 22.5 at u = 1/4. + assert!(quarter(&s, e).distance(at(150.0, 122.5)) < 1e-9, "{:?}", quarter(&s, e)); + s.execute("object.envelope.resetWithWarp", &json!({"bend": -40})).unwrap(); + assert!(matches!(kind(&s, e), EnvelopeKind::Warp { version: live::WARP_NET, .. }), "{:?}", kind(&s, e)); + assert!(quarter(&s, e).distance(at(150.0, 77.5)) < 1e-9, "{:?}", quarter(&s, e)); + // As a file saved before the version existed gives it. + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + if let Some(NodeKind::Envelope { kind, .. }) = doc.node_mut(e).map(|n| &mut n.kind) + && let EnvelopeKind::Warp { version, .. } = &mut **kind + { + *version = 0; + } + s.execute("object.envelope.options", &json!({"fidelity": 75})).unwrap(); + s.execute("object.envelope.resetWithWarp", &json!({"bend": 40})).unwrap(); + assert!(matches!(kind(&s, e), EnvelopeKind::Warp { version: 0, .. }), "{:?}", kind(&s, e)); + // The earlier map's flag: half the bend times sin(π x), x = -1/2 here, in half heights. + assert!(quarter(&s, e).distance(at(150.0, 90.0)) < 1e-9, "{:?}", quarter(&s, e)); + // `version` moves a warp to a map, and a new warp can take the earlier one. + s.execute("object.envelope.options", &json!({"version": 1.0})).unwrap(); + assert!(matches!(kind(&s, e), EnvelopeKind::Warp { version: live::WARP_NET, .. }), "{:?}", kind(&s, e)); + assert!(quarter(&s, e).distance(at(150.0, 122.5)) < 1e-9, "{:?}", quarter(&s, e)); + s.execute("object.envelope.resetWithWarp", &json!({"version": 0})).unwrap(); + assert!(matches!(kind(&s, e), EnvelopeKind::Warp { version: 0, .. }), "{:?}", kind(&s, e)); + let (_, old) = enveloped(&mut s, "object.envelope.makeWithWarp", json!({"style": "flag", "bend": 40, "version": 0})); + assert!(matches!(kind(&s, old), EnvelopeKind::Warp { version: 0, .. }), "{:?}", kind(&s, old)); + for bad in [json!(2), json!(-1), json!(0.5), json!("1"), json!(null)] { + for cmd in ["object.envelope.makeWithWarp", "object.envelope.resetWithWarp", "object.envelope.options"] { + let r = s.execute(cmd, &json!({"version": bad})); + assert!(r.as_ref().is_err_and(|e| e.to_string().contains("`version` must be 0 or 1")), "{cmd} {bad}: {r:?}"); + } + } +} + #[test] fn release_gives_back_the_warp_shape_as_a_mesh_and_keeps_the_transparency() { let mut s = session(); @@ -141,9 +209,9 @@ fn release_gives_back_the_warp_shape_as_a_mesh_and_keeps_the_transparency() { let content = node(&s, a); assert_eq!((content.opacity, content.blend, content.extras().mask.is_some()), (0.4, BlendMode::Multiply, true), "the content keeps the look"); let NodeKind::Mesh(m) = node(&s, ids[1]).kind else { panic!("the warp's shape comes back as a mesh") }; - // The mesh follows the arc: its outline reaches below the content's bottom edge at the sides. + // The mesh follows the arc: its top corners swing out past the content's sides and up. let b = m.outline().bounds().unwrap(); - assert!(b.y1 > 201.0, "{b:?}"); + assert!(b.x0 < 99.0 && b.x1 > 301.0 && b.y0 < 99.0, "{b:?}"); assert_eq!(s.doc().unwrap().selection.objects, ids); } @@ -724,6 +792,56 @@ fn an_envelope_of_type_that_draws_nothing_maps_from_its_laid_out_box() { assert_box(src_of(&s, e), laid, "warp"); } +/// Type that draws nothing adds no box next to other content: Make with Warp and Make with Mesh +/// around it and a rectangle, alone or in a group, map from the rectangle. +#[test] +fn type_that_draws_nothing_adds_no_box_next_to_other_content() { + for (cmd, params) in + [("object.envelope.makeWithWarp", json!({"style": "arc", "bend": 0})), ("object.envelope.makeWithMesh", json!({"rows": 1, "cols": 1}))] + { + for grouped in [false, true] { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 200.0, 100.0); + let want = node(&s, a).geometric_bounds().unwrap(); + let t = id_of(&s.execute("text.create", &json!({"x": 400, "y": 450, "text": " ", "size": 96})).unwrap()); + let laid = node(&s, t).geometric_bounds().unwrap(); + assert!(laid.x1 > want.x1 && laid.y1 > want.y1, "the laid-out box {laid:?} reaches past {want:?}"); + sel(&mut s, &[a, t]); + if grouped { + s.execute("object.group", &json!({})).unwrap(); + } + let layer = s.doc().unwrap().doc.layers[0].clone(); + assert_box(live::envelope_content_bounds(&[layer]).unwrap(), want, "content bounds"); + let e = id_of(&s.execute(cmd, ¶ms).unwrap()); + assert_box(src_of(&s, e), want, &format!("{cmd}, grouped: {grouped}")); + } + } +} + +/// Deleting every character of enveloped type in Edit Contents leaves the envelope mapping from +/// the rectangle beside it; with nothing beside it, from the type's laid-out box. +#[test] +fn edit_contents_that_empties_type_maps_from_the_other_content() { + for with_rect in [true, false] { + let mut s = session(); + let a = with_rect.then(|| rect(&mut s, 100.0, 100.0, 200.0, 100.0)); + let rect_box = a.map(|a| node(&s, a).geometric_bounds().unwrap()); + let t = id_of(&s.execute("text.create", &json!({"x": 400, "y": 450, "text": "Type", "size": 96})).unwrap()); + sel(&mut s, &a.into_iter().chain([t]).collect::<Vec<_>>()); + let e = id_of(&s.execute("object.envelope.makeWithWarp", &json!({"style": "arc", "bend": 0})).unwrap()); + sel(&mut s, &[e]); + s.execute("object.envelope.editContents", &json!({"editing": true})).unwrap(); + s.execute("text.setText", &json!({"ids": [t.0], "text": " "})).unwrap(); + sel(&mut s, &[e]); + s.execute("object.envelope.editContents", &json!({"editing": false})).unwrap(); + let NodeKind::Envelope { content, .. } = node(&s, e).kind else { panic!("envelope") }; + let blank = content.iter().find(|c| c.id == t).expect("the type stays"); + assert!(matches!(&blank.kind, NodeKind::Text(tx) if tx.plain_text().trim().is_empty()), "the type was emptied"); + let want = rect_box.unwrap_or_else(|| blank.geometric_bounds().unwrap()); + assert_box(src_of(&s, e), want, &format!("with a rectangle: {with_rect}")); + } +} + /// The strikethrough bar runs to the last glyph's advance, past its outline: the envelope maps /// from it too. #[test] diff --git a/crates/engine/src/tests/envelope_distort.rs b/crates/engine/src/tests/envelope_distort.rs index 8a1e46c68a..a0193a27f8 100644 --- a/crates/engine/src/tests/envelope_distort.rs +++ b/crates/engine/src/tests/envelope_distort.rs @@ -154,6 +154,35 @@ fn images_bend_as_a_raster_mesh_warp() { assert_eq!(svg.matches("<image").count(), 1, "the pieces share the image's pixels"); } +#[test] +fn a_colorized_image_keeps_its_color_in_an_envelope() { + let mut s = session(); + let img = image::GrayImage::from_pixel(4, 4, image::Luma([0])); + let mut png = vec![]; + image::DynamicImage::ImageLuma8(img).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let im = s + .edit("Place", |d, sel| { + d.images.insert("gray".into(), vectorcraft_doc::ImageBlob::png(png)); + let id = d.alloc_id(); + let xf = Affine::translate((100.0, 100.0)) * Affine::scale(10.0); + let im = + vectorcraft_doc::ImageObject { key: "gray".into(), width: 4, height: 4, xf, link: None, placement: Default::default(), pixels: None }; + d.insert(d.default_layer(), 0, Node::new(id, NodeKind::Image(Box::new(im))))?; + sel.set([id]); + Ok(id) + }) + .unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000", "ids": [im.0]})).unwrap(); + sel(&mut s, &[im]); + arch(&mut s, 80.0, json!({})); + let img = vectorcraft_render::Renderer::new().render_region(&s.doc().unwrap().doc, Rect::new(0.0, 0.0, 200.0, 200.0), 1.0, true); + // The black pixels draw in the fill color, in the bent shape. + let mid = img.pixel(120, 97); + assert!(mid[0] > 200 && mid[1] < 60 && mid[2] < 60, "the middle rose, red: {mid:?}"); + let inside = img.pixel(120, 120); + assert!(inside[0] > 200 && inside[1] < 60 && inside[2] < 60, "red inside: {inside:?}"); +} + /// A selected embedded 2×2 image, 80×80 pt at (100, 100): a red column left of a blue one. fn two_color_image(s: &mut Session) -> NodeId { let img = image::RgbaImage::from_fn(2, 2, |x, _| if x == 0 { image::Rgba([255, 0, 0, 255]) } else { image::Rgba([0, 0, 255, 255]) }); @@ -286,17 +315,18 @@ fn symbols_bend_with_the_envelope() { let e = arch(&mut s, 60.0, json!({})); let pts = anchors(&evaluated(&s, e)); assert!(pts.iter().any(|p| p.y < 90.0), "the symbol's art rose in the middle"); - // Editing the symbol redraws the envelope (the renderer's cache follows the symbol's art). + // Editing the symbol redraws the envelope (the renderer's cache follows the symbol's art). The + // arch lifts the middle of the 100..200 box by about 51, so (200, 120) is inside it. let mut r = vectorcraft_render::Renderer::new(); let region = Rect::new(0.0, 0.0, 400.0, 300.0); - assert!(r.render_region(&s.doc().unwrap().doc, region, 1.0, true).pixel(200, 150)[1] < 60); + assert!(r.render_region(&s.doc().unwrap().doc, region, 1.0, true).pixel(200, 120)[1] < 60); s.edit("edit symbol", |d, _| { let art = Node::path(NodeId(0), shapes::rectangle(Rect::new(-10.0, -10.0, -8.0, -8.0)), Default::default()); d.symbols[0].art = Arc::new(art); Ok(()) }) .unwrap(); - assert!(r.render_region(&s.doc().unwrap().doc, region, 1.0, true).pixel(200, 150)[1] > 200); + assert!(r.render_region(&s.doc().unwrap().doc, region, 1.0, true).pixel(200, 120)[1] > 200); } fn strokes(nodes: &[Node]) -> usize { @@ -601,6 +631,32 @@ fn an_opacity_mask_on_type_bends_as_other_art() { assert_eq!(kept, 1, "the type's stroke stays a stroke"); } +/// An envelope bends the art of a linked opacity mask on its contents with them; an unlinked mask +/// stays where it is. +#[test] +fn an_envelope_bends_a_linked_opacity_mask_and_leaves_an_unlinked_one() { + for linked in [true, false] { + let mut s = session(); + let a = rect(&mut s); + let m = rect(&mut s); + sel(&mut s, &[a, m]); + s.execute("transparency.makeOpacityMask", &json!({})).unwrap(); + if !linked { + s.execute("transparency.unlinkOpacityMask", &json!({})).unwrap(); + } + let before = node(&s, a).extras().mask.as_ref().unwrap().art.path_data().cloned(); + sel(&mut s, &[a]); + let e = arch(&mut s, 60.0, json!({})); + let mut found = vec![]; + for n in &evaluated(&s, e) { + n.walk(&mut |c| found.extend(c.extras().mask.as_ref().map(|k| (c.path_data().cloned(), k.art.path_data().cloned())))); + } + let [(bent, mask)] = found.as_slice() else { panic!("one masked object: {found:?}") }; + assert!(bent != &before, "the contents bend"); + assert_eq!(mask, if linked { bent } else { &before }, "linked: {linked}"); + } +} + /// Expand turns an envelope of stroked type into its bent glyph outlines with the stroke on them, /// at its own weight, as it draws (#6644). #[test] diff --git a/crates/engine/src/tests/envelope_edit.rs b/crates/engine/src/tests/envelope_edit.rs index 7b87bef2cb..ccad701312 100644 --- a/crates/engine/src/tests/envelope_edit.rs +++ b/crates/engine/src/tests/envelope_edit.rs @@ -151,6 +151,239 @@ fn mesh_handles_turn_with_the_envelope_and_round_trip() { assert!(matches!(n.kind, NodeKind::Envelope { kind, .. } if matches!(&*kind, EnvelopeKind::Mesh { handles, .. } if handles.is_empty()))); } +/// The kind of envelope `e`. +fn kind(s: &Session, e: NodeId) -> EnvelopeKind { + match node(s, e).kind { + NodeKind::Envelope { kind, .. } => *kind, + k => panic!("{k:?}"), + } +} + +fn undo_len(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +/// Moving a point of a warp envelope makes it a mesh envelope on the warp's grid with that point +/// moved, as one undo step: the other points and every handle stay where the warp had them, and +/// the shape away from the moved point stays the warp's. Undo gives back the warp, Redo the edit. +#[test] +fn moving_a_warp_point_makes_it_a_mesh_envelope_in_one_step() { + let mut s = session(); + let (_, e) = enveloped(&mut s, "object.envelope.makeWithWarp", json!({"style": "arc", "bend": 50})); + let warp = node(&s, e); + let grid = live::warp_grid(&warp).unwrap(); + assert_eq!((grid.rows, grid.cols), (4, 4)); + let before = EnvelopeMap::of(&warp).unwrap(); + let n = undo_len(&s); + // An interior point. + s.execute("object.mesh.movePoint", &json!({"id": e.0, "index": 6, "x": 160, "y": 120})).unwrap(); + assert_eq!(undo_len(&s), n + 1, "one undo step"); + let (rows, cols, points, handles) = mesh(&s, e); + assert_eq!((rows, cols, points.len(), handles.len()), (4, 4, 25, 25)); + for (i, q) in grid.points.iter().enumerate() { + let want = if i == 6 { Point::new(160.0, 120.0) } else { q.p }; + assert!(points[i].distance(want) < 1e-9, "point {i}: {:?} vs {want:?}", points[i]); + assert_eq!(handles[i], q.handles, "handles of point {i}"); + } + let moved = node(&s, e); + let after = EnvelopeMap::of(&moved).unwrap(); + let b = before.src(); + let tol = b.width().hypot(b.height()) * 1e-3; + for (u, v) in [(0.9, 0.9), (0.6, 0.875), (1.0, 0.5), (0.0, 1.0)] { + assert!(after.at(u, v).distance(before.at(u, v)) <= tol, "({u}, {v}): {:?} vs {:?}", after.at(u, v), before.at(u, v)); + } + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(node(&s, e), warp, "Undo gives back the warp, style and bend included"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(mesh(&s, e).2[6], Point::new(160.0, 120.0)); + // A corner of a warp, and a handle with object.envelope.setMeshPoint. + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("object.mesh.movePoints", &json!({"id": e.0, "points": [0], "dx": -10, "dy": -5})).unwrap(); + assert!(mesh(&s, e).2[0].distance(grid.points[0].p + Vec2::new(-10.0, -5.0)) < 1e-9); + s.execute("edit.undo", &json!({})).unwrap(); + let end = grid.points[12].p + Vec2::new(30.0, -30.0); + s.execute("object.envelope.setMeshPoint", &json!({"id": e.0, "index": 12, "x": end.x, "y": end.y, "handle": 0})).unwrap(); + let (_, _, points, handles) = mesh(&s, e); + assert!((points[12] + handles[12][live::H_RIGHT]).distance(end) < 1e-9); + assert_eq!(handles[12][live::H_LEFT], grid.points[12].handles[live::H_LEFT]); + assert_eq!(undo_len(&s), n + 1); +} + +/// After a warp's point is edited, the envelope keeps its content, options and fidelity; it saves +/// and opens again as it is; Reset with Mesh with Maintain Shape keeps the edited shape and Reset +/// with Warp gives the chosen style; Release gives back the edited mesh as its shape and Expand +/// keeps the edited distortion. +#[test] +fn an_edited_warp_saves_resets_releases_and_expands_as_edited() { + let mut s = session(); + let (_, e) = enveloped(&mut s, "object.envelope.makeWithWarp", json!({"style": "flag", "bend": 40})); + s.execute("object.envelope.options", &json!({"fidelity": 80, "distortAppearance": false})).unwrap(); + let warp = node(&s, e); + // The middle of the bottom edge, 30 down. + s.execute("object.mesh.movePoints", &json!({"id": e.0, "points": [22], "dx": 0, "dy": 30})).unwrap(); + let edited = node(&s, e); + let (NodeKind::Envelope { content: c0, options: o0, fidelity: f0, .. }, NodeKind::Envelope { content: c1, options: o1, fidelity: f1, .. }) = + (&warp.kind, &edited.kind) + else { + panic!("envelopes") + }; + assert_eq!((c0, o0, f0), (c1, o1, f1), "content, options and fidelity stay"); + let d = s.doc().unwrap().doc.clone(); + let back = vectorcraft_format::load(&vectorcraft_format::save(&d, false)).unwrap(); + assert_eq!(back.node(e), d.node(e), "a save opens again as edited"); + // Reset with Mesh, keeping the shape: the edited points. + let (_, _, points, _) = mesh(&s, e); + s.execute("object.envelope.resetWithMesh", &json!({"maintainShape": true})).unwrap(); + let (rows, cols, kept, _) = mesh(&s, e); + assert_eq!((rows, cols), (4, 4)); + for (p, q) in points.iter().zip(&kept) { + assert!(p.distance(*q) < 1e-6, "{p:?} vs {q:?}"); + } + // Reset with Warp: the chosen style replaces the edit. + s.execute("object.envelope.resetWithWarp", &json!({"style": "bulge", "bend": 30})).unwrap(); + assert!(matches!(kind(&s, e), EnvelopeKind::Warp { style, bend, .. } if style == "bulge" && bend == 30.0)); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(node(&s, e), edited); + // Release: the content and the edited mesh as the envelope's shape. + s.execute("select.set", &json!({"ids": [e.0]})).unwrap(); + let ids = s.execute("object.envelope.release", &json!({})).unwrap(); + let ids: Vec<NodeId> = ids["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect(); + let shape = ids.iter().find_map(|id| match node(&s, *id).kind { + NodeKind::Mesh(m) => Some(m), + _ => None, + }); + let shape = shape.expect("the envelope's shape"); + assert_eq!(shape.points.iter().map(|q| q.p).collect::<Vec<_>>(), points); + s.execute("edit.undo", &json!({})).unwrap(); + // Expand: the distorted content follows the moved point, unlike the warp's. + let expanded = |s: &mut Session| { + s.execute("select.set", &json!({"ids": [e.0]})).unwrap(); + s.execute("object.envelope.expand", &json!({})).unwrap(); + let b = node(s, e).geometric_bounds().unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + b + }; + let edited_bounds = expanded(&mut s); + s.execute("edit.undo", &json!({})).unwrap(); + let warp_bounds = expanded(&mut s); + assert!(edited_bounds.y1 > warp_bounds.y1 + 5.0, "{edited_bounds:?} vs {warp_bounds:?}"); +} + +/// An edit of a warp's points that fails (an index out of range, here on the second of two +/// warps) changes neither warp and adds no undo step; a warp that no grid follows closely enough +/// shows no points and is refused, and so is a top object envelope. +#[test] +fn a_warp_point_edit_that_fails_changes_nothing() { + let mut s = session(); + let (_, e) = enveloped(&mut s, "object.envelope.makeWithWarp", json!({"style": "arc", "bend": 50})); + let (_, f) = enveloped(&mut s, "object.envelope.makeWithWarp", json!({"style": "wave", "bend": 50})); + let (we, wf, n) = (node(&s, e), node(&s, f), undo_len(&s)); + let r = s.execute("object.mesh.movePoints", &json!({"items": [{"id": e.0, "points": [0]}, {"id": f.0, "points": [3, 99999]}], "dx": 5, "dy": 5})); + assert!(r.is_err(), "{r:?}"); + let r = s.execute("object.envelope.setMeshPoint", &json!({"id": e.0, "index": 25, "x": 0, "y": 0})); + assert!(r.is_err(), "{r:?}"); + assert_eq!((node(&s, e), node(&s, f), undo_len(&s)), (we, wf, n), "nothing changed"); + // The old point map's fisheye: no grid of up to 16×16 patches follows it. + let (_, g) = enveloped(&mut s, "object.envelope.makeWithWarp", json!({"style": "fisheye", "bend": 100, "version": 0})); + let old = node(&s, g); + assert!(live::warp_grid(&old).is_none()); + assert!(live::envelope_overlay(&old).unwrap().1.is_none(), "no points show"); + let n = undo_len(&s); + for (cmd, p) in [ + ("object.mesh.movePoint", json!({"id": g.0, "index": 0, "x": 0, "y": 0})), + ("object.envelope.setMeshPoint", json!({"id": g.0, "index": 0, "x": 0, "y": 0})), + ("object.mesh.addLine", json!({"id": g.0, "x": 200, "y": 150})), + ] { + let r = s.execute(cmd, &p); + assert!( + matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == "this warp's points can't be edited: use Reset with Mesh first"), + "{cmd}: {r:?}" + ); + } + assert_eq!((node(&s, g), undo_len(&s)), (old, n)); +} + +/// An edit that moves no point of a warp (no points named, a move by nothing, a point placed where +/// it is, a line added through one of its points) leaves it a warp and records no undo step. +#[test] +fn a_warp_edit_that_moves_nothing_leaves_the_warp() { + let mut s = session(); + let (_, e) = enveloped(&mut s, "object.envelope.makeWithWarp", json!({"style": "arc", "bend": 50})); + let (warp, n) = (node(&s, e), undo_len(&s)); + let grid = live::warp_grid(&warp).unwrap(); + s.execute("object.mesh.movePoints", &json!({"id": e.0, "points": [], "dx": 10, "dy": 0})).unwrap(); + s.execute("object.mesh.movePoints", &json!({"id": e.0, "points": [3, 6], "dx": 0, "dy": 0})).unwrap(); + assert_eq!((node(&s, e), undo_len(&s)), (warp.clone(), n)); + let q = grid.points[6].clone(); + s.execute("object.mesh.movePoint", &json!({"id": e.0, "index": 6, "x": q.p.x, "y": q.p.y})).unwrap(); + s.execute("object.envelope.setMeshPoint", &json!({"id": e.0, "index": 6, "x": q.p.x, "y": q.p.y})).unwrap(); + // A line added through a point of the warp's grid adds none. + let r = s.execute("object.mesh.addLine", &json!({"id": e.0, "x": q.p.x, "y": q.p.y})).unwrap(); + assert_eq!(r["index"], json!(6)); + assert_eq!((node(&s, e), undo_len(&s)), (warp, n)); + // An unknown mesh still fails. + assert!(s.execute("object.mesh.movePoints", &json!({"id": 99999, "points": [], "dx": 1, "dy": 0})).is_err()); +} + +/// A handle placed at its own end, sent as point plus handle, leaves a warp a warp, even where +/// `(p + v) - p` rounds to a value other than `v`. +#[test] +fn a_warp_handle_placed_at_its_end_leaves_the_warp() { + let mut s = session(); + let (_, e) = enveloped(&mut s, "object.envelope.makeWithWarp", json!({"style": "arc", "bend": 50})); + let (warp, n) = (node(&s, e), undo_len(&s)); + let grid = live::warp_grid(&warp).unwrap(); + let mut rounds = 0; + for (index, pt) in grid.points.iter().enumerate() { + for (h, v) in pt.handles.iter().enumerate() { + let end = pt.p + *v; + if end - pt.p != *v { + rounds += 1; + } + for cmd in ["object.mesh.movePoint", "object.envelope.setMeshPoint"] { + s.execute(cmd, &json!({"id": e.0, "index": index, "x": end.x, "y": end.y, "handle": h})).unwrap(); + assert_eq!((node(&s, e), undo_len(&s)), (warp.clone(), n), "{cmd}: point {index}, handle {h}"); + } + } + } + assert!(rounds > 0, "the grid has a handle whose end does not give the handle back"); +} + +/// With Direct Selection, a selected warp's point drags as `object.mesh.movePoint`: the preview +/// makes it a mesh envelope, Escape gives back the warp with no undo step, and a finished drag is +/// one undo step. While its contents are edited, its points don't take the press. +#[test] +fn direct_selection_drags_a_warps_point_and_escape_gives_it_back() { + let mut s = session(); + let (_, e) = enveloped(&mut s, "object.envelope.makeWithWarp", json!({"style": "arc", "bend": 50})); + let warp = node(&s, e); + let corner = live::warp_grid(&warp).unwrap().points[24].p; + s.execute("select.set", &json!({"ids": [e.0]})).unwrap(); + let v = ViewInfo::default(); + s.select_tool("directSelection", v).unwrap(); + let n = undo_len(&s); + s.pointer(&PointerEvent::new(PointerKind::Down, corner.x, corner.y), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, corner.x + 20.0, corner.y + 10.0), v).unwrap(); + assert!(mesh(&s, e).2[24].distance(corner + Vec2::new(20.0, 10.0)) < 1e-9, "the preview moves the point"); + s.tool_key(vectorcraft_tools::ToolKey::Escape, vectorcraft_tools::Mods::default(), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, corner.x + 20.0, corner.y + 10.0), v).unwrap(); + assert_eq!((node(&s, e), undo_len(&s)), (warp.clone(), n), "Escape gives back the warp"); + s.pointer(&PointerEvent::new(PointerKind::Down, corner.x, corner.y), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, corner.x + 20.0, corner.y + 10.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, corner.x + 20.0, corner.y + 10.0), v).unwrap(); + assert_eq!(undo_len(&s), n + 1); + assert!(mesh(&s, e).2[24].distance(corner + Vec2::new(20.0, 10.0)) < 1e-9); + // Edit Contents: the press doesn't take the envelope's point. + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("object.envelope.editContents", &json!({"editing": true})).unwrap(); + s.execute("select.set", &json!({"ids": [e.0]})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, corner.x, corner.y), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, corner.x + 20.0, corner.y + 10.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, corner.x + 20.0, corner.y + 10.0), v).unwrap(); + assert!(matches!(kind(&s, e), EnvelopeKind::Warp { .. }), "{:?}", kind(&s, e)); +} + #[test] fn reset_with_mesh_keeps_the_warp_shape_along_the_grid() { let mut s = session(); diff --git a/crates/engine/src/tests/expand.rs b/crates/engine/src/tests/expand.rs index 038b8844bb..d853b91110 100644 --- a/crates/engine/src/tests/expand.rs +++ b/crates/engine/src/tests/expand.rs @@ -126,6 +126,302 @@ fn a_symbol_instance_fill_with_no_opacity_keeps_swatch_links_when_expanded() { assert!(linked > 0, "the expanded art keeps the Brand swatch link"); } +/// The square of [`square`] made a symbol, its instance selected, with a new fill (`fill`) or +/// stroke on top that has no paint: it neither stains nor strokes the art. Returns the instance and +/// the new row's index. +fn instance_with_row(s: &mut Session, name: &str, fill: bool) -> (NodeId, usize) { + square(s); + let id = NodeId(run(s, "symbol.new", json!({"name": name}))["id"].as_u64().unwrap()); + run(s, if fill { "appearance.addFill" } else { "appearance.addStroke" }, json!({"ids": [id.0]})); + let row = node(s, id).appearance.items.len() - 1; + run(s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true})); + (id, row) +} + +fn offset_row(s: &mut Session, id: NodeId, row: usize, offset: f64) { + run(s, "effect.apply", json!({"ids": [id.0], "item": row, "effect": "path.offsetPath", "params": {"offset": offset}})); +} + +fn near(p: [u8; 4], q: [u8; 4]) -> bool { + p.iter().zip(q.iter()).all(|(x, y)| x.abs_diff(*y) <= 24) +} + +const WHITE: [u8; 4] = [255, 255, 255, 255]; +const RED: [u8; 4] = [255, 0, 0, 255]; +const BLUE: [u8; 4] = [0, 0, 255, 255]; + +/// No object in `n` keeps an effect of its own or on a fill or stroke. +fn no_effects_left(n: &Node) { + n.walk(&mut |part| { + assert!(part.appearance.effects.is_empty(), "{:?} keeps object effects", part.id); + assert!(part.appearance.items.iter().all(|i| i.effects().is_empty()), "{:?} keeps fill or stroke effects", part.id); + }); +} + +/// An effect on a symbol instance's fill reshapes the filled shapes of its art, keeping their +/// colors, and leaves their strokes where they were; Expand Appearance bakes the same look into +/// editable art in one undo step. +#[test] +fn a_symbol_instance_fill_effect_reshapes_its_filled_art_and_expands() { + let mut s = session(); + let (id, row) = instance_with_row(&mut s, "Square", true); + assert!(!expandable(&s)); + let plain = render(&s); + assert!(near(plain.pixel(44, 100), WHITE)); + offset_row(&mut s, id, row, 10.0); + assert!(expandable(&s), "the fill's effect can be expanded"); + let before = render(&s); + assert!(near(before.pixel(44, 100), RED), "the art's red fill grows by the offset: {:?}", before.pixel(44, 100)); + assert!(near(before.pixel(50, 100), BLUE), "the blue stroke stays on the square: {:?}", before.pixel(50, 100)); + + run(&mut s, "effect.expandAppearance", json!({})); + let n = node(&s, id); + assert!(!matches!(n.kind, NodeKind::SymbolInstance { .. })); + no_effects_left(&n); + let mut paints = (0, 0); + n.walk(&mut |part| { + if part.appearance.fill().is_some_and(|f| f.paint.color().is_some_and(|c| c.to_hex() == "#ff0000")) { + paints.0 += 1; + } + if part.appearance.stroke().is_some_and(|st| st.paint.color().is_some_and(|c| c.to_hex() == "#0000ff")) { + paints.1 += 1; + } + }); + assert!(paints.0 > 0 && paints.1 > 0, "the art keeps its red fill and blue stroke: {paints:?}"); + let after = render(&s); + assert!(differing(&before, &after, 8) < 200, "expanding changed {} pixels", differing(&before, &after, 8)); + + run(&mut s, "edit.undo", json!({})); + let n = node(&s, id); + assert!(matches!(n.kind, NodeKind::SymbolInstance { .. }), "one undo gives the instance back"); + assert!(n.appearance.items[row].effects().iter().any(|e| e.id == "path.offsetPath")); +} + +/// Export bakes a symbol instance's fill effect into its art as the canvas draws it. +#[test] +fn export_bakes_a_symbol_instance_fill_effect() { + let mut s = session(); + let (id, row) = instance_with_row(&mut s, "Square", true); + offset_row(&mut s, id, row, 10.0); + let doc = s.doc().unwrap().doc.clone(); + let baked = vectorcraft_render::effects::bake_document(&doc).expect("the instance is baked"); + let n = baked.node(id).expect("the baked art keeps the instance's id").clone(); + assert!(!matches!(n.kind, NodeKind::SymbolInstance { .. })); + no_effects_left(&n); + let b = n.geometric_bounds().expect("the baked art has bounds"); + assert!((b.x0 - 40.0).abs() < 1.0 && (b.x1 - 160.0).abs() < 1.0, "the fill grows by the offset: {b:?}"); +} + +/// An effect on a symbol instance's stroke reshapes the stroked shapes of its art and leaves +/// their fills where they were. +#[test] +fn a_symbol_instance_stroke_effect_reshapes_its_stroked_art_and_expands() { + let mut s = session(); + let (id, row) = instance_with_row(&mut s, "Square", false); + assert!(near(render(&s).pixel(40, 100), WHITE)); + offset_row(&mut s, id, row, 10.0); + assert!(expandable(&s)); + let before = render(&s); + assert!(near(before.pixel(40, 100), BLUE), "the stroke moves out with the offset: {:?}", before.pixel(40, 100)); + assert!(near(before.pixel(45, 100), WHITE), "the fill keeps its shape: {:?}", before.pixel(45, 100)); + assert!(near(before.pixel(100, 100), RED)); + + run(&mut s, "effect.expandAppearance", json!({"ids": [id.0]})); + let n = node(&s, id); + assert!(!matches!(n.kind, NodeKind::SymbolInstance { .. })); + no_effects_left(&n); + let after = render(&s); + assert!(differing(&before, &after, 8) < 200, "expanding changed {} pixels", differing(&before, &after, 8)); +} + +/// A dynamic symbol's instance that paints a stroke of its own on art without one: the instance's +/// stroke effect reshapes that stroke, and its bounds take in where the stroke is drawn. +#[test] +fn a_stroke_effect_reshapes_a_stroke_a_dynamic_instance_adds() { + let mut s = session(); + square(&mut s); + run(&mut s, "paint.setStroke", json!({"none": true})); + let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Art", "type": "dynamic"}))["id"].as_u64().unwrap()); + run(&mut s, "appearance.addStroke", json!({"ids": [id.0]})); + let row = node(&s, id).appearance.items.len() - 1; + run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true})); + let blue = vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0)); + s.edit("paint", |d, _| { + let o = vectorcraft_doc::symbol_overrides::SymbolOverride { path: vec![], stroke: Some(blue), ..Default::default() }; + d.node_mut(id).ok_or(EngineError::NoNode(id))?.extras_mut().symbol_overrides.push(o); + Ok(()) + }) + .unwrap(); + // The 1 pt stroke's center moves to x = 30.5, so it covers the pixel column from 30 to 31. + offset_row(&mut s, id, row, 19.5); + assert!(near(render(&s).pixel(30, 100), BLUE), "the added stroke moves out with the offset: {:?}", render(&s).pixel(30, 100)); + let doc = s.doc().unwrap().doc.clone(); + let b = vectorcraft_render::painted_bounds(&doc, doc.node(id).unwrap()).expect("the instance has bounds"); + assert!(b.x0 <= 31.0 && b.x1 >= 169.0, "the bounds take in the offset stroke: {b:?}"); + let drawn = vectorcraft_render::drawn_bounds(&doc, doc.node(id).unwrap()).expect("the instance is drawn"); + assert!(drawn.x0 <= 31.0 && drawn.x1 >= 169.0, "the drawn bounds take in the offset stroke: {drawn:?}"); +} + +/// A group in the symbol's art with a fill of its own: the instance's fill effect reshapes what +/// that fill paints, and the instance's bounds take it in. +#[test] +fn a_fill_effect_reshapes_the_fill_of_a_group_in_the_art() { + let mut s = session(); + square(&mut s); + run(&mut s, "paint.setFill", json!({"none": true})); + run(&mut s, "paint.setStroke", json!({"none": true})); + let g = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap()); + run(&mut s, "appearance.addFill", json!({"ids": [g.0]})); + run(&mut s, "paint.setFill", json!({"ids": [g.0], "item": 0, "color": "#ff0000"})); + let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Group"}))["id"].as_u64().unwrap()); + run(&mut s, "appearance.addFill", json!({"ids": [id.0]})); + let row = node(&s, id).appearance.items.len() - 1; + run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true})); + offset_row(&mut s, id, row, 20.0); + assert!(near(render(&s).pixel(35, 100), RED), "the group's fill grows by the offset: {:?}", render(&s).pixel(35, 100)); + let doc = s.doc().unwrap().doc.clone(); + let b = vectorcraft_render::painted_bounds(&doc, doc.node(id).unwrap()).expect("the instance has bounds"); + assert!(b.x0 <= 31.0 && b.x1 >= 169.0, "the bounds take in the group's grown fill: {b:?}"); + let drawn = vectorcraft_render::drawn_bounds(&doc, doc.node(id).unwrap()).expect("the instance is drawn"); + assert!(drawn.x0 <= 31.0 && drawn.x1 >= 169.0, "the drawn bounds take in the group's grown fill: {drawn:?}"); + + let before = render(&s); + run(&mut s, "effect.expandAppearance", json!({})); + no_effects_left(&node(&s, id)); + let after = render(&s); + assert!(differing(&before, &after, 8) < 200, "expanding changed {} pixels", differing(&before, &after, 8)); +} + +/// Of several fills, only the topmost one's effects reach the art, and only while it is visible. +#[test] +fn only_the_topmost_visible_instance_fill_reshapes_the_art() { + let mut s = session(); + let (id, lower) = instance_with_row(&mut s, "Square", true); + offset_row(&mut s, id, lower, 30.0); + run(&mut s, "appearance.addFill", json!({"ids": [id.0]})); + let top = node(&s, id).appearance.items.len() - 1; + run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": top, "none": true})); + assert!(!expandable(&s), "a lower fill's effect does not reach the art"); + offset_row(&mut s, id, top, 10.0); + let both = render(&s); + assert!(near(both.pixel(44, 100), RED), "the top fill's offset shows"); + assert!(near(both.pixel(25, 100), WHITE), "the lower fill's offset does not: {:?}", both.pixel(25, 100)); + + run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": top, "visible": false})); + assert!(near(render(&s).pixel(44, 100), WHITE), "a hidden top fill reshapes nothing"); + assert!(!expandable(&s)); + + run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": top, "visible": true})); + run(&mut s, "effect.expandAppearance", json!({})); + let after = render(&s); + assert!(differing(&both, &after, 8) < 200, "expanding changed {} pixels", differing(&both, &after, 8)); + let n = node(&s, id); + no_effects_left(&n); +} + +/// An instance inside a symbol's art passes the outer instance's fill effect on to its own art. +#[test] +fn a_nested_symbol_instance_takes_the_outer_fill_effect() { + let mut s = session(); + square(&mut s); + run(&mut s, "symbol.new", json!({"name": "Inner"})); + let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Outer"}))["id"].as_u64().unwrap()); + run(&mut s, "appearance.addFill", json!({"ids": [id.0]})); + let row = node(&s, id).appearance.items.len() - 1; + run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true})); + offset_row(&mut s, id, row, 40.0); + let before = render(&s); + assert!(near(before.pixel(20, 100), RED), "the inner art grows by the offset: {:?}", before.pixel(20, 100)); + assert!(expandable(&s)); + // A view that shows only the grown part, right of the square: the instance is still drawn. + let doc = s.doc().unwrap().doc.clone(); + let opts = vectorcraft_render::RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let right = vectorcraft_render::Renderer::new().render(&doc, 200, 200, vectorcraft_geom::Affine::translate((-155.0, 0.0)), &opts); + assert!(near(right.pixel(20, 100), RED), "the grown art past the square's box is drawn: {:?}", right.pixel(20, 100)); + let b = vectorcraft_render::painted_bounds(&doc, doc.node(id).unwrap()).expect("the instance has bounds"); + assert!(b.x0 <= 11.0 && b.x1 >= 189.0, "the bounds take in the inner art's offset: {b:?}"); + + run(&mut s, "effect.expandAppearance", json!({})); + let n = node(&s, id); + assert!(!matches!(n.kind, NodeKind::SymbolInstance { .. })); + n.walk(&mut |part| assert!(!matches!(part.kind, NodeKind::SymbolInstance { .. }), "the inner instance is expanded too")); + no_effects_left(&n); + let after = render(&s); + assert!(differing(&before, &after, 8) < 200, "expanding changed {} pixels", differing(&before, &after, 8)); +} + +/// A symbol whose art holds an instance of itself draws, exports and expands without running away. +/// The engine keeps no such document after an edit, so Expand Appearance refuses it and the +/// instance stays as it was. +#[test] +fn a_fill_effect_on_an_instance_of_a_symbol_that_holds_itself_ends() { + let mut s = session(); + let (id, row) = instance_with_row(&mut s, "Square", true); + offset_row(&mut s, id, row, 4.0); + { + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let inst = d.node(id).unwrap().clone(); + let sym = d.symbols.iter_mut().find(|sy| sy.name == "Square").unwrap(); + sym.art = std::sync::Arc::new(Node::group(NodeId(90_000), vec![sym.art.clone(), std::sync::Arc::new(inst)])); + } + let doc = s.doc().unwrap().doc.clone(); + assert!(vectorcraft_render::effects::bake_document(&doc).is_some(), "export bakes the instance"); + assert!(vectorcraft_render::painted_bounds(&doc, doc.node(id).unwrap()).is_some(), "the instance is measured"); + render(&s); + assert!(expandable(&s)); + let e = s.execute("effect.expandAppearance", &json!({})).expect_err("the symbol nests without end"); + assert!(e.to_string().contains(crate::TOO_DEEP), "{e}"); + assert!(matches!(node(&s, id).kind, NodeKind::SymbolInstance { .. }), "the instance stays as it was"); +} + +/// A clip group's clipping path in the art keeps its shape, a compound one included, while the art +/// it clips takes the instance's fill effect. +#[test] +fn a_compound_clipping_path_in_the_art_keeps_its_shape() { + let mut s = session(); + let (id, row) = instance_with_row(&mut s, "Square", true); + offset_row(&mut s, id, row, 10.0); + let red = || { + let mut ap = vectorcraft_doc::Appearance::default(); + ap.items.push(vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(vectorcraft_color::Paint::solid( + vectorcraft_color::Color::rgb(1.0, 0.0, 0.0), + )))); + ap + }; + let square = |id: u64, x: f64| { + let rect = vectorcraft_geom::Rect::new(x, 50.0, x + 100.0, 150.0); + std::sync::Arc::new(Node::path(NodeId(id), vectorcraft_geom::shapes::rectangle(rect), red())) + }; + let mut clip = Node::new(NodeId(90_001), NodeKind::Compound { children: vec![square(90_002, 40.0)], rule: Default::default() }); + clip.appearance = red().into(); + let group = Node::new(NodeId(90_003), NodeKind::Group { children: vec![std::sync::Arc::new(clip), square(90_004, 50.0)], clip: true }); + let doc = { + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let sym = d.symbols.iter_mut().find(|sy| sy.name == "Square").unwrap(); + sym.art = std::sync::Arc::new(group); + d.clone() + }; + let inst = doc.node(id).unwrap(); + let art = doc.symbols.iter().find(|sy| sy.name == "Square").unwrap().art.clone(); + let out = vectorcraft_render::effects::outline_art(Some(&doc), inst, Some(&art)).expect("the instance's art"); + let mut seen = (false, false); + out.walk(&mut |part| { + let offset = part.appearance.items.iter().any(|i| i.effects().iter().any(|e| e.id == "path.offsetPath")); + match part.id.0 { + 90_001 => { + seen.0 = true; + assert!(!offset, "the compound clipping path keeps its shape"); + } + 90_004 => { + seen.1 = true; + assert!(offset, "the clipped square takes the fill effect"); + } + _ => {} + } + }); + assert_eq!(seen, (true, true)); +} + #[test] fn two_fills_and_an_offset_stroke_become_three_paths_that_look_the_same() { let mut s = session(); @@ -239,9 +535,9 @@ fn expanded_art_keeps_the_random_transforms_the_canvas_drew() { } /// The reply lists each object whose appearance expanded once, by the id it has in the document, -/// starting with the selected object. In "group copies" the two copies of the square share an id -/// until Expand Appearance gives them ids of their own, and the reply names the group, then each -/// copy by its new id. +/// starting with the selected object. In "group copies" the group's art holds the square with its +/// stroke's effect applied, so the reply names the group alone; the two copies of the square share +/// ids until Expand Appearance gives every object in them an id of its own. #[test] fn the_reply_names_each_expanded_copy_by_its_own_id() { for case in RANDOM_CASES { @@ -255,8 +551,17 @@ fn the_reply_names_each_expanded_copy_by_its_own_id() { assert!(ids.iter().all(|&i| s.doc().unwrap().doc.node(NodeId(i)).is_some()), "{case}: {ids:?}"); if case == "group copies" { let art = node(&s, id); - let copies: Vec<u64> = art.children().unwrap()[0].children().unwrap().iter().map(|c| c.id.0).collect(); - assert_eq!(ids, [vec![id.0], copies].concat(), "{case}"); + assert_eq!(ids, [id.0], "{case}"); + let copies = art.children().unwrap(); + assert_eq!(copies.len(), 2, "{case}"); + let mut seen = std::collections::HashSet::new(); + let mut repeated = vec![]; + art.walk(&mut |n| { + if !seen.insert(n.id) { + repeated.push(n.id); + } + }); + assert!(repeated.is_empty(), "{case}: {repeated:?}"); } } } diff --git a/crates/engine/src/tests/eyedropper.rs b/crates/engine/src/tests/eyedropper.rs index f8363fe93f..b3a9012e06 100644 --- a/crates/engine/src/tests/eyedropper.rs +++ b/crates/engine/src/tests/eyedropper.rs @@ -215,6 +215,291 @@ fn type_picks_up_font_and_size() { assert_eq!((st.size, justify, st.fill.color().unwrap().to_hex()), (12.0, preserved_alignment, "#00ff00".into())); } +/// Sample document-space typography between text objects with different local transforms. +#[test] +fn scaled_type_pick_matches_effective_character_dimensions() { + for source_area in [false, true] { + for target_area in [false, true] { + let mut s = session(); + let create = |s: &mut Session, area: bool, x: f64| { + let mut p = json!({"x": x, "y": 100, "text": "Sample", "size": 12}); + if area { + p["area"] = json!({"width": 160, "height": 80}); + } + id_of(s.execute("text.create", &p).unwrap()) + }; + let src = create(&mut s, source_area, 100.0); + s.execute("object.transform", &json!({"matrix": [3, 0, 0, 2, 0, 0]})).unwrap(); + let dst = create(&mut s, target_area, 300.0); + s.execute("object.transform", &json!({"matrix": [0.5, 0, 0, 1.5, 0, 0]})).unwrap(); + let before = node(&s, dst); + let source = node(&s, src); + let history = undo_len(&s); + s.execute("appearance.copyFrom", &json!({"source": src.0})).unwrap(); + let after = node(&s, dst); + let NodeKind::Text(t) = &after.kind else { panic!("not text") }; + let NodeKind::Text(old) = &before.kind else { panic!("not text") }; + let effective = t.effective_char_style(&t.first_style()).unwrap(); + assert!((effective.size - 24.0).abs() < 1e-8, "sampled font size: {}", effective.size); + assert!((effective.h_scale - 150.0).abs() < 1e-8, "sampled horizontal scale: {}", effective.h_scale); + assert_eq!(t.xf, old.xf, "sampling keeps the target's transform"); + assert_eq!(node(&s, src), source); + assert_eq!(undo_len(&s), history + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(node(&s, dst), before); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(node(&s, dst), after); + } + } +} + +/// A text object snapshot, including the local attributes and retained affine transform. +fn sampled_type(s: &Session, id: NodeId) -> vectorcraft_doc::TextObject { + let NodeKind::Text(t) = node(s, id).kind else { panic!("not text") }; + *t +} + +/// Compare the dimensional character attributes that text controls display in document units. +fn assert_sampled_dimensions(actual: &vectorcraft_doc::CharStyle, expected: &vectorcraft_doc::CharStyle) { + assert_eq!(actual.leading.is_some(), expected.leading.is_some()); + for (a, e) in [ + (actual.size, expected.size), + (actual.h_scale, expected.h_scale), + (actual.v_scale, expected.v_scale), + (actual.leading.unwrap_or(0.0), expected.leading.unwrap_or(0.0)), + (actual.baseline_shift, expected.baseline_shift), + (actual.tcy_up_down, expected.tcy_up_down), + (actual.tcy_left_right, expected.tcy_left_right), + ] { + assert!((a - e).abs() < 1e-8, "sampled dimension: {a} != {e}"); + } +} + +/// Rotation, shear, reflection and grouping stay on the objects while typography is copied. +#[test] +fn scaled_type_pick_preserves_affines_and_document_dimensions() { + for grouped in [false, true] { + let mut s = session(); + let src = id_of(s.execute("text.create", &json!({"x": 100, "y": 100, "text": "Source", "size": 12})).unwrap()); + s.execute("text.setStyle", &json!({"leading": 18})).unwrap(); + s.execute("text.setFormat", &json!({"hScale": 80, "vScale": 125, "baselineShift": 3, "tcyUpDown": 2, "tcyLeftRight": -1})).unwrap(); + if grouped { + s.execute("object.group", &json!({})).unwrap(); + } + s.execute("object.transform", &json!({"matrix": [0, -3, -2, 1, 0, 0]})).unwrap(); + let src_text = sampled_type(&s, src); + let expected = src_text.effective_char_style(&src_text.first_style()).unwrap(); + let dst = id_of(s.execute("text.create", &json!({"x": 300, "y": 100, "text": "Target", "size": 20})).unwrap()); + if grouped { + s.execute("object.group", &json!({})).unwrap(); + } + s.execute("object.transform", &json!({"matrix": [-1, 0.5, 1, 2, 0, 0]})).unwrap(); + let before = sampled_type(&s, dst); + s.execute("appearance.copyFrom", &json!({"source": src.0})).unwrap(); + let after = sampled_type(&s, dst); + assert_sampled_dimensions(&after.effective_char_style(&after.first_style()).unwrap(), &expected); + assert_eq!(after.xf, before.xf); + assert_eq!(sampled_type(&s, src), src_text); + let bytes = vectorcraft_format::save_file(&s.doc().unwrap().doc); + let reopened = vectorcraft_format::load(&bytes).unwrap(); + let NodeKind::Text(t) = &reopened.node(dst).unwrap().kind else { panic!("not text") }; + assert_sampled_dimensions(&t.effective_char_style(&t.first_style()).unwrap(), &expected); + } +} + +/// A transformed target compensates only the highlighted characters, retaining the others. +#[test] +fn scaled_type_pick_changes_only_the_highlighted_range() { + let mut s = session(); + let src = id_of(s.execute("text.create", &json!({"x": 100, "y": 100, "text": "Source", "size": 12})).unwrap()); + s.execute("object.transform", &json!({"matrix": [3, 0, 0, 2, 0, 0]})).unwrap(); + let source = sampled_type(&s, src); + let expected = source.effective_char_style(&source.first_style()).unwrap(); + let dst = id_of(s.execute("text.create", &json!({"x": 300, "y": 100, "text": "Sample", "size": 10})).unwrap()); + s.execute("object.transform", &json!({"matrix": [0.5, 0, 0, 3, 0, 0]})).unwrap(); + let before = sampled_type(&s, dst); + s.select_tool("type", ViewInfo::default()).unwrap(); + s.set_tool_option("textSelection", &json!({"id": dst.0, "start": 1, "end": 4})); + s.select_tool("eyedropper", ViewInfo::default()).unwrap(); + let history = undo_len(&s); + s.execute("appearance.copyFrom", &json!({"source": src.0})).unwrap(); + let after = sampled_type(&s, dst); + assert_eq!(after.runs.len(), 3); + assert_eq!((&*after.runs[0].text, &*after.runs[1].text, &*after.runs[2].text), ("S", "amp", "le")); + assert_eq!(after.runs[0].style, before.first_style()); + assert_eq!(after.runs[2].style, before.first_style()); + assert_sampled_dimensions(&after.effective_char_style(&after.runs[1].style).unwrap(), &expected); + assert_eq!(after.xf, before.xf); + assert_eq!(undo_len(&s), history + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(sampled_type(&s, dst), before); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(sampled_type(&s, dst), after); +} + +/// Reject unusable source or target transforms before any part of a multi-object pick changes. +#[test] +fn scaled_type_pick_rejects_unrepresentable_dimensions_atomically() { + for (bad_source, factor) in [(true, 0.0), (false, 0.0), (false, 1e-306), (true, f64::from_bits(1))] { + let mut s = session(); + let size = if bad_source && factor > 0.0 { 0.1 } else { 24.0 }; + let src = id_of(s.execute("text.create", &json!({"x": 100, "y": 100, "text": "Source", "size": size, "color": "#00ff00"})).unwrap()); + if bad_source { + s.execute("object.transform", &json!({"matrix": [factor, 0, 0, factor, 0, 0]})).unwrap(); + } + let good = id_of(s.execute("text.create", &json!({"x": 300, "y": 100, "text": "Good", "size": 10})).unwrap()); + let other = id_of(s.execute("text.create", &json!({"x": 300, "y": 200, "text": "Other", "size": 12})).unwrap()); + if !bad_source { + s.execute("object.transform", &json!({"matrix": [factor, 0, 0, factor, 0, 0]})).unwrap(); + } + s.execute("select.set", &json!({"ids": [good.0, other.0]})).unwrap(); + let doc = s.doc().unwrap().doc.clone(); + let selection = s.doc().unwrap().selection.clone(); + let paint = s.paint.clone(); + let sample = s.eyedropper_sample.clone(); + let history = undo_len(&s); + let error = s.execute("appearance.copyFrom", &json!({"source": src.0})).unwrap_err(); + assert!(error.to_string().contains("transform"), "{error}"); + assert_eq!(s.doc().unwrap().doc, doc); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.paint, paint); + assert_eq!(s.eyedropper_sample, sample); + assert_eq!(undo_len(&s), history); + // A paint-only pick does not need a usable text transform. + s.execute("appearance.copyFrom", &json!({"source": src.0, "apply": {"character": false, "paragraph": false}})).unwrap(); + } +} + +/// A failed dimensional pick retains highlighted characters and the previously remembered sample. +#[test] +fn scaled_type_pick_rejection_preserves_the_highlighted_range_and_sample() { + let mut s = session(); + let saved = id_of(s.execute("text.create", &json!({"x": 100, "y": 100, "text": "Saved", "size": 18})).unwrap()); + s.execute("select.none", &json!({})).unwrap(); + s.execute("appearance.copyFrom", &json!({"source": saved.0})).unwrap(); + let src = id_of(s.execute("text.create", &json!({"x": 100, "y": 200, "text": "Source", "size": 24, "color": "#00ff00"})).unwrap()); + s.execute("object.transform", &json!({"matrix": [0, 0, 0, 0, 0, 0]})).unwrap(); + let dst = id_of(s.execute("text.create", &json!({"x": 300, "y": 100, "text": "Sample", "size": 10})).unwrap()); + s.select_tool("type", ViewInfo::default()).unwrap(); + s.set_tool_option("textSelection", &json!({"id": dst.0, "start": 1, "end": 4})); + s.select_tool("eyedropper", ViewInfo::default()).unwrap(); + let doc = s.doc().unwrap().doc.clone(); + let selection = s.doc().unwrap().selection.clone(); + let range = s.tool_options(); + let paint = s.paint.clone(); + let sample = s.eyedropper_sample.clone(); + let history = undo_len(&s); + assert!(s.execute("appearance.copyFrom", &json!({"source": src.0})).is_err()); + assert_eq!(s.doc().unwrap().doc, doc); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.tool_options(), range); + assert_eq!(s.paint, paint); + assert_eq!(s.eyedropper_sample, sample); + assert_eq!(undo_len(&s), history); + // Alt-click can still apply the last successful sample after the rejected pick. + s.execute("select.none", &json!({})).unwrap(); + s.execute("appearance.copyFrom", &json!({"source": dst.0, "reverse": true})).unwrap(); + assert_eq!(sampled_type(&s, dst).first_style().size, 18.0); +} + +/// A pick that would extend text beyond the canvas keeps the previous sample and defaults. +#[test] +fn scaled_type_pick_canvas_rejection_preserves_sample_and_defaults() { + for mode in ["selection", "ids", "reverse", "range"] { + let mut s = session(); + let saved = id_of(s.execute("text.create", &json!({"x": 40, "y": 40, "text": "Saved", "size": 18, "color": "#0000ff"})).unwrap()); + let src = id_of(s.execute("text.create", &json!({"x": 100, "y": 100, "text": "Source", "size": 96, "color": "#ff0000"})).unwrap()); + let dst = id_of(s.execute("text.create", &json!({"x": MAX_COORD - 100.0, "y": 200, "text": "WWWW", "size": 10})).unwrap()); + s.execute("appearance.copyFrom", &json!({"source": saved.0, "ids": []})).unwrap(); + let pick = match mode { + "ids" | "reverse" => { + s.execute("select.none", &json!({})).unwrap(); + if mode == "ids" { json!({"source": src.0, "ids": [dst.0]}) } else { json!({"source": dst.0, "ids": [src.0], "reverse": true}) } + } + "range" => { + s.select_tool("type", ViewInfo::default()).unwrap(); + s.set_tool_option("textSelection", &json!({"id": dst.0, "start": 0, "end": 3})); + s.select_tool("eyedropper", ViewInfo::default()).unwrap(); + json!({"source": src.0}) + } + _ => json!({"source": src.0}), + }; + let doc = s.doc().unwrap().doc.clone(); + let selection = s.doc().unwrap().selection.clone(); + let range = s.tool_options(); + let paint = s.paint.clone(); + let sample = s.eyedropper_sample.clone(); + let history = undo_len(&s); + + let error = s.execute("appearance.copyFrom", &pick).unwrap_err(); + assert!(error.to_string().contains("coordinates out of range"), "{mode}: {error}"); + assert_eq!(s.doc().unwrap().doc, doc, "{mode}"); + assert_eq!(s.doc().unwrap().selection, selection, "{mode}"); + assert_eq!(s.tool_options(), range, "{mode}"); + assert_eq!(s.paint, paint, "{mode}"); + assert_eq!(s.eyedropper_sample, sample, "{mode}"); + assert_eq!(undo_len(&s), history, "{mode}"); + } +} + +/// Changing justification can move explicitly targeted point text outside the canvas even +/// when character copying is disabled. +#[test] +fn paragraph_only_pick_rejects_out_of_bounds_explicit_target() { + let mut s = session(); + let saved = id_of(s.execute("text.create", &json!({"x": 40, "y": 40, "text": "Saved", "color": "#0000ff"})).unwrap()); + let src = id_of(s.execute("text.create", &json!({"x": 100, "y": 100, "text": "Source", "color": "#ff0000"})).unwrap()); + s.execute("text.setStyle", &json!({"justify": "left"})).unwrap(); + let dst = id_of(s.execute("text.create", &json!({"x": 100, "y": 200, "text": "WWWW", "size": 16})).unwrap()); + s.execute("text.setStyle", &json!({"justify": "right"})).unwrap(); + s.execute("object.transform", &json!({"matrix": [1, 0, 0, 1, MAX_COORD - 101.0, 0]})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.execute("appearance.copyFrom", &json!({"source": saved.0, "ids": []})).unwrap(); + let doc = s.doc().unwrap().doc.clone(); + let selection = s.doc().unwrap().selection.clone(); + let paint = s.paint.clone(); + let sample = s.eyedropper_sample.clone(); + let history = undo_len(&s); + + let pick = json!({"source": src.0, "ids": [dst.0], "apply": {"character": false}}); + let error = s.execute("appearance.copyFrom", &pick).unwrap_err(); + assert!(error.to_string().contains("coordinates out of range"), "{error}"); + assert_eq!(s.doc().unwrap().doc, doc); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.paint, paint); + assert_eq!(s.eyedropper_sample, sample); + assert_eq!(undo_len(&s), history); +} + +/// Disabled character copying and append preserve typography; reverse and cached picks convert it. +#[test] +fn scaled_type_pick_respects_options_and_reverse_sampling() { + let mut s = session(); + let src = id_of(s.execute("text.create", &json!({"x": 100, "y": 100, "text": "Source", "size": 12})).unwrap()); + s.execute("object.scale", &json!({"sx": 300, "sy": 200})).unwrap(); + let source = sampled_type(&s, src); + let expected = source.effective_char_style(&source.first_style()).unwrap(); + let dst = id_of(s.execute("text.create", &json!({"x": 300, "y": 100, "text": "Target", "size": 20})).unwrap()); + s.execute("object.scale", &json!({"sx": 50, "sy": 150})).unwrap(); + let before = sampled_type(&s, dst); + for options in [json!({"pickUp": {"character": false}}), json!({"apply": {"character": false}}), json!({"append": true})] { + let mut p = json!({"source": src.0, "ids": [dst.0]}); + p.as_object_mut().unwrap().extend(options.as_object().unwrap().clone()); + s.execute("appearance.copyFrom", &p).unwrap(); + assert_sampled_dimensions(&sampled_type(&s, dst).first_style(), &before.first_style()); + } + s.execute("select.set", &json!({"ids": [src.0]})).unwrap(); + s.execute("appearance.copyFrom", &json!({"source": dst.0, "reverse": true})).unwrap(); + let after = sampled_type(&s, dst); + assert_sampled_dimensions(&after.effective_char_style(&after.first_style()).unwrap(), &expected); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.execute("appearance.copyFrom", &json!({"source": src.0})).unwrap(); + s.execute("appearance.copyFrom", &json!({"source": dst.0, "reverse": true})).unwrap(); + let cached = sampled_type(&s, dst); + assert_sampled_dimensions(&cached.effective_char_style(&cached.first_style()).unwrap(), &expected); +} + #[test] fn alt_click_applies_the_selection_to_the_clicked_object() { let mut s = session(); diff --git a/crates/engine/src/tests/fileinfo.rs b/crates/engine/src/tests/fileinfo.rs index c37cbfe90d..4d86a84b3c 100644 --- a/crates/engine/src/tests/fileinfo.rs +++ b/crates/engine/src/tests/fileinfo.rs @@ -161,7 +161,8 @@ fn an_exported_pdf_opens_with_its_file_info() { assert_eq!(back["description"], "A poster\nfor the fair"); assert_eq!(back["keywords"], json!(["fair", "Poster", "print"])); assert!(back["created"].as_str().is_some_and(|c| c.ends_with('Z')), "the file's creation date: {}", back["created"]); - assert_eq!(back["title"], "poster.pdf", "the title stays the file name"); + assert_eq!(back["title"], "Poster", "File Info shows the title the PDF carries"); + assert_eq!(s.doc().unwrap().title(), "poster.pdf", "the document stays named after the file"); assert_eq!(back["copyrightStatus"], "copyrighted"); assert_eq!(back["copyrightNotice"], "(c) 2026 Ada"); assert_eq!(back["copyrightUrl"], "https://example.com/rights"); @@ -277,6 +278,192 @@ fn a_pdf_compatible_ai_opens_with_the_file_info_of_its_xmp_packet() { assert_eq!(m.copyright_url, ""); } +/// A one-page PDF whose trailer names an information dictionary with the entries `info`, and whose +/// catalog has a metadata stream holding an XMP `dc:title` of `xmp_title`. +fn pdf_titled(info: Option<&str>, xmp_title: Option<&str>) -> Vec<u8> { + use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf_with_catalog}; + let first = first_extra(1); + let mut objects = vec![]; + let mut catalog = String::new(); + if let Some(t) = xmp_title { + let xmp = format!( + "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\"><rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\ + <rdf:Description rdf:about=\"\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\ + <dc:title><rdf:Alt><rdf:li xml:lang=\"de\">Zugangswege</rdf:li><rdf:li xml:lang=\"x-default\">{t}</rdf:li></rdf:Alt></dc:title>\ + </rdf:Description></rdf:RDF></x:xmpmeta>" + ); + objects.push(format!("<< /Type /Metadata /Subtype /XML /Length {} >>\nstream\n{xmp}\nendstream", xmp.len())); + catalog = format!("/Metadata {first} 0 R "); + } + let info_at = first + objects.len(); + if let Some(i) = info { + objects.push(format!("<< {i} >>")); + } + let refs: Vec<&str> = objects.iter().map(String::as_str).collect(); + let bytes = pdf_with_catalog(&[PdfPage::new(100.0, 100.0, "0 0 1 rg 10 10 50 50 re f")], &refs, &catalog, None); + if info.is_none() { + return bytes; + } + // The trailer follows the cross-reference table, so a longer trailer moves no object. + String::from_utf8(bytes).unwrap().replacen("/Root 1 0 R", &format!("/Root 1 0 R /Info {info_at} 0 R"), 1).into_bytes() +} + +/// A document called `name` with content `bytes` opened (as `document.open` with no path: the tab +/// shows the document's name), `s` holding it. +fn open_named(s: &mut Session, name: &str, bytes: &[u8]) -> Value { + s.execute("document.open", &json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(bytes)})).unwrap() +} + +/// The document's name (its tab) and its File Info title. +fn titles(s: &mut Session) -> [String; 2] { + let info = s.execute("file.info", &json!({})).unwrap(); + [s.doc().unwrap().title(), info["title"].as_str().unwrap().to_string()] +} + +/// What opening `bytes` as a file called `name` gives: the document's name and its File Info title. +fn opened(name: &str, bytes: &[u8]) -> [String; 2] { + let mut s = Session::new(); + let r = open_named(&mut s, name, bytes); + let t = titles(&mut s); + assert_eq!((r["title"].as_str(), r["fileInfoTitle"].as_str()), (Some(t[0].as_str()), Some(t[1].as_str())), "the open reply"); + assert_eq!(s.doc().unwrap().doc.title, t[0], "the tab is the document's title"); + t +} + +fn svg_titled(inner: &str) -> String { + format!( + "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"20\" height=\"20\">{inner}<rect width=\"5\" height=\"5\"><title>Tooltip" + ) +} + +#[test] +fn import_puts_the_files_own_title_in_file_info_only() { + // SVG: the root's ``, its white space made single spaces (not a shape's tooltip), is the + // File Info title; the document keeps the file's name, with its extension. + assert_eq!(opened("box.svg", svg_titled("<title>\n Access\n paths ").as_bytes()), ["box.svg", "Access paths"]); + assert_eq!( + opened("/work/box.svg", svg_titled("Zugangswege Rechenzentrum – Prüfdiagramm").as_bytes()), + ["box.svg", "Zugangswege Rechenzentrum – Prüfdiagramm"] + ); + // PDF: the XMP `dc:title` (its `x-default` item) beats the Info `Title`; the Info `Title` stands alone. + assert_eq!(opened("plan.pdf", &pdf_titled(Some("/Title (Info title)"), Some("XMP title"))), ["plan.pdf", "XMP title"]); + assert_eq!(opened("plan.pdf", &pdf_titled(None, Some("XMP title"))), ["plan.pdf", "XMP title"]); + assert_eq!(opened("plan.pdf", &pdf_titled(Some("/Title (Info title)"), None)), ["plan.pdf", "Info title"]); + assert_eq!(opened("plan.ai", &pdf_titled(Some("/Title (Info title)"), None)), ["plan.ai", "Info title"]); + // Compressed SVG too. + let svgz = |inner: &str| vectorcraft_svg::compress(&svg_titled(inner)); + assert_eq!(opened("box.svgz", &svgz("Access paths")), ["box.svgz", "Access paths"]); + // A file that gives none (or a blank one) gives File Info the document's name. + assert_eq!(opened("box.svg", svg_titled("").as_bytes()), ["box.svg", "box.svg"]); + assert_eq!(opened("box.svg", svg_titled(" ").as_bytes()), ["box.svg", "box.svg"]); + assert_eq!(opened("plan.pdf", &pdf_titled(None, None)), ["plan.pdf", "plan.pdf"]); + assert_eq!(opened("plan.pdf", &pdf_titled(Some("/Author (Ada)"), None)), ["plan.pdf", "plan.pdf"]); + // The Untitled-N name New gives is no title (a document that never had one writes it). + assert_eq!(opened("plan.pdf", &pdf_titled(Some("/Title (Untitled-2)"), None)), ["plan.pdf", "plan.pdf"]); + // A template opens as a new untitled document, whatever title its file gave. + let [name, info] = opened("plan.ait", &pdf_titled(Some("/Title (Info title)"), None)); + assert!(name.starts_with("Untitled-") && info == name, "{name} / {info}"); +} + +#[test] +fn imported_svg_titles_are_filtered_and_bounded() { + for (raw, expected) in [ + ("Untitled-2".to_string(), None), + ("\u{7f}".to_string(), None), + ("Re\u{7f}lease Plan".to_string(), Some("Release Plan".to_string())), + ("λ".repeat(65_537), Some("λ".repeat(65_536))), + ] { + let svg = svg_titled(&format!("{raw}")); + for format in ["svg", "svgz"] { + let name = format!("box.{format}"); + let bytes = if format == "svgz" { vectorcraft_svg::compress(&svg) } else { svg.as_bytes().to_vec() }; + assert_eq!(opened(&name, &bytes), [name.clone(), expected.clone().unwrap_or(name)], "{format}"); + } + } +} + +#[test] +fn a_file_with_a_title_opened_from_a_path_is_named_after_the_file() { + let dir = std::env::temp_dir().join(format!("vc-infotitle-open-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("box.svg"); + std::fs::write(&path, svg_titled("Access paths")).unwrap(); + let mut s = Session::new(); + let r = s.execute("document.open", &json!({"path": path.to_str().unwrap()})).unwrap(); + assert_eq!((r["title"].as_str(), r["fileInfoTitle"].as_str()), (Some("box.svg"), Some("Access paths"))); + let r = s.execute("document.inspect", &json!({"depth": 0})).unwrap(); + assert_eq!((r["title"].as_str(), r["fileInfoTitle"].as_str()), (Some("box.svg"), Some("Access paths"))); + // The default names of what the document exports are made from the file's name, not its title. + assert_eq!(s.doc().unwrap().doc.title, "box.svg"); + assert_eq!(crate::cmd::fileio::default_name(&s.doc().unwrap().doc, "png"), "box.png"); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn file_info_edits_a_files_own_title_and_the_document_follows() { + let mut s = Session::new(); + open_named(&mut s, "box.svg", svg_titled("Access paths").as_bytes()); + // The dialog sends back the title it was given: nothing changes (no undo step). + let before = s.doc().unwrap().revision; + let shown = s.execute("file.info", &json!({})).unwrap(); + s.execute("file.info", &shown).unwrap(); + assert_eq!(s.doc().unwrap().revision, before, "the title it gave is no edit"); + assert_eq!(titles(&mut s), ["box.svg", "Access paths"]); + // Another title is the document's own, as ever, and the file's is gone. + let r = s.execute("file.info", &json!({"title": "Plan B"})).unwrap(); + assert_eq!(r["title"], "Plan B"); + assert_eq!(titles(&mut s), ["Plan B", "Plan B"]); + assert_eq!(s.doc().unwrap().doc.metadata.title, None); + // Undo brings the file's title back, and the name. + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(titles(&mut s), ["box.svg", "Access paths"]); +} + +#[test] +fn restored_file_info_title_keeps_authored_spaces() { + let mut s = session(); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).metadata.title = Some("Release Plan".into()); + for format in ["vectorcraft", "svg", "pdf"] { + let bytes = b64(&s.execute("document.export", &json!({"format": format, "preserveEditing": true})).unwrap()); + let mut reopened = Session::new(); + let reply = open_named(&mut reopened, &format!("again.{format}"), &bytes); + assert_eq!(reply["restored"], format != "vectorcraft", "{format}"); + assert_eq!(reopened.doc().unwrap().doc.metadata.title.as_deref(), Some("Release Plan"), "{format}"); + assert_eq!(titles(&mut reopened)[1], "Release Plan", "{format}"); + } +} + +#[test] +fn the_files_own_title_is_kept_by_saves_and_written_by_exports() { + let mut s = Session::new(); + open_named(&mut s, "box.svg", svg_titled("Access paths").as_bytes()); + // The native file: its own title is the document's name, the File Info title survives. + let native = b64(&s.execute("document.export", &json!({"format": "vectorcraft"})).unwrap()); + let mut t = Session::new(); + open_named(&mut t, "other.vectorcraft", &native); + assert_eq!(titles(&mut t), ["box.svg", "Access paths"]); + // An SVG with the editing data it carries, reopened under another name. + let svg = s.execute("document.serialize", &json!({"format": "svg", "preserveEditing": true, "metadata": true})).unwrap()["text"] + .as_str() + .unwrap() + .to_string(); + assert!(svg.contains("Access paths") && svg.contains("Access paths"), "{svg}"); + let mut u = Session::new(); + let r = open_named(&mut u, "again.svg", svg.as_bytes()); + assert_eq!(r["restored"], true); + assert_eq!(titles(&mut u), ["again.svg", "Access paths"]); + // PDF: the Info `Title` and the XMP `dc:title`, shown by the viewer. + for pdf in pdf_texts(&mut s) { + assert!(pdf.contains("/Title(Access paths)") && xmp_title(&pdf).contains("Access paths"), "{}", xmp_title(&pdf)); + assert!(pdf.contains("/ViewerPreferences<>"), "{pdf}"); + } + // PNG text. + let png = b64(&s.execute("document.export", &json!({"format": "png"})).unwrap()); + assert!(crate::cmd::fileio::pngtext::text(&png).iter().any(|(k, v)| k == "Title" && v == "Access paths")); + // The default file names are made from the document's name. + assert_eq!(crate::cmd::fileio::default_name(&s.doc().unwrap().doc, "pdf"), "box.pdf"); +} + #[test] fn png_exports_carry_text_chunks() { let mut s = session(); diff --git a/crates/engine/src/tests/flatten.rs b/crates/engine/src/tests/flatten.rs index 84e4724fe6..042f741e0e 100644 --- a/crates/engine/src/tests/flatten.rs +++ b/crates/engine/src/tests/flatten.rs @@ -450,6 +450,54 @@ fn objects_without_transparency_stay_unless_outlined() { } } +/// A row of opaque rectangles 1.5 pt apart (closer than twice the antialiasing margin), with a +/// see-through one touching each end: only the two next to a see-through one are flattened, and +/// the document looks the same. +#[test] +fn opaque_art_that_touches_only_opaque_art_stays() { + let _settings = settings_lock(); + let mut s = session(); + let under = rect(&mut s, 0.0, 50.0, 10.0, 10.0, "#2060c0"); + run(&mut s, "transparency.set", json!({"ids": [under], "opacity": 50})); + let row: Vec = (1..15).map(|i| rect(&mut s, 11.5 * f64::from(i), 50.0, 10.0, 10.0, "#e04010")).collect(); + let over = rect(&mut s, 11.5 * 15.0, 50.0, 10.0, 10.0, "#20a040"); + run(&mut s, "transparency.set", json!({"ids": [over], "opacity": 50, "blend": "Multiply"})); + let before = picture(&s); + run(&mut s, "select.all", json!({})); + let (ids, vector, rasterized) = flatten(&mut s, json!({})); + assert_eq!((vector, rasterized), (4, 0), "two groups of two regions each"); + let (ends, kept) = (row[0], row.last().copied().unwrap()); + assert!(!exists(&s, under) && !exists(&s, over) && !exists(&s, ends) && !exists(&s, kept)); + assert!(row[1..row.len() - 1].iter().all(|id| exists(&s, *id) && ids.contains(id)), "the rest of the row stays"); + assert_eq!(ids.len(), row.len() - 2 + 2); + let diff = changed(&before, &picture(&s)); + assert!(diff == 0.0, "{:.2}% of the pixels changed", diff * 100.0); +} + +/// Opaque art between a see-through object's group and the top of that group, painting over a +/// member, joins the group (along a chain too), so it still paints over it; opaque art under the +/// group stays. +#[test] +fn opaque_art_the_group_would_move_under_joins_it() { + let _settings = settings_lock(); + let mut s = session(); + let d = rect(&mut s, 40.0, 80.0, 25.0, 40.0, "#f0d000"); + let a = rect(&mut s, 60.0, 50.0, 45.0, 40.0, "#e01010"); + let b = rect(&mut s, 20.0, 20.0, 45.0, 35.0, "#10a010"); + let c = rect(&mut s, 0.0, 0.0, 25.0, 25.0, "#1010e0"); + let t = rect(&mut s, 100.0, 50.0, 40.0, 40.0, "#000000"); + run(&mut s, "transparency.set", json!({"ids": [t], "opacity": 50})); + let before = picture(&s); + let (ids, ..) = flatten(&mut s, json!({"ids": [d, a, b, c, t]})); + assert!(exists(&s, d) && ids.contains(&d), "the art under the group stays"); + assert!([a, b, c, t].iter().all(|id| !exists(&s, *id)), "the others are flattened together"); + // Where B paints over A, and C over B, they still do. + for p in [Point::new(62.5, 52.5), Point::new(22.5, 22.5), Point::new(62.5, 85.5), Point::new(102.5, 70.5)] { + assert_eq!(pixel(&picture(&s), p), pixel(&before, p), "at {p:?}"); + } + assert!(changed(&before, &picture(&s)) == 0.0); +} + #[test] fn outlined_type_keeps_its_underline() { let _settings = settings_lock(); diff --git a/crates/engine/src/tests/fontfiles.rs b/crates/engine/src/tests/fontfiles.rs index f31df35eb1..52a8ff08a3 100644 --- a/crates/engine/src/tests/fontfiles.rs +++ b/crates/engine/src/tests/fontfiles.rs @@ -14,12 +14,12 @@ use crate::cmd::findfiles::{self, Limits, Rules, Visitor}; use crate::cmd::fontfiles::{self, FontSearch, MAX_FONT_FILE, Sought, copy_into}; use crate::{EngineError, Session}; -/// A fresh temporary folder (canonical, as a search reports it). -fn folder(tag: &str) -> PathBuf { - let dir = vectorcraft_testkit::temp_dir(&format!("fontfiles-{tag}")); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - findfiles::plain(std::fs::canonicalize(&dir).unwrap()) +/// A fresh temporary folder, removed when the first part is dropped, and its path (canonical, as a +/// search reports it). +fn folder(tag: &str) -> (vectorcraft_testkit::TempDir, PathBuf) { + let dir = vectorcraft_testkit::TempDir::new(&format!("fontfiles-{tag}")); + let path = findfiles::plain(std::fs::canonicalize(&*dir).unwrap()); + (dir, path) } /// A session whose folder searches may go anywhere in `root`, on two threads. @@ -103,7 +103,7 @@ fn missing_fonts_are_listed_symbols_included() { /// listed finds the other fonts' files. #[test] fn an_overlong_font_name_leaves_the_other_fonts_searchable() { - let root = folder("long-name"); + let (_dir, root) = folder("long-name"); std::fs::write(root.join("Findme.otf"), vectorcraft_testkit::fonts::renamed("Findme Sans 3")).unwrap(); let mut s = session_for(&root); s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap(); @@ -120,7 +120,7 @@ fn an_overlong_font_name_leaves_the_other_fonts_searchable() { /// apps' folders, such as the attachments a mail app keeps in the home folder's Library. #[test] fn the_fonts_folder_next_to_a_document_in_another_apps_folder_isnt_offered() { - let root = folder("next-to"); + let (_dir, root) = folder("next-to"); let home = root.join("Users/me"); let mut s = Session::new(); s.search_rules = Some(Rules { home: Some(home.clone()), ..Rules::default() }); @@ -140,7 +140,7 @@ fn the_fonts_folder_next_to_a_document_in_another_apps_folder_isnt_offered() { #[cfg(unix)] #[test] fn the_fonts_folder_next_to_a_document_is_an_absolute_path() { - let root = folder("relative"); + let (_dir, root) = folder("relative"); std::fs::create_dir_all(root.join("pkg/Fonts")).unwrap(); let cwd = std::env::current_dir().unwrap(); let up = "../".repeat(cwd.components().count().saturating_sub(1)); @@ -160,7 +160,7 @@ fn the_fonts_folder_next_to_a_document_is_an_absolute_path() { #[test] fn a_search_finds_a_missing_fonts_file_by_its_names() { - let root = folder("find"); + let (_dir, root) = folder("find"); std::fs::create_dir_all(root.join("x/y")).unwrap(); std::fs::write(root.join("x/y/Findme.otf"), vectorcraft_testkit::fonts::renamed("Findme Sans 3")).unwrap(); std::fs::write(root.join("other.ttf"), bundled("SourceSerif4-Regular.ttf")).unwrap(); @@ -194,9 +194,45 @@ fn a_search_finds_a_missing_fonts_file_by_its_names() { assert!(matches!(r["state"].as_str(), Some("stopped" | "done")), "{r}"); } +/// A caller confined by read roots sees, in the replies to a search another caller started, only +/// the files found inside its read roots, and the folder searched and a failed search's path only +/// when they are inside them. +#[test] +fn a_search_shows_a_confined_caller_only_paths_inside_its_read_roots() { + let (_dir, root) = folder("read-roots"); + let font = vectorcraft_testkit::fonts::renamed("Findme Sans 3"); + let (home, wide) = (root.join("home"), root.join("lrf-wide")); + for dir in [&home, &wide] { + std::fs::create_dir_all(dir).unwrap(); + std::fs::write(dir.join("Findme.otf"), &font).unwrap(); + } + let mut s = session_for(&root); + let roots = |read: &[&Path]| crate::file_access::AutomationRoots::new(read, &[]).unwrap().unwrap(); + let (narrow, broad) = (roots(&[&home]), roots(&[&root])); + let ask = |s: &mut Session, r: &Arc, p: Value| { + crate::file_access::confine(Some(r), || s.execute("text.findFontFiles", &p).unwrap()) + }; + // A font no file has keeps the search going through every folder. + let fonts = json!([{"family": "Findme Sans 3"}, {"family": "No Such Sans"}]); + ask(&mut s, &broad, json!({"folder": root, "fonts": fonts})); + finished(&mut s); + let all = ask(&mut s, &broad, json!({})); + assert_eq!((&all["fonts"][0]["files"], &all["folder"]), (&json!([home.join("Findme.otf"), wide.join("Findme.otf")]), &json!(root)), "{all}"); + for r in [ask(&mut s, &narrow, json!({})), ask(&mut s, &narrow, json!({"stop": true}))] { + assert!(!r.to_string().contains("lrf-wide") && r.get("folder").is_none(), "{r}"); + assert_eq!((&r["fonts"][0]["files"], &r["fonts"][0]["family"]), (&json!([home.join("Findme.otf")]), &json!("Findme Sans 3")), "{r}"); + assert_eq!((&r["state"], &r["searched"], &r["id"]), (&all["state"], &all["searched"], &all["id"]), "{r}"); + } + // A search that failed: the reason shows without the path to a caller outside its folder. + ask(&mut s, &broad, json!({"folder": wide.join("gone"), "fonts": fonts})); + assert!(finished(&mut s)["error"].as_str().is_some_and(|e| e.contains("lrf-wide"))); + let r = ask(&mut s, &narrow, json!({})); + assert_eq!((r["state"].as_str(), r["error"].as_str(), r.get("folder")), (Some("failed"), Some("the folder can't be read"), None), "{r}"); +} + #[test] fn junk_search_params_never_fail_internally() { - let root = folder("junk"); + let (_dir, root) = folder("junk"); let mut s = session_for(&root); s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap(); text(&mut s, 20.0, "No Such Font Family", "Regular"); @@ -260,7 +296,7 @@ impl Visitor for Blocked { #[test] fn stop_ends_only_the_search_it_names() { - let root = folder("stop"); + let (_dir, root) = folder("stop"); std::fs::write(root.join("a.ttf"), b"font").unwrap(); let mut s = session_for(&root); let (tx, rx) = mpsc::channel(); @@ -293,7 +329,7 @@ fn adding_fonts_needs_vectorcraft_s_fonts_folder() { #[test] fn copying_never_replaces_a_file() { - let root = folder("copy"); + let (_dir, root) = folder("copy"); let (src, dest) = (root.join("src"), root.join("dest")); std::fs::create_dir_all(&src).unwrap(); std::fs::create_dir_all(&dest).unwrap(); @@ -339,12 +375,11 @@ fn copying_never_replaces_a_file() { assert_eq!(reasons[..2], ["larger than 256 MB", "not a file"]); assert!(r.copied.is_empty() && reasons.len() == 3, "{r:?}"); assert!(!dest.join("huge.otf").exists() && !dest.join("folder.otf").exists()); - let _ = std::fs::remove_dir_all(&root); } #[test] fn only_font_files_are_copied() { - let root = folder("allowed"); + let (_dir, root) = folder("allowed"); let (src, dest) = (root.join("src"), root.join("dest")); std::fs::create_dir_all(&src).unwrap(); std::fs::create_dir_all(&dest).unwrap(); @@ -358,13 +393,12 @@ fn only_font_files_are_copied() { let not_a_font = |n: &str| (src.join(n), "not a font file".to_string()); assert_eq!(r.skipped, [not_a_font("notes.txt"), not_a_font("Script")]); assert!(!dest.join("notes.txt").exists() && !dest.join("Script").exists()); - let _ = std::fs::remove_dir_all(&root); } /// A search reads no font file larger than Add Fonts copies, and finds a smaller copy of the font. #[test] fn a_search_skips_font_files_too_large_to_add() { - let root = folder("too-large"); + let (_dir, root) = folder("too-large"); let (big, small) = (root.join("big").join("Sizeme.otf"), root.join("small").join("Sizeme.otf")); let font = vectorcraft_testkit::fonts::renamed("Sizeme Sans 3"); for path in [&big, &small] { @@ -378,7 +412,6 @@ fn a_search_skips_font_files_too_large_to_add() { s.execute("text.findFontFiles", &json!({"folder": root, "fonts": [{"family": "Sizeme Sans 3"}, {"family": "No Such Sans"}]})).unwrap(); let r = finished(&mut s); assert_eq!(r["fonts"][0]["files"], json!([small]), "{r}"); - let _ = std::fs::remove_dir_all(&root); } /// A suitcase font: a file without an extension or with `.suit`, empty but for the fonts in its @@ -387,7 +420,7 @@ fn a_search_skips_font_files_too_large_to_add() { #[test] fn suitcase_fonts_are_found_and_copied_with_their_fork() { use vectorcraft_testkit::fonts::{renamed, suitcase_fork}; - let root = folder("suitcase"); + let (_dir, root) = folder("suitcase"); let (src, dest) = (root.join("src"), root.join("dest")); std::fs::create_dir_all(src.join("sub")).unwrap(); std::fs::create_dir_all(&dest).unwrap(); @@ -430,5 +463,4 @@ fn suitcase_fonts_are_found_and_copied_with_their_fork() { // The font scan reads the copies. let db = vectorcraft_text::FontDb::with_font_dirs(vec![dest.clone()]); assert_eq!((db.styles("Suitme Sans 3"), db.styles("Other Sans 33")), (vec!["Regular".to_string()], vec!["Regular".to_string()])); - let _ = std::fs::remove_dir_all(&root); } diff --git a/crates/engine/src/tests/globaledit.rs b/crates/engine/src/tests/globaledit.rs index 60bf81a060..ac5a494dc7 100644 --- a/crates/engine/src/tests/globaledit.rs +++ b/crates/engine/src/tests/globaledit.rs @@ -92,7 +92,50 @@ fn start_global_edit_takes_the_objects_of_the_same_shape_at_any_place_and_size() assert_eq!(crate::cmd::globaledit::highlights(&s).len(), 2); let r = s.execute("select.globalEdit", &json!({})).unwrap(); assert_eq!(r["active"], false, "the second run is Stop Global Edit"); - assert!(s.doc().unwrap().global_edit.is_none() && crate::cmd::globaledit::highlights(&s).is_empty()); + assert!(s.doc().unwrap().global_edit.is_none()); + assert_eq!(crate::cmd::globaledit::highlights(&s).len(), 2, "with the square still selected, the objects it would take are highlighted again"); +} + +#[test] +fn selecting_one_object_highlights_the_similar_objects_before_global_edit_starts() { + use crate::cmd::globaledit::highlights; + let mut s = session(); + let [a, b, _, wide, _] = squares(&mut s); + assert!(highlights(&s).is_empty(), "nothing selected"); + sel(&mut s, &[a]); + assert_eq!(members(&s), None, "Global Edit has not started"); + assert_eq!(highlights(&s).len(), 2, "the copy and the smaller square"); + s.execute("select.globalEditOptions", &json!({"size": true})).unwrap(); + assert_eq!(highlights(&s).len(), 1, "the options narrow them: the copy only"); + s.execute("select.globalEditOptions", &json!({"size": false})).unwrap(); + assert_eq!(highlights(&s).len(), 2); + sel(&mut s, &[b]); + s.execute("edit.clear", &json!({})).unwrap(); + sel(&mut s, &[a]); + assert_eq!(highlights(&s).len(), 1, "a deleted copy is no longer highlighted"); + sel(&mut s, &[wide]); + assert!(highlights(&s).is_empty(), "the rectangle has no similar object"); + sel(&mut s, &[a, wide]); + assert!(highlights(&s).is_empty(), "two objects selected"); +} + +#[test] +fn the_canvas_highlights_similar_objects_before_the_start_with_the_selection_tool_only() { + let mut s = session(); + let [a, b, ..] = squares(&mut s); + let outline = node(&s, b).stroke_path().unwrap(); + let shown = |s: &mut Session| { + s.overlays(ViewInfo::default()) + .iter() + .any(|o| matches!(o, vectorcraft_tools::Overlay::Path { path, width, .. } if *path == outline && *width == 1.0)) + }; + sel(&mut s, &[a]); + s.select_tool("selection", ViewInfo::default()).unwrap(); + assert!(shown(&mut s), "the copy is highlighted with the Selection tool"); + s.select_tool("directSelection", ViewInfo::default()).unwrap(); + assert!(!shown(&mut s), "not with another tool before Global Edit starts"); + s.execute("select.globalEdit", &json!({})).unwrap(); + assert!(shown(&mut s), "while Global Edit is on, with any tool"); } #[test] @@ -506,6 +549,7 @@ fn leaving_out_all_but_one_ends_global_edit_and_the_first_object_stays() { let r = s.execute("select.globalEditExclude", &json!({"id": b.0})).unwrap(); assert_eq!(r, json!({"active": false, "count": 0, "ids": []})); assert_eq!(members(&s), None, "one object left: Global Edit ends"); + sel(&mut s, &[wide]); assert!(crate::cmd::globaledit::highlights(&s).is_empty()); } diff --git a/crates/engine/src/tests/gradient.rs b/crates/engine/src/tests/gradient.rs index a3f7a2ae6e..b8c8bcd325 100644 --- a/crates/engine/src/tests/gradient.rs +++ b/crates/engine/src/tests/gradient.rs @@ -32,7 +32,7 @@ fn fill_gradient(s: &Session, id: NodeId) -> GradientPaint { #[test] fn new_gradient_defaults_follow_the_cmyk_document_mode() { - for kind in ["linear", "radial", "conic", "freeform"] { + for kind in ["linear", "radial", "conic", "diamond", "freeform"] { let mut s = Session::new(); s.execute("file.new", &json!({"width":200,"height":200,"colorMode":"cmyk"})).unwrap(); let id = rect(&mut s, 10.0, 10.0, 100.0, 100.0); @@ -511,7 +511,7 @@ fn an_outlined_stroke_leaves_dither_behind() { /// The Gradient panel's Method (Illustrator 30): `method` set and cleared through the gradient /// commands, on fills and strokes, kept by the params, swatches and a native save and load; -/// anything but classic or perceptual is refused without editing. +/// anything but the four method names is refused without editing. #[test] fn method_is_a_gradient_option_that_saves_and_loads() { use vectorcraft_color::GradientMethod; @@ -548,7 +548,7 @@ fn method_is_a_gradient_option_that_saves_and_loads() { let before = node(&s, id).appearance.clone(); for bad in [json!("smooth"), json!(1), json!(true)] { let e = s.execute("paint.editGradient", &json!({"method": bad})).unwrap_err().to_string(); - assert!(e.contains("`method` must be classic or perceptual"), "{e}"); + assert!(e.contains("`method` must be classic, perceptual, hue-clockwise or hue-counterclockwise"), "{e}"); assert!(s.execute("paint.setFill", &json!({"gradient": {"method": bad}})).is_err()); } assert_eq!(node(&s, id).appearance, before); @@ -566,6 +566,76 @@ fn method_is_a_gradient_option_that_saves_and_loads() { assert!(back.gradient.dither && back.gradient.method == GradientMethod::Perceptual); } +/// The hue methods: `method` hue-clockwise and hue-counterclockwise set through the gradient +/// commands on fills and strokes, as one undo step, kept by the params, a swatch, a saved preset +/// and a native save and load, and written with or without the hyphen. +#[test] +fn the_hue_methods_are_set_saved_and_loaded() { + use vectorcraft_color::GradientMethod; + let mut s = session(); + let id = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let stops = json!([{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]); + s.execute("paint.setFill", &json!({"gradient": {"stops": stops}})).unwrap(); + for (name, method, middle) in + [("hue-clockwise", GradientMethod::HueClockwise, "#ff00ff"), ("hue-counterclockwise", GradientMethod::HueCounterclockwise, "#00ff00")] + { + let undo = s.doc().unwrap().history.undo.len(); + s.execute("paint.editGradient", &json!({"method": name})).unwrap(); + let g = fill_gradient(&s, id); + assert_eq!(g.gradient.method, method); + assert_eq!(g.gradient.stops.len(), 2, "{name}: the stops stay as they were"); + assert_eq!(g.gradient.sample(0.5).0.to_hex(), middle, "{name}: halfway around the wheel"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "{name}: one undo step"); + // The params carry it, so a swatch, a preset and a copied paint keep it. + let p = vectorcraft_tools::params::gradient_params(&g); + assert_eq!(p["method"], json!(name)); + let mut q = gradient_param(&g); + q["name"] = json!(format!("Wheel {name}")); + s.execute("swatch.new", &q).unwrap(); + let Some(Paint::Gradient(sw)) = s.doc().unwrap().doc.swatch(&format!("Wheel {name}")).map(|w| w.paint.clone()) else { + panic!("a gradient swatch") + }; + assert_eq!(sw.gradient.method, method, "{name}: the swatch"); + s.execute("gradient.presets.save", &json!({"name": format!("Preset {name}")})).unwrap(); + s.execute("paint.editGradient", &json!({"method": "classic"})).unwrap(); + s.execute("gradient.presets.apply", &json!({"name": format!("Preset {name}")})).unwrap(); + assert_eq!(fill_gradient(&s, id).gradient.method, method, "{name}: the preset"); + // Saved and opened again. + let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + let Paint::Gradient(saved) = back.node(id).unwrap().appearance.fill_paint() else { panic!("a gradient fill") }; + assert_eq!(saved.gradient.method, method, "{name}: the native file keeps the method"); + } + // Strokes take it too, and the name reads without the hyphen and in any case. + for (name, method) in [("hue-clockwise", GradientMethod::HueClockwise), ("hue-counterclockwise", GradientMethod::HueCounterclockwise)] { + for written in [name.replace('-', " "), name.replace('-', "").to_uppercase()] { + s.execute("paint.setStroke", &json!({"gradient": {"method": "classic"}})).unwrap(); + s.execute("paint.editGradient", &json!({"method": written, "stroke": true})).unwrap(); + let Paint::Gradient(st) = node(&s, id).appearance.stroke_paint() else { panic!("a gradient stroke") }; + assert_eq!(st.gradient.method, method, "{written}"); + } + } + // Reverse gives the same ramp the other way round: the hue method turns with the stops, so + // the middle keeps its color, unless the edit names a method too. + s.execute("paint.editGradient", &json!({"method": "hue-clockwise", "stroke": false})).unwrap(); + let before = fill_gradient(&s, id).gradient; + s.execute("paint.editGradient", &json!({"reverse": true, "stroke": false})).unwrap(); + let after = fill_gradient(&s, id).gradient; + assert_eq!(after.method, GradientMethod::HueCounterclockwise); + assert_eq!((after.stops[0].color.to_hex(), after.stops[1].color.to_hex()), ("#0000ff".to_string(), "#ff0000".to_string())); + for t in [0.25, 0.5, 0.75] { + assert_eq!(after.sample(t).0.to_hex(), before.sample(1.0 - t).0.to_hex(), "reversed at {t}"); + } + s.execute("paint.editGradient", &json!({"reverse": true, "method": "hue-counterclockwise", "stroke": false})).unwrap(); + assert_eq!(fill_gradient(&s, id).gradient.method, GradientMethod::HueCounterclockwise, "a method in the edit wins"); + // Half a name is refused, nothing changed. + let before = node(&s, id).appearance.clone(); + for bad in ["hue", "clockwise", "hue-clock"] { + let e = s.execute("paint.editGradient", &json!({"method": bad})).unwrap_err().to_string(); + assert!(e.contains("`method` must be classic, perceptual, hue-clockwise or hue-counterclockwise"), "{bad}: {e}"); + } + assert_eq!(node(&s, id).appearance, before); +} + /// A conic gradient through `paint.setFill`, the Gradient panel's edits, transforms, the params /// agents and swatches read, and the native format. #[test] @@ -586,7 +656,7 @@ fn a_conic_gradient_is_set_edited_transformed_and_saved() { assert_eq!(fill_gradient(&s, id).gradient.kind, GradientKind::Conic, "{name}"); } let e = s.execute("paint.editGradient", &json!({"kind": "spiral"})).unwrap_err().to_string(); - assert!(e.contains("(linear, radial, conic, freeform)"), "{e}"); + assert!(e.contains("(linear, radial, conic, diamond, freeform)"), "{e}"); // Placed, an angle turns the vector about the center. s.execute("paint.setGradientGeom", &json!({"start": [200, 150], "end": [260, 150], "aspect": 50})).unwrap(); s.execute("paint.editGradient", &json!({"angle": 90})).unwrap(); @@ -747,3 +817,268 @@ fn making_a_gradient_conic_is_one_undo_step() { s.execute("edit.undo", &json!({})).unwrap(); assert_eq!(fill_gradient(&s, id), before); } + +/// A diamond gradient through `paint.setFill`, the Gradient panel's edits, transforms, the params +/// agents and swatches read, and the native format. +#[test] +fn a_diamond_gradient_is_set_edited_transformed_and_saved() { + let mut s = session(); + let id = rect(&mut s, 100.0, 100.0, 200.0, 100.0); + s.execute("paint.setFill", &json!({"gradient": {"kind": "diamond"}})).unwrap(); + let g = fill_gradient(&s, id); + assert_eq!(g.gradient.kind, GradientKind::Diamond); + // Unplaced, it runs from the box's center out to a square whose edges pass through the box's + // corners. + let geom = g.resolve(node(&s, id).geometric_bounds().unwrap()); + assert_eq!((geom.start, geom.end), (Point::new(200.0, 150.0), Point::new(350.0, 150.0))); + for (p, t) in [ + (Point::new(300.0, 200.0), 1.0), + (Point::new(100.0, 100.0), 1.0), + (Point::new(250.0, 150.0), 1.0 / 3.0), + (Point::new(200.0, 175.0), 1.0 / 6.0), + ] { + assert!((geom.param_at(GradientKind::Diamond, p) - t).abs() < 1e-9, "{p:?}"); + } + s.execute("paint.editGradient", &json!({"kind": "linear"})).unwrap(); + s.execute("paint.editGradient", &json!({"kind": "DIAMOND"})).unwrap(); + assert_eq!(fill_gradient(&s, id).gradient.kind, GradientKind::Diamond); + let e = s.execute("paint.editGradient", &json!({"kind": "spiral"})).unwrap_err().to_string(); + assert!(e.contains("(linear, radial, conic, diamond, freeform)"), "{e}"); + // Placed, an angle turns the vector about the center. + s.execute("paint.setGradientGeom", &json!({"start": [200, 150], "end": [260, 150], "aspect": 50})).unwrap(); + s.execute("paint.editGradient", &json!({"angle": 90})).unwrap(); + let g = fill_geom(&s, id); + assert!(g.start.distance(Point::new(200.0, 150.0)) < 1e-9 && g.end.distance(Point::new(200.0, 90.0)) < 1e-9, "{g:?}"); + // A reflection keeps each point's color. + let p = Point::new(230.0, 170.0); + let before = g.param_at(GradientKind::Diamond, p); + s.execute("object.reflect", &json!({"axis": "vertical"})).unwrap(); + let m = fill_geom(&s, id); + assert!(m.aspect > 0.0, "{m:?}"); + assert!((m.param_at(GradientKind::Diamond, Point::new(170.0, 170.0)) - before).abs() < 1e-9); + // A rotation carries it along. + let before = m.param_at(GradientKind::Diamond, p); + s.execute("object.rotate", &json!({"angle": 30, "origin": [200, 150]})).unwrap(); + let r = vectorcraft_geom::Affine::rotate_about(-30f64.to_radians(), Point::new(200.0, 150.0)); + let after = fill_geom(&s, id).param_at(GradientKind::Diamond, r * p); + assert!((after - before).abs() < 1e-9, "{before} vs {after}"); + // The params give it back, and the native format keeps it. + s.execute("paint.editGradient", &json!({"aspect": 60})).unwrap(); + let want = fill_gradient(&s, id); + let params = vectorcraft_tools::params::gradient_params(&want); + assert_eq!((params["kind"].as_str(), params["aspect"].as_f64()), (Some("diamond"), Some(60.0))); + s.execute("paint.setFill", &json!({"gradient": {"kind": "linear"}})).unwrap(); + s.execute("paint.setFill", &json!({ "gradient": params })).unwrap(); + let got = fill_gradient(&s, id); + assert_eq!((&got.gradient, got.geom), (&want.gradient, want.geom)); + let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + let Paint::Gradient(g) = back.node(id).unwrap().appearance.fill_paint() else { panic!("the gradient is lost") }; + assert_eq!((g.gradient.kind, g.geom), (GradientKind::Diamond, want.geom)); +} + +/// A diamond refuses a negative aspect and a focal point, from every command that gives one, and +/// the gradient stays as it was; a null focal point is allowed. +#[test] +fn a_diamond_refuses_a_negative_aspect_and_a_focal_point() { + let mut s = session(); + let id = rect(&mut s, 100.0, 100.0, 200.0, 100.0); + s.execute("paint.setFill", &json!({"gradient": {"kind": "diamond", "start": [200, 150], "end": [260, 150], "aspect": 50}})).unwrap(); + let before = fill_gradient(&s, id); + for p in [ + json!({"gradient": {"kind": "diamond", "aspect": -50}}), + json!({"gradient": {"kind": "diamond", "start": [0, 0], "end": [10, 0], "aspect": -50}}), + ] { + assert!(s.execute("paint.setFill", &p).unwrap_err().to_string().contains("aspect"), "{p}"); + } + assert!(s.execute("paint.editGradient", &json!({"aspect": -50})).is_err()); + assert!(s.execute("paint.setGradientGeom", &json!({"aspect": -50})).is_err()); + assert!(s.execute("paint.editGradient", &json!({"kind": "radial", "aspect": -50})).is_err()); + let e = s.execute("paint.setFill", &json!({"gradient": {"kind": "diamond", "start": [200, 150], "end": [260, 150], "focal": [210, 150]}})); + assert!(e.unwrap_err().to_string().contains("focal")); + assert!(s.execute("paint.setGradientGeom", &json!({"focal": [210, 150]})).unwrap_err().to_string().contains("focal")); + assert_eq!(fill_gradient(&s, id), before); + s.execute("paint.setFill", &json!({"gradient": {"kind": "diamond", "start": [200, 150], "end": [260, 150], "focal": null}})).unwrap(); + assert_eq!(fill_gradient(&s, id).geom.unwrap().focal, None); +} + +/// A free distort that is not affine moves a diamond by the warp near its center, as it moves a +/// radial gradient. +#[test] +fn a_warp_moves_a_diamond_by_its_center() { + let warped = |kind: &str| { + let mut s = session(); + let id = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + s.execute("paint.setFill", &json!({"gradient": {"kind": kind, "start": [20, 30], "end": [90, 30], "aspect": 60}})).unwrap(); + s.execute("object.distort", &json!({"corners": [[0, 0], [100, 0], [140, 130], [-20, 100]]})).unwrap(); + fill_geom(&s, id) + }; + let (diamond, radial) = (warped("diamond"), warped("radial")); + assert!(diamond.start.distance(radial.start) < 1e-9, "{diamond:?} vs {radial:?}"); +} + +/// Saved as `.ai`, as PDF with its editing data and as SVG with its editing data, then opened, a +/// turned, squashed diamond comes back as it was. +#[test] +fn a_diamond_survives_saving_as_ai_pdf_and_svg() { + let mut s = session(); + let id = rect(&mut s, 100.0, 100.0, 200.0, 100.0); + s.execute("paint.setFill", &json!({"gradient": {"kind": "diamond", "start": [180, 140], "end": [240, 110], "aspect": 60}})).unwrap(); + let want = fill_gradient(&s, id); + for format in ["ai", "pdf", "svg"] { + let r = s.execute("file.saveCopy", &json!({"format": format, "preserveEditing": true})).unwrap(); + let mut back = session(); + back.execute("document.open", &json!({"name": format!("t.{format}"), "dataBase64": r["dataBase64"]})).unwrap(); + let mut found = None; + back.doc().unwrap().doc.walk(|n| { + if let (None, Paint::Gradient(g)) = (&found, n.appearance.fill_paint()) { + found = Some(*g.clone()); + } + }); + let got = found.unwrap_or_else(|| panic!("{format}: the gradient is lost")); + assert_eq!((got.gradient.kind, got.geom), (GradientKind::Diamond, want.geom), "{format}"); + } +} + +/// Turning a gradient diamond is one undo step, and undoing it gives the gradient back as it was. +#[test] +fn making_a_gradient_diamond_is_one_undo_step() { + let mut s = session(); + let id = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + s.execute("paint.setFill", &json!({"gradient": {"kind": "radial"}})).unwrap(); + let (before, steps) = (fill_gradient(&s, id), s.doc().unwrap().history.undo.len()); + s.execute("paint.editGradient", &json!({"kind": "diamond", "angle": 45})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(fill_gradient(&s, id), before); +} + +/// `paint.setFill` and `paint.editGradient` take a spread and a count for each kind of gradient +/// that has ends; the params give them back, the native format keeps them, and a change is one +/// undo step while an edit that changes nothing records none. +#[test] +fn a_gradient_takes_a_spread_and_a_count() { + use vectorcraft_color::GradientSpread; + let mut s = session(); + let id = rect(&mut s, 100.0, 100.0, 200.0, 100.0); + for kind in ["linear", "radial", "conic", "diamond"] { + s.execute("paint.setFill", &json!({"gradient": {"kind": kind, "spread": "Reflect", "repeats": 4}})).unwrap(); + let g = fill_gradient(&s, id); + assert_eq!((g.gradient.spread, g.gradient.repeats), (GradientSpread::Reflect, 4), "{kind}"); + let params = vectorcraft_tools::params::gradient_params(&g); + assert_eq!((params["spread"].as_str(), params["repeats"].as_u64()), (Some("reflect"), Some(4)), "{kind}"); + s.execute("paint.setFill", &json!({"gradient": {"kind": "linear"}})).unwrap(); + assert_eq!(fill_gradient(&s, id).gradient.spread, GradientSpread::Pad, "a new gradient pads"); + s.execute("paint.setFill", &json!({ "gradient": params })).unwrap(); + assert_eq!(fill_gradient(&s, id).gradient, g.gradient, "{kind}"); + } + let steps = s.doc().unwrap().history.undo.len(); + s.execute("paint.editGradient", &json!({"spread": "repeat", "repeats": 2})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one step"); + let g = fill_gradient(&s, id); + assert_eq!((g.gradient.spread, g.gradient.repeats), (GradientSpread::Repeat, 2)); + s.execute("paint.editGradient", &json!({"spread": "repeat", "repeats": 2})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "nothing changed: no step"); + s.execute("paint.editGradient", &json!({"spread": "pad"})).unwrap(); + assert_eq!(fill_gradient(&s, id).gradient.repeats, 2, "Pad keeps the count for later"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(fill_gradient(&s, id), g); + let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + let Paint::Gradient(saved) = back.node(id).unwrap().appearance.fill_paint() else { panic!("the gradient is lost") }; + assert_eq!((saved.gradient.spread, saved.gradient.repeats), (GradientSpread::Repeat, 2)); + // The params of a gradient that pads give back the count it keeps. + s.execute("paint.editGradient", &json!({"spread": "pad"})).unwrap(); + let params = vectorcraft_tools::params::gradient_params(&fill_gradient(&s, id)); + s.execute("paint.setFill", &json!({"gradient": {"kind": "linear"}})).unwrap(); + s.execute("paint.setFill", &json!({ "gradient": params })).unwrap(); + assert_eq!((fill_gradient(&s, id).gradient.spread, fill_gradient(&s, id).gradient.repeats), (GradientSpread::Pad, 2), "{params}"); +} + +/// A spread or count a gradient can't take is an error, from every command that sets one, and the +/// gradient stays as it was: an unknown spread, a count that is not a whole number from 1 to 100, +/// and a spread other than pad on a freeform gradient. +#[test] +fn a_bad_spread_or_count_is_refused() { + let mut s = session(); + let id = rect(&mut s, 100.0, 100.0, 200.0, 100.0); + s.execute("paint.setFill", &json!({"gradient": {"kind": "radial", "spread": "repeat", "repeats": 3}})).unwrap(); + let before = fill_gradient(&s, id); + let steps = s.doc().unwrap().history.undo.len(); + for bad in [json!({"spread": "mirror"}), json!({"spread": 1}), json!({"spread": true})] { + let e = s.execute("paint.editGradient", &bad).unwrap_err().to_string(); + assert!(e.contains("`spread` must be pad, repeat or reflect"), "{bad}: {e}"); + } + for n in [json!(0), json!(-2), json!(1.5), json!(101), json!(1e9), json!("3"), json!(f64::MAX)] { + let e = s.execute("paint.editGradient", &json!({ "repeats": n })).unwrap_err().to_string(); + assert!(e.contains("`repeats` must be a whole number from 1 to 100"), "{n}: {e}"); + let e = s.execute("paint.setFill", &json!({"gradient": {"kind": "linear", "repeats": n}})).unwrap_err().to_string(); + assert!(e.contains("`repeats`"), "{n}: {e}"); + } + let freeform = json!({"kind": "freeform", "spread": "reflect"}); + let e = s.execute("paint.editGradient", &freeform).unwrap_err().to_string(); + assert!(e.contains("`spread` applies to linear, radial, conic and diamond gradients"), "{e}"); + let e = s.execute("paint.setFill", &json!({ "gradient": freeform })).unwrap_err().to_string(); + assert!(e.contains("`spread` applies to"), "{e}"); + assert_eq!(fill_gradient(&s, id), before); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); + // Pad on a freeform gradient is allowed (it has nothing to spread), and 100 is the most. + s.execute("paint.editGradient", &json!({"repeats": 100})).unwrap(); + s.execute("paint.editGradient", &json!({"kind": "freeform", "spread": "pad"})).unwrap(); + // A repeating gradient turned freeform: its params, which carry no spread, set it again. + s.execute("paint.editGradient", &json!({"kind": "radial", "spread": "reflect"})).unwrap(); + s.execute("paint.editGradient", &json!({"kind": "freeform"})).unwrap(); + let params = vectorcraft_tools::params::gradient_params(&fill_gradient(&s, id)); + assert!(params.get("spread").is_none(), "{params}"); + s.execute("paint.setFill", &json!({ "gradient": params })).unwrap(); +} + +/// A spread for a selected gradient applies while the gradient used last, the default, is a +/// freeform one, which keeps no spread. +#[test] +fn a_spread_for_a_selected_gradient_leaves_a_freeform_default_alone() { + use vectorcraft_color::GradientSpread; + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + s.execute("paint.setFill", &json!({"gradient": {"kind": "linear"}})).unwrap(); + rect(&mut s, 200.0, 0.0, 100.0, 100.0); + s.execute("paint.setFill", &json!({"gradient": {"kind": "freeform"}})).unwrap(); + s.execute("paint.editGradient", &json!({"ids": [a.0], "spread": "repeat", "repeats": 3})).unwrap(); + let g = fill_gradient(&s, a); + assert_eq!((g.gradient.spread, g.gradient.repeats), (GradientSpread::Repeat, 3)); +} + +/// A preset keeps its spread and count: saved from a gradient, applied to another object. +#[test] +fn a_gradient_preset_keeps_its_spread() { + use vectorcraft_color::GradientSpread; + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + s.execute("paint.setFill", &json!({"gradient": {"kind": "conic", "spread": "reflect", "repeats": 5}})).unwrap(); + s.execute("gradient.presets.save", &json!({"name": "Fan"})).unwrap(); + let b = rect(&mut s, 200.0, 0.0, 100.0, 100.0); + s.execute("paint.setFill", &json!({"gradient": {"kind": "linear"}})).unwrap(); + s.execute("gradient.presets.apply", &json!({"name": "Fan"})).unwrap(); + let g = fill_gradient(&s, b); + assert_eq!((g.gradient.kind, g.gradient.spread, g.gradient.repeats), (GradientKind::Conic, GradientSpread::Reflect, 5)); + assert_eq!(fill_gradient(&s, a).gradient.repeats, 5); +} + +/// A gradient set back to Pad keeps its count for later, and still matches a saved preset and a +/// swatch of the same gradient; while it repeats, the spread tells them apart. +#[test] +fn a_padding_gradient_matches_whatever_count_it_keeps() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let ramp = json!({"kind": "linear", "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]}); + s.execute("paint.setFill", &json!({ "gradient": ramp })).unwrap(); + s.execute("gradient.presets.save", &json!({"name": "Plain"})).unwrap(); + s.execute("swatch.new", &json!({"name": "Plain", "paint": {"gradient": ramp}})).unwrap(); + let unused = |s: &mut Session| s.execute("swatch.unused", &json!({})).unwrap()["names"].as_array().unwrap().contains(&json!("Plain")); + assert!(!unused(&mut s)); + s.execute("paint.editGradient", &json!({"spread": "repeat", "repeats": 5})).unwrap(); + assert_eq!(s.active_saved_gradient_preset(), None, "a repeating gradient is another ramp"); + assert!(unused(&mut s), "nothing paints the swatch's gradient"); + s.execute("paint.editGradient", &json!({"spread": "pad"})).unwrap(); + assert_eq!(fill_gradient(&s, a).gradient.repeats, 5); + assert_eq!(s.active_saved_gradient_preset(), Some("Plain")); + assert!(!unused(&mut s), "the gradient paints as the swatch does"); +} diff --git a/crates/engine/src/tests/gradpanel.rs b/crates/engine/src/tests/gradpanel.rs index 85fd4cf02c..680abfa9e8 100644 --- a/crates/engine/src/tests/gradpanel.rs +++ b/crates/engine/src/tests/gradpanel.rs @@ -132,6 +132,44 @@ fn graphic_styles_keep_gradients_relative_to_the_bounds() { assert!(close(fill_geom(&s, dst).unwrap().start, Point::new(0.2, 0.5)), "legacy styles are applied as stored"); } +/// Applying a style with a placed gradient to objects of different sizes gives each its own +/// appearance with the gradient on its own bounds, through undo and redo; a style from an older +/// file applies the same stored gradient to each, as one shared appearance. +#[test] +fn a_style_places_its_gradient_on_each_object() { + let (mut s, src, dst) = source_and_target(); + let other = rect(&mut s, 100.0, 300.0, 50.0, 200.0); + s.execute("select.set", &json!({"ids": [src.0]})).unwrap(); + s.execute("graphicStyle.new", &json!({"name": "Glow"})).unwrap(); + s.execute("graphicStyle.apply", &json!({"name": "Glow", "ids": [dst.0, other.0]})).unwrap(); + let placed = |s: &Session| { + let (g, h) = (fill_geom(s, dst).unwrap(), fill_geom(s, other).unwrap()); + close(g.start, Point::new(540.0, 60.0)) + && close(g.end, Point::new(660.0, 60.0)) + && close(h.start, Point::new(110.0, 400.0)) + && close(h.end, Point::new(140.0, 400.0)) + }; + let shared = |s: &Session| { + let d = &s.doc().unwrap().doc; + vectorcraft_doc::Shared::ptr_eq(&d.node(dst).unwrap().appearance, &d.node(other).unwrap().appearance) + }; + assert!(placed(&s) && !shared(&s)); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(placed(&s) && !shared(&s)); + + let glow = s.doc().unwrap().doc.graphic_styles.iter().find(|g| g.name == "Glow").cloned().unwrap(); + let legacy = vectorcraft_doc::GraphicStyle { name: "Old".into(), id: 0, unit_box: false, ..glow }; + s.edit("Add", |d, _| { + d.graphic_styles.push(legacy); + Ok(()) + }) + .unwrap(); + s.execute("graphicStyle.apply", &json!({"name": "Old", "ids": [dst.0, other.0]})).unwrap(); + assert!(shared(&s)); + assert!(close(fill_geom(&s, other).unwrap().start, Point::new(0.2, 0.5)), "legacy styles are applied as stored"); +} + #[test] fn eyedropper_options_choose_what_copy_from_takes() { let mut s = session(); diff --git a/crates/engine/src/tests/gradpresets.rs b/crates/engine/src/tests/gradpresets.rs index 437f96d26c..4328361b8b 100644 --- a/crates/engine/src/tests/gradpresets.rs +++ b/crates/engine/src/tests/gradpresets.rs @@ -38,7 +38,19 @@ fn built_in_presets_are_the_gradient_libraries_by_theme_with_unique_names() { // Grouped by library, the gradient libraries first, then the swatch libraries holding gradients. let mut libraries: Vec<&str> = rows.iter().map(|r| r["library"].as_str().unwrap()).collect(); libraries.dedup(); - assert_eq!(libraries, ["Spectrum Gradients", "Sky Gradients", "Neutral Gradients", "Duotone Gradients", "Radial Glows", "Metallic Gradients"]); + assert_eq!( + libraries, + [ + "Spectrum Gradients", + "Sky Gradients", + "Neutral Gradients", + "Organic Fades", + "Holographic", + "Duotone Gradients", + "Radial Glows", + "Metallic Gradients" + ] + ); let mut seen = std::collections::HashSet::new(); assert!(names(&list).iter().all(|n| seen.insert(n.to_lowercase())), "a name names one preset"); let vignette = rows.iter().find(|r| r["name"] == "Vignette").unwrap(); @@ -65,6 +77,56 @@ fn applying_a_preset_edits_the_gradient_in_place_as_one_undo_step() { assert_eq!(paint(&s, id, false), before); } +#[test] +fn an_organic_fade_applies_with_its_method_midpoints_and_opacities() { + let (mut s, id) = session_with(json!({"color": "#336699"})); + let mist = s.gradient_preset("Mist").unwrap(); + assert_eq!((mist.library, mist.gradient.method), (Some("Organic Fades"), GradientMethod::Perceptual)); + s.execute("gradient.presets.apply", &json!({"name": "Mist"})).unwrap(); + let g = paint(&s, id, false).gradient; + assert_eq!((g.kind, g.method, &g.stops), (GradientKind::Linear, GradientMethod::Perceptual, &mist.gradient.stops)); + assert_eq!(s.gradient_preset_name(&g).as_deref(), Some("Mist")); + let list = s.execute("gradient.presets.list", &json!({})).unwrap(); + let row = list["presets"].as_array().unwrap().iter().find(|r| r["name"] == "Mist").unwrap().clone(); + assert_eq!(row["gradient"]["method"], "perceptual"); +} + +#[test] +fn a_holographic_foil_applies_in_place_as_one_undo_step() { + let (mut s, id) = session_with(json!({"gradient": {"angle": 30}})); + let before = paint(&s, id, false); + let undo = s.doc().unwrap().history.undo.len(); + let veil = s.gradient_preset("prism veil").unwrap(); + assert_eq!((veil.library, veil.gradient.method), (Some("Holographic"), GradientMethod::Perceptual)); + let r = s.execute("gradient.presets.apply", &json!({"name": "prism veil"})).unwrap(); + assert_eq!(r["name"].as_str(), Some("Prism Veil")); + let g = paint(&s, id, false); + assert_eq!((g.gradient.kind, g.gradient.method, &g.gradient.stops), (GradientKind::Linear, GradientMethod::Perceptual, &veil.gradient.stops)); + assert_eq!(g.gradient.stops.len(), 6); + assert_eq!(g.angle, before.angle, "the placement stays"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + assert_eq!(s.gradient_preset_name(&g.gradient).as_deref(), Some("Prism Veil")); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(paint(&s, id, false), before); +} + +/// A preset saved as "Mint Halo" before Holographic existed stays listed under a free name. +#[test] +fn a_saved_preset_named_like_a_holographic_glow_gets_a_free_name() { + let (mut s, id) = session_with(json!({"gradient": {"kind": "radial"}})); + let halo = s.gradient_preset("Mint Halo").unwrap().gradient; + let mut own = paint(&s, id, false).gradient; + own.dither = true; + let mut prefs = s.prefs.clone(); + prefs.gradient_presets = vec![crate::cmd::GradientPreset { name: "MINT HALO".into(), gradient: own.clone() }]; + s.apply_prefs(prefs); + assert_eq!(s.prefs.gradient_presets.iter().map(|p| p.name.as_str()).collect::>(), ["MINT HALO 2"]); + s.execute("gradient.presets.apply", &json!({"name": "mint halo 2"})).unwrap(); + assert_eq!(paint(&s, id, false).gradient, own); + s.execute("gradient.presets.apply", &json!({"name": "Mint Halo"})).unwrap(); + assert_eq!(paint(&s, id, false).gradient.stops, halo.stops); +} + #[test] fn a_preset_applies_to_the_stroke_and_to_a_solid_paint() { let (mut s, id) = session_with(json!({"color": "#336699"})); @@ -334,3 +396,37 @@ fn saved_presets_round_trip_with_the_preferences() { fresh.apply_prefs(back); assert!(fresh.gradient_preset("mine").is_some_and(|e| e.library.is_none())); } + +/// Preferences can hold saved presets named like a built-in preset (saved before it existed) or +/// like each other (edited by hand): applied, each gets a name of its own, any case. +#[test] +fn saved_presets_named_like_a_built_in_or_another_saved_one_get_a_free_name() { + let (mut s, id) = session_with(json!({"gradient": {"kind": "radial"}})); + let mist = s.gradient_preset("Mist").unwrap().gradient; + let mut own = paint(&s, id, false).gradient; + own.dither = true; + let preset = |name: &str| crate::cmd::GradientPreset { name: name.into(), gradient: own.clone() }; + let mut prefs = s.prefs.clone(); + prefs.gradient_presets = + vec![preset("mist"), preset("Mine"), preset("MINE"), preset("Mist 2"), preset("Plain"), preset("PLAIN"), preset("plain")]; + s.apply_prefs(prefs); + let saved: Vec<&str> = s.prefs.gradient_presets.iter().map(|p| p.name.as_str()).collect(); + assert_eq!(saved, ["mist 3", "Mine", "MINE 2", "Mist 2", "Plain", "PLAIN 2", "plain 3"]); + let list = s.execute("gradient.presets.list", &json!({})).unwrap(); + let mut seen = std::collections::HashSet::new(); + assert!(names(&list).iter().all(|n| seen.insert(n.to_lowercase())), "a name names one preset"); + // The renamed one applies and deletes; the built-in Mist stays as it was. + s.execute("gradient.presets.apply", &json!({"name": "mist 3"})).unwrap(); + assert_eq!(paint(&s, id, false).gradient, own); + assert_eq!(s.gradient_preset("Mist").unwrap().gradient, mist); + assert_eq!(s.execute("gradient.presets.delete", &json!({"name": "Mist 3"})).unwrap()["deleted"], "mist 3"); + assert!(s.execute("gradient.presets.delete", &json!({"name": "Mist"})).is_err(), "built in"); + assert_eq!(s.prefs.gradient_presets.len(), 6); + // Many presets with one name each get their own number. + let mut prefs = s.prefs.clone(); + prefs.gradient_presets = (0..2000).map(|_| preset("Same")).collect(); + s.apply_prefs(prefs); + let mut seen = std::collections::HashSet::new(); + assert!(s.prefs.gradient_presets.iter().all(|p| seen.insert(p.name.to_lowercase()))); + assert_eq!(s.prefs.gradient_presets.last().map(|p| p.name.as_str()), Some("Same 2000")); +} diff --git a/crates/engine/src/tests/ids_without_selection.rs b/crates/engine/src/tests/ids_without_selection.rs index 1e13c468c3..b274e7956f 100644 --- a/crates/engine/src/tests/ids_without_selection.rs +++ b/crates/engine/src/tests/ids_without_selection.rs @@ -94,10 +94,49 @@ fn run_fresh( params: &serde_json::Value, ) -> (std::result::Result, Option>) { let (mut s, ..) = doc_with_type(); - let r = s.execute(cmd, params).map_err(|e| e.to_string()); + let r = s.execute(cmd, params).map(|v| without_plugin_effects(cmd, v)).map_err(|e| e.to_string()); (r, s.doc().ok().map(|d| d.doc.clone())) } +/// `cmd`'s result with the plug-in effects (`plugin.`) taken out of `effect.list`'s catalog. +/// The plug-in tests install and remove plug-ins in the process-wide registry while these +/// comparisons run, so two runs of `effect.list` can list different plug-ins. +fn without_plugin_effects(cmd: &str, mut r: serde_json::Value) -> serde_json::Value { + if cmd == "effect.list" + && let Some(catalog) = r.get_mut("catalog").and_then(serde_json::Value::as_array_mut) + { + catalog.retain(|e| !e["id"].as_str().is_some_and(|id| id.starts_with(vectorcraft_plugins::PREFIX))); + } + r +} + +/// Whether two results of `cmd` are the same, apart from the plug-in effects in `effect.list`'s +/// catalog ([`without_plugin_effects`]). +fn same_without_plugin_effects(cmd: &str, x: &serde_json::Value, y: &serde_json::Value) -> bool { + if cmd == "effect.list" { without_plugin_effects(cmd, x.clone()) == without_plugin_effects(cmd, y.clone()) } else { x == y } +} + +/// Two `effect.list` results that differ only in a plug-in effect in the catalog compare the same; +/// a difference in a built-in effect, in `applied` or in `activeItem`, or in another command's +/// result, does not. +#[test] +fn plugin_effects_are_left_out_of_the_effect_list_comparison() { + let list = |catalog: &[&str], applied: serde_json::Value, active: serde_json::Value| { + let catalog: Vec<_> = catalog.iter().map(|id| json!({"id": id, "label": id})).collect(); + json!({"catalog": catalog, "applied": applied, "activeItem": active}) + }; + let base = list(&["stylize.dropShadow"], json!([]), json!(null)); + let with_plugin = list(&["stylize.dropShadow", "plugin.test.glow"], json!([]), json!(null)); + assert!(same_without_plugin_effects("effect.list", &base, &with_plugin)); + assert!(same_without_plugin_effects("effect.list", &with_plugin, &base)); + assert_eq!(without_plugin_effects("effect.list", with_plugin.clone()), base); + assert!(!same_without_plugin_effects("effect.list", &base, &list(&[], json!([]), json!(null))), "a built-in effect"); + assert!(!same_without_plugin_effects("effect.list", &base, &list(&["stylize.dropShadow"], json!([{"id": 3}]), json!(null))), "applied"); + assert!(!same_without_plugin_effects("effect.list", &base, &list(&["stylize.dropShadow"], json!([]), json!(0))), "activeItem"); + assert!(!same_without_plugin_effects("object.transform", &base, &with_plugin), "another command"); + assert_eq!(without_plugin_effects("object.transform", with_plugin.clone()), with_plugin); +} + /// Every command whose params description names both `id` and `ids` (`{ids?|id?}`, `{id?, ids?: /// … (instead of id)}`), with nothing selected: `id` does what `ids` of that one object does (the /// same result or the same error, and the same document), for objects of the document and for an @@ -265,7 +304,7 @@ fn ids_and_selection(cmd: &str, picks: &[usize]) -> std::result::Result x == y, + (Ok(x), Ok(y)) => same_without_plugin_effects(cmd, x, y), (Err(x), Err(y)) => x.to_string() == y.to_string(), _ => false, }; @@ -329,6 +368,7 @@ fn ids_cases(d: u64) -> Vec<(&'static str, &'static str, serde_json::Value, Unse ("edit.colors.invert", "ids", json!({}), Selected), ("edit.colors.toCMYK", "ids", json!({}), Selected), ("edit.colors.toGrayscale", "ids", json!({}), Selected), + ("edit.colors.toIndexed", "ids", json!({}), Selected), ("edit.colors.toRGB", "ids", json!({}), Selected), ("edit.colors.saturate", "ids", json!({"intensity": 50}), Selected), ("edit.colors.adjustBalance", "ids", json!({"r": 20}), Selected), diff --git a/crates/engine/src/tests/interactivity.rs b/crates/engine/src/tests/interactivity.rs index 36a2855dfb..6f3878f9c9 100644 --- a/crates/engine/src/tests/interactivity.rs +++ b/crates/engine/src/tests/interactivity.rs @@ -3,6 +3,7 @@ use serde_json::{Value, json}; +use crate::tests_links::{Folder, save, write}; use crate::*; fn session() -> Session { @@ -110,6 +111,124 @@ fn javascript_files_are_linked_once_and_unlinked() { assert_eq!(files(&mut s), json!(["menu.js", "https://example.com/a.js"])); } +/// `cmd` with `p` for a caller whose read roots are `read` and whose write roots are `write`. +fn confined(s: &mut Session, read: &[&Folder], write: &[&Folder], cmd: &str, p: Value) -> std::result::Result { + let read: Vec<&std::path::Path> = read.iter().map(|f| f.0.as_path()).collect(); + let write: Vec<&std::path::Path> = write.iter().map(|f| f.0.as_path()).collect(); + let roots = crate::file_access::AutomationRoots::new(&read, &write).unwrap(); + crate::file_access::confine(roots.as_ref(), || s.execute(cmd, &p)).map_err(|e| e.to_string()) +} + +/// `info`, `addFile` and `removeFile` for a caller with read roots name a linked file outside them +/// by its file name, a relative one taken from the document's folder; a file inside them and a URL +/// are named as they are, and the document keeps every path. +#[test] +fn javascript_file_replies_hide_paths_outside_read_roots() { + let (away, home) = (Folder::new("js-replies-away"), Folder::new("js-replies-home")); + let (outside, inside) = (away.file("menu.js"), home.file("in.js")); + for f in [&outside, &inside, &away.file("lib/rel.js")] { + write(f, b"void 0;"); + } + let url = "https://example.com/a.js"; + let mut s = session(); + for f in [outside.as_str(), inside.as_str(), url, "lib/rel.js"] { + run(&mut s, "svgInteractivity.addFile", json!({ "file": f })); + } + save(&mut s, &away.file("poster.vectorcraft")); + let stored = s.doc().unwrap().doc.svg_scripts.clone(); + let shown = json!(["menu.js", inside, url, "rel.js"]); + let info = confined(&mut s, &[&home], &[], "svgInteractivity.info", json!({})).unwrap(); + assert_eq!(info["files"], shown, "{info}"); + let added = confined(&mut s, &[&home], &[], "svgInteractivity.addFile", json!({"file": "https://example.com/b.js"})).unwrap(); + assert_eq!(added["files"], json!(["menu.js", inside, url, "rel.js", "https://example.com/b.js"]), "{added}"); + let removed = confined(&mut s, &[&home], &[], "svgInteractivity.removeFile", json!({"file": "https://example.com/b.js"})).unwrap(); + assert_eq!(removed["files"], shown, "{removed}"); + assert!(!format!("{info}{added}{removed}").contains("js-replies-away")); + // A caller with only write roots reads none of the paths. + let info = confined(&mut s, &[], &[&home], "svgInteractivity.info", json!({})).unwrap(); + assert_eq!(info["files"], json!(["menu.js", "in.js", url, "rel.js"]), "{info}"); + // A caller whose read roots hold the files, and one without roots, sees every path. + assert_eq!(confined(&mut s, &[&away, &home], &[], "svgInteractivity.info", json!({})).unwrap()["files"], json!(stored)); + assert_eq!(run(&mut s, "svgInteractivity.info", json!({}))["files"], json!(stored)); + assert_eq!(s.doc().unwrap().doc.svg_scripts, stored, "the document keeps its paths"); +} + +/// A caller with read roots unlinks a file a reply names by its file name alone by that name, as +/// one undo step; the name is not taken for a file it may read, nor without read roots. +#[test] +fn hidden_javascript_file_can_be_removed_by_unique_shown_name() { + let (away, home) = (Folder::new("js-remove-away"), Folder::new("js-remove-home")); + let (outside, inside) = (away.file("menu.js"), home.file("other.js")); + let mut s = session(); + for f in [&outside, &inside] { + run(&mut s, "svgInteractivity.addFile", json!({ "file": f })); + } + assert!(s.execute("svgInteractivity.removeFile", &json!({"file": "menu.js"})).is_err(), "no name without read roots"); + let e = confined(&mut s, &[&home], &[], "svgInteractivity.removeFile", json!({"file": "other.js"})).unwrap_err(); + assert!(e.contains("\"other.js\" isn't linked"), "a file inside the roots is unlinked by its path: {e}"); + let steps = s.doc().unwrap().history.undo.len(); + let r = confined(&mut s, &[&home], &[], "svgInteractivity.removeFile", json!({"file": "menu.js"})).unwrap(); + assert_eq!(r["files"], json!([inside]), "{r}"); + assert_eq!(s.doc().unwrap().doc.svg_scripts, [inside.as_str()]); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc().unwrap().doc.svg_scripts, [outside.as_str(), inside.as_str()]); + // A caller that knows the whole path unlinks the file by it. + let r = confined(&mut s, &[&home], &[], "svgInteractivity.removeFile", json!({ "file": outside })).unwrap(); + assert_eq!(r["files"], json!([inside]), "{r}"); +} + +/// Two linked files outside the read roots with the same file name: that name unlinks neither, +/// and the error names no path. +#[test] +fn ambiguous_hidden_javascript_file_name_is_refused_without_edit() { + let (away, home) = (Folder::new("js-ambiguous-away"), Folder::new("js-ambiguous-home")); + let (a, b) = (away.file("a/menu.js"), away.file("b/menu.js")); + let mut s = session(); + for f in [&a, &b] { + run(&mut s, "svgInteractivity.addFile", json!({ "file": f })); + } + let steps = s.doc().unwrap().history.undo.len(); + let e = confined(&mut s, &[&home], &[], "svgInteractivity.removeFile", json!({"file": "menu.js"})).unwrap_err(); + assert!(e.contains("\"menu.js\" names more than one linked JavaScript file") && !e.contains("js-ambiguous-away"), "{e}"); + assert_eq!(s.doc().unwrap().doc.svg_scripts, [a.as_str(), b.as_str()]); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "no undo step"); + let e = confined(&mut s, &[&home], &[], "svgInteractivity.removeFile", json!({"file": "nav.js"})).unwrap_err(); + assert!(e.contains("\"nav.js\" isn't linked") && !e.contains("js-ambiguous-away"), "{e}"); + // A file linked as the name itself, beside one outside the roots shown by that name: neither. + run(&mut s, "svgInteractivity.removeFile", json!({ "file": b })); + run(&mut s, "svgInteractivity.addFile", json!({"file": "menu.js"})); + let e = confined(&mut s, &[&home], &[], "svgInteractivity.removeFile", json!({"file": "menu.js"})).unwrap_err(); + assert!(e.contains("names more than one"), "{e}"); + assert_eq!(s.doc().unwrap().doc.svg_scripts, [a.as_str(), "menu.js"]); + // Without read roots the name is the file linked as it. + run(&mut s, "svgInteractivity.removeFile", json!({"file": "menu.js"})); + assert_eq!(s.doc().unwrap().doc.svg_scripts, [a.as_str()]); +} + +/// `addFile` takes a file the same text links as already linked: a file name that a reply shows for +/// a different file is linked as one more file, within the 64-file limit. +#[test] +fn adding_a_shown_name_does_not_deduplicate_a_different_hidden_path() { + let (away, home) = (Folder::new("js-add-away"), Folder::new("js-add-home")); + let mut s = session(); + let outside = away.file("0.js"); + run(&mut s, "svgInteractivity.addFile", json!({ "file": outside })); + let r = confined(&mut s, &[&home], &[], "svgInteractivity.addFile", json!({"file": "0.js"})).unwrap(); + assert_eq!(r["files"], json!(["0.js", "0.js"]), "{r}"); + assert_eq!(s.doc().unwrap().doc.svg_scripts, [outside.as_str(), "0.js"]); + run(&mut s, "edit.undo", json!({})); + for i in 1..64 { + run(&mut s, "svgInteractivity.addFile", json!({ "file": away.file(&format!("{i}.js")) })); + } + let e = confined(&mut s, &[&home], &[], "svgInteractivity.addFile", json!({"file": "0.js"})).unwrap_err(); + assert!(e.contains("at most 64"), "a 65th file is refused: {e}"); + let steps = s.doc().unwrap().history.undo.len(); + let r = confined(&mut s, &[&home], &[], "svgInteractivity.addFile", json!({ "file": outside })).unwrap(); + assert_eq!(r["files"].as_array().map(Vec::len), Some(64), "the same path is already linked"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); +} + #[test] fn a_document_links_at_most_64_javascript_files() { let mut s = session(); diff --git a/crates/engine/src/tests/intertwine.rs b/crates/engine/src/tests/intertwine.rs index ecb9742a30..a7fbf93ea2 100644 --- a/crates/engine/src/tests/intertwine.rs +++ b/crates/engine/src/tests/intertwine.rs @@ -104,6 +104,45 @@ fn the_object_brought_over_shows_no_seam_of_the_one_below() { assert!(worst < 8, "blue shows through ring A at the top crossing (blue {worst})"); } +fn green(r: &Rendered, x: u32, y: u32) -> bool { + let p = r.pixel(x, y); + p[3] > 200 && p[1] > 200 && p[0] < 60 && p[2] < 60 +} + +/// The margin an object brought over another is raised in past their overlap reaches only where +/// that object alone paints: a third member that meets the overlap's edge stays in front of it +/// there. Red A (20..80 × 20..60) and blue B (40..60 × 30..70) overlap in 40..60 × 30..60; the +/// green sliver C (38..40 × 40..50), in front of both, meets that overlap at x = 40 over A only. +#[test] +fn raising_one_overlap_keeps_an_adjacent_third_member_above_its_seam() { + let mut s = session(); + let rect = |s: &mut Session, x: f64, y: f64, w: f64, h: f64, color: &str| { + let id = id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()); + s.execute("paint.setFill", &json!({"ids": [id.0], "color": color})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id.0], "none": true})).unwrap(); + id + }; + let a = rect(&mut s, 20.0, 20.0, 60.0, 40.0, "#ff0000"); + let b = rect(&mut s, 40.0, 30.0, 20.0, 40.0, "#0000ff"); + let c = rect(&mut s, 38.0, 40.0, 2.0, 10.0, "#00ff00"); + select(&mut s, &[a, b, c]); + let g = id_of(&s.execute("object.intertwine.make", &json!({})).unwrap()); + let r = render(&s); + assert!(green(&r, 39, 45) && blue(&r, 50, 45) && red(&r, 39, 55)); + let v = arrange(&mut s, json!({"at": [50, 45], "order": "front", "member": a.0})); + assert_eq!((&v["count"], &v["top"]), (&json!(1), &json!([a.0]))); + assert_eq!(order_at(&s.doc().unwrap().doc, g, 50.0, 45.0), [b, a]); + let r = render(&s); + assert!(red(&r, 50, 45), "A is brought over B"); + assert!(green(&r, 39, 45), "C stays in front of A within the margin"); + assert!(red(&r, 39, 55)); + let raised = area(&s, a).unwrap(); + let inside = |x, y| vectorcraft_tools::intertwine::contains(&raised, vectorcraft_geom::Point::new(x, y)); + assert!(inside(50.5, 45.5), "the overlap"); + assert!(inside(39.5, 55.5), "the margin where only A paints"); + assert!(!inside(39.5, 45.5), "the margin leaves out where C paints too"); +} + #[test] fn clicking_the_same_overlap_again_swaps_back() { let mut s = session(); diff --git a/crates/engine/src/tests/journal.rs b/crates/engine/src/tests/journal.rs index f6ee8015be..1c4287e9c1 100644 --- a/crates/engine/src/tests/journal.rs +++ b/crates/engine/src/tests/journal.rs @@ -192,9 +192,143 @@ fn fit_steps_take_the_batchs_artboard_and_actions_leave_out_their_index() { assert_eq!(action, [fit("artboard.fitToArt"), fit("artboard.fitToArt"), fit("artboard.fitToSelection")]); } +/// A document of three artboards with art of its own on each → its artboards before any fit. +fn three_artboards_with_art(s: &mut Session) -> Vec { + s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 3, "created": null})).unwrap(); + for (x, h) in [(10, 30), (130, 20), (250, 40)] { + s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 20, "height": h})).unwrap(); + } + s.execute("select.all", &json!({})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.doc().unwrap().doc.artboards.iter().map(|a| a.rect).collect() +} + +/// The artboards of [`three_artboards_with_art`], each fitted to its art. +fn three_fitted_artboards() -> [vectorcraft_geom::Rect; 3] { + let rect = vectorcraft_geom::Rect::new; + [rect(10.0, 10.0, 30.0, 40.0), rect(130.0, 10.0, 150.0, 30.0), rect(250.0, 10.0, 270.0, 50.0)] +} + +/// A Fit to Artwork Bounds step that names neither `index` nor `indices`, while the Artboard tool +/// is chosen with several artboards selected, fits each of those (not the batch's artboard), as the +/// command does on its own; a step's own `index` or `indices` wins, and with one artboard or none +/// selected the step takes the batch's artboard. +#[test] +fn a_batch_fit_step_uses_the_artboard_tool_selection() { + let fitted = three_fitted_artboards(); + let boards = |s: &Session| s.doc().unwrap().doc.artboards.iter().map(|a| a.rect).collect::>(); + let fit = |params: Value| json!({"artboard": 1, "commands": [{"command": "artboard.fitToArt", "params": params}]}); + let session = |picks: &Value| { + let mut s = Session::new(); + let was = three_artboards_with_art(&mut s); + s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap(); + s.set_tool_option("selected", picks); + (s, was) + }; + let (mut s, was) = session(&json!([2, 0])); + s.execute("command.batch", &fit(json!({}))).unwrap(); + assert_eq!(boards(&s), [fitted[0], was[1], fitted[2]], "artboards 1 and 3, the selected ones, and not the batch's artboard 2"); + let (mut s, was) = session(&json!([2, 0])); + s.execute("command.batch", &fit(json!({"index": 1}))).unwrap(); + assert_eq!(boards(&s), [was[0], fitted[1], was[2]], "a step's own index"); + let (mut s, was) = session(&json!([2, 0])); + s.execute("command.batch", &fit(json!({"indices": [1, 2]}))).unwrap(); + assert_eq!(boards(&s), [was[0], fitted[1], fitted[2]], "a step's own indices"); + for picks in [json!([2]), json!([])] { + let (mut s, was) = session(&picks); + s.execute("command.batch", &fit(json!({}))).unwrap(); + assert_eq!(boards(&s), [was[0], fitted[1], was[2]], "the batch's artboard with {picks} selected"); + } +} + +/// The journal records the artboards a batch's Fit to Artwork Bounds step took from the Artboard +/// tool, so a replay in a new session fits the same ones; an action leaves them out and fits the +/// artboards selected when it plays. +#[test] +fn a_batch_fit_selection_replays_but_an_action_uses_the_current_selection() { + let fitted = three_fitted_artboards(); + let boards = |s: &Session| s.doc().unwrap().doc.artboards.iter().map(|a| a.rect).collect::>(); + let mut s = Session::new(); + let was = three_artboards_with_art(&mut s); + s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap(); + s.set_tool_option("selected", &json!([0, 2])); + let start = s.journal.len(); + let steps = json!([{"command": "artboard.fitToArt", "params": {}}]); + s.execute("command.batch", &json!({"artboard": 1, "commands": steps})).unwrap(); + assert_eq!(boards(&s), [fitted[0], was[1], fitted[2]]); + let (id, p) = s.journal.last().unwrap().clone(); + assert_eq!((id.as_str(), &p["commands"][0]["params"]), ("command.batch", &json!({"indices": [0, 2]}))); + let r = replayed(&s); + assert_ne!(r.tool_id(), "artboard", "the new session's tool selects no artboards"); + assert_eq!(boards(&r), boards(&s), "the replay fits the recorded artboards"); + let action = s.journal_for_action(start); + assert_eq!(action, [("command.batch".to_string(), json!({"commands": steps}))]); + // Played on a fresh copy of the document with other artboards selected. + let mut a = Session::new(); + three_artboards_with_art(&mut a); + a.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap(); + a.set_tool_option("selected", &json!([1, 2])); + a.execute("command.batch", &json!({"artboard": 0, "commands": action[0].1["commands"]})).unwrap(); + assert_eq!(boards(&a), [was[0], fitted[1], fitted[2]], "the action fits the artboards selected when it plays"); +} + +/// The journal records the `index` a batch's Fit to Artwork Bounds step took from the batch's +/// `artboard`, or the command's default (the first artboard) when the batch names none, so a replay +/// fits that artboard even when the Artboard tool then has several selected. +#[test] +fn a_batch_fit_step_records_the_batchs_artboard() { + let fitted = three_fitted_artboards(); + let boards = |s: &Session| s.doc().unwrap().doc.artboards.iter().map(|a| a.rect).collect::>(); + let steps = json!([{"command": "artboard.fitToArt", "params": {}}]); + for (batch, index, picks) in [(json!({"artboard": 1, "commands": steps}), 1, json!([0, 2])), (json!({"commands": steps}), 0, json!([1, 2]))] { + let mut s = Session::new(); + let was = three_artboards_with_art(&mut s); + let start = s.journal.len(); + s.execute("command.batch", &batch).unwrap(); + let mut want = was.clone(); + want[index] = fitted[index]; + assert_eq!(boards(&s), want, "{batch}"); + let (id, p) = s.journal.last().unwrap().clone(); + assert_eq!((id.as_str(), &p["commands"][0]["params"]), ("command.batch", &json!({ "index": index }))); + let mut r = Session::new(); + for (n, (id, p)) in s.journal.iter().enumerate() { + if n == start { + r.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap(); + r.set_tool_option("selected", &picks); + } + r.execute(id, p).unwrap(); + } + assert_eq!(boards(&r), want, "{batch}: the replay fits artboard {index}, not the selected ones"); + assert_eq!(s.journal_for_action(start), [("command.batch".to_string(), json!({"commands": steps}))]); + } +} + +/// A batch step with `"params": null` gets the Artboard tool's selected artboards, or else the +/// batch's `artboard`, as a step without params does. +#[test] +fn a_batch_fit_step_with_null_params_gets_the_artboards() { + let fitted = three_fitted_artboards(); + let boards = |s: &Session| s.doc().unwrap().doc.artboards.iter().map(|a| a.rect).collect::>(); + let steps = json!([{"command": "artboard.fitToArt", "params": null}]); + let mut s = Session::new(); + let was = three_artboards_with_art(&mut s); + s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap(); + s.set_tool_option("selected", &json!([2, 0])); + s.execute("command.batch", &json!({"artboard": 1, "commands": steps})).unwrap(); + assert_eq!(boards(&s), [fitted[0], was[1], fitted[2]], "the selected artboards"); + let (_, p) = s.journal.last().unwrap().clone(); + assert_eq!(p["commands"][0]["params"], json!({"indices": [0, 2]})); + let mut s = Session::new(); + three_artboards_with_art(&mut s); + s.execute("command.batch", &json!({"artboard": 1, "commands": steps})).unwrap(); + assert_eq!(boards(&s), [was[0], fitted[1], was[2]], "the batch's artboard"); +} + #[test] fn a_save_records_its_date_and_replays_it() { - let path = vectorcraft_testkit::temp_dir("journal-save").join("a.vectorcraft").to_string_lossy().into_owned(); + let dir = vectorcraft_testkit::TempDir::new("journal-save"); + let path = dir.join("a.vectorcraft").to_string_lossy().into_owned(); let mut s = Session::new(); s.execute("file.new", &json!({"created": null})).unwrap(); s.execute("document.save", &json!({"path": path})).unwrap(); @@ -209,7 +343,6 @@ fn a_save_records_its_date_and_replays_it() { assert_eq!(s.doc().unwrap().doc.metadata.modified, Some(2_000_000_000)); assert!(s.execute("document.save", &json!({"path": path, "modified": "today"})).is_err()); // Save As stamps the same way; Save a Copy leaves the document's dates (and records none). - let dir = vectorcraft_testkit::temp_dir("journal-save"); s.execute("file.saveAs", &json!({"path": dir.join("b.vectorcraft").to_string_lossy(), "modified": 2_000_000_100})).unwrap(); assert_eq!(s.journal.last().unwrap().1["modified"], json!(2_000_000_100)); s.execute("file.saveCopy", &json!({"path": dir.join("c.vectorcraft").to_string_lossy()})).unwrap(); @@ -235,7 +368,8 @@ fn replayed(s: &Session) -> Session { #[test] fn a_save_in_a_batch_records_its_date_and_replays_it() { - let path = vectorcraft_testkit::temp_dir("journal-batch").join("a.vectorcraft").to_string_lossy().into_owned(); + let dir = vectorcraft_testkit::TempDir::new("journal-batch"); + let path = dir.join("a.vectorcraft").to_string_lossy().into_owned(); let mut s = Session::new(); s.execute("file.new", &json!({"created": 1_000_000_000})).unwrap(); let rect = json!({"x": 10, "y": 10, "width": 50, "height": 40}); @@ -617,7 +751,8 @@ fn a_failed_batch_closes_the_documents_it_opened_and_restores_the_ones_it_closed #[test] fn a_failed_batch_brings_back_a_document_it_reverted() { - let path = vectorcraft_testkit::temp_dir("journal-batch").join("revert.vectorcraft").to_string_lossy().into_owned(); + let dir = vectorcraft_testkit::TempDir::new("journal-batch"); + let path = dir.join("revert.vectorcraft").to_string_lossy().into_owned(); let mut s = Session::new(); s.execute("file.new", &json!({"created": null})).unwrap(); s.execute("document.save", &json!({"path": path, "modified": null})).unwrap(); diff --git a/crates/engine/src/tests/library.rs b/crates/engine/src/tests/library.rs index 15a8da8104..c2dccc7bb5 100644 --- a/crates/engine/src/tests/library.rs +++ b/crates/engine/src/tests/library.rs @@ -635,6 +635,209 @@ fn a_library_style_named_with_spaces_comes_in_trimmed() { assert_eq!((text.runs[0].style.size, text.runs[0].style.style_name.as_deref()), (31.0, Some("Body"))); } +/// The size of the first run of text object `id`. +fn run_size(s: &Session, id: &Value) -> f64 { + match &s.doc().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.runs[0].style.size, + _ => 0.0, + } +} + +/// Add to Character Styles puts a library character style into the document's character styles +/// without applying it, with or without type selected, in one undo step; the same style there is +/// reused without a step, and a name taken by other attributes gets a number. A bad call changes +/// nothing. +#[test] +fn a_library_character_style_is_added_to_the_document_without_applying_it() { + let mut s = session(); + let data = json!({"name": "Kept", "charStyles": [{"name": "Headline", "attrs": {"size": 31.0}}, {"name": "Broken", "attrs": {"size": "big"}}]}); + let lib = run(&mut s, "library.import", json!({"data": data.to_string()}))["id"].as_str().unwrap().to_string(); + let styles = |s: &Session| s.doc().unwrap().doc.char_styles.iter().map(|c| c.name.clone()).collect::>(); + let undo = |s: &Session| s.doc().unwrap().history.undo.len(); + // Nothing selected. + let before = undo(&s); + let r = run(&mut s, "library.addToCharacterStyles", json!({"library": lib, "item": "Headline"})); + assert_eq!((r["style"].as_str(), r["existing"].as_bool()), (Some("Headline"), Some(false))); + assert_eq!(styles(&s), ["Headline"]); + assert_eq!(undo(&s), before + 1, "one undo step"); + let attrs = &s.doc().unwrap().doc.char_styles[0].attrs; + assert_eq!(attrs.get("size"), Some(&json!(31.0))); + // Selected type keeps its look. + let t = run(&mut s, "text.create", json!({"x": 10, "y": 50, "text": "Body", "size": 9}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [t]})); + let before = undo(&s); + let r = run(&mut s, "library.addToCharacterStyles", json!({"library": lib, "item": "Headline"})); + assert_eq!((r["style"].as_str(), r["existing"].as_bool()), (Some("Headline"), Some(true))); + assert_eq!((undo(&s), run_size(&s, &t), styles(&s).len()), (before, 9.0, 1), "reused: no step, the type unchanged"); + // Another style of that name: numbered, still not applied. + run(&mut s, "charStyle.setAttrs", json!({"name": "Headline", "attrs": {"size": 5}})); + let r = run(&mut s, "library.addToCharacterStyles", json!({"library": lib, "item": "Headline"})); + assert_eq!((r["style"].as_str(), r["existing"].as_bool()), (Some("Headline 2"), Some(false))); + assert_eq!(run_size(&s, &t), 9.0); + let vectorcraft_doc::NodeKind::Text(text) = &s.doc().unwrap().doc.node(NodeId(t.as_u64().unwrap())).unwrap().kind else { panic!("not text") }; + assert_eq!(text.runs[0].style.style_name, None, "no style applied"); + // Undo takes the added style back alone. + run(&mut s, "edit.undo", json!({})); + assert_eq!(styles(&s), ["Headline"]); + // Bad calls: nothing changes. + let before = (undo(&s), styles(&s)); + for bad in [ + json!({"library": lib}), + json!({"library": lib, "item": 3}), + json!({"library": lib, "item": "Nope"}), + json!({"library": "Nope", "item": "Headline"}), + json!({"library": lib, "item": "Broken"}), + json!({"recorded": {"name": "X", "attrs": "damaged"}}), + ] { + assert!(s.execute("library.addToCharacterStyles", &bad).is_err(), "{bad}"); + assert_eq!((undo(&s), styles(&s)), before, "{bad}"); + } + // Without a document it isn't available. + run(&mut s, "file.close", json!({})); + assert!(s.active().is_none()); + assert!(s.execute("library.addToCharacterStyles", &json!({"library": lib, "item": "Headline"})).is_err()); +} + +/// A library character style whose fill links to a swatch the document lacks is added and applied +/// with the color it shows, unlinked at full tint; a global swatch of that name in the document +/// keeps the link and gives its color. +#[test] +fn a_library_character_style_linked_to_a_missing_swatch_is_added_unlinked() { + let base = vectorcraft_color::Color::rgb(0.2, 0.4, 0.6); + let shown = base.tinted(0.5); + let linked = vectorcraft_color::Paint::Solid { color: shown, swatch: Some("Brand".into()), tint: 0.5 }; + let data = json!({"name": "Kept", "charStyles": [{"name": "Accent", "attrs": {"size": 20.0, "fill": linked}}]}); + let mut s = session(); + let lib = run(&mut s, "library.import", json!({"data": data.to_string()}))["id"].as_str().unwrap().to_string(); + let fill = |s: &Session, name: &str| { + let st = s.doc().unwrap().doc.char_styles.iter().find(|c| c.name == name).map(|c| c.attrs.clone()).unwrap(); + serde_json::from_value::(st["fill"].clone()).unwrap() + }; + run(&mut s, "library.addToCharacterStyles", json!({"library": lib, "item": "Accent"})); + assert_eq!(fill(&s, "Accent"), vectorcraft_color::Paint::Solid { color: shown, swatch: None, tint: 1.0 }); + // Apply as well, on selected type. + let t = run(&mut s, "text.create", json!({"x": 10, "y": 50, "text": "Body", "size": 9}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [t]})); + let r = run(&mut s, "library.use", json!({"library": lib, "kind": "charStyle", "item": "Accent"})); + assert_eq!(r["style"], "Accent", "the added style is reused"); + assert_eq!(run_size(&s, &t), 20.0); + // A document with a global swatch of that name keeps the link. + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let other = vectorcraft_color::Color::rgb(0.8, 0.1, 0.1); + run(&mut s, "swatch.new", json!({"name": "Brand", "color": other, "global": true})); + run(&mut s, "library.addToCharacterStyles", json!({"library": lib, "item": "Accent"})); + let vectorcraft_color::Paint::Solid { swatch, tint, .. } = fill(&s, "Accent") else { panic!("not a solid fill") }; + assert_eq!((swatch.as_deref(), tint), (Some("Brand"), 0.5)); + // The style with the document's swatch color is the same style: added again, it is reused. + let r = run(&mut s, "library.addToCharacterStyles", json!({"library": lib, "item": "Accent"})); + assert_eq!((r["style"].as_str(), r["existing"].as_bool()), (Some("Accent"), Some(true))); +} + +/// A library style is compared with the document's in the form the document stores it in, so a +/// style whose file writes a size as a whole number is reused, by Add to Character Styles and by a +/// click alike. +#[test] +fn a_library_style_is_reused_whatever_form_its_file_writes_it_in() { + let data = json!({"name": "Kept", "charStyles": [{"name": "Whole", "attrs": {"size": 31}}], "paraStyles": [{"name": "Para", "attrs": {"left_indent": 4}}]}); + let mut s = session(); + let lib = run(&mut s, "library.import", json!({"data": data.to_string()}))["id"].as_str().unwrap().to_string(); + run(&mut s, "library.addToCharacterStyles", json!({"library": lib, "item": "Whole"})); + let r = run(&mut s, "library.addToCharacterStyles", json!({"library": lib, "item": "Whole"})); + assert_eq!((r["style"].as_str(), r["existing"].as_bool()), (Some("Whole"), Some(true))); + let t = run(&mut s, "text.create", json!({"x": 10, "y": 50, "text": "Body", "size": 9}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [t]})); + for (kind, item) in [("charStyle", "Whole"), ("paraStyle", "Para"), ("paraStyle", "Para")] { + assert_eq!(run(&mut s, "library.use", json!({"library": lib, "kind": kind, "item": item}))["style"], item); + } + let d = &s.doc().unwrap().doc; + assert_eq!((d.char_styles.len(), d.para_styles.iter().filter(|p| p.name.starts_with("Para")).count()), (1, 1)); +} + +/// Rename gives a library item a new name, trimmed, in its place and its group; a character style +/// keeps its attributes, a graphic its id. Another item of its kind with that name, an empty or +/// too long name, a name that isn't text and an unknown item or library are errors that change +/// nothing; a name with path characters is a name like any other; the item's own name writes +/// nothing; and the document's history is not touched. +#[test] +fn library_items_are_renamed_in_place() { + let (mut s, g, c, st) = brand(); + let t = run(&mut s, "text.create", json!({"x": 10, "y": 120, "text": "Body", "size": 9}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [t]})); + let other = run(&mut s, "library.add", json!({"kind": "charStyle", "name": "Body"}))["name"].as_str().unwrap().to_string(); + run(&mut s, "library.createGroup", json!({"name": "Brand", "items": [{"kind": "charStyle", "item": st}, {"kind": "fillColor", "item": c}]})); + let undo = s.doc().unwrap().history.undo.len(); + let attrs = run(&mut s, "library.get", json!({}))["charStyles"][0]["attrs"].clone(); + let r = run(&mut s, "library.renameItem", json!({"kind": "charStyle", "item": st, "name": " Title "})); + assert_eq!((r["item"].as_str(), r["name"].as_str()), (Some("Title"), Some("Title"))); + let got = run(&mut s, "library.get", json!({})); + assert_eq!(got["charStyles"][0], json!({"name": "Title", "attrs": attrs}), "first still, the attributes kept"); + assert_eq!(got["charStyles"][1]["name"], other.as_str()); + assert_eq!(groups(&mut s), [("Brand".into(), refs(&[("charStyle", "Title"), ("color", &c)]))]); + // A colour keeps its group under its new name; a graphic keeps its id. + run(&mut s, "library.renameItem", json!({"kind": "strokeColor", "item": c, "name": "Navy"})); + assert_eq!(groups(&mut s), [("Brand".into(), refs(&[("charStyle", "Title"), ("color", "Navy")]))]); + let r = run(&mut s, "library.renameItem", json!({"kind": "graphic", "item": "Logo", "name": "Mark"})); + assert_eq!(r["item"], g.as_str()); + let graphic = run(&mut s, "library.get", json!({}))["graphics"][0].clone(); + assert_eq!((graphic["id"].as_str(), graphic["name"].as_str()), (Some(g.as_str()), Some("Mark"))); + // Path characters are kept. + run(&mut s, "library.renameItem", json!({"kind": "charStyle", "item": "Title", "name": "a/b\\c:d"})); + assert_eq!(style_order_of(&mut s)[0], "a/b\\c:d"); + // Errors change nothing. + let before = run(&mut s, "library.get", json!({})); + let long = "x".repeat(257); + for bad in [ + json!({"kind": "charStyle", "item": "a/b\\c:d", "name": other}), + json!({"kind": "charStyle", "item": "a/b\\c:d", "name": " "}), + json!({"kind": "charStyle", "item": "a/b\\c:d", "name": long}), + json!({"kind": "charStyle", "item": "a/b\\c:d", "name": 5}), + json!({"kind": "charStyle", "item": "a/b\\c:d"}), + json!({"kind": "charStyle", "item": "Nope", "name": "X"}), + json!({"kind": "paraStyle", "item": "a/b\\c:d", "name": "X"}), + json!({"kind": "brush", "item": "a/b\\c:d", "name": "X"}), + json!({"library": "Nope", "kind": "charStyle", "item": "a/b\\c:d", "name": "X"}), + ] { + assert!(s.execute("library.renameItem", &bad).is_err(), "{bad}"); + assert_eq!(run(&mut s, "library.get", json!({})), before, "{bad}"); + } + // A style of another kind may have the name, and 256 characters are allowed. + run(&mut s, "library.renameItem", json!({"kind": "charStyle", "item": "a/b\\c:d", "name": "Navy"})); + run(&mut s, "library.renameItem", json!({"kind": "charStyle", "item": "Navy", "name": "y".repeat(256)})); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no document undo step"); +} + +/// The current library's character style names, in order. +fn style_order_of(s: &mut Session) -> Vec { + order(s, "charStyles", "name") +} + +/// A rename is kept in the library's file; renaming an item to its own name writes nothing; and a +/// rename whose file can't be written is taken back. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_library_item_rename_is_saved_or_taken_back() { + let dir = vectorcraft_testkit::TempDir::new("library-rename-item"); + let folder = dir.to_string_lossy().to_string(); + let mut s = session(); + s.libraries.set_dir(Some(folder.clone())); + let lib = run(&mut s, "library.create", json!({"name": "Kept"}))["id"].as_str().unwrap().to_string(); + let t = run(&mut s, "text.create", json!({"x": 10, "y": 50, "text": "Body", "size": 12}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [t]})); + run(&mut s, "library.add", json!({"kind": "charStyle", "name": "Body"})); + run(&mut s, "library.renameItem", json!({"kind": "charStyle", "item": "Body", "name": "Text"})); + let mut t2 = session(); + t2.libraries.set_dir(Some(folder.clone())); + assert_eq!(style_order_of(&mut t2), ["Text"], "kept in the file"); + // The file can't be written (a folder stands where it goes): its own name still succeeds, as + // it writes nothing; a new name fails and is taken back. + let file = dir.join(format!("{lib}.vclibrary")); + std::fs::remove_file(&file).unwrap(); + std::fs::create_dir(&file).unwrap(); + run(&mut s, "library.renameItem", json!({"kind": "charStyle", "item": "Text", "name": " Text "})); + assert!(s.execute("library.renameItem", &json!({"kind": "charStyle", "item": "Text", "name": "Copy"})).is_err()); + assert_eq!(style_order_of(&mut s), ["Text"], "taken back"); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn libraries_are_kept_in_files_across_sessions() { @@ -852,7 +1055,8 @@ fn a_new_item_is_added_where_it_is_dropped() { #[cfg(not(target_arch = "wasm32"))] #[test] fn an_add_that_cannot_be_placed_makes_no_library() { - let folder = vectorcraft_testkit::temp_dir("library-add-unplaced").to_string_lossy().to_string(); + let dir = vectorcraft_testkit::TempDir::new("library-add-unplaced"); + let folder = dir.to_string_lossy().to_string(); let mut s = session(); s.libraries.set_dir(Some(folder.clone())); for bad in [json!({"kind": "fillColor", "color": "#808080", "group": "Nope"}), json!({"kind": "fillColor", "color": "#808080", "after": "Nope"})] @@ -959,7 +1163,7 @@ fn a_library_of_one_repeated_name_imports_numbered() { #[cfg(not(target_arch = "wasm32"))] #[test] fn a_library_is_exported_to_a_file_and_imported_from_it() { - let dir = vectorcraft_testkit::temp_dir("library-export"); + let dir = vectorcraft_testkit::TempDir::new("library-export"); let path = dir.join("Brand.vclibrary").to_string_lossy().to_string(); let (mut s, g, ..) = brand(); run(&mut s, "library.createGroup", json!({"name": "Logos", "items": [{"kind": "graphic", "item": g}]})); diff --git a/crates/engine/src/tests/library_roots.rs b/crates/engine/src/tests/library_roots.rs index 30a8776b35..5ce4a3757e 100644 --- a/crates/engine/src/tests/library_roots.rs +++ b/crates/engine/src/tests/library_roots.rs @@ -214,26 +214,72 @@ fn swatch_library_replies_leave_out_paths_outside_the_read_root() { let mine = format!("loaded/{}", text(&inside)); let copied = confine(roots.as_ref(), || run(&mut s, "swatch.library.copyToUser", json!({"library": mine}))); assert_eq!((copied["library"].as_str(), copied["copied"].as_bool()), (Some("user/Kit.vcswatches"), Some(true)), "{copied}"); - assert_eq!(copied["path"], Value::Null, "{copied}"); + assert_eq!(copied.get("path"), None, "{copied}"); let saved = confine(roots.as_ref(), || run(&mut s, "swatch.library.save", json!({"user": true, "name": "Mine"}))); assert_eq!((saved["library"].as_str(), saved.get("path")), (Some("user/Mine.vcswatches"), None), "{saved}"); for reply in [&added, &copied, &saved] { assert!(!holds(reply, &base.join("a")) && !holds(reply, &base.join("user")), "{reply}"); } - // A library loaded from data under the file name keeps its id; each concealed one takes the next - // free one, so no two rows share an id. + // A library loaded from data under the file name keeps its id; the concealed one shown under that + // id takes the next free one, the other keeps its id, and no two rows share an id. let data = run(&mut s, "swatch.library.save", json!({}))["data"].as_str().unwrap().to_string(); run(&mut s, "swatch.library.load", json!({"data": data, "name": "Kit.vcswatches"})); let list = confine(roots.as_ref(), || run(&mut s, "swatch.library.list", json!({}))); let ids: Vec = loaded(&list).into_iter().map(|(id, ..)| id).collect(); - assert_eq!(ids, [json!("loaded/Kit.vcswatches (2)"), json!("loaded/Kit.vcswatches (3)"), json!("loaded/Kit.vcswatches")], "{list}"); + assert_eq!(ids, [json!("loaded/Kit.vcswatches (3)"), json!("loaded/Kit.vcswatches (2)"), json!("loaded/Kit.vcswatches")], "{list}"); // Copied into the user library folder, it is still found by that id, which no other library takes. confine(roots.as_ref(), || run(&mut s, "swatch.library.copyToUser", json!({"library": "loaded/Kit.vcswatches"}))); let list = confine(roots.as_ref(), || run(&mut s, "swatch.library.list", json!({}))); let ids: Vec = loaded(&list).into_iter().map(|(id, ..)| id).collect(); - assert_eq!(ids, [json!("loaded/Kit.vcswatches (2)"), json!("loaded/Kit.vcswatches (3)")], "{list}"); + assert_eq!(ids, [json!("loaded/Kit.vcswatches (3)"), json!("loaded/Kit.vcswatches (2)")], "{list}"); // The person sees the folder. let saved = run(&mut s, "swatch.library.save", json!({"user": true, "name": "Theirs"})); assert_eq!(saved["path"], json!(text(&base.join("user").join("Theirs.vcswatches")))); let _ = std::fs::remove_dir_all(base); } + +/// Outside Windows a `\` is part of a file name: a concealed library saved at `/weird\name.gpl` +/// is shown under its whole file name. Another platform's absolute path is still named by the part +/// after its last `\`. +#[cfg(not(windows))] +#[test] +fn a_concealed_library_keeps_a_backslash_in_its_file_name() { + let base = folder("backslash-name"); + let roots = AutomationRoots::new(&[&base.join("in")], &[]).unwrap(); + let native = format!("loaded/{}/weird\\name.gpl", text(&base.join("a"))); + let foreign = r"loaded/C:\Users\someone\other.gpl".to_string(); + let s = Session::new(); + let mut hidden = confine(roots.as_ref(), || cmd::swatchlib::concealed_library_ids(&s, [native.clone(), foreign.clone()])); + let _ = std::fs::remove_dir_all(base); + hidden.sort(); + let mut want = vec![(foreign, "loaded/other.gpl".to_string()), (native, "loaded/weird\\name.gpl".to_string())]; + want.sort(); + assert_eq!(hidden, want); +} + +/// A concealed library keeps the id a client was shown when another library with the same file name, +/// whose full id sorts before it, is loaded later: the id still finds the first library. +#[test] +fn a_concealed_library_keeps_its_id_after_another_with_its_file_name_loads() { + let base = folder("keeps-id"); + let roots = AutomationRoots::new(&[&base.join("in")], &[&base.join("out")]).unwrap(); + let (first, later) = (base.join("b").join("Kit.vcswatches"), base.join("a").join("Kit.vcswatches")); + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + (SWATCHES.add)(&mut s, "First"); + run(&mut s, "swatch.library.save", json!({"path": text(&first), "name": "Kit"})); + (SWATCHES.add)(&mut s, "Second"); + run(&mut s, "swatch.library.save", json!({"path": text(&later), "name": "Kit"})); + let shown = "loaded/Kit.vcswatches"; + let count = run(&mut s, "swatch.library.load", json!({"path": text(&first)}))["count"].clone(); + let list = confine(roots.as_ref(), || run(&mut s, "swatch.library.list", json!({}))); + assert_eq!(loaded(&list), [(json!(shown), Value::Null, count)], "{list}"); + run(&mut s, "swatch.library.load", json!({"path": text(&later)})); + let list = confine(roots.as_ref(), || run(&mut s, "swatch.library.list", json!({}))); + let ids: Vec = loaded(&list).into_iter().map(|(id, ..)| id).collect(); + assert_eq!(ids, [json!(shown), json!("loaded/Kit.vcswatches (2)")], "{list}"); + let theirs = run(&mut s, "swatch.library.get", json!({"library": format!("loaded/{}", text(&first))})); + let got = confine(roots.as_ref(), || run(&mut s, "swatch.library.get", json!({"library": shown}))); + assert_eq!((&got["id"], &got["swatches"]), (&json!(shown), &theirs["swatches"]), "the first library: {got}"); + let _ = std::fs::remove_dir_all(base); +} diff --git a/crates/engine/src/tests/linked_stops.rs b/crates/engine/src/tests/linked_stops.rs index 7f70d24ff0..9ed3db2724 100644 --- a/crates/engine/src/tests/linked_stops.rs +++ b/crates/engine/src/tests/linked_stops.rs @@ -416,6 +416,34 @@ fn spot_gradients_drawn_as_images_warn() { assert!(!spot_warning(&warnings), "{warnings:?}"); } +/// A spot gradient mixed around the hue wheel is an image in process colors with the warning, +/// where the same stops mixed by Perceptual are a Separation or DeviceN shading: the colors +/// between its stops are not tints or mixes of the stops' inks. +#[test] +fn hue_wheel_spot_gradients_export_as_images_and_warn() { + let (mut s, _) = setup(); + run(&mut s, "swatch.new", json!({"name": "Leaf", "color": {"c": 1, "m": 0, "y": 1, "k": 0}, "spot": true})); + let spot_warning = |w: &[String]| w.iter().any(|w| w.contains("spot colors in gradients exported as images")); + let ink_to_leaf = json!({"stops": [{"offset": 0, "swatch": "Ink"}, {"offset": 1, "swatch": "Leaf"}]}); + for method in ["hue-clockwise", "hue-counterclockwise"] { + for (what, stops) in [("Ink → paper", ink_to_white(80.0)), ("Ink → Leaf", ink_to_leaf.clone())] { + for kind in ["linear", "radial", "conic", "diamond"] { + run(&mut s, "paint.editGradient", with(stops.clone(), json!({"method": method, "kind": kind}))); + let (pdf, warnings) = pdf_of(&s); + assert!(pdf.contains("/Subtype/Image"), "{method} {kind} {what}: an image"); + assert!(!pdf.contains("/Separation") && !pdf.contains("/DeviceN"), "{method} {kind} {what}: no spot ink shading"); + assert!(spot_warning(&warnings), "{method} {kind} {what}: {warnings:?}"); + } + } + // Without spot inks: an image, without the warning. + let red_blue = json!({"stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}], "kind": "linear"}); + run(&mut s, "paint.editGradient", with(red_blue, json!({"method": method}))); + let (pdf, warnings) = pdf_of(&s); + assert!(pdf.contains("/Subtype/Image"), "{method}: a process gradient is an image"); + assert!(!spot_warning(&warnings), "{method}: {warnings:?}"); + } +} + #[test] fn freeform_gradients_without_points_warn_about_spot_stops() { let (mut s, id) = setup(); diff --git a/crates/engine/src/tests/linkfiles.rs b/crates/engine/src/tests/linkfiles.rs index 695ea41419..6f64a2fe33 100644 --- a/crates/engine/src/tests/linkfiles.rs +++ b/crates/engine/src/tests/linkfiles.rs @@ -14,12 +14,12 @@ use crate::cmd::linkfiles::{self, LinkSearch, Sought}; use crate::tests_links::{BLUE, RED, place, png}; use crate::{EngineError, Session}; -/// A fresh temporary folder (canonical, as a search reports it). -fn folder(tag: &str) -> PathBuf { - let dir = vectorcraft_testkit::temp_dir(&format!("linkfiles-{tag}")); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - findfiles::plain(std::fs::canonicalize(&dir).unwrap()) +/// A fresh temporary folder, removed when the first part is dropped, and its path (canonical, as a +/// search reports it). +fn folder(tag: &str) -> (vectorcraft_testkit::TempDir, PathBuf) { + let dir = vectorcraft_testkit::TempDir::new(&format!("linkfiles-{tag}")); + let path = findfiles::plain(std::fs::canonicalize(&*dir).unwrap()); + (dir, path) } /// Write `bytes` to the file at `path`, making its folders. @@ -80,7 +80,7 @@ fn found(r: &Value, name: &str, root: &Path) -> Vec<(String, String, bool)> { /// innermost out up to the first that differs. #[test] fn files_found_are_ranked_by_what_the_link_saved() { - let root = folder("rank"); + let (_dir, root) = folder("rank"); let mut s = session_for(&root); let (logo, photo) = (png(60, 40, RED), png(50, 30, BLUE)); write(&root.join("orig/logo.png"), &logo); @@ -127,7 +127,7 @@ fn files_found_are_ranked_by_what_the_link_saved() { /// the files found are ranked by the folder names they share with that path. #[test] fn a_classic_mac_path_is_found_by_its_name_and_folders() { - let root = folder("classic"); + let (_dir, root) = folder("classic"); let mut s = session_for(&root); let photo = png(50, 30, BLUE); write(&root.join("orig/photo.png"), &photo); @@ -158,7 +158,7 @@ fn a_classic_mac_path_is_found_by_its_name_and_folders() { #[test] fn parent_components_in_a_saved_path_are_resolved_before_ranking() { for (tag, saved) in [("classic-up", "Old Disk:Projects:Art::photo.png"), ("slash-up", "/old/Projects/Art/../photo.png")] { - let root = folder(tag); + let (_dir, root) = folder(tag); let mut s = session_for(&root); let photo = png(50, 30, BLUE); write(&root.join("orig/photo.png"), &photo); @@ -188,7 +188,7 @@ fn parent_components_in_a_saved_path_are_resolved_before_ranking() { /// files, whatever their status. #[test] fn a_search_looks_for_the_missing_files_or_the_objects_given() { - let root = folder("which"); + let (_dir, root) = folder("which"); let mut s = session_for(&root); write(&root.join("orig/gone.png"), &png(40, 30, RED)); write(&root.join("orig/here.png"), &png(40, 30, BLUE)); @@ -225,7 +225,7 @@ fn a_search_looks_for_the_missing_files_or_the_objects_given() { /// other contents leaves it to search every folder. #[test] fn a_search_ends_once_every_linked_file_has_its_same_file() { - let root = folder("early"); + let (_dir, root) = folder("early"); let mut s = session_for(&root); s.search_threads = Some(1); let bytes = png(40, 30, RED); @@ -265,13 +265,13 @@ impl Visitor for Blocked { #[test] fn stop_ends_only_the_search_it_names() { - let root = folder("stop"); + let (_dir, root) = folder("stop"); std::fs::write(root.join("a.png"), b"png").unwrap(); let mut s = session_for(&root); let (tx, rx) = mpsc::channel(); let search = findfiles::start(root.clone(), s.search_rules.clone(), Limits::default(), 1, 2, Arc::new(Blocked(Mutex::new(rx)))).unwrap(); let links = vec![Sought { name: "a.png".into(), path: "/gone/a.png".into(), ids: vec![], size: None, hash: None }]; - s.link_search = Some(LinkSearch { id: 7, folder: root.to_string_lossy().into_owned(), links, sizes: Arc::default(), search }); + s.link_search = Some(LinkSearch { id: 7, folder: root.to_string_lossy().into_owned(), doc: None, links, sizes: Arc::default(), search }); let until = Instant::now() + WAIT; while s.execute("links.findFiles", &json!({})).unwrap()["searched"]["read"] != 1 && Instant::now() < until { std::thread::sleep(Duration::from_millis(2)); @@ -284,9 +284,116 @@ fn stop_ends_only_the_search_it_names() { drop(tx); } +/// A caller confined by read roots sees, in the replies to a search another caller started and to +/// its own, only the paths inside its read roots: the files found outside them, a link's saved path +/// outside them and the folder searched are left out, and the rows, ids and counts stay. Without +/// roots, the replies are as before. +#[test] +fn a_search_shows_a_confined_caller_only_paths_inside_its_read_roots() { + let (_dir, root) = folder("read-roots"); + let mut s = session_for(&root); + let photo = png(40, 30, RED); + write(&root.join("lrf-away/photo.png"), &photo); + let id = placed(&mut s, &root.join("lrf-away/photo.png")); + std::fs::remove_file(root.join("lrf-away/photo.png")).unwrap(); + // Files of the name with other contents: the search reads every folder. + let other = png(40, 30, BLUE); + let (home, wide) = (root.join("home"), root.join("lrf-wide")); + write(&home.join("photo.png"), &other); + write(&wide.join("photo.png"), &other); + let roots = |read: &[&Path], write: &[&Path]| crate::file_access::AutomationRoots::new(read, write).unwrap().unwrap(); + let (narrow, write_only, broad) = (roots(&[&home], &[]), roots(&[], &[&root]), roots(&[&root], &[])); + let ask = |s: &mut Session, r: &Arc, p: Value| { + crate::file_access::confine(Some(r), || s.execute("links.findFiles", &p).unwrap()) + }; + let hidden = |r: &Value| { + let text = r.to_string(); + assert!(!text.contains("lrf-away") && !text.contains("lrf-wide") && r.get("folder").is_none(), "{r}"); + let row = &r["links"][0]; + assert_eq!((row["name"].as_str(), &row["ids"], row.get("path")), (Some("photo.png"), &json!([id]), None), "{r}"); + }; + // Started with the broad roots, over the whole folder. + let r = ask(&mut s, &broad, json!({"folder": root})); + assert_eq!(r["folder"], json!(root), "{r}"); + finished(&mut s); + let all = ask(&mut s, &broad, json!({})); + assert_eq!(all["links"][0]["files"].as_array().map(Vec::len), Some(2), "{all}"); + for r in [ask(&mut s, &narrow, json!({})), ask(&mut s, &narrow, json!({"stop": true}))] { + hidden(&r); + assert_eq!(r["links"][0]["files"], json!([{"path": home.join("photo.png"), "size": other.len(), "match": "name"}]), "{r}"); + assert_eq!((&r["state"], &r["searched"], &r["id"]), (&all["state"], &all["searched"], &all["id"]), "{r}"); + } + let r = ask(&mut s, &write_only, json!({})); + hidden(&r); + assert_eq!(r["links"][0]["files"], json!([]), "{r}"); + // Without roots, every path shows. + let r = s.execute("links.findFiles", &json!({})).unwrap(); + assert_eq!((&r["folder"], &r["links"][0]["path"]), (&json!(root), &json!(root.join("lrf-away/photo.png"))), "{r}"); + assert_eq!(r["links"][0]["files"].as_array().map(Vec::len), Some(2), "{r}"); + // The narrow caller's own search shows the folder it gave. + let r = ask(&mut s, &narrow, json!({"folder": home})); + assert_eq!(r["folder"], json!(home), "{r}"); + finished(&mut s); + let r = ask(&mut s, &narrow, json!({})); + assert_eq!((&r["folder"], r["links"][0].get("path")), (&json!(home), None), "{r}"); + // A search that failed: the reason shows without the path to a caller outside its folder. + ask(&mut s, &broad, json!({"folder": root.join("lrf-wide/gone")})); + let r = finished(&mut s); + assert!(r["error"].as_str().is_some_and(|e| e.contains("lrf-wide")), "{r}"); + let r = ask(&mut s, &narrow, json!({})); + assert_eq!((r["state"].as_str(), r["error"].as_str()), (Some("failed"), Some("the folder can't be read")), "{r}"); + hidden(&r); +} + +/// A link's saved path relative to the document is shown to a confined caller when it leads to a +/// file inside its read roots, and left out when `..` leads out of them. +#[test] +fn a_relative_link_path_is_judged_from_the_documents_folder() { + let (_dir, root) = folder("read-roots-relative"); + let mut s = session_for(&root); + let home = root.join("home"); + write(&root.join("lrf-away/photo.png"), &png(40, 30, RED)); + let id = placed(&mut s, &root.join("lrf-away/photo.png")); + std::fs::create_dir_all(&home).unwrap(); + s.execute("document.save", &json!({"path": home.join("poster.vectorcraft")})).unwrap(); + let narrow = crate::file_access::AutomationRoots::new(&[&home], &[]).unwrap().unwrap(); + for (saved, shown) in [("sub/photo.png", true), ("../lrf-away/photo.png", false)] { + s.edit("relative path", |d, _| { + if let NodeKind::Image(im) = &mut d.node_mut(NodeId(id)).unwrap().kind { + im.link.as_mut().unwrap().path = saved.into(); + } + Ok(()) + }) + .unwrap(); + let r = crate::file_access::confine(Some(&narrow), || s.execute("links.findFiles", &json!({"folder": home, "ids": [id]})).unwrap()); + assert_eq!(r["links"][0].get("path"), shown.then(|| json!(saved)).as_ref(), "{saved}: {r}"); + finished(&mut s); + } +} + +/// `image.info` leaves a linked file outside the confined caller's read roots unnamed (`link` +/// null), as `links.info` leaves it out, and keeps the other fields. +#[test] +fn image_info_leaves_out_a_link_outside_the_read_roots() { + let (_dir, root) = folder("read-roots-info"); + let mut s = session_for(&root); + let pic = root.join("lrf-away/photo.png"); + write(&pic, &png(40, 30, RED)); + let id = placed(&mut s, &pic); + std::fs::create_dir_all(root.join("home")).unwrap(); + let narrow = crate::file_access::AutomationRoots::new(&[&root.join("home")], &[]).unwrap().unwrap(); + let ask = |s: &mut Session, cmd: &str| crate::file_access::confine(Some(&narrow), || s.execute(cmd, &json!({"id": id})).unwrap()); + let r = ask(&mut s, "image.info"); + assert_eq!((&r["link"], &r["linked"], &r["pixelWidth"], &r["id"]), (&Value::Null, &json!(true), &json!(40), &json!(id)), "{r}"); + assert!(!r.to_string().contains("lrf-away"), "{r}"); + let info = ask(&mut s, "links.info"); + assert!(info.get("link").is_none() && !info.to_string().contains("lrf-away"), "{info}"); + assert_eq!(s.execute("image.info", &json!({"id": id})).unwrap()["link"], json!(pic)); +} + #[test] fn relinking_with_copy_puts_the_file_in_the_documents_folder() { - let root = folder("copy"); + let (_dir, root) = folder("copy"); let mut s = session_for(&root); write(&root.join("orig/photo.png"), &png(40, 30, RED)); let id = placed(&mut s, &root.join("orig/photo.png")); @@ -333,14 +440,13 @@ fn relinking_with_copy_puts_the_file_in_the_documents_folder() { let image = placed(&mut unsaved, &found); let r = unsaved.execute("links.relink", &json!({"ids": [image], "path": found, "copy": true})); assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg.contains("save the document first")), "{r:?}"); - let _ = std::fs::remove_dir_all(&root); } /// Copy takes images only: with copy, a call that includes a placed document fails and copies /// nothing; without it, the document is relinked where its file is. #[test] fn copy_refuses_placed_documents() { - let root = folder("copy-placed"); + let (_dir, root) = folder("copy-placed"); let mut s = session_for(&root); s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); let badge = root.join("badge.vectorcraft"); @@ -361,7 +467,7 @@ fn copy_refuses_placed_documents() { #[cfg(unix)] #[test] fn a_copy_stays_inside_the_write_root() { - let root = folder("roots"); + let (_dir, root) = folder("roots"); let mut s = session_for(&root); write(&root.join("orig/photo.png"), &png(40, 30, RED)); let id = placed(&mut s, &root.join("orig/photo.png")); @@ -377,14 +483,13 @@ fn a_copy_stays_inside_the_write_root() { assert!(matches!(&r, Err(EngineError::Other(m)) if m.contains("outside the write root")), "{r:?}"); assert!(!root.join("doc/photo 2.png").exists()); assert_eq!(std::fs::read(allowed.join("photo.png")).unwrap(), b"kept as it is"); - let _ = std::fs::remove_dir_all(&root); } /// An SVG's linked files are read on the importer's own thread (it needs a deep stack): the roots /// in force on the thread that opens the SVG hold there too. #[test] fn an_svg_reads_its_links_within_the_read_root() { - let root = folder("svg-roots"); + let (_dir, root) = folder("svg-roots"); for dir in ["in", "out"] { write(&root.join(dir).join("dot.png"), &png(4, 4, RED)); } @@ -403,12 +508,11 @@ fn an_svg_reads_its_links_within_the_read_root() { assert_eq!(import("in"), inside, "inside the read root: read as before"); assert_ne!(import("out"), outside, "outside the read root: not read"); }); - let _ = std::fs::remove_dir_all(&root); } #[test] fn junk_search_params_never_fail_internally() { - let root = folder("junk"); + let (_dir, root) = folder("junk"); let mut s = session_for(&root); write(&root.join("orig/a.png"), &png(4, 4, RED)); let id = placed(&mut s, &root.join("orig/a.png")); diff --git a/crates/engine/src/tests/links.rs b/crates/engine/src/tests/links.rs index f0a0674f08..e683b156e1 100644 --- a/crates/engine/src/tests/links.rs +++ b/crates/engine/src/tests/links.rs @@ -5,7 +5,7 @@ use std::path::{Path, PathBuf}; use serde_json::{Value, json}; -use vectorcraft_doc::{Document, ImageObject, LinkInfo, NodeKind}; +use vectorcraft_doc::{Document, ImageObject, LinkInfo, NodeKind, StoredRoot}; use vectorcraft_geom::Rect; use crate::*; @@ -446,8 +446,8 @@ fn links_outside_the_layers_find_their_files_after_the_folder_moves() { } /// With Update Links: Automatically, a file in a symbol and in the layers that changed and moved -/// with the document is read again for the layers' image and for the symbol's, and both links take -/// its new path, size and hash. +/// with the document is read again for the layers' image and for the symbol's, both are listed by +/// their ids, and both links take its new path, size and hash. #[test] fn a_symbols_link_to_a_moved_and_modified_file_takes_its_new_path() { let a = Folder::new("nested-modified-a"); @@ -458,13 +458,14 @@ fn a_symbols_link_to_a_moved_and_modified_file_takes_its_new_path() { s.execute("prefs.set", &json!({"key": "updateLinks", "value": "automatically"})).unwrap(); let id = place(&mut s, &pic); s.execute("symbol.new", &json!({"name": "Mark", "ids": [id.0]})).unwrap(); + let in_symbol = stored_image_in(&s, StoredRoot::Symbol(0)); let id = place(&mut s, &pic); save(&mut s, &a.file("poster.vectorcraft")); write(&pic, &png(30, 30, BLUE)); std::fs::remove_dir_all(&b.0).unwrap(); std::fs::rename(&a.0, &b.0).unwrap(); let r = open(&mut s, &b.file("poster.vectorcraft")); - assert_eq!((r["modifiedLinks"].clone(), r["updatedLinks"][0]["ids"].clone()), (json!([]), json!([id.0])), "{r}"); + assert_eq!((r["modifiedLinks"].clone(), r["updatedLinks"][0]["ids"].clone()), (json!([]), json!([id.0, in_symbol.0])), "{r}"); let moved = PathBuf::from(b.file("art/photo.png")); let blue = png(30, 30, BLUE); let mut images = vec![]; @@ -521,7 +522,8 @@ fn a_symbols_link_without_a_relative_path_follows_the_moved_file() { /// Update Links reads a changed file again for the images inside symbols, patterns and opacity /// masks too: those showing the same content as an image in the layers, and those no object in the -/// layers shows. Each takes the file's place as its own Placement Options say, in one undo step. +/// layers shows. Each takes the file's place as its own Placement Options say, in one undo step, +/// and the reply lists each by its id. #[test] fn update_links_reads_files_again_inside_symbols_patterns_and_masks() { let dir = Folder::new("nested-update"); @@ -533,11 +535,13 @@ fn update_links_reads_files_again_inside_symbols_patterns_and_masks() { let id = place(&mut s, &photo); s.execute("links.placementOptions", &json!({"ids": [id.0], "preserve": "fill", "clip": true})).unwrap(); s.execute("symbol.new", &json!({"name": "Mark", "ids": [id.0]})).unwrap(); + let in_symbol = stored_image_in(&s, StoredRoot::Symbol(0)); let id = place(&mut s, &photo); // logo.png only in a pattern and in an opacity mask. let p = place(&mut s, &logo); s.execute("object.pattern.make", &json!({"ids": [p.0], "edit": false})).unwrap(); s.execute("edit.clear", &json!({"ids": [p.0]})).unwrap(); + let p = stored_image_in(&s, StoredRoot::Pattern { pattern: 0, art: 0 }); let masked = super::rect(&mut s, 10.0, 10.0, 60.0, 60.0); let mask = place(&mut s, &logo); s.execute("transparency.makeOpacityMask", &json!({"ids": [masked.0, mask.0]})).unwrap(); @@ -546,7 +550,8 @@ fn update_links_reads_files_again_inside_symbols_patterns_and_masks() { write(&photo, &blue); write(&logo, &green); let u = s.execute("links.update", &json!({})).unwrap(); - assert_eq!(u, json!({"updated": [id.0], "missing": []})); + // By file: photo.png in the layers and the symbol, then logo.png in the mask and the pattern. + assert_eq!(u, json!({"updated": [id.0, in_symbol.0, mask.0, p.0], "missing": []})); // (name, size, hash, pixel size) of each image, which shows its file's pixels. let images = |s: &Session| { let d = &s.doc().unwrap().doc; @@ -576,6 +581,229 @@ fn update_links_reads_files_again_inside_symbols_patterns_and_masks() { assert!(images(&s).iter().all(|(_, _, _, size)| *size == (20, 10)), "{:?}", images(&s)); } +/// The files only art outside the layers shows: one in a symbol, a graph design, a pattern and an +/// opacity mask each, no object in the layers linked to any of them. +const NESTED: [&str; 4] = ["symbol.png", "design.png", "pattern.png", "mask.png"]; + +/// A document whose only links are [`NESTED`]'s files in `dir`. +fn nested_links(dir: &Folder) -> Session { + for (i, name) in (0u8..).zip(NESTED) { + write(&dir.file(name), &png(20, 10, [20 + 50 * i, 90, 160])); + } + let mut s = session(); + let id = place(&mut s, &dir.file("symbol.png")); + s.execute("symbol.new", &json!({"name": "Mark", "ids": [id.0]})).unwrap(); + s.execute("edit.clear", &json!({"ids": [s.doc().unwrap().selection.objects[0].0]})).unwrap(); + let id = place(&mut s, &dir.file("design.png")); + s.execute("graph.design", &json!({"new": "Bar"})).unwrap(); + s.execute("edit.clear", &json!({"ids": [id.0]})).unwrap(); + let id = place(&mut s, &dir.file("pattern.png")); + s.execute("object.pattern.make", &json!({"ids": [id.0], "edit": false})).unwrap(); + s.execute("edit.clear", &json!({"ids": [id.0]})).unwrap(); + let masked = super::rect(&mut s, 10.0, 10.0, 60.0, 60.0); + let mask = place(&mut s, &dir.file("mask.png")); + s.execute("transparency.makeOpacityMask", &json!({"ids": [masked.0, mask.0]})).unwrap(); + s.execute("select.set", &json!({"ids": []})).unwrap(); + s +} + +/// The id of the `links.list` row of file `name`. +fn row_id(s: &mut Session, name: &str) -> u64 { + let list = s.execute("links.list", &json!({})).unwrap(); + let row = list["links"].as_array().unwrap().iter().find(|r| r["name"] == name).unwrap_or_else(|| panic!("{name} in {list}")); + row["id"].as_u64().unwrap() +} + +/// The link of stored object `id`. +fn stored_link(s: &Session, id: u64) -> Option { + match &s.doc().unwrap().doc.stored_node(NodeId(id)).unwrap().0.kind { + NodeKind::Image(im) => im.link.clone(), + k => panic!("not an image: {k:?}"), + } +} + +/// The id of the first image stored in the art of `root`. +fn stored_image_in(s: &Session, root: StoredRoot) -> NodeId { + let mut found = None; + s.doc().unwrap().doc.visit_stored(|n, place| { + if found.is_none() && place.root == root && matches!(n.kind, NodeKind::Image(_)) { + found = Some(n.id); + } + }); + found.unwrap_or_else(|| panic!("no image in {root:?}")) +} + +/// Images in symbols, graph designs, patterns and opacity masks are listed and checked with ids of +/// their own, one row each with what holds it, and the missing filter counts them. +#[test] +fn links_outside_the_layers_are_listed_and_checked_with_ids() { + let dir = Folder::new("nested-ids"); + let mut s = nested_links(&dir); + let list = s.execute("links.list", &json!({})).unwrap(); + let rows = list["links"].as_array().unwrap(); + let owners: Vec<(&str, &str)> = rows.iter().map(|r| (r["name"].as_str().unwrap(), r["owner"]["kind"].as_str().unwrap_or("-"))).collect(); + assert_eq!(owners, [("mask.png", "layers"), ("symbol.png", "symbol"), ("design.png", "graphDesign"), ("pattern.png", "pattern")], "{list}"); + assert_eq!(rows[1]["owner"]["name"], "Mark"); + let masked = s.doc().unwrap().doc.layers[0].children().unwrap().iter().find(|n| n.extras().mask.is_some()).unwrap().id; + assert_eq!(rows[0]["owner"]["maskOf"], json!(masked.0)); + let ids: std::collections::BTreeSet = rows.iter().map(|r| r["id"].as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 4, "{list}"); + assert!(rows.iter().all(|r| r["status"] == "ok" && r["linked"] == true), "{list}"); + let check = s.execute("links.check", &json!({})).unwrap(); + let checked: Vec<(&str, &Value)> = check["links"].as_array().unwrap().iter().map(|l| (l["name"].as_str().unwrap(), &l["ids"])).collect(); + assert_eq!(checked.len(), 4, "{check}"); + for (name, ids) in checked { + assert_eq!(*ids, json!([row_id(&mut s, name)]), "{check}"); + } + std::fs::remove_file(dir.file("design.png")).unwrap(); + let check = s.execute("links.check", &json!({})).unwrap(); + assert_eq!((check["missing"].as_u64(), check["modified"].as_u64()), (Some(1), Some(0)), "{check}"); + let design = row_id(&mut s, "design.png"); + let missing = s.execute("links.list", &json!({"show": "missing"})).unwrap(); + assert_eq!((missing["missing"].as_u64(), &missing["links"][0]["id"]), (Some(1), &json!(design)), "{missing}"); + let one = s.execute("links.check", &json!({"ids": [design]})).unwrap(); + assert_eq!(one["links"][0]["status"], "missing", "{one}"); +} + +/// Every links command takes the id of an image outside the layers and acts on that object: Link +/// Info, Go To (which clears the selection and names the symbol), Placement Options, Relink, Update and +/// Embed. +#[test] +fn links_commands_act_on_images_outside_the_layers_by_id() { + let dir = Folder::new("nested-act"); + let mut s = nested_links(&dir); + let symbol = row_id(&mut s, "symbol.png"); + let info = s.execute("links.info", &json!({"id": symbol})).unwrap(); + assert_eq!((info["fileName"].as_str(), info["status"].as_str(), info["id"].as_u64()), (Some("symbol.png"), Some("ok"), Some(symbol)), "{info}"); + let other = super::rect(&mut s, 0.0, 0.0, 5.0, 5.0); + s.execute("select.set", &json!({"ids": [other.0]})).unwrap(); + let go = s.execute("links.goTo", &json!({"id": symbol})).unwrap(); + assert_eq!( + (go["onCanvas"].clone(), go["owner"]["kind"].clone(), go["owner"]["name"].clone()), + (json!(false), json!("symbol"), json!("Mark")), + "{go}" + ); + assert!(s.doc().unwrap().selection.objects.is_empty(), "nothing on the canvas is selected"); + s.execute("links.placementOptions", &json!({"ids": [symbol], "preserve": "fit"})).unwrap(); + let placement = s.execute("links.placementOptions", &json!({"ids": [symbol]})).unwrap(); + assert_eq!(placement["placement"]["preserve"], "fit"); + // Relink: the symbol's image shows the new file. + let other = dir.file("other.png"); + write(&other, &png(40, 20, BLUE)); + let r = s.execute("links.relink", &json!({"ids": [symbol], "path": other})).unwrap(); + assert_eq!(r["relinked"], json!([symbol]), "{r}"); + assert_eq!(stored_link(&s, symbol).unwrap().path, other); + // Update: a changed pattern file is read again for the pattern's image. + let pattern = row_id(&mut s, "pattern.png"); + let changed = png(30, 30, RED); + write(&dir.file("pattern.png"), &changed); + let r = s.execute("links.update", &json!({"ids": [pattern]})).unwrap(); + assert_eq!(r["updated"], json!([pattern]), "{r}"); + assert_eq!(stored_link(&s, pattern).unwrap().size, Some(changed.len() as u64)); + // Embed: the design's image keeps its pixels and no longer links. + let design = row_id(&mut s, "design.png"); + let r = s.execute("links.embed", &json!({"ids": [design]})).unwrap(); + assert_eq!(r["embedded"], json!([design]), "{r}"); + assert!(stored_link(&s, design).is_none()); + let row = s.execute("links.list", &json!({"show": "embedded"})).unwrap(); + assert_eq!(row["links"][0]["id"], json!(design), "{row}"); + // Relink All Instances takes the other stored objects linked to the same file. + let mask = row_id(&mut s, "mask.png"); + let r = s.execute("links.relink", &json!({"ids": [symbol], "path": dir.file("mask.png"), "scope": "all"})).unwrap(); + assert_eq!(r["relinked"], json!([symbol]), "{r}"); + let r = s.execute("links.relink", &json!({"ids": [mask], "path": other, "scope": "all"})).unwrap(); + let mut relinked: Vec = r["relinked"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + relinked.sort(); + let mut both = vec![symbol, mask]; + both.sort(); + assert_eq!(relinked, both, "{r}"); +} + +/// Opening a document reports missing and modified files that only art outside the layers shows, +/// by their objects' ids, and those ids stay the same after the document is saved and opened again. +#[test] +fn open_reports_links_outside_the_layers_by_id() { + let dir = Folder::new("nested-open"); + let mut s = nested_links(&dir); + let path = dir.file("poster.vectorcraft"); + save(&mut s, &path); + let ids: Vec = NESTED.iter().map(|name| row_id(&mut s, name)).collect(); + std::fs::remove_file(dir.file("symbol.png")).unwrap(); + write(&dir.file("pattern.png"), &png(30, 30, RED)); + let r = open(&mut s, &path); + let names = |k: &str| r[k].as_array().unwrap().iter().map(|l| (l["name"].as_str().unwrap().to_string(), l["ids"].clone())).collect::>(); + assert_eq!(names("missingLinks"), [("symbol.png".to_string(), json!([ids[0]]))], "{r}"); + assert_eq!(names("modifiedLinks"), [("pattern.png".to_string(), json!([ids[2]]))], "{r}"); + let again: Vec = NESTED.iter().map(|name| row_id(&mut s, name)).collect(); + assert_eq!(again, ids, "the ids are saved"); +} + +/// A document whose symbol and mask art repeat the ids of objects in the layers (or have none) +/// opens with ids of their own there, the layer tree's kept; the links commands then tell them apart. +#[test] +fn nested_objects_that_repeat_ids_open_with_ids_of_their_own() { + let dir = Folder::new("nested-repeat"); + let mut s = nested_links(&dir); + let layer_image = place(&mut s, &dir.file("symbol.png")); + let path = dir.file("poster.vectorcraft"); + save(&mut s, &path); + // The symbol's image takes the id of the image in the layers, the mask's image none. + let mut saved: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + saved["document"]["symbols"][0]["art"]["id"] = json!(layer_image.0); + let layer = &mut saved["document"]["layers"][0]["kind"]["children"]; + let masked = layer.as_array_mut().unwrap().iter_mut().find(|n| n.get("mask").is_some() || n["extras"].get("mask").is_some()).unwrap(); + let mask = if masked.get("mask").is_some() { &mut masked["mask"] } else { &mut masked["extras"]["mask"] }; + mask["art"]["id"] = json!(0); + std::fs::write(&path, serde_json::to_vec(&saved).unwrap()).unwrap(); + open(&mut s, &path); + let list = s.execute("links.list", &json!({})).unwrap(); + let ids: Vec = list["links"].as_array().unwrap().iter().map(|r| r["id"].as_u64().unwrap()).collect(); + let unique: std::collections::BTreeSet = ids.iter().copied().collect(); + assert_eq!((ids.len(), unique.len()), (5, 5), "{list}"); + assert!(!ids.contains(&0), "{list}"); + assert_eq!(list["links"][0]["id"], json!(layer_image.0), "the layer tree keeps its ids: {list}"); + let symbol = list["links"].as_array().unwrap().iter().find(|r| r["owner"]["kind"] == "symbol").unwrap()["id"].as_u64().unwrap(); + s.execute("links.embed", &json!({"ids": [symbol]})).unwrap(); + assert!(stored_link(&s, symbol).is_none()); + assert!(image(&s, layer_image).link.is_some(), "the image in the layers stays linked"); +} + +/// An image that Placement Options clip, alone in a group the user made, goes into a new clip group +/// inside that group when its file grows, in the layers and in a symbol's art; the user's group +/// stays a plain group. +#[test] +fn placement_options_clip_an_image_alone_in_a_group_inside_that_group() { + let dir = Folder::new("clip-in-group"); + let photo = dir.file("photo.png"); + write(&photo, &png(20, 10, RED)); + let mut s = session(); + let mut groups = vec![]; + for _ in 0..2 { + let id = place(&mut s, &photo); + s.execute("links.placementOptions", &json!({"ids": [id.0], "preserve": "fill", "clip": true})).unwrap(); + let g = NodeId(s.execute("object.group", &json!({"ids": [id.0]})).unwrap()["id"].as_u64().unwrap()); + groups.push((g, id)); + } + let (in_symbol, _) = groups[1]; + s.execute("symbol.new", &json!({"name": "Mark", "ids": [in_symbol.0]})).unwrap(); + write(&photo, &png(60, 20, BLUE)); + s.execute("links.update", &json!({})).unwrap(); + // A plain group holding just a clip group of a clipping path and an image. + let plain_of_clip = |n: &vectorcraft_doc::Node| match &n.kind { + NodeKind::Group { children, clip: false } => matches!(&children[..], [c] if matches!(&c.kind, + NodeKind::Group { children, clip: true } if matches!(&children[..], [p, im] + if matches!(p.kind, NodeKind::Path { clipping: true, .. }) && matches!(im.kind, NodeKind::Image(_))))), + _ => false, + }; + let d = &s.doc().unwrap().doc; + let (g, id) = groups[0]; + assert!(plain_of_clip(d.node(g).unwrap()), "{:?}", d.node(g)); + assert_ne!(d.parent_of(id), Some(g), "the image is in a new clip group"); + let mut found = false; + d.symbols[0].art.walk(&mut |n| found |= plain_of_clip(n)); + assert!(found, "{:?}", d.symbols[0].art); +} + #[test] fn a_missing_link_renders_its_preview_and_relinks() { let dir = Folder::new("missing"); @@ -728,6 +956,56 @@ fn relink_each_with_copy_copies_nothing_when_a_file_cant_be_read() { assert_eq!(link_path(&s, a), one); } +/// With copy, for a client whose read roots don't hold the document's folder: the reply names the +/// copy by its file name, and a copy refused there keeps the write root and names the folder and +/// the file by their names. +#[test] +fn relink_with_copy_names_the_documents_folder_by_its_name_outside_the_read_roots() { + use crate::file_access::{AutomationRoots, confine}; + + let dir = Folder::new("relink-copy-roots"); + let one = dir.file("doc/one.png"); + write(&one, &png(60, 30, RED)); + let mut s = session(); + let a = place(&mut s, &one); + save(&mut s, &dir.file("doc/poster.vectorcraft")); + let x = dir.file("new/x.png"); + write(&x, &png(60, 30, BLUE)); + let (new, doc) = (Path::new(&x).parent().unwrap().to_path_buf(), Path::new(&one).parent().unwrap().to_path_buf()); + let hidden = doc.to_string_lossy().into_owned(); + let p = json!({"ids": [a.0], "path": x, "copy": true}); + + let writes_there = AutomationRoots::new(&[new.as_path()], &[doc.as_path()]).unwrap(); + let r = confine(writes_there.as_ref(), || s.execute("links.relink", &p)).unwrap(); + assert_eq!(r["copied"], json!([{"from": x, "to": "x.png"}]), "{r}"); + assert!(!r.to_string().contains(&hidden), "{r}"); + std::fs::remove_file(dir.file("doc/x.png")).unwrap(); + + let elsewhere = AutomationRoots::new(&[new.as_path()], &[new.as_path()]).unwrap(); + let root = crate::cmd::findfiles::plain(std::fs::canonicalize(&new).unwrap()).display().to_string(); + let e = confine(elsewhere.as_ref(), || s.execute("links.relink", &p)).unwrap_err().to_string(); + assert_eq!(e, format!("doc: automation path rejected: outside the write root {root}: x.png")); + assert!(!Path::new(&dir.file("doc/x.png")).exists()); +} + +/// With copy, for a document whose path has no folder: outside the read roots the error does not +/// name the path, and without roots it names it whole. +#[test] +fn relink_with_copy_names_a_document_path_without_a_folder_as_the_request_may_see_it() { + use crate::file_access::{AutomationRoots, confine}; + + let dir = Folder::new("relink-copy-no-folder"); + let mut s = session(); + s.doc_mut().unwrap().path = Some("/".into()); + let p = json!({"path": dir.file("x.png"), "copy": true}); + let roots = AutomationRoots::new(&[dir.0.as_path()], &[dir.0.as_path()]).unwrap(); + let e = confine(roots.as_ref(), || s.execute("links.relink", &p)).unwrap_err().to_string(); + assert_eq!(e, "invalid parameters for `links.relink`: a file or folder outside the read roots has no folder"); + let whole = s.execute("links.relink", &p).unwrap_err().to_string(); + let doc = crate::cmd::fileio::absolute_path("/"); + assert_eq!(whole, format!("invalid parameters for `links.relink`: {doc} has no folder")); +} + /// A scope or paths that doesn't fit is refused, and nothing is relinked. #[test] fn relink_refuses_scopes_and_paths_that_dont_fit() { diff --git a/crates/engine/src/tests/linkspanel.rs b/crates/engine/src/tests/linkspanel.rs index 56784b69d9..a9a3a17ec7 100644 --- a/crates/engine/src/tests/linkspanel.rs +++ b/crates/engine/src/tests/linkspanel.rs @@ -213,7 +213,7 @@ fn go_to_selects_the_image() { run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})); assert_ne!(s.doc().unwrap().selection.objects, vec![id]); let r = run(&mut s, "links.goTo", json!({"id": id.0})); - assert_eq!(r, json!({"id": id.0, "bounds": [-100.0, 0.0, 500.0, 300.0]})); + assert_eq!(r, json!({"id": id.0, "bounds": [-100.0, 0.0, 500.0, 300.0], "onCanvas": true})); assert_eq!(s.doc().unwrap().selection.objects, vec![id]); let rect = s.doc().unwrap().doc.layers[0].children().unwrap()[1].id; assert!(s.execute("links.goTo", &json!({"id": rect.0})).is_err(), "not an image"); @@ -296,6 +296,59 @@ fn link_info_stays_within_the_asking_callers_roots() { assert_ne!(i["status"], "ok", "{i}"); } +/// A confined caller's `links.list`, `links.check` and `links.info` replies, and its +/// `document.open` reply, leave out the path and folder of a linked file outside its read roots +/// and keep the row with the file's name. A file found by name inside the roots shows its path. +#[test] +fn link_paths_outside_the_read_roots_are_left_out() { + let away = Folder::new("lrr-away"); + let home = Folder::new("lrr-home"); + let pic = away.file("photo.png"); + let bytes = png(60, 30, RED); + write(&pic, &bytes); + let mut s = session(); + let id = place(&mut s, &pic); + let roots = crate::file_access::AutomationRoots::new(&[&home.0], &[]).unwrap().unwrap(); + let ask = |s: &mut Session, cmd: &str, p: Value| crate::file_access::confine(Some(&roots), || run(s, cmd, p)); + let hidden = |r: &Value| assert!(!r.to_string().contains("lrr-away"), "{r}"); + let list = ask(&mut s, "links.list", json!({})); + hidden(&list); + let row = &list["links"][0]; + assert_eq!((row["id"].as_u64(), row["name"].as_str(), row["status"].as_str()), (Some(id.0), Some("photo.png"), Some("missing")), "{list}"); + let check = ask(&mut s, "links.check", json!({})); + hidden(&check); + assert_eq!((check["links"][0]["name"].as_str(), check["missing"].as_u64()), (Some("photo.png"), Some(1)), "{check}"); + let info = ask(&mut s, "links.info", json!({"id": id.0})); + hidden(&info); + assert_eq!( + (info["fileName"].as_str(), info["status"].as_str(), info["linked"].as_bool()), + (Some("photo.png"), Some("missing"), Some(true)), + "{info}" + ); + for k in ["path", "link", "location", "fileSize", "modified", "created"] { + assert!(info.get(k).is_none(), "{k}: {info}"); + } + // Unconfined, the same replies carry the paths. + assert_eq!(run(&mut s, "links.list", json!({}))["links"][0]["path"], json!(pic)); + let i = run(&mut s, "links.info", json!({"id": id.0})); + assert_eq!((&i["path"], &i["link"], i["fileSize"].as_u64()), (&json!(pic), &json!(pic), Some(bytes.len() as u64)), "{i}"); + // Saved inside the roots next to a copy of the file: the copy is found by name and shown. + save(&mut s, &home.file("poster.vectorcraft")); + let copy = home.file("photo.png"); + write(©, &bytes); + let check = ask(&mut s, "links.check", json!({})); + hidden(&check); + assert_eq!((check["links"][0]["status"].as_str(), &check["links"][0]["found"]), (Some("ok"), &json!(copy)), "{check}"); + let list = ask(&mut s, "links.list", json!({})); + hidden(&list); + assert_eq!(list["links"][0]["found"], json!(copy), "{list}"); + // Opened again without the copy: the missing link's row has no path. + std::fs::remove_file(©).unwrap(); + let opened = ask(&mut Session::new(), "document.open", json!({"path": home.file("poster.vectorcraft")})); + hidden(&opened); + assert_eq!(opened["missingLinks"][0]["name"], "photo.png", "{opened}"); +} + /// A 600×300 pt image at the centre of the artboard, its placement options set to `options`, /// relinked to a 300×100 px file → the image's id and session. fn relinked(name: &str, options: Value) -> (Session, NodeId, Folder) { diff --git a/crates/engine/src/tests/linkwatch.rs b/crates/engine/src/tests/linkwatch.rs index 7fc8f0a4ba..0a5b9d7dbe 100644 --- a/crates/engine/src/tests/linkwatch.rs +++ b/crates/engine/src/tests/linkwatch.rs @@ -47,6 +47,30 @@ fn update_changed_reads_changed_files_again_once() { assert_eq!(s.execute("links.check", &json!({})).unwrap()["modified"], 1); } +/// A file only a symbol's art shows is watched too, and read again by the id of the symbol's image. +#[test] +fn update_changed_reads_a_file_only_a_symbol_shows() { + let dir = Folder::new("watch-symbol"); + let path = dir.file("art.png"); + std::fs::write(&path, png(40, 40, RED)).unwrap(); + let mut s = session(); + let id = place(&mut s, &path); + s.execute("symbol.new", &json!({"name": "Mark", "ids": [id.0]})).unwrap(); + let instance = s.doc().unwrap().selection.objects[0]; + s.execute("edit.clear", &json!({"ids": [instance.0]})).unwrap(); + let mut in_symbol = None; + s.doc().unwrap().doc.symbols[0].art.walk(&mut |n| { + if matches!(n.kind, vectorcraft_doc::NodeKind::Image(_)) { + in_symbol = Some(n.id.0); + } + }); + let in_symbol = in_symbol.expect("the symbol's image"); + assert_eq!(s.execute("links.updateChanged", &json!({})).unwrap()["updated"], json!([])); + save(&path, &png(40, 40, BLUE)); + assert_eq!(s.execute("links.updateChanged", &json!({})).unwrap()["updated"], json!([in_symbol])); + assert_eq!(s.execute("links.check", &json!({})).unwrap()["modified"], 0); +} + #[test] fn a_background_look_follows_update_links() { for (mode, key) in [("automatically", "updated"), ("askWhenModified", "ask"), ("manually", "modified")] { diff --git a/crates/engine/src/tests/live.rs b/crates/engine/src/tests/live.rs index 9fc790efa2..c372bcf784 100644 --- a/crates/engine/src/tests/live.rs +++ b/crates/engine/src/tests/live.rs @@ -424,6 +424,93 @@ fn blend_replace_spine_follows_path() { assert!(first.distance(Point::new(100.0, 300.0)) < 1.0, "{first:?}"); } +/// #6809: after Replace Spine, moving a key object moves the drawn key and its end of the spine, +/// not only the key's selection outline. +#[test] +fn moving_a_key_of_a_replaced_spine_blend_moves_what_is_drawn() { + let mut s = session(); + let (a, _, g) = blend(&mut s, json!({"steps": 5})); + let arc = id_of(&s.execute("path.create", &json!({"d": "M100 300 C100 245 145 200 200 200 C255 200 300 245 300 300"})).unwrap()); + sel(&mut s, &[g, arc]); + s.execute("object.blend.replaceSpine", &json!({})).unwrap(); + let center = |n: &Node| n.geometric_bounds().unwrap().center(); + let before = steps_of(&s, g); + assert!(center(&before[0]).distance(Point::new(100.0, 300.0)) < 1e-6); + // Direct Selection picks the key inside the blend; the drag moves it. + sel(&mut s, &[a]); + s.execute("object.move", &json!({"dx": -50, "dy": 40})).unwrap(); + let key = center(&node(&s, a)); + assert!(key.distance(Point::new(50.0, 340.0)) < 1e-6, "{key:?}"); + let after = steps_of(&s, g); + assert_eq!(after.len(), before.len()); + let drawn = center(&after[0]); + assert!(drawn.distance(key) < 1e-6, "the key is drawn where it was moved to: {drawn:?}, outline at {key:?}"); + assert!(center(&after[1]).distance(center(&before[1])) > 1.0, "the first step follows the moved key"); + let last = center(&after[after.len() - 1]); + assert!(last.distance(Point::new(300.0, 300.0)) < 1e-6, "the other key stays put: {last:?}"); + // Undo puts the key back on the spine as Replace Spine left it. + s.execute("edit.undo", &json!({})).unwrap(); + let back = steps_of(&s, g); + assert!(center(&back[0]).distance(Point::new(100.0, 300.0)) < 1e-6); + assert!(center(&back[1]).distance(center(&before[1])) < 1e-6); +} + +/// #6809 on a closed spine, where both end keys start on its first point: moving the first key +/// moves its end of the spine without dragging the last key's end along. +#[test] +fn moving_the_first_key_of_a_closed_replaced_spine_blend_moves_what_is_drawn() { + let mut s = session(); + let (a, _, g) = blend(&mut s, json!({"steps": 5})); + let square = id_of(&s.execute("path.create", &json!({"d": "M100 100 L300 100 L300 300 L100 300 Z"})).unwrap()); + sel(&mut s, &[g, square]); + s.execute("object.blend.replaceSpine", &json!({})).unwrap(); + let center = |n: &Node| n.geometric_bounds().unwrap().center(); + let before = steps_of(&s, g); + assert!(center(&before[0]).distance(Point::new(100.0, 100.0)) < 1e-6); + sel(&mut s, &[a]); + s.execute("object.move", &json!({"dx": -50, "dy": -40})).unwrap(); + let key = center(&node(&s, a)); + assert!(key.distance(Point::new(50.0, 60.0)) < 1e-6, "{key:?}"); + let after = steps_of(&s, g); + assert_eq!(after.len(), before.len()); + let drawn = center(&after[0]); + assert!(drawn.distance(key) < 1e-6, "the key is drawn where it was moved to: {drawn:?}, outline at {key:?}"); + assert!(center(&after[1]).distance(center(&before[1])) > 1.0, "the first step follows the moved key"); + let last = center(&after[after.len() - 1]); + assert!(last.distance(Point::new(100.0, 100.0)) < 1e-6, "the other key stays put: {last:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + let back = steps_of(&s, g); + assert!(center(&back[0]).distance(Point::new(100.0, 100.0)) < 1e-6); + assert!(center(&back[1]).distance(center(&before[1])) < 1e-6); +} + +/// #6809 on a closed spine pinned by a spine edit: the end keys get points of their own, so +/// moving the first key afterwards still moves only its end. +#[test] +fn moving_the_first_key_of_a_pinned_closed_spine_blend_moves_what_is_drawn() { + let mut s = session(); + let (a, _, g) = blend(&mut s, json!({"steps": 5})); + let square = id_of(&s.execute("path.create", &json!({"d": "M100 100 L300 100 L300 300 L100 300 Z"})).unwrap()); + sel(&mut s, &[g, square]); + s.execute("object.blend.replaceSpine", &json!({})).unwrap(); + // Dragging a corner away from the keys pins the spine to them. + s.execute("object.blend.spine.moveAnchor", &json!({"id": g.0, "anchor": 2, "x": 320, "y": 320})).unwrap(); + let NodeKind::Blend { spec, .. } = node(&s, g).kind else { panic!() }; + assert_eq!(spec.key_anchors.len(), 2, "{:?}", spec.key_anchors); + let center = |n: &Node| n.geometric_bounds().unwrap().center(); + let before = steps_of(&s, g); + sel(&mut s, &[a]); + s.execute("object.move", &json!({"dx": -50, "dy": -40})).unwrap(); + let key = center(&node(&s, a)); + assert!(key.distance(Point::new(50.0, 60.0)) < 1e-6, "{key:?}"); + let after = steps_of(&s, g); + assert_eq!(after.len(), before.len()); + let drawn = center(&after[0]); + assert!(drawn.distance(key) < 1e-6, "the key is drawn where it was moved to: {drawn:?}, outline at {key:?}"); + let last = center(&after[after.len() - 1]); + assert!(last.distance(Point::new(100.0, 100.0)) < 1e-6, "the other key stays put: {last:?}"); +} + #[test] fn blend_align_to_path_rotates_steps() { let mut s = session(); @@ -483,8 +570,8 @@ fn envelope_warp_make_and_content_stays_inside_bounds() { let pts = all_anchors(&out); assert!(pts.len() > 4, "curves are subdivided"); assert!(pts.iter().all(|p| b.contains(*p)), "{b:?}"); - // It really is bent: the sides moved down. - assert!(pts.iter().any(|p| p.y > 201.0)); + // It really is bent: the top corners swung out past the sides. + assert!(pts.iter().any(|p| p.x < 99.0) && pts.iter().any(|p| p.x > 301.0)); } #[test] @@ -556,6 +643,32 @@ fn envelope_top_object_shares_a_side_by_control_polygon_length() { assert!(near(Point::new(500.0, 200.0)) < 0.5, "the middle of the bottom: {pts:?}"); } +#[test] +fn envelope_top_object_keeps_its_look_when_anchors_are_added() { + // Add Anchor Points splits each segment of the top object in two without changing its shape. + // The top curve's parameter runs fast at its start, so its halves have control polygons of + // different lengths; the envelope still bends the two rectangles as the unsplit curve does. + let made = |add_anchors: bool| { + let mut s = session(); + let left = rect(&mut s, 100.0, 100.0, 100.0, 100.0); + let right = rect(&mut s, 200.0, 100.0, 100.0, 100.0); + let d = "M400 100 C520 40 590 70 600 100 L600 200 L400 200 Z"; + let t = id_of(&s.execute("path.create", &json!({ "d": d })).unwrap()); + if add_anchors { + sel(&mut s, &[t]); + s.execute("object.path.addAnchorPoints", &json!({})).unwrap(); + assert_eq!(node(&s, t).path_data().map(|p| p.anchor_count()), Some(8)); + } + sel(&mut s, &[left, right, t]); + let e = id_of(&s.execute("object.envelope.makeWithTopObject", &json!({})).unwrap()); + all_anchors(&live::expand_live(&node(&s, e))) + }; + let (plain, split) = (made(false), made(true)); + assert_eq!(plain.len(), split.len()); + let off = plain.iter().zip(&split).map(|(p, q)| p.distance(*q)).fold(0.0, f64::max); + assert!(off < 1e-6, "the art moves by up to {off} pt"); +} + #[test] fn envelope_release_and_expand() { let mut s = session(); @@ -1049,7 +1162,12 @@ fn mesh_points_move_and_colour_together() { assert!(s.execute("object.mesh.movePoints", &p).is_err(), "{p}"); } assert!(s.execute("object.mesh.setPointColor", &json!({"id": a.0, "points": [0, 9], "color": "#000000"})).is_err()); - assert_eq!(((mesh_of(&s, a), mesh_of(&s, b)), undo_len(&s)), (before, n), "nothing changed"); + assert_eq!(((mesh_of(&s, a), mesh_of(&s, b)), undo_len(&s)), (before.clone(), n), "nothing changed"); + // A call that changes no point records no undo step. + s.execute("object.mesh.movePoints", &json!({"id": a.0, "points": [], "dx": 1, "dy": 1})).unwrap(); + s.execute("object.mesh.movePoints", &json!({"id": a.0, "points": [0, 1], "dx": 0, "dy": 0})).unwrap(); + s.execute("object.mesh.setPointColor", &json!({"id": a.0, "points": [2, 6], "color": "#0000ff", "opacity": 0.25})).unwrap(); + assert_eq!(((mesh_of(&s, a), mesh_of(&s, b)), undo_len(&s)), (before, n), "no change, no undo step"); } #[test] @@ -1097,6 +1215,47 @@ fn mesh_add_line_on_the_edge_from_just_outside() { assert!(s.execute("object.mesh.addLine", &json!({"id": a.0, "x": 140, "y": 210, "tolerance": 3})).is_err(), "past the tolerance"); } +/// `object.mesh.addLine` and Create Gradient Mesh `at` a point exactly on the outline add their +/// lines there with no tolerance, on the bottom and right edges as on the top and left ones. +#[test] +fn mesh_add_line_exactly_on_the_edge_needs_no_tolerance() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + sel(&mut s, &[a]); + let r = s.execute("object.mesh.create", &json!({"at": [50, 100]})).unwrap(); + let m = mesh_of(&s, a); + assert_eq!((m.rows, m.cols), (1, 2), "a column through the bottom edge"); + assert!(m.points[r["index"].as_u64().unwrap() as usize].p.distance(Point::new(50.0, 100.0)) < 0.5); + for (x, y) in [(100.0, 30.0), (20.0, 0.0), (0.0, 80.0)] { + let r = s.execute("object.mesh.addLine", &json!({"id": a.0, "x": x, "y": y})).unwrap(); + let p = mesh_of(&s, a).points[r["index"].as_u64().unwrap() as usize].p; + assert!(p.distance(Point::new(x, y)) < 0.5, "({x}, {y}): {p:?}"); + } + assert_eq!((mesh_of(&s, a).rows, mesh_of(&s, a).cols), (3, 3)); + let n = undo_len(&s); + assert!(s.execute("object.mesh.addLine", &json!({"id": a.0, "x": 60, "y": 100.01})).is_err(), "just outside"); + assert_eq!(undo_len(&s), n, "nothing changed"); +} + +/// `object.mesh.addLine` at a point that is already a mesh point (a corner, a point on an edge or +/// inside) adds no line and records no undo step; with a new `color` there it is one step. +#[test] +fn mesh_add_line_at_a_mesh_point_records_no_undo_step() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + sel(&mut s, &[a]); + s.execute("object.mesh.create", &json!({"rows": 2, "cols": 2})).unwrap(); + let (before, n) = (mesh_of(&s, a), undo_len(&s)); + for (x, y) in [(0.0, 0.0), (100.0, 100.0), (50.0, 100.0), (100.0, 50.0), (50.0, 50.0)] { + let r = s.execute("object.mesh.addLine", &json!({"id": a.0, "x": x, "y": y})).unwrap(); + let p = mesh_of(&s, a).points[r["index"].as_u64().unwrap() as usize].p; + assert!(p.distance(Point::new(x, y)) < 0.5, "({x}, {y}): {p:?}"); + assert_eq!((mesh_of(&s, a), undo_len(&s)), (before.clone(), n), "({x}, {y}): nothing changed"); + } + s.execute("object.mesh.addLine", &json!({"id": a.0, "x": 100, "y": 100, "color": "#00ff00"})).unwrap(); + assert_eq!(undo_len(&s), n + 1, "a new color is a step"); +} + /// A mesh point `index`, and `rows`, `cols` or `columns` for Create Gradient Mesh, that is not a /// whole number is an error that changes nothing; 4.0 names point 4. #[test] diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index e9a30c57e1..abb0bf31eb 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -1855,6 +1855,38 @@ fn convert_to_artboards_names_by_the_artboards_the_document_has() { assert_eq!(name_after(&|s| _ = s.execute("edit.undo", &json!({})).unwrap()), "Artboard 3"); } +/// Convert to Artboards on several objects gives each new artboard an id above the ids given out +/// before and the deleted artboard's, and names it one past the highest id the artboards have, +/// counting the artboards it has just added. With an artboard whose id is `u32::MAX` (a damaged +/// file), each new artboard takes the smallest free id and the name stays at `u32::MAX`. +#[test] +fn convert_to_artboards_gives_each_object_the_next_id_and_name() { + let convert = |s: &mut Session| { + let ids: Vec = (0..3).map(|i| rect(s, 3000.0 + 300.0 * f64::from(i), 0.0, 200.0, 100.0)).collect(); + sel(s, &ids); + assert_eq!(s.execute("artboard.convertToArtboards", &json!({})).unwrap()["artboards"], 3); + let d = &s.doc().unwrap().doc; + d.artboards.iter().map(|a| (a.id, a.name.clone())).collect::>() + }; + let named = |pairs: &[(u32, &str)]| pairs.iter().map(|&(id, n)| (id, n.to_string())).collect::>(); + + // Artboards 1 and 2 are left after artboard 3 is deleted, so its id stays given out. + let mut s = session(); + s.execute("artboard.new", &json!({})).unwrap(); + s.execute("artboard.new", &json!({})).unwrap(); + s.execute("artboard.delete", &json!({"index": 2})).unwrap(); + let ids: Vec = s.doc().unwrap().doc.artboards.iter().map(|a| a.id).collect(); + assert_eq!(ids, [1, 2]); + let got = convert(&mut s); + assert_eq!(got, named(&[(1, "Artboard 1"), (2, "Artboard 2"), (4, "Artboard 3"), (5, "Artboard 5"), (6, "Artboard 6")])); + + let mut s = session(); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).artboards[0].id = u32::MAX; + let got = convert(&mut s); + let top = format!("Artboard {}", u32::MAX); + assert_eq!(got, named(&[(u32::MAX, "Artboard 1"), (1, &top), (2, &top), (3, &top)])); +} + /// Rearrange All Artboards refuses `columns` that are not a whole number (a fraction, a negative number or a string), /// and the artboards stay where they were; 1.0, as the Rearrange All Artboards dialog sends a count, is one column. #[test] @@ -4008,9 +4040,11 @@ fn ruler_guides_select_move_and_delete() { assert!(selected(&s).is_empty()); assert_eq!(s.execute("guide.select", &json!({"indexes": [1], "toggle": true})).unwrap()["selected"], json!([0, 1])); let layer = s.doc().unwrap().current_layer().unwrap().0; + let id = s.doc().unwrap().doc.ruler_guides()[1].id.unwrap().0; assert_eq!( s.execute("guide.list", &json!({})).unwrap()[1], - json!({"index": 1, "vertical": false, "pos": 50.0, "selected": true, "layer": layer, "shown": true, "editable": true}) + json!({"index": 1, "id": id, "vertical": false, "pos": 50.0, "selected": true, "layer": layer, + "hidden": false, "locked": false, "shown": true, "editable": true}) ); assert!(s.execute("guide.select", &json!({"indexes": [7]})).is_err()); // A move takes each selected guide along its own axis, in one undo step. @@ -4107,6 +4141,60 @@ fn invalid_clear_guides_parameters_delete_nothing() { assert_eq!(guides(&s).len(), 1); } +/// Run `cmd` with `params`, expect an error naming `msg`, and check that the documents, the undo +/// history, the guides, the saved selections and the selection are as they were. +fn refuses_wrong_type(s: &mut Session, cmd: &str, params: Value, msg: &str) { + let state = |s: &Session| { + let st = s.doc().unwrap(); + (s.documents().len(), undo_len(s), guides(s), st.doc.saved_selections.clone(), st.selection.clone()) + }; + let before = state(s); + match s.execute(cmd, ¶ms) { + Ok(v) => panic!("{cmd} accepted {params}: {v}"), + Err(e) => assert!(e.to_string().contains(msg), "{cmd} {params}: {e}"), + } + assert!(state(s) == before, "{cmd} changed something for {params}"); +} + +#[test] +fn edit_guide_and_slice_commands_refuse_params_of_the_wrong_type() { + let mut s = session(); + let a = rect(&mut s, 10.0, 10.0, 40.0, 20.0); + s.execute("guide.add", &json!({"vertical": true, "pos": 200})).unwrap(); + let slice = s.execute("object.slice.fromSelection", &json!({"ids": [a.0]})).unwrap()["id"].as_u64().unwrap(); + sel(&mut s, &[a]); + s.execute("select.save", &json!({"name": "A"})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + for (cmd, params, msg) in [ + ("edit.duplicate", json!({"dx": "5"}), "`dx` must be a number, not \"5\""), + ("edit.duplicate", json!({"dy": true}), "`dy` must be a number, not true"), + ("edit.paste", json!({"dx": "5"}), "`dx` must be a number, not \"5\""), + ("edit.paste", json!({"dy": [1]}), "`dy` must be a number, not [1]"), + ("document.node", json!({"id": a.0, "summary": "yes"}), "`summary` must be true or false"), + ("file.close", json!({"index": "0"}), "`index` must be a non-negative integer"), + ("guide.add", json!({"pos": 50, "vertical": "true"}), "`vertical` must be true or false"), + ("guide.select", json!({"indexes": [0], "toggle": 1}), "`toggle` must be true or false"), + ("select.save", json!({"name": 5}), "`name` must be a string"), + ("select.editSaved", json!({"name": "A", "delete": "yes"}), "`delete` must be true or false"), + ("select.editSaved", json!({"name": "A", "newName": 5}), "`newName` must be a string"), + ] { + refuses_wrong_type(&mut s, cmd, params, msg); + } + s.execute("guide.select", &json!({"indexes": [0]})).unwrap(); + refuses_wrong_type(&mut s, "guide.move", json!({"dx": "10"}), "`dx` must be a number, not \"10\""); + refuses_wrong_type(&mut s, "guide.move", json!({"dy": 5, "copy": "yes"}), "`copy` must be true or false"); + s.execute("object.slice.select", &json!({"slices": [slice]})).unwrap(); + refuses_wrong_type(&mut s, "object.slice.duplicate", json!({"dx": "10"}), "`dx` must be a number, not \"10\""); + refuses_wrong_type(&mut s, "object.slice.select", json!({"slices": [slice], "toggle": "no"}), "`toggle` must be true or false"); + s.execute("edit.undoGroup.begin", &json!({})).unwrap(); + refuses_wrong_type(&mut s, "edit.undoGroup.end", json!({"cancel": "yes"}), "`cancel` must be true or false"); + // Null is read as a key left out. + s.execute("edit.undoGroup.end", &json!({"cancel": null})).unwrap(); + s.execute("guide.select", &json!({"indexes": [0]})).unwrap(); + s.execute("guide.move", &json!({"dx": 10, "dy": null, "copy": null})).unwrap(); + assert_eq!(guides(&s), vec![(true, 210.0)]); +} + /// When ruler guides and art are selected together, moving the art moves the guides as well; /// copy leaves both in place and moves the copies; single undo reverts both. #[test] @@ -4237,11 +4325,14 @@ fn artboard_guides_go_with_their_artboard() { s.execute("guide.add", &json!({"vertical": false, "pos": 100})).unwrap(); let list = |s: &mut Session| s.execute("guide.list", &json!({})).unwrap(); let layer = s.doc().unwrap().current_layer().unwrap().0; + let ids: Vec = s.doc().unwrap().doc.ruler_guides().iter().map(|g| g.id.unwrap().0).collect(); assert_eq!( list(&mut s), json!([ - {"index": 0, "vertical": true, "pos": 1000.0, "selected": false, "artboard": 1, "layer": layer, "shown": true, "editable": true}, - {"index": 1, "vertical": false, "pos": 100.0, "selected": false, "layer": layer, "shown": true, "editable": true}, + {"index": 0, "id": ids[0], "vertical": true, "pos": 1000.0, "selected": false, "artboard": 1, "layer": layer, + "hidden": false, "locked": false, "shown": true, "editable": true}, + {"index": 1, "id": ids[1], "vertical": false, "pos": 100.0, "selected": false, "layer": layer, + "hidden": false, "locked": false, "shown": true, "editable": true}, ]) ); let spans = |s: &Session| { @@ -4282,7 +4373,8 @@ fn artboard_guides_go_with_their_artboard() { assert_eq!((guides(&s).len(), selected_guides(&s)), (3, vec![0, 1])); assert_eq!( list(&mut s)[0], - json!({"index": 0, "vertical": false, "pos": 100.0, "selected": true, "layer": layer, "shown": true, "editable": true}) + json!({"index": 0, "id": ids[1], "vertical": false, "pos": 100.0, "selected": true, "layer": layer, + "hidden": false, "locked": false, "shown": true, "editable": true}) ); assert_eq!(undo_len(&s), n + 1); s.execute("edit.undo", &json!({})).unwrap(); @@ -4326,9 +4418,11 @@ fn guides_dragged_out_of_a_ruler_snap_and_take_the_artboard_tool_s_artboard() { s.ruler_guide(false, &ev(PointerKind::Drag, 1000.0, 50.0), true, v).unwrap(); s.ruler_guide(false, &ev(PointerKind::Up, 1000.0, 50.0), true, v).unwrap(); let layer = s.doc().unwrap().current_layer().unwrap().0; + let id = s.doc().unwrap().doc.ruler_guides()[1].id.unwrap().0; assert_eq!( s.execute("guide.list", &json!({})).unwrap()[1], - json!({"index": 1, "vertical": false, "pos": 50.0, "selected": false, "artboard": 1, "layer": layer, "shown": true, "editable": true}) + json!({"index": 1, "id": id, "vertical": false, "pos": 50.0, "selected": false, "artboard": 1, "layer": layer, + "hidden": false, "locked": false, "shown": true, "editable": true}) ); } @@ -4403,6 +4497,41 @@ fn cmd_ruler_drags_make_guides_of_the_active_artboard_when_the_preference_is_on( assert_eq!(owners(&mut s)[4..], [Value::Null, json!(1)]); } +/// The rulers' origin dragged out of their corner snaps as a drawn point does: onto a shape's +/// corner and edge, the artboard's centre, and with Snap to Point along a ruler guide; with +/// nothing on it stays at the pointer. The drag changes nothing, and its guides go when it ends. +#[test] +fn the_ruler_origin_dragged_from_the_corner_snaps_as_a_drawn_point() { + use vectorcraft_geom::Point; + let mut s = session(); + rect(&mut s, 100.0, 100.0, 100.0, 100.0); + s.execute("guide.add", &json!({"vertical": true, "pos": 300})).unwrap(); + let (n, doc) = (undo_len(&s), s.doc().unwrap().doc.clone()); + let v = ViewInfo::default(); + let at = |s: &mut Session, x, y| s.ruler_origin_drag(Some(Point::new(x, y)), v).unwrap(); + assert_eq!(at(&mut s, 101.5, 98.5), Point::new(100.0, 100.0), "the corner"); + assert!(!s.overlays(v).is_empty(), "the guide showing it"); + assert_eq!(at(&mut s, 130.0, 202.0), Point::new(130.0, 200.0), "the bottom edge"); + assert_eq!(at(&mut s, 398.0, 301.5), Point::new(400.0, 300.0), "the artboard's centre"); + assert_eq!(at(&mut s, 302.0, 50.0).x, 300.0, "along the ruler guide"); + assert_eq!(s.ruler_origin_drag(None, v), None, "off the canvas"); + assert!(s.overlays(v).is_empty()); + assert_eq!(at(&mut s, 101.5, 98.5), Point::new(100.0, 100.0)); + s.end_ruler_origin_drag(); + assert!(s.overlays(v).is_empty()); + assert_eq!((undo_len(&s), &*s.doc().unwrap().doc), (n, &*doc), "nothing changed"); + // Nothing on: it stays at the pointer. + let off = ViewInfo { smart_guides: false, snap_to_point: false, ..v }; + assert_eq!(s.ruler_origin_drag(Some(Point::new(101.5, 98.5)), off), Some(Point::new(101.5, 98.5))); + s.end_ruler_origin_drag(); + // Snap to Grid: onto a gridline crossing. + let grid = ViewInfo { snap_to_grid: true, ..v }; + let p = s.ruler_origin_drag(Some(Point::new(101.5, 98.5)), grid).unwrap(); + s.end_ruler_origin_drag(); + assert_eq!(p, Point::new(p.x.round(), p.y.round()), "{p:?}"); + assert_ne!(p, Point::new(101.5, 98.5)); +} + /// Guides saved before guides had layers are put on a layer when the document opens. #[test] fn guides_from_older_files_are_put_on_a_layer() { @@ -4448,6 +4577,12 @@ fn ruler_guides_live_on_layers() { assert!(s.doc().unwrap().doc.ruler_guides().iter().all(|g| g.layer == Some(first))); s.execute("guide.setLayer", &json!({"indexes": [1], "layer": second.0})).unwrap(); assert!(s.execute("guide.setLayer", &json!({"indexes": [7], "layer": first.0})).is_err()); + // `indexes` that is not a list, or given with `index`, is an error; an index given twice counts once. + assert!(s.execute("guide.setLayer", &json!({"indexes": 0, "layer": first.0})).is_err()); + assert!(s.execute("guide.setLayer", &json!({"index": 0, "indexes": [1], "layer": first.0})).is_err()); + assert!(s.doc().unwrap().doc.ruler_guides().iter().map(|g| g.layer).eq([Some(first), Some(second)])); + assert_eq!(s.execute("guide.setLayer", &json!({"indexes": [1, 1], "layer": first.0})).unwrap()["count"], 1); + s.execute("guide.setLayer", &json!({"indexes": [1], "layer": second.0})).unwrap(); // Deleting a layer deletes its guides; undo brings them back. s.execute("layer.delete", &json!({"ids": [second.0]})).unwrap(); assert_eq!(guides(&s), [(true, 200.0)]); @@ -4485,6 +4620,122 @@ fn guides_on_hidden_or_locked_layers_are_left_alone() { assert_eq!(guides(&s).len(), 3); } +/// A guide hidden or locked on its own can't be moved, deleted or moved to another layer, and the +/// error names the guide, not its layer; a guide on a hidden or locked layer names the layer. +#[test] +fn a_guide_hidden_or_locked_on_its_own_is_named_in_the_error() { + let mut s = session(); + let first = s.doc().unwrap().current_layer().unwrap(); + for pos in [100.0, 200.0] { + s.execute("guide.add", &json!({"vertical": true, "pos": pos})).unwrap(); + } + let second = id_of(&s.execute("layer.new", &json!({})).unwrap()); + let ids: Vec = s.doc().unwrap().doc.ruler_guides().iter().map(|g| g.id.unwrap().0).collect(); + s.execute("layer.setProps", &json!({"ids": [ids[0]], "locked": true})).unwrap(); + s.execute("layer.setProps", &json!({"ids": [ids[1]], "visible": false})).unwrap(); + let own = "the guide is hidden or locked"; + for i in [0, 1] { + assert_eq!(s.execute("guide.move", &json!({"index": i, "pos": 50})).unwrap_err().to_string(), own, "{i}"); + assert_eq!(s.execute("guide.remove", &json!({"index": i})).unwrap_err().to_string(), own, "{i}"); + assert_eq!(s.execute("guide.remove", &json!({"indexes": [i]})).unwrap_err().to_string(), own, "{i}"); + let p = json!({"index": i, "layer": second.0}); + assert_eq!(s.execute("guide.setLayer", &p).unwrap_err().to_string(), own, "{i}"); + } + // Shown and unlocked, but on a locked layer: the error names the layer. + s.execute("layer.setProps", &json!({"ids": [ids[0]], "locked": false})).unwrap(); + s.execute("layer.setProps", &json!({"ids": [first.0], "locked": true})).unwrap(); + let e = s.execute("guide.move", &json!({"index": 0, "pos": 50})).unwrap_err().to_string(); + assert_eq!(e, "the guide is on a hidden or locked layer"); +} + +/// Object › Lock › Selection and Hide › Selection lock and hide a selected ruler guide on its own, +/// with the selected art, in one undo step; Unlock All and Show All unlock and show it again and +/// select it as a guide. While Lock Guides is on nothing selects it, and in isolation mode Lock +/// leaves it alone. +#[test] +fn lock_hide_unlock_and_show_all_reach_ruler_guides() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + for pos in [100.0, 200.0] { + s.execute("guide.add", &json!({"vertical": true, "pos": pos})).unwrap(); + } + let flags = |s: &Session| s.doc().unwrap().doc.ruler_guides().iter().map(|g| (g.hidden, g.locked)).collect::>(); + let undo = |s: &Session| s.doc().unwrap().history.undo.len(); + let clear = (false, false); + // A guide selected on its own: Lock locks it alone and deselects it. + s.execute("guide.select", &json!({"indexes": [0]})).unwrap(); + let n = undo(&s); + s.execute("object.lock", &json!({})).unwrap(); + assert_eq!((flags(&s), undo(&s)), (vec![(false, true), clear], n + 1)); + assert!(selected_guides(&s).is_empty()); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((flags(&s), selected_guides(&s)), (vec![clear, clear], vec![0])); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(flags(&s)[0], (false, true)); + // A guide and art selected together: Hide hides both, in one step. + sel(&mut s, &[a]); + s.execute("guide.select", &json!({"indexes": [1], "toggle": true})).unwrap(); + let n = undo(&s); + s.execute("object.hide", &json!({})).unwrap(); + assert_eq!((flags(&s), undo(&s)), (vec![(false, true), (true, false)], n + 1)); + assert!(!s.doc().unwrap().doc.node(a).unwrap().visible); + // Unlock All and Show All reach the guides and select them as guides. + assert_eq!(s.execute("object.unlockAll", &json!({})).unwrap()["count"], 1); + assert_eq!((flags(&s)[0], selected_guides(&s), selected(&s)), (clear, vec![0], vec![])); + assert_eq!(s.execute("object.showAll", &json!({})).unwrap()["count"], 2); + assert_eq!((flags(&s), selected_guides(&s), selected(&s)), (vec![clear, clear], vec![1], vec![a])); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(flags(&s)[1], (true, false), "Show All is one undo step"); + s.execute("edit.redo", &json!({})).unwrap(); + // With Lock Guides on, Unlock All unlocks a guide but leaves it unselected. + s.execute("guide.select", &json!({"indexes": [0]})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + s.execute("view.guides.lock", &json!({"locked": true})).unwrap(); + s.execute("object.unlockAll", &json!({})).unwrap(); + assert_eq!((flags(&s)[0], selected_guides(&s)), (clear, vec![])); + s.execute("view.guides.lock", &json!({"locked": false})).unwrap(); + // In isolation mode Lock takes only the objects inside the isolated group. + let b = rect(&mut s, 20.0, 0.0, 10.0, 10.0); + sel(&mut s, &[a, b]); + let g = id_of(&s.execute("object.group", &json!({})).unwrap()); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + sel(&mut s, &[a]); + let _ = s.execute("guide.select", &json!({"indexes": [0], "toggle": true})); + s.execute("object.lock", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.node(a).unwrap().locked); + assert_eq!(flags(&s)[0], clear); +} + +/// `guide.remove` with `indexes` deletes those guides in one undo step, an index given twice +/// once; a locked guide among them, or an unknown index, deletes nothing. +#[test] +fn guide_remove_takes_several_indexes() { + let mut s = session(); + for pos in [100.0, 200.0, 300.0] { + s.execute("guide.add", &json!({"vertical": true, "pos": pos})).unwrap(); + } + let id = s.doc().unwrap().doc.ruler_guides()[2].id.unwrap(); + s.execute("layer.setProps", &json!({"ids": [id.0], "locked": true})).unwrap(); + assert!(s.execute("guide.remove", &json!({"indexes": [0, 2]})).is_err()); + assert!(s.execute("guide.remove", &json!({"indexes": [0, 7]})).is_err()); + assert!(s.execute("guide.remove", &json!({"indexes": 0})).is_err()); + assert!(s.execute("guide.remove", &json!({"index": 0, "indexes": [1]})).is_err()); + // A list longer than 10,000 entries is refused by every guide command that takes one. + let long = json!(vec![0; 10_001]); + assert!(s.execute("guide.remove", &json!({"indexes": long})).is_err()); + assert!(s.execute("guide.select", &json!({"indexes": long})).is_err()); + let layer = s.doc().unwrap().doc.layers[0].id; + assert!(s.execute("guide.setLayer", &json!({"indexes": long, "layer": layer.0})).is_err()); + assert_eq!(s.execute("guide.select", &json!({"indexes": vec![0; 10_000]})).unwrap()["selected"], json!([0])); + s.execute("select.none", &json!({})).unwrap(); + assert_eq!(guides(&s).len(), 3); + let n = s.doc().unwrap().history.undo.len(); + assert_eq!(s.execute("guide.remove", &json!({"indexes": [1, 0, 1]})).unwrap()["count"], 2); + assert_eq!((guides(&s), s.doc().unwrap().history.undo.len()), (vec![(true, 300.0)], n + 1)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(guides(&s).len(), 3); +} + /// Guides follow their layers through Duplicate, Merge Selected and Flatten Artwork, in one undo /// step each. #[test] diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index 067631eeca..209d22a42a 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -233,7 +233,7 @@ fn a_saved_preset_with_values_out_of_range_reads_in_range() { saved, [ (1.0, 1.0, 1.0, 0.0, vec![0.0, 0.0, 0.0, 9.0]), - (163830.0, 163830.0, 1.0, 1.0e5, vec![72.0, 72.0, 72.0, 0.0]), + (3_999_856.0, 200000.0, 1.0, 1.0e5, vec![72.0, 72.0, 72.0, 0.0]), (10.0, 10.0, 1000.0, 0.0, vec![0.0; 4]), ] ); @@ -242,7 +242,7 @@ fn a_saved_preset_with_values_out_of_range_reads_in_range() { s.execute("file.new", &json!({"preset": "Low"})).unwrap(); assert_eq!((boards(&s), s.doc().unwrap().doc.setup.bleed), (vec![Rect::new(0.0, 0.0, 1.0, 1.0)], [0.0, 0.0, 0.0, 9.0])); s.execute("file.new", &json!({"preset": "High"})).unwrap(); - assert_eq!((boards(&s), s.doc().unwrap().doc.setup.bleed), (vec![Rect::new(0.0, 0.0, 163830.0, 163830.0)], [72.0, 72.0, 72.0, 0.0])); + assert_eq!((boards(&s), s.doc().unwrap().doc.setup.bleed), (vec![Rect::new(0.0, 0.0, 3_999_856.0, 200000.0)], [72.0, 72.0, 72.0, 0.0])); s.execute("file.new", &json!({"preset": "Many"})).unwrap(); assert_eq!(boards(&s).len(), 1000); let custom = presets(&mut s, "Recent").into_iter().find(|p| p["name"] == "Custom").unwrap(); @@ -250,6 +250,63 @@ fn a_saved_preset_with_values_out_of_range_reads_in_range() { assert_eq!(boards(&s).iter().map(|r| r.x0).collect::>(), [0.0, 100.0, 200.0], "side by side, not overlapping"); } +/// `file.new` and `artboard.new` take the same largest artboard side (the canvas less the largest +/// bleed on both sides) and refuse a side just past it, or of 0 or less, with an error that names +/// the limit in points and, when the document's units aren't points, in those units too. +#[test] +fn file_new_and_artboard_new_take_the_same_largest_side() { + let max = 3_999_856.0; + let in_meters = "at most 3999856 pt (1411.0603 m)"; + let s = new_doc(json!({"width": max, "height": 170078})); + assert_eq!(boards(&s), [Rect::new(0.0, 0.0, max, 170078.0)]); + let mut s = Session::new(); + let err = s.execute("file.new", &json!({"width": max + 1.0, "height": 100})).unwrap_err().to_string(); + assert!(err.contains("width and height must be more than 0 and at most 3999856 pt") && !err.contains('('), "{err}"); + let err = s.execute("file.new", &json!({"width": 100, "height": "1412 m", "units": "Meters"})).unwrap_err().to_string(); + assert!(err.contains(in_meters), "{err}"); + // The value in other units is rounded down, so it is one file.new takes. + let err = s.execute("file.new", &json!({"width": 100, "height": "56000 in", "units": "Inches"})).unwrap_err().to_string(); + assert!(err.contains("at most 3999856 pt (55553.5555 in)"), "{err}"); + assert!(s.execute("file.new", &json!({"width": 0, "height": 100})).is_err()); + assert!(s.doc().is_err(), "no document was made"); + s.execute("file.new", &json!({"width": "55553.5555 in", "height": 100, "units": "Inches"})).unwrap(); + + let mut s = new_doc(json!({"units": "Meters"})); + s.execute("artboard.new", &json!({"x": -2_000_000, "y": 0, "width": max, "height": 100})).unwrap(); + assert_eq!(boards(&s)[1], Rect::new(-2_000_000.0, 0.0, max - 2_000_000.0, 100.0)); + for p in [ + json!({"x": -2_000_000, "y": 0, "width": max + 1.0, "height": 100}), + json!({"x": 0, "y": 2000, "width": 100, "height": max + 1.0}), + json!({"width": 0}), + json!({"height": -1}), + ] { + let err = s.execute("artboard.new", &p).unwrap_err().to_string(); + assert!(err.contains(in_meters), "{p}: {err}"); + } + assert_eq!(boards(&s).len(), 2, "the refused artboards were not added"); + // A size taken from a wider artboard is refused too. + s.execute("artboard.setProps", &json!({"index": 1, "x": -2_000_000, "y": 0, "width": max + 1.0, "height": 100})).unwrap(); + for p in [json!({}), json!({"x": 0, "y": 5000, "height": 100}), json!({"side": "bottom", "beside": 1})] { + let err = s.execute("artboard.new", &p).unwrap_err().to_string(); + assert!(err.contains(in_meters), "{p}: {err}"); + } + assert_eq!(boards(&s).len(), 2); + + // A side below 1 pt is kept as given, as file.new keeps it, and a size taken from such an artboard keeps it too. + let mut s = new_doc(json!({"width": 0.5, "height": 0.25})); + assert_eq!(boards(&s), [Rect::new(0.0, 0.0, 0.5, 0.25)]); + s.execute("artboard.new", &json!({"x": 0, "y": 10, "width": 0.5, "height": 0.75})).unwrap(); + s.execute("artboard.new", &json!({"x": 0, "y": 20})).unwrap(); + assert_eq!(boards(&s)[1..], [Rect::new(0.0, 10.0, 0.5, 10.75), Rect::new(0.0, 20.0, 0.5, 20.75)]); + // artboard.setProps keeps such sides when it changes something else, on a locked artboard too, + // and still raises a supplied side to 1 pt. + s.execute("artboard.setProps", &json!({"index": 1, "name": "Small"})).unwrap(); + s.execute("artboard.setProps", &json!({"index": 2, "locked": true})).unwrap(); + s.execute("artboard.setProps", &json!({"index": 2, "name": "Small locked"})).unwrap(); + s.execute("artboard.setProps", &json!({"index": 0, "height": 0.5})).unwrap(); + assert_eq!(boards(&s), [Rect::new(0.0, 0.0, 0.5, 1.0), Rect::new(0.0, 10.0, 0.5, 10.75), Rect::new(0.0, 20.0, 0.5, 20.75)]); +} + #[test] fn saved_presets_live_in_the_preferences() { let mut s = Session::new(); @@ -292,6 +349,57 @@ fn a_saved_preset_with_the_resolution_out_of_range_reads_in_range() { assert_eq!(s.doc().unwrap().doc.raster_effects_ppi, 1.0); } +/// Advanced Options › Align New Objects to Pixel Grid starts on in the Mobile and Web presets and +/// off in the others and without a preset; a `file.new` param overrides the preset; the document +/// takes the value; saved presets and Recent keep it, and a saved preset from before it reads off. +#[test] +fn align_new_objects_to_pixel_grid_follows_the_preset() { + let align = |s: &Session| s.doc().unwrap().doc.setup.align_new_objects_to_pixel_grid; + let mut s = Session::new(); + for category in ["Mobile", "Web"] { + assert!(presets(&mut s, category).iter().all(|p| p["alignNewObjectsToPixelGrid"] == true), "{category}"); + } + for category in ["Print", "Film & Video", "Art & Illustration", "Branding", "Social"] { + assert!(presets(&mut s, category).iter().all(|p| p["alignNewObjectsToPixelGrid"] == false), "{category}"); + } + s.execute("file.new", &json!({"preset": "Web 1920×1080"})).unwrap(); + assert!(align(&s)); + assert_eq!(presets(&mut s, "Recent")[0]["alignNewObjectsToPixelGrid"], true); + s.execute("file.new", &json!({"preset": "Phone 390×844"})).unwrap(); + assert!(align(&s)); + s.execute("file.new", &json!({"preset": "Letter"})).unwrap(); + assert!(!align(&s)); + s.execute("file.new", &json!({"width": 300, "height": 200})).unwrap(); + assert!(!align(&s)); + s.execute("file.new", &json!({"preset": "Web 1920×1080", "alignNewObjectsToPixelGrid": false})).unwrap(); + assert!(!align(&s)); + s.execute("file.new", &json!({"preset": "A4", "alignNewObjectsToPixelGrid": true})).unwrap(); + assert!(align(&s)); + assert!(Session::new().execute("file.new", &json!({"alignNewObjectsToPixelGrid": "on"})).is_err()); + // A Recent entry passed back makes the document it was made as. + let recent = presets(&mut s, "Recent")[0].clone(); + assert_eq!((recent["name"].as_str(), recent["alignNewObjectsToPixelGrid"].as_bool()), (Some("A4"), Some(true))); + s.execute("file.new", &recent).unwrap(); + assert!(align(&s)); + // Saved presets keep it. + s.execute("file.newPresets.save", &json!({"name": "Icons", "width": 64, "height": 64, "alignNewObjectsToPixelGrid": true})).unwrap(); + s.execute("file.newPresets.save", &json!({"name": "Banner", "preset": "Web 1920×1080", "alignNewObjectsToPixelGrid": false})).unwrap(); + let saved: Vec = presets(&mut s, "Saved").iter().map(|p| p["alignNewObjectsToPixelGrid"].clone()).collect(); + assert_eq!(saved, [json!(true), json!(false)]); + s.execute("file.new", &json!({"preset": "Icons"})).unwrap(); + assert!(align(&s)); + s.execute("file.new", &json!({"preset": "Banner"})).unwrap(); + assert!(!align(&s)); + let prefs: crate::Prefs = serde_json::from_value(s.prefs.to_json()).unwrap(); + assert_eq!(prefs.new_doc_presets, s.prefs.new_doc_presets); + // A saved preset from before the setting reads off, whatever its name. + let mut old = Session::new(); + old.apply_prefs(serde_json::from_value(json!({"newDocPresets": [{"name": "My Web", "width": 100, "height": 100}]})).unwrap()); + assert_eq!(presets(&mut old, "Saved")[0]["alignNewObjectsToPixelGrid"], false); + old.execute("file.new", &json!({"preset": "My Web"})).unwrap(); + assert!(!align(&old)); +} + #[test] fn rearrange_keeps_its_grid() { let mut s = new_doc(json!({"width": 100, "height": 50, "artboards": 3})); @@ -404,3 +512,262 @@ fn rearrange_that_moves_no_artboard_records_no_undo_step() { assert_eq!(s.execute("artboard.rearrange", &p).unwrap(), json!({"artboards": 0, "rows": 1, "columns": 1})); assert_eq!(history(&s), before); } + +/// A session whose New Document profiles are in a fresh folder for test `name` (not made yet). +fn with_profiles(name: &str) -> (Session, std::path::PathBuf) { + let dir = std::env::temp_dir().join(format!("vc-newdoc-profiles-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut s = Session::new(); + s.attach_new_doc_profiles(dir.clone()); + (s, dir) +} + +fn swatch_names(s: &Session) -> Vec { + s.doc().unwrap().doc.swatches.iter().map(|w| w.name.clone()).collect() +} + +/// Edit the Print profile: Brand Red, the Brand Box style, the Badge and Logo symbols (Logo's art an +/// embedded image) and an image left on its layer, saved. +fn edit_print_profile(s: &mut Session, dir: &std::path::Path) { + // Edit writes the shipped profile and opens it. + s.execute("file.newProfiles.edit", &json!({"name": "print"})).unwrap(); + assert!(dir.join("Print.vectorcraft").is_file()); + assert_eq!(s.doc().unwrap().doc.color_mode, ColorMode::Cmyk); + s.execute("swatch.new", &json!({"name": "Brand Red", "color": "#cc2200"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); + s.execute("graphicStyle.new", &json!({"name": "Brand Box"})).unwrap(); + s.execute("symbol.new", &json!({"name": "Badge"})).unwrap(); + // One embedded image becomes a symbol's art, another stays on the profile's layer. + let png = |rgb: [u8; 3]| { + let mut out = vec![]; + image::RgbaImage::from_pixel(4, 4, image::Rgba([rgb[0], rgb[1], rgb[2], 255])) + .write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png) + .unwrap(); + vectorcraft_format::base64_encode(&out) + }; + s.execute("file.place", &json!({"name": "red.png", "dataBase64": png([255, 0, 0]), "link": false})).unwrap(); + s.execute("symbol.new", &json!({"name": "Logo"})).unwrap(); + s.execute("file.place", &json!({"name": "blue.png", "dataBase64": png([0, 0, 255]), "link": false})).unwrap(); + assert_eq!(s.doc().unwrap().doc.images.len(), 2); + s.execute("document.save", &json!({})).unwrap(); + assert_eq!(s.execute("file.newProfiles", &json!({})).unwrap()["profiles"][2]["customized"], true); +} + +#[test] +fn an_edited_profile_starts_the_documents_of_its_category() { + let (mut s, dir) = with_profiles("edited"); + let listed = s.execute("file.newProfiles", &json!({})).unwrap(); + let names: Vec<&str> = listed["profiles"].as_array().unwrap().iter().map(|p| p["name"].as_str().unwrap()).collect(); + assert_eq!(names, ["Mobile", "Web", "Print", "Film & Video", "Art & Illustration", "Branding", "Social"]); + assert!(listed["profiles"].as_array().unwrap().iter().all(|p| p["customized"] == false), "{listed}"); + edit_print_profile(&mut s, &dir); + + let r = s.execute("file.new", &json!({"preset": "A4"})).unwrap(); + assert_eq!(r["profile"], "Print", "{r}"); + assert!(swatch_names(&s).contains(&"Brand Red".to_string())); + let d = &s.doc().unwrap().doc; + assert!(d.graphic_styles.iter().any(|g| g.name == "Brand Box")); + let badge = d.symbols.iter().find(|y| y.name == "Badge").expect("the profile's symbol"); + assert!(d.symbols.iter().any(|y| y.name == "Logo")); + assert_eq!(d.images.len(), 1, "only the symbol's image comes along"); + // The profile's art stays behind: one empty layer, with an id the symbol's art doesn't use. + assert_eq!(d.layers.len(), 1); + assert!(d.layers[0].children().is_none_or(Vec::is_empty)); + let mut symbol_ids = vec![]; + badge.art.walk(&mut |n| symbol_ids.push(n.id)); + assert!(!symbol_ids.contains(&d.layers[0].id), "{symbol_ids:?}"); + assert_eq!(d.artboards[0].rect.width().round(), 595.0); + let red = d.swatches.iter().find(|w| w.name == "Brand Red").cloned().unwrap(); + assert!(matches!(red.paint, vectorcraft_color::Paint::Solid { color: vectorcraft_color::Color::Cmyk { .. }, .. }), "{:?}", red.paint); + // In RGB the profile's colors are converted, as Document Color Mode converts them. + s.execute("file.new", &json!({"preset": "A4", "colorMode": "rgb"})).unwrap(); + let red = s.doc().unwrap().doc.swatches.iter().find(|w| w.name == "Brand Red").cloned().expect("converted, not dropped"); + assert!(matches!(red.paint, vectorcraft_color::Paint::Solid { color: vectorcraft_color::Color::Rgb { .. }, .. }), "{:?}", red.paint); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn the_profile_follows_the_preset_access_and_reset() { + let (mut s, dir) = with_profiles("choice"); + edit_print_profile(&mut s, &dir); + // A request that may not read the folder gets the defaults, and the reason; edit is refused + // before anything is written. + let elsewhere = dir.with_extension("elsewhere"); + std::fs::create_dir_all(&elsewhere).unwrap(); + let roots = crate::file_access::AutomationRoots::new(&[elsewhere.as_path()], &[dir.as_path()]).unwrap().unwrap(); + let r = crate::file_access::confine(Some(&roots), || s.execute("file.new", &json!({"preset": "A4"}))).unwrap(); + assert!(r.get("profile").is_none() && r["profileError"]["profile"] == "Print", "{r}"); + // The reason does not say where the folder is. + let reason = r["profileError"]["reason"].as_str().unwrap_or_default(); + let folder = dir.file_name().unwrap().to_string_lossy().to_string(); + assert!(!reason.is_empty() && !reason.contains(&folder), "{reason}"); + assert!(!swatch_names(&s).contains(&"Brand Red".to_string())); + // Nothing tells such a request which profiles have files. + let r = crate::file_access::confine(Some(&roots), || s.execute("file.new", &json!({"preset": "Web 1920×1080"}))).unwrap(); + assert_eq!(r["profileError"]["profile"], "Web", "{r}"); + let listed = crate::file_access::confine(Some(&roots), || s.execute("file.newProfiles", &json!({}))).unwrap(); + assert!(listed["profiles"].as_array().unwrap().iter().all(|p| p.get("customized").is_none() && p.get("path").is_none()), "{listed}"); + assert!(crate::file_access::confine(Some(&roots), || s.execute("file.newProfiles.edit", &json!({"name": "Web"}))).is_err()); + assert!(!dir.join("Web.vectorcraft").exists()); + let _ = std::fs::remove_dir_all(&elsewhere); + // A saved preset made from a Print preset keeps the profile. + s.execute("file.newPresets.save", &json!({"name": "Zine", "preset": "A5"})).unwrap(); + assert_eq!(presets(&mut s, "Saved")[0]["profile"], "Print"); + assert_eq!(s.execute("file.new", &json!({"preset": "Zine"})).unwrap()["profile"], "Print"); + + // Other categories, no preset and `profile: null` start with the defaults. + for p in [json!({"preset": "Web 1920×1080"}), json!({}), json!({"preset": "A4", "profile": null})] { + let r = s.execute("file.new", &p).unwrap(); + assert!(r.get("profile").is_none() && !swatch_names(&s).contains(&"Brand Red".to_string()), "{p}: {r}"); + } + // `profile` picks one for any settings. + assert_eq!(s.execute("file.new", &json!({"width": 300, "height": 300, "profile": "PRINT"})).unwrap()["profile"], "Print"); + + // Reset deletes the file, once; the shipped profile applies again. + assert_eq!(s.execute("file.newProfiles.reset", &json!({"name": "Print"})).unwrap(), json!({"name": "Print", "reset": true})); + assert_eq!(s.execute("file.newProfiles.reset", &json!({"name": "Print"})).unwrap(), json!({"name": "Print", "reset": false})); + let r = s.execute("file.new", &json!({"preset": "A4"})).unwrap(); + assert!(r.get("profile").is_none() && !swatch_names(&s).contains(&"Brand Red".to_string()), "{r}"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn profile_errors_name_the_file_by_its_name_outside_the_read_roots() { + let (mut s, dir) = with_profiles("errors"); + let elsewhere = dir.with_extension("elsewhere"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::create_dir_all(&elsewhere).unwrap(); + let whole = dir.join("Print.vectorcraft").to_string_lossy().to_string(); + let run = |s: &mut Session, roots: &std::sync::Arc, cmd: &str| { + crate::file_access::confine(Some(roots), || s.execute(cmd, &json!({"name": "Print"}))).unwrap_err().to_string() + }; + // No write access: edit and reset are refused before anything is written or deleted. + let read_only = crate::file_access::AutomationRoots::new(&[elsewhere.as_path()], &[]).unwrap().unwrap(); + for cmd in ["file.newProfiles.edit", "file.newProfiles.reset"] { + let e = run(&mut s, &read_only, cmd); + assert!(e.ends_with(": Print.vectorcraft") && !e.contains(&whole), "{cmd}: {e}"); + } + // Write access without read access: edit is refused, and nothing is written. + let write_only = crate::file_access::AutomationRoots::new(&[elsewhere.as_path()], &[dir.as_path()]).unwrap().unwrap(); + let e = run(&mut s, &write_only, "file.newProfiles.edit"); + assert!(e.contains("outside the read root") && e.ends_with(": Print.vectorcraft") && !e.contains(&whole), "{e}"); + assert!(!dir.join("Print.vectorcraft").exists()); + // A file reset cannot delete (a folder in its place) is named by its file name too. + std::fs::create_dir_all(dir.join("Print.vectorcraft")).unwrap(); + let e = run(&mut s, &write_only, "file.newProfiles.reset"); + assert!(e.starts_with("Print.vectorcraft: ") && !e.contains(&whole), "{e}"); + // Inside the read roots the error names the whole path. + let inside = crate::file_access::AutomationRoots::new(&[dir.as_path()], &[dir.as_path()]).unwrap().unwrap(); + let e = run(&mut s, &inside, "file.newProfiles.reset"); + assert!(e.starts_with(&format!("{whole}: ")), "{e}"); + let _ = std::fs::remove_dir_all(&elsewhere); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The new document's links find their files from the profile's file, as a document opened from +/// that file does; a document without a profile has no such file. +#[test] +fn the_new_document_links_from_the_profile_file() { + let (mut s, dir) = with_profiles("links"); + edit_print_profile(&mut s, &dir); + assert_eq!(s.execute("file.new", &json!({"preset": "A4"})).unwrap()["profile"], "Print"); + let file = dir.join("Print.vectorcraft").to_string_lossy().to_string(); + assert_eq!(s.doc().unwrap().links_from.as_deref(), Some(file.as_str())); + s.execute("file.new", &json!({"preset": "Web 1920×1080"})).unwrap(); + assert_eq!(s.doc().unwrap().links_from, None); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A color profile the profile's file carries is installed when this machine lacks it, as opening +/// the file installs it, so the new document keeps it and a save carries it; one that can't be used +/// is a warning. +#[test] +fn a_profile_brings_the_color_profile_its_file_carries() { + use vectorcraft_color::cms; + let (mut s, dir) = with_profiles("icc"); + let builtin = cms::profiles().into_iter().find(|p| p.kind == cms::ProfileKind::Rgb && p.builtin && p.name != cms::SRGB).unwrap(); + let icc = cms::icc_bytes(&builtin.name).unwrap().to_vec(); + let name = format!("Profile RGB {}", std::process::id()); + cms::register_icc(&icc, Some(name.clone())).unwrap(); + let bytes_of = |v: &Value| vectorcraft_format::base64_decode(v.as_str().expect("base64")).unwrap(); + s.execute("file.new", &json!({"preset": "Web 1920×1080", "profile": null})).unwrap(); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).color_profiles.rgb = Some(name.clone()); + let file = String::from_utf8(bytes_of(&s.execute("file.saveCopy", &json!({"compress": false})).unwrap()["dataBase64"])).unwrap(); + cms::unregister_icc(&name); + // A profile made on another machine names a color profile this one lacks. + let elsewhere = format!("Profile RGB elsewhere {}", std::process::id()); + assert!(cms::profile(&elsewhere).is_none()); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("Web.vectorcraft"), file.replace(&name, &elsewhere)).unwrap(); + let r = s.execute("file.new", &json!({"preset": "Web 1920×1080"})).unwrap(); + assert!(r["profile"] == "Web" && r.get("warnings").is_none(), "{r}"); + assert_eq!(cms::profile(&elsewhere).map(|p| p.kind), Some(cms::ProfileKind::Rgb)); + assert_eq!(s.doc().unwrap().doc.color_profiles.rgb.as_deref(), Some(elsewhere.as_str())); + let saved: Value = serde_json::from_slice(&bytes_of(&s.execute("file.saveCopy", &json!({"compress": false})).unwrap()["dataBase64"])).unwrap(); + assert_eq!(vectorcraft_format::base64_decode(saved["profiles"][&elsewhere]["data"].as_str().unwrap()).unwrap(), icc); + cms::unregister_icc(&elsewhere); + // Damaged profile data starts the document with a warning. + let broken = format!("Profile RGB broken {}", std::process::id()); + let mut v: Value = serde_json::from_str(&file.replace(&name, &broken)).unwrap(); + v["profiles"][&broken]["data"] = json!("AAAA"); + std::fs::write(dir.join("Web.vectorcraft"), serde_json::to_vec(&v).unwrap()).unwrap(); + let r = s.execute("file.new", &json!({"preset": "Web 1920×1080"})).unwrap(); + assert!(r["profile"] == "Web" && r["warnings"][0].as_str().unwrap_or_default().contains(&broken), "{r}"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_damaged_or_oversized_profile_leaves_the_defaults_and_is_reported() { + let (mut s, dir) = with_profiles("damaged"); + s.execute("file.new", &json!({"preset": "Letter", "profile": null})).unwrap(); + let defaults = swatch_names(&s); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("Print.vectorcraft"), b"not a document").unwrap(); + let r = s.execute("file.new", &json!({"preset": "Letter"})).unwrap(); + assert_eq!(r["profileError"]["profile"], "Print", "{r}"); + assert!(!r["profileError"]["reason"].as_str().unwrap_or("").is_empty(), "{r}"); + assert!(r.get("profile").is_none()); + assert_eq!(swatch_names(&s), defaults); + // Past the limit the file is not read at all (a sparse file of that length). + let big = std::fs::File::create(dir.join("Web.vectorcraft")).unwrap(); + big.set_len(crate::cmd::newdoc::MAX_PROFILE_BYTES + 1).unwrap(); + drop(big); + let r = s.execute("file.new", &json!({"preset": "Web 1920×1080"})).unwrap(); + assert!(r["profileError"]["reason"].as_str().unwrap_or("").contains("larger than"), "{r}"); + assert_eq!(s.doc().unwrap().doc.artboards[0].rect.width(), 1920.0); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn profile_names_are_checked_and_editing_needs_the_folder() { + let mut s = Session::new(); + for p in [json!({"profile": "Posters"}), json!({"profile": 5}), json!({"profile": ""})] { + let e = s.execute("file.new", &p).unwrap_err().to_string(); + assert!(e.contains("no New Document profile called") && e.contains("Film & Video"), "{p}: {e}"); + } + assert!(s.execute("file.newProfiles.edit", &json!({"name": "Posters"})).is_err()); + for cmd in ["file.newProfiles.edit", "file.newProfiles.reset"] { + let e = s.execute(cmd, &json!({"name": "Print"})).unwrap_err().to_string(); + assert!(e.contains("preferences folder"), "{cmd}: {e}"); + } + // Without a folder every profile is the shipped one and documents start with the defaults. + let r = s.execute("file.newProfiles", &json!({})).unwrap(); + assert!(r["folder"].is_null() && r["profiles"][0].get("path").is_none(), "{r}"); + let r = s.execute("file.new", &json!({"preset": "A4"})).unwrap(); + assert!(r.get("profile").is_none() && r.get("profileError").is_none(), "{r}"); +} + +#[test] +fn the_new_layer_takes_an_id_no_profile_art_has() { + // A damaged profile whose symbol art has the id the new layer would otherwise take. + let settings = crate::cmd::newdoc::DocSettings::default(); + let mut profile = settings.document(); + let next = settings.document().peek_next_id().max(profile.peek_next_id()); + let art = std::sync::Arc::new(vectorcraft_doc::Node::group(vectorcraft_doc::NodeId(next), vec![])); + profile.symbols.push(vectorcraft_doc::Symbol { name: "Badge".into(), art, dynamic: false }); + let d = settings.document_from_profile(profile); + assert_eq!(d.layers.len(), 1); + assert_ne!(d.layers[0].id, vectorcraft_doc::NodeId(next)); + // Ids given out later skip the symbol's art too. + assert!(d.peek_next_id() > d.layers[0].id.0 && d.peek_next_id() > next); +} diff --git a/crates/engine/src/tests/objects_on_path.rs b/crates/engine/src/tests/objects_on_path.rs index 8c0f359df4..d9e76f85bf 100644 --- a/crates/engine/src/tests/objects_on_path.rs +++ b/crates/engine/src/tests/objects_on_path.rs @@ -531,6 +531,139 @@ fn a_space_that_is_not_usable_is_refused_and_one_too_large_is_kept_to_the_path() assert_eq!(space(&s, g), (Some(100.0), 0.0)); } +/// The ids of group `g`'s objects in their order along the path, and of its children in the +/// Layers panel's order. +fn orders(s: &Session, g: NodeId) -> (Vec, Vec) { + let n = s.doc().unwrap().doc.node(g).unwrap(); + let path = n.extras().objects_on_path.as_deref().unwrap().members.iter().map(|m| m.id).collect(); + (path, n.children().unwrap().iter().map(|c| c.id).collect()) +} + +/// Three objects of different widths (20, 40 and 10 pt) attached to a 300 pt line from (50, 300), +/// in that order, with a Space of 100 pt from 0, Pivot 4 and Rotate 0. +fn three_on_a_line(s: &mut Session) -> (NodeId, [NodeId; 3], NodeId) { + let a = rect(s, 0.0, 0.0, 20.0, 20.0); + let b = rect(s, 100.0, 0.0, 40.0, 20.0); + let c = rect(s, 200.0, 0.0, 10.0, 20.0); + let path = line(s, (50.0, 300.0), (350.0, 300.0)); + let g = attach(s, path, &[a, b, c], json!({})); + s.execute("object.objectsOnPath.options", &json!({"spacing": 100})).unwrap(); + (g, [a, b, c], path) +} + +#[test] +fn move_member_takes_the_target_s_place_and_shifts_the_objects_between() { + let mut s = session(); + let (g, [a, b, c], path) = three_on_a_line(&mut s); + let (_, layers) = orders(&s, g); + let before = s.doc().unwrap().doc.node(g).unwrap().extras().objects_on_path.as_deref().cloned().unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + let v = s.execute("object.objectsOnPath.moveMember", &json!({"member": a.0, "target": c.0})).unwrap(); + assert_eq!(v, json!({"group": g.0, "member": a.0, "index": 2})); + assert_eq!(orders(&s, g), (vec![b, c, a], layers.clone()), "the order along the path changes, the Layers order does not"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one undo step"); + assert_eq!(center(&s, b), Point::new(50.0, 300.0)); + assert_eq!(center(&s, c), Point::new(150.0, 300.0)); + assert_eq!(center(&s, a), Point::new(250.0, 300.0)); + let after = s.doc().unwrap().doc.node(g).unwrap().extras().objects_on_path.as_deref().cloned().unwrap(); + assert_eq!( + (after.path, after.pivot, after.rotate, after.spacing, after.start), + (path, before.pivot, before.rotate, before.spacing, before.start) + ); + let w = bounds(&s, a); + assert!((w.width() - 20.0).abs() < 1e-9, "the object keeps its art: {w:?}"); + // The last one back to the first place, with its group named. + let v = s.execute("object.objectsOnPath.moveMember", &json!({"group": g.0, "member": a.0, "target": b.0})).unwrap(); + assert_eq!(v["index"], 0); + assert_eq!(orders(&s, g).0, [a, b, c]); + assert_eq!(center(&s, a), Point::new(50.0, 300.0)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(orders(&s, g).0, [b, c, a]); + assert_eq!(center(&s, a), Point::new(250.0, 300.0)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(orders(&s, g).0, [a, b, c]); + assert_eq!(center(&s, c), Point::new(250.0, 300.0)); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(orders(&s, g).0, [b, c, a]); + // Onto its own place: nothing changes and no step is recorded. + let steps = s.doc().unwrap().history.undo.len(); + let v = s.execute("object.objectsOnPath.moveMember", &json!({"member": c.0, "target": c.0})).unwrap(); + assert_eq!(v["index"], 1); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); + // The order saves and reopens. + let data = s.execute("document.export", &json!({"format": "vectorcraft"})).unwrap()["dataBase64"].clone(); + let mut o = Session::new(); + o.execute("document.open", &json!({"name": "objects.vectorcraft", "dataBase64": data})).unwrap(); + assert_eq!(orders(&o, g), (vec![b, c, a], layers)); + assert_eq!(center(&o, a), Point::new(250.0, 300.0)); +} + +#[test] +fn move_member_refuses_what_is_not_an_object_on_the_same_path() { + let mut s = session(); + let (g, [a, b, c], path) = three_on_a_line(&mut s); + let loose = rect(&mut s, 300.0, 20.0, 10.0, 10.0); + let x = rect(&mut s, 0.0, 200.0, 10.0, 10.0); + let other_line = line(&mut s, (50.0, 380.0), (350.0, 380.0)); + let h = attach(&mut s, other_line, &[x], json!({})); + let err = |s: &mut Session, p: Value| s.execute("object.objectsOnPath.moveMember", &p).unwrap_err().to_string(); + assert!(err(&mut s, json!({"member": path.0, "target": a.0})).contains("`member` must name an object attached"), "the path"); + assert!(err(&mut s, json!({"member": a.0, "target": path.0})).contains("`target` must name"), "the path as the target"); + assert!(err(&mut s, json!({"member": loose.0, "target": a.0})).contains("`member` must name"), "an object on no path"); + assert!(err(&mut s, json!({"member": g.0, "target": a.0})).contains("`member` must name"), "the group itself"); + assert!(err(&mut s, json!({"member": a.0, "target": x.0})).contains("same Objects on Path group"), "another group's object"); + assert!(err(&mut s, json!({"member": a.0, "target": b.0, "group": h.0})).contains("`group` must be"), "another group named"); + assert!(err(&mut s, json!({"target": b.0})).contains("missing `member`")); + assert!(err(&mut s, json!({"member": a.0})).contains("missing `target`")); + assert!(err(&mut s, json!({"member": 99999, "target": b.0})).contains("no such object")); + assert!(err(&mut s, json!({"member": "a", "target": b.0})).contains("invalid object id")); + // A locked object neither moves nor gives its place, and is not chosen. + select(&mut s, &[c]); + s.execute("object.lock", &json!({})).unwrap(); + assert!(err(&mut s, json!({"member": c.0, "target": a.0})).contains("`member` names an object that is hidden or locked")); + assert!(err(&mut s, json!({"member": a.0, "target": c.0})).contains("`target` names an object that is hidden or locked")); + assert!(s.execute("object.objectsOnPath.selectMember", &json!({"member": c.0})).is_err()); + s.execute("object.unlockAll", &json!({})).unwrap(); + // A locked object between the two keeps its place, and the others pass over it. + select(&mut s, &[b]); + s.execute("object.lock", &json!({})).unwrap(); + let v = s.execute("object.objectsOnPath.moveMember", &json!({"member": a.0, "target": c.0})).unwrap(); + assert_eq!(v["index"], 2); + assert_eq!(orders(&s, g).0, [c, b, a]); + assert_eq!(center(&s, b), Point::new(150.0, 300.0), "the locked object stays where it was"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("object.unlockAll", &json!({})).unwrap(); + select(&mut s, &[g]); + s.execute("object.lock", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.node(g).unwrap().locked); + let e = err(&mut s, json!({"member": a.0, "target": b.0})); + assert!(e.contains("hidden or locked"), "a locked group: {e}"); + assert!(s.execute("object.objectsOnPath.selectMember", &json!({"member": a.0})).is_err(), "a locked group's object is not chosen"); + assert_eq!(orders(&s, g).0, [a, b, c], "nothing refused changed the order"); +} + +#[test] +fn select_member_selects_the_group_with_the_object_chosen() { + let mut s = session(); + let (g, [a, b, _], path) = three_on_a_line(&mut s); + let v = s.execute("object.objectsOnPath.selectMember", &json!({"member": b.0})).unwrap(); + assert_eq!(v, json!({"group": g.0, "member": b.0})); + let sel = &s.doc().unwrap().selection; + assert_eq!((sel.objects.as_slice(), sel.on_path_member), (&[g][..], Some(b))); + // Moving the chosen object keeps it chosen. + s.execute("object.objectsOnPath.moveMember", &json!({"member": b.0, "target": a.0})).unwrap(); + assert_eq!(s.doc().unwrap().selection.on_path_member, Some(b)); + assert!(s.execute("object.objectsOnPath.selectMember", &json!({"member": path.0})).is_err()); + select(&mut s, &[g]); + assert_eq!(s.doc().unwrap().selection.on_path_member, None, "another selection clears it"); + // Both take their objects without a selection. + select(&mut s, &[]); + s.execute("object.objectsOnPath.moveMember", &json!({"member": a.0, "target": b.0})).unwrap(); + assert_eq!(orders(&s, g).0[..2], [a, b]); + s.execute("object.objectsOnPath.selectMember", &json!({"member": a.0})).unwrap(); + assert_eq!(s.doc().unwrap().selection.on_path_member, Some(a)); +} + #[test] fn the_space_saves_and_reopens_and_goes_with_a_copy() { let mut s = session(); @@ -548,3 +681,197 @@ fn the_space_saves_and_reopens_and_goes_with_a_copy() { let copy = s.doc().unwrap().selection.objects.to_vec(); assert_eq!(space(&s, copy[0]), (Some(40.0), 25.0)); } + +/// Where `id` is in the tree: its parent and its index there (0 at the bottom). +fn place_of(s: &Session, id: NodeId) -> (Option, usize) { + let (parent, index, _) = s.doc().unwrap().doc.position(id).unwrap(); + (parent, index) +} + +#[test] +fn detach_takes_the_chosen_object_off_the_path_and_the_others_move_up_in_one_undo_step() { + let mut s = session(); + let ([left, middle, right], path) = squares_and_line(&mut s); + let g = attach(&mut s, path, &[left, middle, right], json!({"rotate": 30})); + let (layer, at) = place_of(&s, g); + s.execute("object.objectsOnPath.selectMember", &json!({"member": middle.0})).unwrap(); + let drawn = s.doc().unwrap().doc.node(middle).unwrap().clone(); + let steps = s.doc().unwrap().history.undo.len(); + let v = s.execute("object.objectsOnPath.detach", &json!({})).unwrap(); + assert_eq!(v, json!({"group": g.0, "member": middle.0})); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one undo step"); + let (on_path, children) = orders(&s, g); + assert_eq!(on_path, [left, right]); + assert!(children.len() == 3 && !children.contains(&middle), "{children:?}"); + assert_eq!(place_of(&s, middle), (layer, at + 1), "just above the group, in its layer"); + assert_eq!(s.doc().unwrap().doc.node(middle), Some(&drawn), "the object keeps its art, place and rotation"); + let sel = &s.doc().unwrap().selection; + assert_eq!((sel.objects.as_slice(), sel.on_path_member), (&[middle][..], None), "the detached object alone is selected"); + // The two left stay on the ends of the path; the path stays. + assert_eq!(center(&s, left), Point::new(50.0, 300.0)); + assert_eq!(center(&s, right), Point::new(350.0, 300.0)); + assert_eq!(s.doc().unwrap().doc.node(g).unwrap().extras().objects_on_path.as_deref().unwrap().path, path); + // The detached object is free: moving it moves it, and the group does not take it back. + s.execute("object.move", &json!({"ids": [middle.0], "dx": 0, "dy": -100})).unwrap(); + assert_eq!(center(&s, middle), Point::new(200.0, 200.0)); + assert_eq!(orders(&s, g).0, [left, right]); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + let (on_path, children) = orders(&s, g); + assert_eq!(on_path, [left, middle, right], "undo puts it back on the path"); + assert!(children.contains(&middle), "{children:?}"); + assert_eq!(center(&s, middle), Point::new(200.0, 300.0)); + assert_eq!(center(&s, right), Point::new(350.0, 300.0)); + let sel = &s.doc().unwrap().selection; + assert_eq!((sel.objects.as_slice(), sel.on_path_member), (&[g][..], Some(middle)), "and the choice back"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(orders(&s, g).0, [left, right]); + assert_eq!(place_of(&s, middle), (layer, at + 1)); +} + +#[test] +fn after_the_first_object_is_detached_the_second_takes_the_start() { + let mut s = session(); + let ([left, middle, right], path) = squares_and_line(&mut s); + let g = attach(&mut s, path, &[left, middle, right], json!({})); + select(&mut s, &[]); + let v = s.execute("object.objectsOnPath.detach", &json!({"member": left.0})).unwrap(); + assert_eq!(v, json!({"group": g.0, "member": left.0})); + assert_eq!(orders(&s, g).0, [middle, right]); + assert_eq!(center(&s, middle), Point::new(50.0, 300.0), "the second object moves up to the start"); + assert_eq!(center(&s, right), Point::new(350.0, 300.0)); + assert_eq!(center(&s, left), Point::new(50.0, 300.0), "the detached object stays where it was drawn"); + assert_eq!(s.doc().unwrap().selection.objects.to_vec(), [left]); +} + +#[test] +fn detach_on_a_closed_path_spreads_the_others_all_the_way_round_again() { + let mut s = session(); + let ids: Vec = (0..4).map(|i| rect(&mut s, 10.0 + 40.0 * f64::from(i), 0.0, 10.0, 10.0)).collect(); + let ring = rect(&mut s, 100.0, 100.0, 200.0, 200.0); + let g = attach(&mut s, ring, &ids, json!({})); + s.execute("object.objectsOnPath.detach", &json!({"member": ids[1].0})).unwrap(); + assert_eq!(orders(&s, g).0, [ids[0], ids[2], ids[3]]); + let data = s.doc().unwrap().doc.node(ring).unwrap().path_data().unwrap().clone(); + let stops = vectorcraft_doc::objects_on_path::stops(&data, 3, None, 0.0).unwrap(); + for (id, (p, _)) in [ids[0], ids[2], ids[3]].iter().zip(stops) { + let c = center(&s, *id); + assert!((c.x - p.x).abs() < 1e-3 && (c.y - p.y).abs() < 1e-3, "a third of the way round apart: {c:?} {p:?}"); + } +} + +#[test] +fn detach_keeps_a_space_value_and_the_start() { + let mut s = session(); + let (g, [a, b, c], _) = three_on_a_line(&mut s); + s.execute("object.objectsOnPath.options", &json!({"start": 20})).unwrap(); + s.execute("object.objectsOnPath.detach", &json!({"member": a.0})).unwrap(); + assert_eq!(space(&s, g), (Some(100.0), 20.0)); + assert_eq!(center(&s, b), Point::new(70.0, 300.0), "the second object moves up to the first place"); + assert_eq!(center(&s, c), Point::new(170.0, 300.0)); + // A Space value the path is too short for stays, and two objects get more of the path. + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("object.objectsOnPath.options", &json!({"spacing": 200, "start": 0})).unwrap(); + assert_eq!(center(&s, c), Point::new(350.0, 300.0), "three objects drawn 150 pt apart"); + s.execute("object.objectsOnPath.detach", &json!({"member": b.0})).unwrap(); + assert_eq!(space(&s, g), (Some(200.0), 0.0)); + assert_eq!(center(&s, a), Point::new(50.0, 300.0)); + assert_eq!(center(&s, c), Point::new(250.0, 300.0), "two objects 200 pt apart"); +} + +#[test] +fn the_group_and_its_path_stay_with_one_object_or_none_left() { + let mut s = session(); + let ([left, middle, _], path) = squares_and_line(&mut s); + let g = attach(&mut s, path, &[left, middle], json!({"pivot": 7})); + s.execute("object.objectsOnPath.options", &json!({"spacing": 30})).unwrap(); + s.execute("object.objectsOnPath.detach", &json!({"member": left.0})).unwrap(); + assert_eq!(orders(&s, g), (vec![middle], vec![path, middle])); + let b = bounds(&s, middle); + assert!((b.center().x - 50.0).abs() < 1e-6 && (b.y1 - 300.0).abs() < 1e-6, "the one left on the start, by its Pivot: {b:?}"); + s.execute("object.objectsOnPath.detach", &json!({"member": middle.0})).unwrap(); + let n = s.doc().unwrap().doc.node(g).unwrap().clone(); + let rec = n.extras().objects_on_path.as_deref().unwrap(); + assert_eq!((rec.path, rec.members.len(), rec.pivot, rec.spacing), (path, 0, 7, Some(30.0)), "a live group with no objects"); + assert_eq!(orders(&s, g).1, [path]); + // An object moved back in joins the path. + s.execute("layer.move", &json!({"ids": [left.0], "target": g.0, "place": "inside"})).unwrap(); + assert_eq!(orders(&s, g).0, [left]); +} + +#[test] +fn detach_refuses_what_is_not_one_chosen_editable_object_on_a_path() { + let mut s = session(); + let (g, [a, b, c], path) = three_on_a_line(&mut s); + let loose = rect(&mut s, 300.0, 20.0, 10.0, 10.0); + let err = |s: &mut Session, p: Value| s.execute("object.objectsOnPath.detach", &p).unwrap_err().to_string(); + let choose = "choose the object to detach with its Select/Move widget"; + let steps = s.doc().unwrap().history.undo.len(); + select(&mut s, &[g]); + assert!(err(&mut s, json!({})).contains(choose), "the group without a chosen object"); + select(&mut s, &[]); + assert!(err(&mut s, json!({})).contains(choose), "nothing selected"); + assert!(err(&mut s, json!({"member": path.0})).contains("`member` must name an object attached"), "the path"); + assert!(err(&mut s, json!({"member": g.0})).contains("`member` must name"), "the group itself"); + assert!(err(&mut s, json!({"member": loose.0})).contains("`member` must name"), "an object on no path"); + assert!(err(&mut s, json!({"member": 99999})).contains("no such object")); + assert!(err(&mut s, json!({"member": "a"})).contains("invalid object id")); + // Hidden and locked objects stay; a locked group keeps all of its objects. + select(&mut s, &[c]); + s.execute("object.lock", &json!({})).unwrap(); + assert!(err(&mut s, json!({"member": c.0})).contains("`member` names an object that is hidden or locked")); + s.execute("object.unlockAll", &json!({})).unwrap(); + select(&mut s, &[b]); + s.execute("object.hide", &json!({})).unwrap(); + assert!(err(&mut s, json!({"member": b.0})).contains("hidden or locked"), "a hidden object"); + s.execute("object.showAll", &json!({})).unwrap(); + select(&mut s, &[g]); + s.execute("object.lock", &json!({})).unwrap(); + assert!(err(&mut s, json!({"member": a.0})).contains("the Objects on Path group is hidden or locked")); + s.execute("object.unlockAll", &json!({})).unwrap(); + assert_eq!(orders(&s, g).0, [a, b, c], "nothing refused detached anything"); + let undone = s.doc().unwrap().history.undo.len(); + assert_eq!(undone, steps + 6, "only the lock, hide and show steps"); +} + +#[test] +fn an_object_detached_from_a_group_on_another_path_does_not_join_that_path() { + let mut s = session(); + let ([left, middle, right], path) = squares_and_line(&mut s); + let inner = attach(&mut s, path, &[left, middle], json!({})); + let outer_line = line(&mut s, (20.0, 380.0), (380.0, 380.0)); + let outer = attach(&mut s, outer_line, &[inner, right], json!({})); + let outer_members = orders(&s, outer).0; + s.execute("object.objectsOnPath.detach", &json!({"member": left.0})).unwrap(); + assert_eq!(orders(&s, inner).0, [middle]); + assert_eq!(orders(&s, outer).0, outer_members, "the outer path keeps its objects and takes no new one"); + let (layer, at) = place_of(&s, outer); + assert_eq!(place_of(&s, left), (layer, at + 1), "above the outer group"); +} + +#[test] +fn hidden_and_locked_objects_left_on_the_path_move_up_too() { + let mut s = session(); + let ([left, middle, right], path) = squares_and_line(&mut s); + let g = attach(&mut s, path, &[left, middle, right], json!({})); + select(&mut s, &[right]); + s.execute("object.lock", &json!({})).unwrap(); + select(&mut s, &[middle]); + s.execute("object.hide", &json!({})).unwrap(); + s.execute("object.objectsOnPath.detach", &json!({"member": left.0})).unwrap(); + assert_eq!(orders(&s, g).0, [middle, right]); + assert_eq!(center(&s, middle), Point::new(50.0, 300.0), "the hidden object moves up to the start"); + assert_eq!(center(&s, right), Point::new(350.0, 300.0)); +} + +#[test] +fn objects_moved_out_together_in_the_layers_panel_all_leave_the_path() { + let mut s = session(); + let ([left, middle, right], path) = squares_and_line(&mut s); + let g = attach(&mut s, path, &[left, middle, right], json!({})); + s.execute("layer.move", &json!({"ids": [left.0, middle.0], "target": g.0, "place": "above"})).unwrap(); + assert_eq!(orders(&s, g), (vec![right], vec![path, right])); + assert_eq!(center(&s, right), Point::new(50.0, 300.0), "the one left takes the start"); + let (layer, at) = place_of(&s, g); + assert_eq!((place_of(&s, left), place_of(&s, middle)), ((layer, at + 1), (layer, at + 2)), "above the group, in their order"); +} diff --git a/crates/engine/src/tests/objexpand.rs b/crates/engine/src/tests/objexpand.rs index f638355c52..32c0cb143f 100644 --- a/crates/engine/src/tests/objexpand.rs +++ b/crates/engine/src/tests/objexpand.rs @@ -191,6 +191,91 @@ fn a_fitted_gradient_turned_by_a_transform_expands_as_the_canvas_draws_it() { } } +/// A Transform effect after a drop shadow, on the object or on the fill, scales and turns the +/// shadow on the canvas; Object › Expand of the gradient fill keeps the shadow the canvas drew. +#[test] +fn a_shadow_before_a_transform_expands_as_the_canvas_draws_it() { + for item in [json!(null), json!(0)] { + let mut s = session(); + let id = gradient_rect(&mut s, Rect::new(80.0, 80.0, 120.0, 120.0), white_black(), false); + for (effect, params) in [ + ("stylize.dropShadow", json!({"x": 10, "y": 0, "blur": 0, "opacity": 100})), + ("distort.transform", json!({"scaleH": 200, "scaleV": 200, "rotate": 90})), + ] { + run(&mut s, "effect.apply", json!({"effect": effect, "params": params, "ids": [id.0], "item": item})); + } + let before = render(&s); + run(&mut s, "object.expand", json!({"object": false, "stroke": false, "steps": 64})); + let after = render(&s); + let diff = differing(&before, &after, 64); + assert_eq!(diff, 0, "item {item}: {diff} pixels differ"); + } +} + +/// The object's Transform effect scales and turns the drop shadow of its gradient fill on the +/// canvas; Object › Expand of the fill keeps the shadow the canvas drew. +#[test] +fn a_fills_shadow_under_the_objects_transform_expands_as_the_canvas_draws_it() { + let mut s = session(); + let id = gradient_rect(&mut s, Rect::new(80.0, 80.0, 120.0, 120.0), white_black(), false); + for (effect, params, item) in [ + ("stylize.dropShadow", json!({"x": 10, "y": 0, "blur": 0, "opacity": 100}), json!(0)), + ("distort.transform", json!({"scaleH": 200, "scaleV": 100, "rotate": 90}), json!(null)), + ] { + run(&mut s, "effect.apply", json!({"effect": effect, "params": params, "ids": [id.0], "item": item})); + } + let before = render(&s); + run(&mut s, "object.expand", json!({"object": false, "stroke": false, "steps": 64})); + let after = render(&s); + let diff = differing(&before, &after, 64); + assert_eq!(diff, 0, "{diff} pixels differ"); +} + +/// A group's Transform effect scales and turns its member's drop shadow on the canvas, and an +/// object's scales and turns its fill's, with Scale Strokes & Effects off or on; Expand Appearance +/// keeps the shadows the canvas drew. +#[test] +fn shadows_under_a_groups_or_an_objects_transform_expand_appearance_as_the_canvas_draws_them() { + let shadow = json!({"x": 10, "y": 0, "blur": 0, "opacity": 100}); + for strokes in [false, true] { + let transform = json!({"scaleH": 200, "scaleV": 100, "rotate": 90, "strokes": strokes}); + for group in [false, true] { + let mut s = session(); + let id = gradient_rect(&mut s, Rect::new(80.0, 80.0, 120.0, 120.0), white_black(), false); + let item = if group { json!(null) } else { json!(0) }; + run(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "params": shadow, "ids": [id.0], "item": item})); + if group { + run(&mut s, "object.group", json!({})); + } + run(&mut s, "effect.apply", json!({"effect": "distort.transform", "params": transform})); + let before = render(&s); + run(&mut s, "effect.expandAppearance", json!({})); + let after = render(&s); + let diff = differing(&before, &after, 64); + assert_eq!(diff, 0, "group {group}, Scale Strokes & Effects {strokes}: {diff} pixels differ"); + } + } +} + +/// A group's Transform effect runs after its member's own Offset Path in Expand Appearance as on +/// the canvas: the 100 pt square offset to 120 pt and scaled by half expands 60 pt wide. +#[test] +fn a_groups_effects_after_its_members_own_expand_as_the_canvas_draws_them() { + let mut s = session(); + run(&mut s, "shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100})); + run(&mut s, "effect.apply", json!({"effect": "path.offsetPath", "params": {"offset": 10}})); + run(&mut s, "object.group", json!({})); + run(&mut s, "effect.apply", json!({"effect": "distort.transform", "params": {"scaleH": 50, "scaleV": 50}})); + let before = render(&s); + run(&mut s, "effect.expandAppearance", json!({})); + let after = render(&s); + let diff = differing(&before, &after, 64); + assert_eq!(diff, 0, "{diff} pixels differ"); + let doc = &s.doc().unwrap().doc; + let w = doc.node(doc.layers[0].id).and_then(|l| l.geometric_bounds()).unwrap().width(); + assert!((w - 60.0).abs() < 1e-6, "{w}"); +} + #[test] fn a_placed_gradient_moved_by_a_warp_expands_as_the_canvas_draws_it() { // The object's own effect, and the fill's (the first appearance item). @@ -393,6 +478,240 @@ fn a_mirrored_or_flat_conic_expands_as_the_canvas_draws_it() { } } +/// Three opaque stops running from the center out to the square. +fn diamond_stops() -> Value { + json!({"kind": "diamond", "stops": [{"offset": 0, "color": "#ffff00"}, {"offset": 0.5, "color": "#ff00ff"}, {"offset": 1, "color": "#004080"}]}) +} + +#[test] +fn a_diamond_gradient_becomes_nested_squares_or_a_mesh_that_paint_it() { + // Objects: nested squares about the center, largest first, together painting what the + // canvas painted. + let mut s = session(); + gradient_rect(&mut s, Rect::new(30.0, 40.0, 170.0, 160.0), diamond_stops(), false); + let before = render(&s); + run(&mut s, "object.expand", json!({"steps": 120})); + let g = selected(&s); + let (_, squares) = clip_parts(&g); + assert_eq!(squares.len(), 120); + let corners = |n: &Node| n.path_data().unwrap().subpaths[0].anchors.iter().map(|a| a.p).collect::>(); + let (outer, inner) = (corners(squares[0]), corners(squares[119])); + assert_eq!((outer.len(), inner.len()), (4, 4)); + let reach = |pts: &[vectorcraft_geom::Point]| pts.iter().map(|p| p.distance(vectorcraft_geom::Point::new(100.0, 100.0))).fold(0.0, f64::max); + assert!(reach(&outer) > reach(&inner) * 100.0, "largest first: {outer:?} then {inner:?}"); + let after = render(&s); + assert!(differing(&before, &after, 48) < 200, "{}", differing(&before, &after, 48)); + assert!(mean_diff(&before, &after) < 2.0, "{}", mean_diff(&before, &after)); + // Translucent stops: each square is a ring with the next one cut out, so none doubles up. + let mut s = session(); + let gr = json!({"kind": "diamond", "stops": [{"offset": 0, "color": "#ff0000", "opacity": 0.5}, {"offset": 1, "color": "#0000ff"}]}); + gradient_rect(&mut s, Rect::new(30.0, 40.0, 170.0, 160.0), gr, false); + let before = render(&s); + run(&mut s, "object.expand", json!({"steps": 60})); + let g = selected(&s); + let (_, squares) = clip_parts(&g); + assert!(squares[..59].iter().all(|n| n.path_data().unwrap().subpaths.len() == 2), "rings"); + assert!(mean_diff(&before, &render(&s)) < 4.0, "{}", mean_diff(&before, &render(&s))); + // Mesh: rings of patches about the center. + let mut s = session(); + gradient_rect(&mut s, Rect::new(30.0, 40.0, 170.0, 160.0), diamond_stops(), false); + let before = render(&s); + run(&mut s, "object.expand", json!({"gradient": "mesh"})); + let g = selected(&s); + let (_, content) = clip_parts(&g); + let NodeKind::Mesh(m) = &content[0].kind else { panic!("a mesh node: {:?}", content[0].kind) }; + assert!(m.is_valid()); + let after = render(&s); + assert!(differing(&before, &after, 48) < 200, "{}", differing(&before, &after, 48)); + assert!(mean_diff(&before, &after) < 2.5, "{}", mean_diff(&before, &after)); +} + +/// A turned, squashed diamond, and one whose square is flat (as a file can hold it), expand as +/// the canvas draws them. +#[test] +fn a_turned_or_flat_diamond_expands_as_the_canvas_draws_it() { + for aspect in [0.6, 0.0] { + for how in [json!({"steps": 120}), json!({"gradient": "mesh"})] { + let mut s = session(); + let id = gradient_rect(&mut s, Rect::new(30.0, 40.0, 170.0, 160.0), diamond_stops(), false); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let n = d.node_mut(id).unwrap(); + let Paint::Gradient(mut g) = n.appearance.fill_paint().clone() else { panic!("a gradient fill") }; + let (start, end) = (vectorcraft_geom::Point::new(90.0, 110.0), vectorcraft_geom::Point::new(130.0, 80.0)); + g.geom = Some(vectorcraft_color::GradientGeom { start, end, aspect, focal: None }); + n.appearance.set_fill(Paint::Gradient(g)); + let before = render(&s); + run(&mut s, "object.expand", how.clone()); + let after = render(&s); + assert!(differing(&before, &after, 48) < 200, "{aspect} {how}: {}", differing(&before, &after, 48)); + assert!(mean_diff(&before, &after) < 2.5, "{aspect} {how}: {}", mean_diff(&before, &after)); + } + } +} + +/// A gradient that repeats or reflects expands, into objects or a mesh, as the canvas paints it: +/// its stops repeated across the box, for each kind. +#[test] +fn a_spread_gradient_expands_as_the_canvas_paints_it() { + for kind in ["linear", "radial", "conic", "diamond"] { + for spread in ["repeat", "reflect"] { + for to in [json!({"steps": 240}), json!({"gradient": "mesh"})] { + let mut s = session(); + let gr = json!({"kind": kind, "spread": spread, "repeats": 3, "stops": [{"offset": 0, "color": "#ffff00"}, {"offset": 1, "color": "#004080"}]}); + gradient_rect(&mut s, Rect::new(30.0, 40.0, 170.0, 160.0), gr, false); + let before = render(&s); + run(&mut s, "object.expand", to.clone()); + let after = render(&s); + // Where Repeat starts the stops again, the hard edge may land a pixel off. + assert!(mean_diff(&before, &after) < 4.0, "{kind} {spread} {to}: {}", mean_diff(&before, &after)); + } + } + } +} + +/// A gradient that repeats or reflects expands into the same whole number of objects in each run, +/// so each run starts on an object's edge: a sharp step in the middle of each of 7 runs, expanded +/// into about 15 objects (2 a run), lands where the canvas paints it. +#[test] +fn a_spread_gradient_expands_into_whole_bands_for_each_run() { + let stops = json!([ + {"offset": 0, "color": "#ffff00"}, {"offset": 0.5, "color": "#ffff00"}, + {"offset": 0.5, "color": "#004080"}, {"offset": 1, "color": "#004080"} + ]); + for kind in ["linear", "conic"] { + for spread in ["repeat", "reflect"] { + let mut s = session(); + // A conic gradient turns about the box's center. + let start = if kind == "conic" { [100, 100] } else { [30, 100] }; + let gr = json!({"kind": kind, "spread": spread, "repeats": 7, "start": start, "end": [170, 100], "stops": stops}); + gradient_rect(&mut s, Rect::new(30.0, 40.0, 170.0, 160.0), gr, false); + let before = render(&s); + run(&mut s, "object.expand", json!({"steps": 15})); + let after = render(&s); + assert!(mean_diff(&before, &after) < 2.0, "{kind} {spread}: {}", mean_diff(&before, &after)); + } + } +} + +/// A gradient that repeats across a box in more runs than are written (700 runs of 0.2 pt) is not +/// expanded into its first runs and a flat last color: the fill stays a gradient, and the rest of +/// the object (its stroke) still expands. `object.expand.info` reports no gradient or fill to +/// expand, and Expand with only Fill on reports nothing to expand; the same gradient in 70 runs +/// (10 repeats) reports both. +#[test] +fn a_spread_gradient_with_more_runs_than_written_stays_a_gradient() { + let gradient = |repeats: u32| { + json!({"kind": "linear", "spread": "repeat", "repeats": repeats, "start": [30, 100], "end": [50, 100], + "stops": [{"offset": 0, "color": "#ffff00"}, {"offset": 1, "color": "#004080"}]}) + }; + for (repeats, expands) in [(10, true), (100, false)] { + let mut s = session(); + gradient_rect(&mut s, Rect::new(30.0, 40.0, 170.0, 160.0), gradient(repeats), true); + let info = s.execute("object.expand.info", &json!({})).unwrap(); + assert_eq!( + (info["gradient"].clone(), info["fill"].clone(), info["stroke"].clone()), + (json!(expands), json!(expands), json!(true)), + "{repeats}" + ); + let only_fill = s.execute("object.expand", &json!({"object": false, "stroke": false})); + assert_eq!(only_fill.is_ok(), expands, "{repeats}: {only_fill:?}"); + } + for to in [json!({"steps": 240}), json!({"gradient": "mesh"})] { + let mut s = session(); + gradient_rect(&mut s, Rect::new(30.0, 40.0, 170.0, 160.0), gradient(100), true); + let before = render(&s); + run(&mut s, "object.expand", to.clone()); + let after = render(&s); + assert!(mean_diff(&before, &after) < 2.0, "{to}: {}", mean_diff(&before, &after)); + let mut gradients = 0; + s.doc().unwrap().doc.walk(|n| gradients += usize::from(matches!(n.appearance.fill_paint(), Paint::Gradient(_)))); + assert_eq!(gradients, 1, "{to}"); + } +} + +/// Selected type "Hi" at 48 pt, its characters filled with a gradient that repeats 100 times along +/// a vector `len` pt long. +fn spread_gradient_type(s: &mut Session, len: f64) -> u64 { + let t = run(s, "text.create", json!({"x": 50, "y": 100, "text": "Hi", "size": 48}))["id"].as_u64().unwrap(); + run(s, "select.set", json!({"ids": [t]})); + run( + s, + "paint.setFill", + json!({"gradient": {"kind": "linear", "spread": "repeat", "repeats": 100, "start": [50, 100], "end": [50.0 + len, 100], + "stops": [{"offset": 0, "color": "#ffff00"}, {"offset": 1, "color": "#004080"}]}}), + ); + t +} + +/// How many objects in the document have a gradient fill, and how many are type. +fn gradients_and_type(s: &Session) -> (usize, usize) { + let (mut gradients, mut texts) = (0, 0); + s.doc().unwrap().doc.walk(|n| { + gradients += usize::from(matches!(n.appearance.fill_paint(), Paint::Gradient(_))); + texts += usize::from(matches!(n.kind, NodeKind::Text(_))); + }); + (gradients, texts) +} + +/// Type is outlined before its fills expand, and each glyph's gradient fits that glyph's own box: +/// `object.expand.info` reports a gradient (and a fill) only when a glyph's box needs no more runs +/// than are written, so Expand turns it into art. Both Expand Gradient To options leave the +/// glyphs whose gradient needs more runs with their gradient, and Object still outlines the type. +/// The query leaves the document and its history as they are. +#[test] +fn type_whose_gradient_needs_more_runs_than_written_reports_no_gradient() { + // 0.2 pt runs (100 repeats over 20 pt) across glyphs about 30 pt wide: under the limit. + // 0.02 pt runs (over 2 pt): far over it. + for (len, expands) in [(20.0, true), (2.0, false)] { + let mut s = session(); + spread_gradient_type(&mut s, len); + let before = (s.doc().unwrap().revision, s.doc().unwrap().history.undo.len(), s.doc().unwrap().doc.layers.clone()); + let info = run(&mut s, "object.expand.info", json!({})); + assert_eq!((info["gradient"].clone(), info["fill"].clone(), info["object"].clone()), (json!(expands), json!(expands), json!(true)), "{len}"); + assert!( + before == (s.doc().unwrap().revision, s.doc().unwrap().history.undo.len(), s.doc().unwrap().doc.layers.clone()), + "{len}: the query changed the document" + ); + for to in [json!({}), json!({"gradient": "mesh"})] { + let mut s = session(); + spread_gradient_type(&mut s, len); + run(&mut s, "object.expand", to.clone()); + let (gradients, texts) = gradients_and_type(&s); + assert_eq!(texts, 0, "{len} {to}: outlined"); + assert_eq!(gradients == 0, expands, "{len} {to}: {gradients} gradient fills left"); + } + } +} + +/// One glyph whose box needs more runs than are written does not hide another that Expand turns +/// into art: the 200 pt "H" keeps its gradient, the 48 pt "i" expands, and the query reports it. +#[test] +fn type_reports_a_gradient_when_any_glyph_expands() { + let mut s = session(); + let t = spread_gradient_type(&mut s, 20.0); + run(&mut s, "text.setRangeStyle", json!({"id": t, "start": 0, "end": 1, "size": 200})); + let info = run(&mut s, "object.expand.info", json!({})); + assert_eq!((info["gradient"].clone(), info["fill"].clone()), (json!(true), json!(true))); + run(&mut s, "object.expand", json!({})); + assert_eq!(gradients_and_type(&s), (1, 0), "the large glyph keeps its gradient"); +} + +/// The same rule for type in the art of a symbol instance that Object expands. The symbol's art +/// is the type scaled down (its "i" about 2.5 pt wide), so its glyphs need more runs than are +/// written with 0.002 pt runs (over a 0.2 pt vector). +#[test] +fn type_in_symbol_art_reports_a_gradient_only_when_it_expands() { + for (len, expands) in [(20.0, true), (0.2, false)] { + let mut s = session(); + spread_gradient_type(&mut s, len); + let inst = run(&mut s, "symbol.new", json!({"name": "Hi"}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids": [inst]})); + let info = run(&mut s, "object.expand.info", json!({})); + assert_eq!(info["gradient"], json!(expands), "{len}"); + assert_eq!((info["symbolArt"]["gradient"].clone(), info["symbolArt"]["fill"].clone()), (json!(expands), json!(expands)), "{len}: {info}"); + } +} + #[test] fn the_mesh_option_makes_a_mesh_that_paints_the_gradient() { for gradient in [ @@ -1281,3 +1600,54 @@ fn expand_info_counts_two_fills_but_not_a_plain_rectangle() { run(&mut s, "appearance.addFill", json!({})); assert_eq!(run(&mut s, "object.expand.info", json!({}))["appearance"], json!(true), "two fills"); } + +/// A Transform effect left out past the effect budget (its result over 8 million lines drawn) +/// leaves the art where it is, and Expand, Expand Appearance and Outline Stroke keep the drop +/// shadow before it with its own offset and blur, as the canvas draws it: the object's, the fill's +/// and the stroke's. +#[test] +fn a_shadow_before_a_skipped_transform_expands_with_its_own_offset() { + use vectorcraft_doc::{Appearance, Effect}; + use vectorcraft_geom::{Anchor, PathData, Point, SubPath}; + let anchors = (0..=30_000) + .map(|i| { + let x = 2.0 * f64::from(i); + Anchor::with_handles(Point::new(x, 0.0), Point::new(x - 0.5, -20.0), Point::new(x + 0.5, 20.0)) + }) + .collect(); + let path = PathData::single(SubPath::new(anchors, true)); + let bounds = path.bounds().unwrap(); + let effects = || { + vec![ + Effect { id: "stylize.dropShadow".into(), params: json!({"x": 10, "y": 5, "blur": 4}), visible: true }, + Effect { id: "distort.transform".into(), params: json!({"scaleH": 100000, "scaleV": 100000}), visible: true }, + ] + }; + let shadow = |effects: &[Effect]| match vectorcraft_render::effects::raster_effects(effects).first() { + Some(vectorcraft_render::effects::RasterFx::DropShadow { dx, dy, blur, .. }) => (*dx, *dy, *blur), + other => panic!("expected a drop shadow, got {other:?}"), + }; + let mut d = vectorcraft_doc::Document::new(200.0, 200.0); + let basic = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 2.0); + let mut object = Node::path(NodeId(1), path.clone(), basic.clone()); + object.appearance.effects = effects(); + let m = crate::cmd::expand::reshaped(&d, &object).unwrap(); + assert_eq!(m.geometric_bounds(), Some(bounds), "the art stays where it is"); + assert_eq!(shadow(&m.appearance.effects), (10.0, 5.0, 4.0), "the object's shadow"); + let mut fill = Node::path(NodeId(2), path.clone(), basic.clone()); + *fill.appearance.items[0].effects_mut() = effects(); + let (_, _, _, moved) = crate::cmd::expand::fill_shape(&d, &fill, &fill.appearance.items[0], &path, bounds).unwrap(); + assert_eq!(shadow(moved.effects()), (10.0, 5.0, 4.0), "the fill's shadow"); + let mut stroke = Node::path(NodeId(3), path.clone(), basic); + *stroke.appearance.items[1].effects_mut() = effects(); + let outlined = crate::cmd::pathops::outline_strokes(&mut d, &[], &stroke).unwrap(); + let mut drawn = vec![]; + outlined.walk(&mut |n| { + for item in &n.appearance.items { + if !vectorcraft_render::effects::raster_effects(item.effects()).is_empty() { + drawn.push(shadow(item.effects())); + } + } + }); + assert_eq!(drawn, [(10.0, 5.0, 4.0)], "the stroke's shadow"); +} diff --git a/crates/engine/src/tests/outlinestroke.rs b/crates/engine/src/tests/outlinestroke.rs index 166c88725e..16b57a628c 100644 --- a/crates/engine/src/tests/outlinestroke.rs +++ b/crates/engine/src/tests/outlinestroke.rs @@ -73,14 +73,13 @@ fn arrowheads_are_part_of_the_outline() { assert_eq!(path_of(&n).subpaths.len(), 1, "line and head are one shape"); } -/// Outline Stroke of a Lens-profile line covers 7/12 of the full-width rectangle. +/// Outline Stroke of a Lens-profile line covers 2/3 of the full-width rectangle. #[test] -fn a_lens_profile_outlines_to_seven_twelfths_of_the_rectangle() { +fn a_lens_profile_outlines_to_two_thirds_of_the_rectangle() { let mut s = session(); line(&mut s, json!({"weight": 10, "profile": "lens"})); let n = outline(&mut s); - // Each half of the lens swells on a cubic, flat at the middle (#5714). - assert!(near(area(&n), 7.0 / 12.0 * 10.0 * 100.0, 2.0), "{}", area(&n)); + assert!(near(area(&n), 2.0 / 3.0 * 10.0 * 100.0, 2.0), "{}", area(&n)); } #[test] @@ -309,6 +308,54 @@ fn the_outline_of_a_reshaped_stroke_keeps_its_drop_shadow() { assert_eq!(differing(&before, &render(&s), 64), 0, "the shadowed outline draws as the stroke did"); } +/// A Transform effect after a drop shadow, on the object or on the stroke (brushed or not), turns +/// and scales the shadow on the canvas; outlining the stroke keeps the shadow the canvas drew. +#[test] +fn a_shadow_before_a_transform_outlines_as_the_canvas_draws_it() { + let effects = [ + ("stylize.dropShadow", json!({"x": 10, "y": 0, "blur": 0, "opacity": 100})), + ("distort.transform", json!({"scaleH": 50, "scaleV": 50, "rotate": 90})), + ]; + for (item, brush) in [(Value::Null, false), (json!(1), false), (json!(1), true)] { + // Flatten Transparency draws a brushed stroke's drop shadow differently with or without a + // Transform effect, so the brushed stroke is checked with the other two commands. + for (command, p) in outlining().into_iter().filter(|(command, _)| !(brush && *command == "object.flattenTransparency")) { + let mut s = session(); + square_with(&mut s, json!({"color": "#ff0000"}), item.clone(), &effects); + if brush { + s.execute("brush.apply", &json!({"name": "Tapered Stroke"})).unwrap(); + } + let before = render(&s); + outlined_by(&mut s, command, &p); + assert_eq!(differing(&before, &render(&s), 64), 0, "{command}, item {item}, brush {brush}"); + } + } +} + +/// The object's Transform effect turns and scales the drop shadow of its stroke (brushed or not) +/// on the canvas; outlining the stroke keeps the shadow the canvas drew. +#[test] +fn a_strokes_shadow_under_the_objects_transform_outlines_as_the_canvas_draws_it() { + for brush in [false, true] { + for (command, p) in outlining().into_iter().filter(|(command, _)| !(brush && *command == "object.flattenTransparency")) { + let mut s = session(); + square_with( + &mut s, + json!({"color": "#ff0000"}), + json!(1), + &[("stylize.dropShadow", json!({"x": 10, "y": 0, "blur": 0, "opacity": 100}))], + ); + s.execute("effect.apply", &json!({"effect": "distort.transform", "params": {"scaleH": 50, "scaleV": 100, "rotate": 90}})).unwrap(); + if brush { + s.execute("brush.apply", &json!({"name": "Tapered Stroke"})).unwrap(); + } + let before = render(&s); + outlined_by(&mut s, command, &p); + assert_eq!(differing(&before, &render(&s), 64), 0, "{command}, brush {brush}"); + } + } +} + /// The brush art of a brushed stroke with a geometry effect follows the path the effect makes. #[test] fn a_brush_draws_along_the_path_the_stroke_effects_make() { diff --git a/crates/engine/src/tests/package.rs b/crates/engine/src/tests/package.rs index 01550b5ad1..2e57ed048c 100644 --- a/crates/engine/src/tests/package.rs +++ b/crates/engine/src/tests/package.rs @@ -280,6 +280,103 @@ fn a_missing_link_is_reported_not_copied() { assert!(report.contains("blue.png: not found"), "{report}"); } +/// Packaged for a client whose read root holds neither the document's file nor its links: the report, +/// its Document Info part included, names them by their file names, and `document.info` gives no +/// link. The person's report names them whole. +#[test] +fn a_confined_package_names_files_outside_the_read_root_by_name() { + let dir = Folder::new("package-roots"); + let mut s = poster(&dir); + std::fs::create_dir_all(dir.file("in")).unwrap(); + std::fs::remove_file(dir.file("art/blue.png")).unwrap(); + open(&mut s, &dir.file("poster.vectorcraft")); + let report = |r: &Value| { + let zip = unzip(&vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap()); + String::from_utf8(zip["poster Folder/poster Report.txt"].clone()).unwrap() + }; + let person = report(&run(&mut s, "file.package", json!({}))); + assert!(person.contains(&format!("From: {}\n", dir.file("poster.vectorcraft"))), "{person}"); + assert!(person.contains(&format!("{} → Links/red.png", dir.file("art/red.png"))), "{person}"); + assert!(person.contains(&format!("blue.png: not found ({})", dir.file("art/blue.png"))), "{person}"); + + let in_root = dir.0.join("in"); + let roots = crate::file_access::AutomationRoots::new(&[in_root.as_path()], &[]).unwrap(); + let client = crate::file_access::confine(roots.as_ref(), || run(&mut s, "file.package", json!({}))); + let text = report(&client); + assert!(text.contains("From: poster.vectorcraft\n"), "{text}"); + assert!(text.contains("\nred.png → Links/red.png\n") && text.contains("\nblue.png: not found (blue.png), not copied\n"), "{text}"); + let base = dir.0.to_string_lossy().into_owned(); + assert!(!text.contains(&base), "{text}"); + for key in ["missingLinks", "warnings", "files"] { + assert!(!client[key].to_string().contains(&base), "{key}: {client}"); + } + // Document Info, whose report the package holds, gives no link either. + for p in [json!({}), json!({"format": "text"})] { + let info = crate::file_access::confine(roots.as_ref(), || run(&mut s, "document.info", p.clone())); + assert!(!info.to_string().contains(&base), "{p}: {info}"); + } + let info = run(&mut s, "document.info", json!({"format": "text"})); + assert!(info.to_string().contains(&dir.file("art/red.png")), "the person's: {info}"); +} + +/// A missing link stored as a path relative to the document names a file inside a confined +/// request's read root: the package report and Document Info give its stored path. +#[test] +fn a_relative_link_inside_the_read_root_keeps_its_path() { + let dir = Folder::new("package-roots-relative"); + write(&dir.file("art/near.png"), &png(8, 8, RED)); + let mut s = session(); + let id = place(&mut s, &dir.file("art/near.png")); + let mut doc = (*s.doc().unwrap().doc).clone(); + let Some(vectorcraft_doc::NodeKind::Image(im)) = doc.node_mut(id).map(|n| &mut n.kind) else { panic!("not an image") }; + im.link = Some(vectorcraft_doc::LinkInfo::new("art/near.png")); + write(&dir.file("near.vectorcraft"), &vectorcraft_format::save(&doc, false)); + // Missing, the link keeps its stored path when the document opens (the package copies the + // image the document holds). + std::fs::remove_file(dir.file("art/near.png")).unwrap(); + open(&mut s, &dir.file("near.vectorcraft")); + let roots = crate::file_access::AutomationRoots::new(&[dir.0.as_path()], &[]).unwrap(); + let r = crate::file_access::confine(roots.as_ref(), || run(&mut s, "file.package", json!({}))); + let zip = unzip(&vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap()); + let text = String::from_utf8(zip["near Folder/near Report.txt"].clone()).unwrap(); + assert!(text.contains("\nart/near.png → Links/near.png\n"), "{text}"); + let info = crate::file_access::confine(roots.as_ref(), || run(&mut s, "document.info", json!({}))); + let links: Vec<&Value> = info["images"].as_object().unwrap().values().map(|i| &i["link"]).collect(); + assert_eq!(links, [&json!("art/near.png")], "{info}"); + let text = crate::file_access::confine(roots.as_ref(), || run(&mut s, "document.info", json!({"format": "text"}))); + assert!(text.to_string().contains("art/near.png"), "{text}"); +} + +/// A link whose stored path names a place outside a confined request's read root, with its file +/// found by name beside the document inside the root: the package report and reply give the file +/// name, not the stored path. +#[test] +fn a_stored_path_outside_the_read_root_is_left_out_when_its_file_is_found_inside() { + let dir = Folder::new("package-roots-stale"); + write(&dir.file("in/near.png"), &png(8, 8, RED)); + let mut s = session(); + let id = place(&mut s, &dir.file("in/near.png")); + let mut doc = (*s.doc().unwrap().doc).clone(); + let Some(vectorcraft_doc::NodeKind::Image(im)) = doc.node_mut(id).map(|n| &mut n.kind) else { panic!("not an image") }; + let stale = dir.file("out/near.png"); + im.link = Some(vectorcraft_doc::LinkInfo::new(&stale)); + write(&dir.file("in/near.vectorcraft"), &vectorcraft_format::save(&doc, false)); + // Missing when the document opens, the link keeps its stored path; the file then appears beside it. + std::fs::remove_file(dir.file("in/near.png")).unwrap(); + open(&mut s, &dir.file("in/near.vectorcraft")); + write(&dir.file("in/near.png"), &png(8, 8, RED)); + let in_root = dir.0.join("in"); + let roots = crate::file_access::AutomationRoots::new(&[in_root.as_path()], &[]).unwrap(); + let r = crate::file_access::confine(roots.as_ref(), || run(&mut s, "file.package", json!({}))); + let zip = unzip(&vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap()); + let text = String::from_utf8(zip["near Folder/near Report.txt"].clone()).unwrap(); + assert!(text.contains("\nnear.png → Links/near.png\n"), "{text}"); + assert!(!text.contains(&stale), "{text}"); + for key in ["missingLinks", "warnings", "files"] { + assert!(!r[key].to_string().contains(&stale), "{key}: {r}"); + } +} + /// A file missing from a document that moved keeps the place its relative path names from the /// document's folder: the packaged document writes its relative path from there. #[test] @@ -418,7 +515,7 @@ fn the_document_info_report_has_every_category() { "OBJECTS", "GRAPHIC STYLES", "BRUSHES", - "SPOT COLORS", + "SPOT COLOR OBJECTS", "PATTERN OBJECTS", "GRADIENT OBJECTS", "SYMBOLS", diff --git a/crates/engine/src/tests/panelcmds.rs b/crates/engine/src/tests/panelcmds.rs index 28f81587ab..ac39de0646 100644 --- a/crates/engine/src/tests/panelcmds.rs +++ b/crates/engine/src/tests/panelcmds.rs @@ -2109,7 +2109,7 @@ fn empty_artboard_checks_match_the_visual_bounds_on_varied_strokes() { st.cap = [LineCap::Butt, LineCap::Round, LineCap::Square][next(3) as usize]; st.align = [StrokeAlign::Center, StrokeAlign::Inside, StrokeAlign::Outside][next(3) as usize]; st.miter_limit = 1.0 + next(20) as f64; - let mut head = || (next(3) == 0).then(|| Arrowhead::ALL[next(Arrowhead::ALL.len() as u64) as usize]); + let mut head = || (next(3) == 0).then(|| Arrowhead::ALL[next(Arrowhead::ALL.len() as u64) as usize].clone()); (st.start_arrow, st.end_arrow) = (head(), head()); st.arrow_scale = (50.0 + next(250) as f64, 50.0 + next(250) as f64); if next(3) == 0 { diff --git a/crates/engine/src/tests/params.rs b/crates/engine/src/tests/params.rs index b0345db4ff..e72f607030 100644 --- a/crates/engine/src/tests/params.rs +++ b/crates/engine/src/tests/params.rs @@ -400,6 +400,141 @@ fn stroke_set_refuses_an_unknown_key() { } } +/// An object id given as something other than a whole number (`"5"`, `-1`) is refused as such, +/// naming its key, not as a missing id; an id left out is still a missing one. +#[test] +fn a_malformed_object_id_is_not_reported_as_missing() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap(); + let undo = |s: &Session| s.doc().unwrap().history.undo.len(); + let before = undo(&s); + let points = json!([[0, 0], [10, 10], [20, 0]]); + for bad in [json!("5"), json!(-1)] { + let id = || json!({ "id": bad }); + let with = |extra: serde_json::Value| { + let mut p = id(); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + p + }; + for (cmd, p, key) in [ + ("stroke.widthPoint.set", id(), "id"), + ("stroke.widthPoint.copy", id(), "id"), + ("stroke.widthPoint.remove", id(), "id"), + ("path.curvatureEdit", id(), "id"), + ("path.removeAnchor", id(), "id"), + ("path.convertAnchor", id(), "id"), + ("path.reshapeSegment", id(), "id"), + ("path.split", id(), "id"), + ("path.appendAnchor", id(), "id"), + ("path.close", id(), "id"), + ("path.setHandle", id(), "id"), + ("path.moveAnchor", id(), "id"), + ("path.setAnchors", id(), "id"), + ("path.reshape", id(), "id"), + ("path.insertAnchor", id(), "id"), + ("path.freehand", json!({"points": points, "extend": {"id": bad}}), "id"), + ("path.freehand", json!({"points": points, "redraw": {"id": bad}}), "id"), + ("document.node", id(), "id"), + ("layer.target", id(), "id"), + ("layer.setCurrent", id(), "id"), + ("layer.selectAll", id(), "id"), + ("layer.move", with(json!({"target": 1})), "id"), + ("layer.move", json!({"ids": [1], "target": bad}), "target"), + ("node.move", id(), "id"), + ("node.move", json!({"id": 1, "parent": bad}), "parent"), + ("text.reshapeArea", with(json!({"anchors": []})), "id"), + ("text.reshapeArea", json!({"items": [{"id": bad, "anchors": []}]}), "id"), + ("text.reshapePath", id(), "id"), + ("text.setPathHandle", id(), "id"), + ("text.editRange", id(), "id"), + ("text.startList", id(), "id"), + ("text.getRange", id(), "id"), + ("text.setGlyphAlternate", id(), "id"), + ("text.glyphAlternates", id(), "id"), + ("text.touchType", id(), "id"), + ("text.discardEmpty", id(), "id"), + ("text.createInPath", json!({"path": bad}), "path"), + ("object.envelope.setMeshPoint", id(), "id"), + ("object.mesh.setPointColor", with(json!({"index": 0})), "id"), + ("object.mesh.movePoint", with(json!({"index": 0, "x": 0, "y": 0})), "id"), + ("object.mesh.movePoints", json!({"items": [{"id": bad, "index": 0}]}), "id"), + ("object.mesh.addLine", with(json!({"x": 0, "y": 0})), "id"), + ("object.mesh.deletePoint", with(json!({"index": 0})), "id"), + ("object.slice.setRect", id(), "id"), + ("appearance.transfer", json!({"source": bad, "target": 1}), "source"), + ("appearance.transfer", json!({"source": 1, "target": bad}), "target"), + ("appearance.copyFrom", json!({"source": bad}), "source"), + ("livePaint.strokeEdge", json!({"point": [0, 0], "group": bad}), "group"), + ("livePaint.fill", json!({"point": [0, 0], "group": bad}), "group"), + ("livePaint.info", json!({"group": bad}), "group"), + ("livePaint.info", id(), "id"), + ("select.magicWand", id(), "id"), + ] { + let e = s.execute(cmd, &p).unwrap_err().to_string(); + // `layer.move` checks an `id` that stands in for `ids` before it runs. + let named = e.contains(&format!("`{key}` must be a whole number")) || (cmd == "layer.move" && e.contains("invalid object id")); + assert!(named, "{cmd} {p}: {e}"); + } + } + for cmd in ["path.close", "layer.target", "text.reshapePath", "object.mesh.movePoint", "select.magicWand"] { + let e = s.execute(cmd, &json!({})).unwrap_err().to_string(); + assert!(e.contains("missing"), "{cmd}: {e}"); + } + assert_eq!(undo(&s), before); +} + +/// A required number given as something other than a number (`"40"`, `true`, `[]`, `{}`) is refused +/// as the wrong type, naming its key and showing the value as given, not as a missing number; one left +/// out or given as null is still a missing number. Neither changes the document or records an undo step. +#[test] +fn a_malformed_required_number_is_not_reported_as_missing() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap(); + let doc = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + let with = |base: &serde_json::Value, key: &str, v: Option| { + let mut p = base.clone(); + let o = p.as_object_mut().unwrap(); + match v { + Some(v) => o.insert(key.into(), v), + None => o.remove(key), + }; + p + }; + let cases = [ + ("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10}), "x"), + ("edit.colors.saturate", json!({"intensity": 40}), "intensity"), + ("object.envelope.setMeshPoint", json!({"id": 1, "index": 0, "x": 0, "y": 0}), "index"), + ("object.envelope.setMeshPoint", json!({"id": 1, "index": 0, "x": 0, "y": 0}), "x"), + ("object.mesh.movePoint", json!({"id": 1, "index": 0, "x": 0, "y": 0}), "y"), + ("guide.add", json!({"pos": 40}), "pos"), + ]; + for (cmd, base, key) in &cases { + for (v, shown) in [(json!("40"), "\"40\""), (json!(true), "true"), (json!([]), "[]"), (json!({}), "{}")] { + let p = with(base, key, Some(v)); + match s.execute(cmd, &p) { + Err(EngineError::BadParams { cmd: c, msg }) => { + assert_eq!((c.as_str(), msg), (*cmd, format!("`{key}` must be a number, not {shown}")), "{p}"); + } + other => panic!("{cmd} {p}: {other:?}"), + } + } + for p in [with(base, key, None), with(base, key, Some(json!(null)))] { + match s.execute(cmd, &p) { + Err(EngineError::BadParams { cmd: c, msg }) => assert_eq!((c.as_str(), msg), (*cmd, format!("missing number `{key}`")), "{p}"), + other => panic!("{cmd} {p}: {other:?}"), + } + } + } + assert_eq!(s.doc().unwrap().doc, doc); + assert_eq!(s.doc().unwrap().history.undo.len(), undo); + // A whole JSON number is a number for a fractional parameter. + s.execute("guide.add", &json!({"pos": 40})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); +} + /// A command that takes the keys of one that isn't checked yet isn't checked either. #[test] fn a_reference_to_an_unchecked_command_is_unchecked() { @@ -465,6 +600,105 @@ fn effect_params_are_the_effects_own() { assert!(s.check_params("effect.setParams", &json!({"index": 7, "params": {"blurr": 3}})).is_ok()); } +/// An effect parameter that only the effect's params description names, with no dialog default, +/// is held to the type the effect reads: the earlier 3D Perspective and light, Scribble's +/// `variation` and an Outline Stroke's `width` are numbers, and a Gaussian Blur's `linear` is true +/// or false. The `style` of Crop Marks is `roman` or `japanese`. Every such key of every effect is +/// listed, or has a check of its own. A key left out keeps its default. +#[test] +fn an_effect_parameter_without_a_default_is_held_to_its_type() { + use crate::cmd::params::undefaulted_type; + use vectorcraft_render::effects::effect_catalog; + // Read by checks of their own: a stored texture or a texture to load, an SVG filter, a Warp's + // map and the style of Crop Marks. + let own_check = |effect: &str, key: &str| match key { + "textureImage" | "name" | "xml" => true, + "version" => effect.starts_with("warp."), + "style" => effect == "cropMarks", + _ => false, + }; + let mut unlisted = vec![]; + for e in effect_catalog() { + for key in doc_keys(e.params).unwrap().keys { + if e.defaults.get(key).is_none() && undefaulted_type(e.id, key).is_none() && !own_check(e.id, key) { + unlisted.push(format!("{}.{key}", e.id)); + } + } + } + assert!(unlisted.is_empty(), "parameters without a default or a listed type: {unlisted:?}"); + let apply = |effect: &str, params| json!({"effect": effect, "params": params}); + for (effect, params, why) in [ + ("threeD.revolve", json!({"perspective": true}), "`perspective` must be a number"), + ("threeD.extrude", json!({"lightAzimuth": "30"}), "`lightAzimuth` must be a number"), + ("threeD.rotate", json!({"lightElevation": null}), "`lightElevation` must be a number"), + ("threeD.inflate", json!({"perspective": "50%"}), "`perspective` must be a number"), + ("path.outlineStroke", json!({"width": "10 pt"}), "`width` must be a number"), + ("stylize.scribble", json!({"variation": false}), "`variation` must be a number"), + ("blur.gaussian", json!({"radius": 2, "linear": 1}), "`linear` must be true or false"), + ("cropMarks", json!({"style": "bogus"}), "`style` must be roman or japanese"), + ("cropMarks", json!({"style": 1}), "`style` must be roman or japanese"), + ("cropMarks", json!({"style": null}), "`style` must be roman or japanese"), + ] { + assert_eq!(refusal("effect.apply", apply(effect, params.clone())), why, "{effect} {params}"); + assert_eq!(refusal("appearance.addEffect", apply(effect, params.clone())), why, "{effect} {params}"); + } + for (effect, params) in [ + ("threeD.revolve", json!({"perspective": 40, "lightAzimuth": 30.5, "lightElevation": 0})), + ("path.outlineStroke", json!({"width": 10})), + ("stylize.scribble", json!({"variation": 2})), + ("blur.gaussian", json!({"linear": true})), + ("blur.gaussian", json!({})), + ("cropMarks", json!({"style": "japanese"})), + ("cropMarks", json!({})), + ] { + assert!(check_params("effect.apply", &apply(effect, params.clone())).is_ok(), "{effect} {params}"); + } +} + +/// `effect.apply`, `appearance.addEffect` and `effect.setParams` refuse such a parameter of the +/// wrong type when they run, and so does a step of a `command.batch` whose effect a step before it +/// added, with the document and its undo history as they were. A saved step still plays with it, +/// as with a key the effect no longer takes. +#[test] +fn effect_commands_refuse_an_undefaulted_parameter_of_the_wrong_type() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap(); + let state = |s: &Session| { + let st = s.doc().unwrap(); + (st.history.undo.len(), st.doc.clone()) + }; + let before = state(&s); + let apply = |effect: &str, params| json!({"effect": effect, "params": params}); + for (id, params, why) in [ + ("effect.apply", apply("path.outlineStroke", json!({"width": "10 pt"})), "`width` must be a number"), + ("appearance.addEffect", apply("blur.gaussian", json!({"linear": 1})), "`linear` must be true or false"), + ("effect.apply", apply("threeD.revolve", json!({"perspective": "50"})), "`perspective` must be a number"), + ] { + let e = s.execute(id, ¶ms).unwrap_err().to_string(); + assert!(e.contains(why), "{id} {params}: {e}"); + assert_eq!(state(&s), before, "{id} {params}"); + } + let batch = json!({"commands": [ + {"command": "effect.apply", "params": apply("path.outlineStroke", json!({"width": 3}))}, + {"command": "effect.setParams", "params": {"index": 0, "params": {"width": "10 pt"}}}, + ]}); + let e = s.execute("command.batch", &batch).unwrap_err().to_string(); + assert!(e.contains("`width` must be a number"), "{e}"); + assert_eq!(state(&s), before); + s.execute("effect.apply", &apply("path.outlineStroke", json!({"width": 3}))).unwrap(); + let applied = state(&s); + for params in [json!({"width": "10 pt"}), json!({"width": null}), json!({"width": true})] { + let e = s.execute("effect.setParams", &json!({"index": 0, "params": params.clone()})).unwrap_err().to_string(); + assert!(e.contains("`width` must be a number"), "{params}: {e}"); + assert_eq!(state(&s), applied, "{params}"); + } + s.execute("effect.setParams", &json!({"index": 0, "params": {"width": 4}})).unwrap(); + s.replay("effect.setParams", &json!({"index": 0, "params": {"retired": "x", "width": "10 pt"}})).unwrap(); + let st = s.doc().unwrap(); + assert_eq!(st.doc.layers[0].children().unwrap()[0].appearance.effects[0].params["width"], json!("10 pt")); +} + /// The Transform effect (`distort.transform`) is held to its params description: `effect.apply` /// and `effect.setParams` refuse each of its on/off options given as text, such as `reflectX: /// "false"`, and each of its numbers given as text, such as `copies: "0"`, and leave the effect diff --git a/crates/engine/src/tests/pathtype.rs b/crates/engine/src/tests/pathtype.rs index 5ead0cbd22..8aa8c05684 100644 --- a/crates/engine/src/tests/pathtype.rs +++ b/crates/engine/src/tests/pathtype.rs @@ -184,6 +184,184 @@ fn a_flip_round_a_closed_path_keeps_the_type_in_place() { assert!(origins(&s, id)[0].distance(first) < 8.0); } +/// A circle of radius 100 round (200, 200), starting at 9 o'clock and running clockwise, with +/// type on it from its start. +fn on_circle(s: &mut Session, text: &str) -> NodeId { + path_type(s, "M100 200 A100 100 0 1 1 300 200 A100 100 0 1 1 100 200 Z", [90.0, 200.0], text) +} + +#[test] +fn center_on_top_and_bottom_of_a_circle() { + let mut s = session(); + let id = on_circle(&mut s, "OOOO"); + assert!(near(brackets(&s, id).0, 0.0), "{:?}", brackets(&s, id)); + let steps = undo_len(&s); + let r = s.execute("type.pathCenter.top", &json!({})).unwrap(); + // Once round, its middle at 12 o'clock, a quarter of the way round: the type sits on the top, centered. + let (start, end) = brackets(&s, id); + assert!(near(start, 0.75) && end.is_none(), "{start} {end:?}"); + assert_eq!((r["ids"].clone(), r["end"].clone()), (json!([id.0]), Value::Null)); + assert_eq!(text(&s, id).para_at(0).justify, vectorcraft_doc::Justify::Center); + let top = ink(&s, id); + assert!((top.center().x - 200.0).abs() < 0.5 && top.y1 < 101.0, "{top:?}"); + assert_eq!((undo_len(&s), last_step(&s)), (steps + 1, "Center on Top".to_string())); + // Again: nothing moves, and no undo step is recorded. + s.execute("type.pathCenter.top", &json!({})).unwrap(); + assert_eq!(undo_len(&s), steps + 1); + // The bottom: 6 o'clock, outside the circle (the type is not flipped). + s.execute("type.pathCenter.bottom", &json!({})).unwrap(); + let (start, end) = brackets(&s, id); + assert!(near(start, 0.25) && end.is_none(), "{start} {end:?}"); + let bottom = ink(&s, id); + assert!((bottom.center().x - 200.0).abs() < 0.5 && bottom.y0 > 299.0, "{bottom:?}"); + assert_eq!((undo_len(&s), last_step(&s)), (steps + 2, "Center on Bottom".to_string())); + // Justify Center stays as it is. + s.execute("text.setStyle", &json!({"justify": "justifyCenter"})).unwrap(); + s.execute("type.pathCenter.top", &json!({})).unwrap(); + assert_eq!(text(&s, id).para_at(0).justify, vectorcraft_doc::Justify::JustifyCenter); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(near(brackets(&s, id).0, 0.25)); + // Brackets already in place with another alignment: only the alignment changes, in one step. + s.execute("text.setStyle", &json!({"justify": "left"})).unwrap(); + let (steps, before) = (undo_len(&s), brackets(&s, id)); + s.execute("type.pathCenter.bottom", &json!({})).unwrap(); + assert_eq!((undo_len(&s), brackets(&s, id)), (steps + 1, before)); + assert_eq!(text(&s, id).para_at(0).justify, vectorcraft_doc::Justify::Center); +} + +#[test] +fn center_on_top_twice_records_one_step_for_any_span() { + let mut s = session(); + let id = on_circle(&mut s, "OOOO"); + for (start, end) in [(0.0, 0.2), (0.13, 0.41), (0.37, 0.52), (0.61, 0.97), (0.89, 0.07), (0.3, 0.3001)] { + s.execute("type.pathOptions", &json!({"start": start, "end": end})).unwrap(); + for c in ["type.pathCenter.top", "type.pathCenter.bottom"] { + s.execute(c, &json!({})).unwrap(); + let (steps, placed) = (undo_len(&s), brackets(&s, id)); + // Again: the brackets stay exactly where they are, and no undo step is recorded. + s.execute(c, &json!({})).unwrap(); + assert_eq!((undo_len(&s), brackets(&s, id)), (steps, placed), "{c} {start} {end}"); + } + } +} + +#[test] +fn center_on_top_keeps_the_span_and_measures_the_path_as_drawn() { + let mut s = session(); + let id = on_circle(&mut s, "OOOO"); + // A span of a fifth of the path keeps its length. + s.execute("type.pathOptions", &json!({"end": 0.2})).unwrap(); + s.execute("type.pathCenter.top", &json!({})).unwrap(); + let (start, end) = brackets(&s, id); + assert!(near(start, 0.15) && end.is_some_and(|e| near(e, 0.35)), "{start} {end:?}"); + // Turned a quarter turn counter-clockwise, its 3 o'clock point, halfway round, is at the top. + s.execute("type.pathOptions", &json!({"start": 0, "end": null})).unwrap(); + s.execute("object.rotate", &json!({"angle": 90})).unwrap(); + s.execute("type.pathCenter.top", &json!({})).unwrap(); + let (start, _) = brackets(&s, id); + assert!(near(start.rem_euclid(1.0), 0.0) || near(start, 1.0), "{start}"); + let bounds = text(&s, id).bounds().unwrap(); + let top = ink(&s, id); + assert!((top.center().x - bounds.center().x).abs() < 0.5 && top.y1 < bounds.y0 + 1.0, "{top:?} {bounds:?}"); + // A rectangle: the middle of its top edge. + let id = path_type(&mut s, "M100 100 L300 100 L300 300 L100 300 Z", [90.0, 100.0], "OOOO"); + s.execute("type.pathCenter.top", &json!({})).unwrap(); + let (start, end) = brackets(&s, id); + assert!(near(start, 0.625) && end.is_none(), "{start} {end:?}"); + assert!((ink(&s, id).center().x - 200.0).abs() < 0.5); +} + +#[test] +fn center_on_top_moves_every_selected_type_on_a_path_in_one_step() { + let mut s = session(); + let a = on_circle(&mut s, "OOOO"); + let b = path_type(&mut s, "M100 100 L300 100 L300 300 L100 300 Z", [90.0, 100.0], "OOOO"); + let p = s.execute("text.create", &json!({"x": 40, "y": 40, "text": "Point"})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a.0, b.0, p]})).unwrap(); + let steps = undo_len(&s); + let r = s.execute("type.pathCenter.top", &json!({})).unwrap(); + assert_eq!(r["ids"], json!([a.0, b.0])); + assert!(near(brackets(&s, a).0, 0.75) && near(brackets(&s, b).0, 0.625)); + assert_eq!(undo_len(&s), steps + 1); + // Dynamic Text stays on, and the layout fits the text to the span where it now runs: a fifth of + // the circle, at its bottom. + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("type.pathOptions", &json!({"start": 0, "end": 0.2})).unwrap(); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + s.execute("type.pathCenter.bottom", &json!({})).unwrap(); + assert!(text(&s, a).dynamic_text && near(brackets(&s, a).0, 0.65), "{:?}", brackets(&s, a)); + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &text(&s, a)); + assert!(lay.fit_scale > 1.5 && !lay.overflow, "{}", lay.fit_scale); + let bottom = ink(&s, a); + assert!((bottom.center().x - 200.0).abs() < 1.0 && bottom.y1 > 300.0, "{bottom:?}"); + // Vertical type on a path moves the same way. + s.execute("type.pathOptions", &json!({"start": 0, "end": null})).unwrap(); + s.execute("type.orientation.vertical", &json!({})).unwrap(); + s.execute("type.pathCenter.top", &json!({})).unwrap(); + assert!(near(brackets(&s, a).0, 0.75)); +} + +#[test] +fn center_on_top_refuses_open_compound_and_threaded_type() { + let mut s = session(); + let circle = on_circle(&mut s, "OOOO"); + let line = on_line(&mut s); + s.execute("select.set", &json!({"ids": [circle.0, line.0]})).unwrap(); + let steps = undo_len(&s); + let before = brackets(&s, circle); + let e = s.execute("type.pathCenter.top", &json!({})).unwrap_err().to_string(); + assert!(e.contains("type on an open or compound path cannot be centered on its top or bottom") && e.ends_with(&line.0.to_string()), "{e}"); + // Nothing changes, the type on the circle included, and the same holds for an explicit list. + assert_eq!((undo_len(&s), brackets(&s, circle)), (steps, before)); + let e = s.execute("type.pathCenter.bottom", &json!({"ids": [circle.0, line.0]})).unwrap_err().to_string(); + assert!(e.contains("open or compound path") && e.ends_with(&line.0.to_string()), "{e}"); + s.execute("select.set", &json!({"ids": [circle.0]})).unwrap(); + for bad in [json!({"ids": "all"}), json!({"ids": [999_999]})] { + assert!(s.execute("type.pathCenter.top", &bad).is_err(), "{bad}"); + } + assert_eq!(undo_len(&s), steps); + // Two circles side by side in one path: a compound path. + let pair = path_type( + &mut s, + "M100 450 A40 40 0 1 1 180 450 A40 40 0 1 1 100 450 Z M300 450 A40 40 0 1 1 380 450 A40 40 0 1 1 300 450 Z", + [90.0, 450.0], + "OOOO", + ); + let e = s.execute("type.pathCenter.top", &json!({})).unwrap_err().to_string(); + assert!(e.contains("open or compound path") && e.ends_with(&pair.0.to_string()), "{e}"); + // A closed path that is level all round has no height. + let flat = path_type(&mut s, "M100 400 L300 400 Z", [90.0, 400.0], "OOOO"); + let e = s.execute("type.pathCenter.top", &json!({})).unwrap_err().to_string(); + assert!(e.contains("type on a path with no length or no height cannot be centered") && e.ends_with(&flat.0.to_string()), "{e}"); + // A frame of a thread is refused, alone or with other type on a closed path. + let threaded = on_circle(&mut s, "Threaded story"); + let frame = s.execute("shape.rectangle", &json!({"x": 400, "y": 100, "width": 200, "height": 100})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [threaded.0, frame]})).unwrap(); + s.execute("text.thread.create", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [threaded.0]})).unwrap(); + let before = brackets(&s, threaded); + for ids in [json!([threaded.0]), json!([circle.0, threaded.0])] { + let steps = undo_len(&s); + let e = s.execute("type.pathCenter.top", &json!({ "ids": ids })).unwrap_err().to_string(); + assert!(e.contains("type on a path in a thread cannot be centered on its top or bottom") && e.ends_with(&threaded.0.to_string()), "{e}"); + assert_eq!((undo_len(&s), brackets(&s, threaded)), (steps, before)); + } + // Without type on one closed path selected, the commands are not available. + let p = s.execute("text.create", &json!({"x": 40, "y": 40, "text": "Point"})).unwrap()["id"].as_u64().unwrap(); + for (ids, why) in [ + (json!([p]), "select type on a closed path"), + (json!([line.0]), "open or compound path"), + (json!([circle.0, line.0]), "open or compound path"), + (json!([threaded.0]), "in a thread"), + ] { + s.execute("select.set", &json!({ "ids": ids })).unwrap(); + for c in ["type.pathCenter.top", "type.pathCenter.bottom"] { + let e = s.execute(c, &json!({})).unwrap_err().to_string(); + assert!(e.contains(why), "{c} {ids}: {e}"); + } + } +} + #[test] fn align_to_path_and_spacing() { let mut s = session(); diff --git a/crates/engine/src/tests/pattern.rs b/crates/engine/src/tests/pattern.rs index 0b948242db..0f29befd80 100644 --- a/crates/engine/src/tests/pattern.rs +++ b/crates/engine/src/tests/pattern.rs @@ -2,7 +2,7 @@ use serde_json::{Value, json}; use vectorcraft_color::Paint; -use vectorcraft_doc::pattern::{PATTERN_EDIT_LAYER, RepeatKind, TileType}; +use vectorcraft_doc::pattern::{PATTERN_EDIT_LAYER, RepeatKind, TileType, pattern_paint}; use vectorcraft_doc::{Node, NodeKind}; use vectorcraft_geom::{Point, Rect}; use vectorcraft_tools::{Mods, PointerEvent, PointerKind}; @@ -212,6 +212,186 @@ fn cancel_new_pattern_removes_it() { assert_eq!(doc(&s).layers.len(), 1); } +fn doc_mut(s: &mut Session) -> &mut vectorcraft_doc::Document { + Arc::make_mut(&mut s.doc_mut().unwrap().doc) +} + +fn is_pattern(p: &Paint, name: &str) -> bool { + matches!(p, Paint::Pattern { pattern, .. } if pattern == name) +} + +/// How many paints of pattern `name` the document holds: in the art and the definitions +/// ([`vectorcraft_doc::Document::visit_paints`]), the swatches, the character styles and the +/// stored brush library. +fn pattern_uses(d: &vectorcraft_doc::Document, name: &str) -> usize { + let mut n = 0; + d.visit_paints(&mut |p| n += usize::from(is_pattern(p, name))); + n += d.swatches_iter().filter(|w| is_pattern(&w.paint, name)).count(); + let styled = d.char_styles.iter().flat_map(|c| ["fill", "stroke"].map(|k| c.attrs.get(k).cloned())).flatten(); + n += styled.filter(|v| serde_json::from_value::(v.clone()).is_ok_and(|p| is_pattern(&p, name))).count(); + let needle = format!("\"pattern\":\"{name}\""); + n + d.unknown.get(vectorcraft_brush::DOC_KEY).map_or(0, |v| v.to_string().matches(&needle).count()) +} + +/// Canceling a new pattern removes every swatch of it, a color group's included, and the fills and +/// strokes of it on art outside the editing layer become no paint. The object's other paints, and +/// a swatch that only shares the pattern's name, stay. +#[test] +fn cancel_new_pattern_forgets_group_swatch_and_outside_fills_and_strokes() { + let mut s = session(); + let other = rect(&mut s, 100.0, 100.0, 50.0, 50.0); + s.execute("paint.setStroke", &json!({"ids": [other.0], "color": "#00ff00"})).unwrap(); + let r = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + sel(&mut s, &[r]); + s.execute("object.pattern.make", &json!({"name": "Tiles"})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [other.0], "swatch": "Tiles"})).unwrap(); + let d = doc_mut(&mut s); + let solid = Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0)); + d.swatch_groups.push(vectorcraft_color::SwatchGroup { + name: "Mine".into(), + swatches: vec![ + vectorcraft_color::Swatch { name: "Grouped".into(), paint: pattern_paint("Tiles"), global: false, spot: false }, + vectorcraft_color::Swatch { name: "Tiles".into(), paint: solid.clone(), global: false, spot: false }, + ], + }); + assert!(pattern_uses(doc(&s), "Tiles") >= 3); + s.execute("object.pattern.cancel", &json!({})).unwrap(); + let d = doc(&s); + assert!(d.pattern("Tiles").is_none()); + assert_eq!(pattern_uses(d, "Tiles"), 0); + assert!(d.swatch("Grouped").is_none(), "the group's pattern swatch goes"); + assert_eq!(d.swatch("Tiles").map(|w| &w.paint), Some(&solid), "a color swatch named like the pattern stays"); + let n = node(&s, other); + assert!(n.appearance.fill_paint().is_none()); + assert!(matches!(n.appearance.stroke_paint(), Paint::Solid { .. }), "the stroke stays"); +} + +/// Save a Copy keeps the copy as its own pattern when the new pattern is canceled, and the copy's +/// tile art loses its paints of the canceled pattern. +#[test] +fn cancel_new_pattern_forgets_its_paints_in_a_saved_copy() { + let mut s = session(); + let r = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + sel(&mut s, &[r]); + s.execute("object.pattern.make", &json!({"name": "Tiles"})).unwrap(); + let layer = doc(&s).pattern_edit.as_ref().unwrap().layer; + let tile = doc(&s).node(layer).unwrap().children().unwrap()[0].id; + s.execute("paint.setFill", &json!({"ids": [tile.0], "swatch": "Tiles"})).unwrap(); + assert_eq!(s.execute("object.pattern.saveCopy", &json!({})).unwrap()["name"], "Tiles copy"); + s.execute("object.pattern.cancel", &json!({})).unwrap(); + let d = doc(&s); + let copy = d.pattern("Tiles copy").expect("the copy stays"); + assert_eq!(copy.art.len(), 1); + assert!(copy.art[0].appearance.fill_paint().is_none()); + assert_eq!(pattern_uses(d, "Tiles"), 0); +} + +/// Canceling a new pattern also clears its paints in type, opacity mask art, symbol definitions, +/// graph designs, graphic and character styles and brush art, and in the fill, stroke and +/// appearance new art takes, so new art does not take a paint of a pattern that is gone. +#[test] +fn cancel_new_pattern_forgets_hidden_paints_and_new_art_defaults() { + let mut s = session(); + let masked = rect(&mut s, 100.0, 100.0, 50.0, 50.0); + let m = rect(&mut s, 100.0, 100.0, 50.0, 50.0); + s.execute("transparency.makeOpacityMask", &json!({"ids": [masked.0, m.0]})).unwrap(); + let t = id_of(&s.execute("text.create", &json!({"x": 20, "y": 300, "text": "Hi"})).unwrap()); + let band = rect(&mut s, 200.0, 200.0, 40.0, 10.0); + let r = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + sel(&mut s, &[r]); + s.execute("object.pattern.make", &json!({"name": "Tiles"})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [band.0], "swatch": "Tiles"})).unwrap(); + s.execute("brush.new", &json!({"type": "art", "name": "Band", "ids": [band.0]})).unwrap(); + let p = pattern_paint("Tiles"); + let d = doc_mut(&mut s); + let art = d.node(band).unwrap().clone(); + d.symbols.push(vectorcraft_doc::Symbol { name: "Sym".into(), art: Arc::new(art.clone()), dynamic: false }); + d.graph_designs.push(vectorcraft_doc::GraphDesign { name: "Bar".into(), art: Arc::new(art.clone()) }); + d.graphic_styles.push(vectorcraft_doc::GraphicStyle { + name: "Style".into(), + appearance: (*art.appearance).clone(), + id: 0, + opacity: 1.0, + blend: Default::default(), + isolate: false, + knockout: Default::default(), + unit_box: true, + }); + let attrs = json!({"fill": p, "stroke": p, "size": 12}); + d.char_styles.push(vectorcraft_doc::TextStyleDef { name: "Char".into(), attrs: attrs.as_object().unwrap().clone() }); + if let Some(NodeKind::Text(text)) = d.node_mut(t).map(|n| &mut n.kind) { + text.runs[0].style.fill = p.clone(); + } + let mask = d.node_mut(masked).and_then(|n| n.extras_if_any()).and_then(|e| e.mask.as_deref_mut()).expect("the mask"); + Arc::make_mut(&mut mask.art).appearance = vectorcraft_doc::Appearance::basic(p.clone(), Paint::None, 0.0).into(); + s.paint.fill = p.clone(); + s.paint.appearance = Some(vectorcraft_doc::Appearance::basic(Paint::None, p.clone(), 1.0)); + assert!(pattern_uses(doc(&s), "Tiles") >= 10, "{}", pattern_uses(doc(&s), "Tiles")); + s.execute("object.pattern.cancel", &json!({})).unwrap(); + assert_eq!(pattern_uses(doc(&s), "Tiles"), 0); + assert!(doc(&s).char_styles[0].attrs["size"] == json!(12), "the style's other attributes stay"); + assert!(s.paint.fill.is_none()); + assert!(s.paint.appearance.as_ref().unwrap().items.iter().all(|it| match it { + vectorcraft_doc::AppearanceItem::Fill(f) => !is_pattern(&f.paint, "Tiles"), + vectorcraft_doc::AppearanceItem::Stroke(k) => !is_pattern(&k.paint, "Tiles"), + })); + let fresh = rect(&mut s, 300.0, 300.0, 20.0, 20.0); + let n = node(&s, fresh); + assert!(!is_pattern(&n.appearance.fill_paint(), "Tiles") && !is_pattern(&n.appearance.stroke_paint(), "Tiles")); +} + +/// Cancel is one undo step: Undo gives the pattern, its paints and the fill new art takes back, and +/// Redo clears them again. +#[test] +fn cancel_new_pattern_is_one_undo_step() { + let mut s = session(); + let other = rect(&mut s, 100.0, 100.0, 50.0, 50.0); + let r = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + sel(&mut s, &[r]); + s.execute("object.pattern.make", &json!({"name": "Tiles"})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [other.0], "swatch": "Tiles"})).unwrap(); + s.paint.fill = pattern_paint("Tiles"); + let steps = s.doc().unwrap().history.undo.len(); + s.execute("object.pattern.cancel", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); + assert!(s.paint.fill.is_none() && doc(&s).pattern("Tiles").is_none()); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(is_pattern(&s.paint.fill, "Tiles")); + assert!(doc(&s).pattern("Tiles").is_some() && doc(&s).pattern_edit.is_some()); + assert!(is_pattern(&node(&s, other).appearance.fill_paint(), "Tiles")); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(s.paint.fill.is_none() && doc(&s).pattern("Tiles").is_none()); + assert_eq!(pattern_uses(doc(&s), "Tiles"), 0); +} + +/// Canceling the edit of a pattern that Pattern Options renamed while it was edited gives the +/// pattern its old name back, with its swatch and the paints of it, so nothing is left painted +/// with a name no pattern has. +#[test] +fn cancel_after_renaming_an_edited_pattern_restores_its_name_and_paints() { + let mut s = session(); + make_dots(&mut s); + let big = rect(&mut s, 100.0, 100.0, 50.0, 50.0); + s.execute("paint.setFill", &json!({"ids": [big.0], "swatch": "Dots"})).unwrap(); + s.execute("object.pattern.edit", &json!({"name": "Dots"})).unwrap(); + s.execute("pattern.options", &json!({"newName": "Spots"})).unwrap(); + assert!(is_pattern(&node(&s, big).appearance.fill_paint(), "Spots")); + s.execute("object.pattern.cancel", &json!({})).unwrap(); + let d = doc(&s); + assert!(d.pattern("Dots").is_some() && d.pattern("Spots").is_none()); + assert!(d.swatch("Dots").is_some_and(|w| is_pattern(&w.paint, "Dots"))); + assert!(is_pattern(&node(&s, big).appearance.fill_paint(), "Dots")); + assert_eq!(pattern_uses(d, "Spots"), 0); + // When Save a Copy has taken the old name since, the pattern keeps its new name and paints. + s.execute("object.pattern.edit", &json!({"name": "Dots"})).unwrap(); + s.execute("pattern.options", &json!({"newName": "Spots"})).unwrap(); + s.execute("object.pattern.saveCopy", &json!({"name": "Dots"})).unwrap(); + s.execute("object.pattern.cancel", &json!({})).unwrap(); + let d = doc(&s); + assert!(d.pattern("Dots").is_some() && d.pattern("Spots").is_some()); + assert!(is_pattern(&node(&s, big).appearance.fill_paint(), "Spots")); +} + #[test] fn edit_then_cancel_restores_definition() { let mut s = session(); @@ -381,6 +561,187 @@ fn delete_pattern_unpaints_objects() { assert!(s.execute("pattern.delete", &json!({"name": "Dots"})).is_err()); } +/// Puts paints of pattern `name` where the layers do not reach: a symbol definition, another +/// pattern's tile, a graphic style, a character style, a type run, a color group's swatch and the +/// fill new art takes. +fn paint_outside_the_layers(s: &mut Session, name: &str) { + let t = id_of(&s.execute("text.create", &json!({"x": 20, "y": 300, "text": "Hi"})).unwrap()); + let p = pattern_paint(name); + let d = doc_mut(s); + let shape = vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)); + let art = Node::path(d.alloc_id(), shape, vectorcraft_doc::Appearance::basic(p.clone(), Paint::None, 0.0)); + d.symbols.push(vectorcraft_doc::Symbol { name: "Sym".into(), art: Arc::new(art.clone()), dynamic: false }); + d.patterns.push(vectorcraft_doc::pattern::PatternDef::new("Other", vec![Arc::new(art.clone())])); + d.graphic_styles.push(vectorcraft_doc::GraphicStyle { + name: "Style".into(), + appearance: (*art.appearance).clone(), + id: 0, + opacity: 1.0, + blend: Default::default(), + isolate: false, + knockout: Default::default(), + unit_box: true, + }); + let attrs = json!({"fill": p}); + d.char_styles.push(vectorcraft_doc::TextStyleDef { name: "Char".into(), attrs: attrs.as_object().unwrap().clone() }); + if let Some(NodeKind::Text(text)) = d.node_mut(t).map(|n| &mut n.kind) { + text.runs[0].style.fill = p.clone(); + } + d.swatch_groups.push(vectorcraft_color::SwatchGroup { + name: "Mine".into(), + swatches: vec![vectorcraft_color::Swatch { name: "Grouped".into(), paint: p.clone(), global: false, spot: false }], + }); + s.paint.fill = p; +} + +/// Delete Pattern clears the pattern's paints outside the layers too, and in the fill new art takes. +#[test] +fn delete_pattern_forgets_paints_outside_the_layers() { + let mut s = session(); + make_dots(&mut s); + paint_outside_the_layers(&mut s, "Dots"); + assert_eq!(pattern_uses(doc(&s), "Dots"), 7); + let v = s.execute("pattern.delete", &json!({"name": "Dots"})).unwrap(); + assert_eq!(v["unpainted"], 5, "the symbol, the other tile, the graphic style, the character style and the type"); + assert_eq!(pattern_uses(doc(&s), "Dots"), 0); + assert!(doc(&s).swatch("Grouped").is_none() && doc(&s).pattern("Other").is_some()); + assert!(s.paint.fill.is_none()); +} + +/// A Pattern Options rename renames the pattern's paints outside the layers too, and in the fill +/// new art takes. +#[test] +fn rename_pattern_reaches_paints_outside_the_layers() { + let mut s = session(); + make_dots(&mut s); + paint_outside_the_layers(&mut s, "Dots"); + s.execute("pattern.options", &json!({"name": "Dots", "newName": "Spots"})).unwrap(); + assert_eq!(pattern_uses(doc(&s), "Dots"), 0); + assert_eq!(pattern_uses(doc(&s), "Spots"), 7); + assert!(is_pattern(&s.paint.fill, "Spots")); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(is_pattern(&s.paint.fill, "Dots"), "Undo gives the fill its old name back"); +} + +/// A new graph whose stored series fill and stroke and value label fill and stroke are pattern +/// `name`, as a later redraw would give them to its marks and labels. +fn graph_painted_with(s: &mut Session, name: &str) -> NodeId { + let v = s.execute("graph.create", &json!({"type": "column", "x": 200, "y": 200, "width": 60, "height": 40, "csv": ",2024\nQ1,3\nQ2,5"})); + let id = id_of(&v.unwrap()); + let p = pattern_paint(name); + let mut extras = doc_mut(s).node_mut(id).unwrap().extras_mut(); + let spec = extras.graph.as_mut().unwrap(); + spec.series_paints = vec![vectorcraft_doc::SeriesPaint { fill: Some(p.clone()), stroke: Some(p.clone()), ..Default::default() }]; + spec.label_styles.values = Some(vectorcraft_doc::CharStyle { fill: p.clone(), stroke: p, ..Default::default() }); + id +} + +/// The series and label paints a graph stores, in order: series fill and stroke, then the value +/// labels' fill and stroke. +fn stored_graph_paints(s: &Session, id: NodeId) -> Vec { + let n = node(s, id); + let g = n.extras().graph.as_deref().unwrap(); + let series = g.series_paints.iter().flat_map(|p| [p.fill.clone(), p.stroke.clone()]).flatten(); + series.chain(g.label_styles.values.iter().flat_map(|st| [st.fill.clone(), st.stroke.clone()])).collect() +} + +/// Delete Pattern clears the series and label paints a graph stores, and a rename renames them, so +/// a later `graph.setData` draws no paint of a missing pattern. +#[test] +fn delete_and_rename_reach_a_graphs_stored_paints() { + let mut s = session(); + make_dots(&mut s); + let g = graph_painted_with(&mut s, "Dots"); + s.execute("pattern.options", &json!({"name": "Dots", "newName": "Spots"})).unwrap(); + assert!(stored_graph_paints(&s, g).iter().all(|p| is_pattern(p, "Spots")), "the rename reaches the graph"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(stored_graph_paints(&s, g).iter().all(|p| is_pattern(p, "Dots"))); + let v = s.execute("pattern.delete", &json!({"name": "Dots"})).unwrap(); + assert_eq!(v["unpainted"], 4, "the series fill and stroke and the value labels' fill and stroke"); + assert!(stored_graph_paints(&s, g).iter().all(Paint::is_none)); + s.execute("graph.setData", &json!({"id": g.0, "rows": [[2], [4]]})).unwrap(); + assert_eq!(pattern_uses(doc(&s), "Dots"), 0, "the redrawn graph holds no paint of the deleted pattern"); +} + +/// Canceling a new pattern clears the series and label paints a graph stores. +#[test] +fn cancel_new_pattern_reaches_a_graphs_stored_paints() { + let mut s = session(); + // The graph is made outside the editing layer, and its paints take the new pattern's name. + let g = graph_painted_with(&mut s, "Tiles"); + let r = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + sel(&mut s, &[r]); + s.execute("object.pattern.make", &json!({"name": "Tiles"})).unwrap(); + s.execute("object.pattern.cancel", &json!({})).unwrap(); + assert_eq!(stored_graph_paints(&s, g).len(), 4); + assert!(stored_graph_paints(&s, g).iter().all(Paint::is_none)); + assert_eq!(pattern_uses(doc(&s), "Tiles"), 0); +} + +/// With New Art Has Basic Appearance off, Redo of Delete Pattern gives new art the paints the +/// command left, the selected object's appearance taken after the pattern's fill was cleared. +#[test] +fn redo_of_delete_pattern_keeps_the_inherited_new_art_paints() { + let mut s = session(); + let r = make_dots(&mut s); + s.prefs.new_art_basic = false; + sel(&mut s, &[r]); + s.paint.fill = pattern_paint("Dots"); + s.execute("pattern.delete", &json!({"name": "Dots"})).unwrap(); + let after = s.paint.clone(); + assert!(!is_pattern(&after.fill, "Dots")); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.paint, after); +} + +/// A Pattern Options rename tried as a preview changes the fill new art takes only while the +/// preview stands: another preview and Cancel start from the fill the interaction began with. +/// Keeping the preview keeps the rename, and Undo takes it back. +#[test] +fn rename_previews_restore_the_fill_new_art_takes() { + let mut s = session(); + make_dots(&mut s); + s.paint.fill = pattern_paint("Dots"); + s.begin_interaction("Pattern Options").unwrap(); + s.preview("pattern.options", &json!({"name": "Dots", "newName": "Spots"})).unwrap(); + assert!(is_pattern(&s.paint.fill, "Spots")); + s.preview("pattern.options", &json!({"name": "Dots", "newName": "Tiles"})).unwrap(); + assert!(is_pattern(&s.paint.fill, "Tiles")); + s.cancel_interaction().unwrap(); + assert!(is_pattern(&s.paint.fill, "Dots") && doc(&s).pattern("Dots").is_some()); + s.begin_interaction("Pattern Options").unwrap(); + s.preview("pattern.options", &json!({"name": "Dots", "newName": "Spots"})).unwrap(); + s.commit_interaction().unwrap(); + assert!(is_pattern(&s.paint.fill, "Spots") && doc(&s).pattern("Spots").is_some()); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(is_pattern(&s.paint.fill, "Dots") && doc(&s).pattern("Dots").is_some()); +} + +/// With New Art Has Basic Appearance off, a canceled rename preview leaves new art with the +/// appearance of the selected object as the document has it again, so no paint of the previewed +/// name is left. +#[test] +fn canceled_rename_preview_leaves_no_inherited_paint_of_the_new_name() { + let mut s = session(); + make_dots(&mut s); + let big = rect(&mut s, 100.0, 100.0, 50.0, 50.0); + s.execute("paint.setFill", &json!({"ids": [big.0], "swatch": "Dots"})).unwrap(); + s.prefs.new_art_basic = false; + sel(&mut s, &[big]); + s.paint = vectorcraft_tools::PaintDefaults::default(); + s.begin_interaction("Pattern Options").unwrap(); + s.preview("pattern.options", &json!({"name": "Dots", "newName": "Spots"})).unwrap(); + s.cancel_interaction().unwrap(); + assert!(doc(&s).pattern("Dots").is_some() && doc(&s).pattern("Spots").is_none()); + let items = s.paint.appearance.iter().flat_map(|a| a.items.iter()).map(|it| match it { + vectorcraft_doc::AppearanceItem::Fill(f) => f.paint.clone(), + vectorcraft_doc::AppearanceItem::Stroke(k) => k.paint.clone(), + }); + let paints: Vec = [s.paint.fill.clone(), s.paint.stroke.clone()].into_iter().chain(items).collect(); + assert!(paints.iter().all(|p| !is_pattern(p, "Spots")), "{paints:?}"); +} + #[test] fn transform_patterns_only_moves_placement() { let mut s = session(); diff --git a/crates/engine/src/tests/pdfpresets.rs b/crates/engine/src/tests/pdfpresets.rs index 7de08463f3..ecdf140c0e 100644 --- a/crates/engine/src/tests/pdfpresets.rs +++ b/crates/engine/src/tests/pdfpresets.rs @@ -123,40 +123,49 @@ fn presets_export_and_import_round_trip() { assert!(is_bad_params(Session::new().execute("pdf.preset.export", &json!({}))), "nothing saved to export"); } -/// `longPagesInPoints` is saved with a preset, comes back through a presets file and the -/// preferences, shows in `document.pdfSettings`, and a 10 m page exported with it reopens at 10 m. -/// A value that isn't a boolean is refused. +/// `longPagesInPoints` is on by default: a 10 m page exported without options is written in +/// points and reopens at 10 m. Turned off, it is saved with a preset, comes back through a presets +/// file and the preferences, shows in `document.pdfSettings`, and the page exported with it has a +/// `UserUnit` and reopens at 10 m. A value that isn't a boolean is refused. #[test] fn long_pages_in_points_round_trips_through_presets_and_reopens_at_full_size() { let mut s = Session::new(); s.execute("file.new", &json!({"width": 28_346.456_692_913_386, "height": 2_834.645_669_291_338_5})).unwrap(); - s.execute("pdf.preset.save", &json!({"name": "Banner", "longPagesInPoints": true, "preserveEditing": false})).unwrap(); - assert!(s.prefs.pdf_presets[0].settings.long_pages_in_points); + let reopened = |bytes: &[u8]| { + let mut o = Session::new(); + o.execute("document.open", &json!({"name": "banner.pdf", "dataBase64": vectorcraft_format::base64_encode(bytes)})).unwrap(); + let rect = o.doc().unwrap().doc.artboards[0].rect; + assert!((rect.width() - 28_346.46).abs() < 0.01 && (rect.height() - 2_834.65).abs() < 0.01, "{rect:?}"); + }; + let warned = |v: &Value, end: &str| v["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().ends_with(end)); + // By default the page is written in points. + assert_eq!(s.execute("document.pdfSettings", &json!({})).unwrap()["settings"]["longPagesInPoints"], json!(true)); + let v = s.execute("document.exportPdf", &json!({"preserveEditing": false})).unwrap(); + let bytes = pdf(&v); + assert!(!String::from_utf8_lossy(&bytes).contains("/UserUnit")); + assert!(warned(&v, "written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in"), "{v}"); + reopened(&bytes); + // Off in a preset. + s.execute("pdf.preset.save", &json!({"name": "Banner", "longPagesInPoints": false, "preserveEditing": false})).unwrap(); + assert!(!s.prefs.pdf_presets[0].settings.long_pages_in_points); let back: crate::Prefs = serde_json::from_value(s.prefs.to_json()).unwrap(); assert_eq!(back.pdf_presets, s.prefs.pdf_presets); let text = s.execute("pdf.preset.export", &json!({"names": ["Banner"]})).unwrap()["data"].as_str().unwrap().to_string(); let mut t = session(); t.execute("pdf.preset.import", &json!({"data": text})).unwrap(); assert_eq!(t.prefs.pdf_presets, s.prefs.pdf_presets); - let v = s.execute("document.pdfSettings", &json!({"longPagesInPoints": true})).unwrap(); - assert_eq!((&v["settings"]["longPagesInPoints"], &v["changed"]), (&json!(true), &json!([{"option": "longPagesInPoints", "value": true}])), "{v}"); - assert_eq!(s.execute("document.pdfSettings", &json!({})).unwrap()["settings"]["longPagesInPoints"], json!(false)); - // The preset writes the page in points; the file reopens at 10 m. - let v = s.execute("document.exportPdf", &json!({"preset": "Banner"})).unwrap(); - let bytes = pdf(&v); - assert!(!String::from_utf8_lossy(&bytes).contains("/UserUnit")); - assert!( - v["warnings"] - .as_array() - .unwrap() - .iter() - .any(|w| w.as_str().unwrap().ends_with("written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in")), + let v = s.execute("document.pdfSettings", &json!({"longPagesInPoints": false})).unwrap(); + assert_eq!( + (&v["settings"]["longPagesInPoints"], &v["changed"]), + (&json!(false), &json!([{"option": "longPagesInPoints", "value": false}])), "{v}" ); - let mut o = Session::new(); - o.execute("document.open", &json!({"name": "banner.pdf", "dataBase64": vectorcraft_format::base64_encode(&bytes)})).unwrap(); - let rect = o.doc().unwrap().doc.artboards[0].rect; - assert!((rect.width() - 28_346.46).abs() < 0.01 && (rect.height() - 2_834.65).abs() < 0.01, "{rect:?}"); + // The preset writes the page with a `UserUnit`; the file reopens at 10 m. + let v = s.execute("document.exportPdf", &json!({"preset": "Banner"})).unwrap(); + let bytes = pdf(&v); + assert!(String::from_utf8_lossy(&bytes).contains("/UserUnit 1.969")); + assert!(warned(&v, "it is written with a UserUnit of 1.969, so apps that ignore UserUnit show it that many times smaller"), "{v}"); + reopened(&bytes); for bad in [json!("yes"), json!(1)] { assert!(is_bad_params(s.execute("document.exportPdf", &json!({"longPagesInPoints": bad}))), "{bad}"); assert!(is_bad_params(s.execute("pdf.preset.save", &json!({"name": "Bad", "longPagesInPoints": bad}))), "{bad}"); diff --git a/crates/engine/src/tests/pixelalign.rs b/crates/engine/src/tests/pixelalign.rs index 081497d2ac..06057d1fc0 100644 --- a/crates/engine/src/tests/pixelalign.rs +++ b/crates/engine/src/tests/pixelalign.rs @@ -767,6 +767,131 @@ fn objects_on_path_members_stay_on_the_grid() { assert!(points(&s, a).iter().all(|(_, y)| *y > 105.0), "followed the path: {:?}", points(&s, a)); } +fn align_new(s: &Session) -> bool { + s.doc().unwrap().doc.setup.align_new_objects_to_pixel_grid +} + +/// Align New Objects to Pixel Grid (`document.setup`): while it is on, a rectangle and an open path +/// drawn in the document are pixel-aligned and snapped in the step that makes them, and type is +/// not; art already in the document, duplicates and pastes keep their own setting; turning it off +/// leaves the next drawing as it is drawn, and the object's own setting can be turned off while +/// the document's stays on. +#[test] +fn align_new_objects_makes_new_paths_pixel_aligned() { + let mut s = new_doc(); + assert!(!align_new(&s)); + assert_eq!(s.execute("document.setup", &json!({})).unwrap()["alignNewObjectsToPixelGrid"], false); + let old = path(&mut s, "M10.3 120.6 L40.7 120.6 L40.7 130.3 L10.3 130.3 Z", 2.0); + let old_points = points(&s, old); + let steps = undo_len(&s); + let r = s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap(); + assert_eq!(r["alignNewObjectsToPixelGrid"], true); + assert!(align_new(&s)); + assert_eq!(undo_len(&s), steps + 1, "one undo step"); + // Art already in the document stays as it was. + assert!(!aligned(&s, old)); + assert_eq!(points(&s, old), old_points); + // A rectangle is drawn pixel-aligned: with the 2 pt stroke `path` left as the current one, its + // edges go to whole points. + let steps = undo_len(&s); + let rect = s.execute("shape.rectangle", &json!({"x": 10.3, "y": 20.6, "width": 30.4, "height": 9.7})).unwrap()["id"].as_u64().unwrap(); + assert!(aligned(&s, rect)); + assert_eq!(points(&s, rect), [(10.0, 21.0), (41.0, 21.0), (41.0, 30.0), (10.0, 30.0)]); + assert_eq!(undo_len(&s), steps + 1, "made and snapped in one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.node(NodeId(rect)).is_none()); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(aligned(&s, rect)); + // An open path from the Pen. + let line = s.execute("path.create", &json!({"anchors": [{"x": 50.3, "y": 60.2}, {"x": 90.6, "y": 60.2}]})).unwrap()["id"].as_u64().unwrap(); + assert!(aligned(&s, line)); + // Its horizontal segment goes to a whole point. + assert!(points(&s, line).iter().all(|(_, y)| *y == 60.0), "{:?}", points(&s, line)); + // Type cannot be pixel-aligned. + let text = s.execute("text.create", &json!({"x": 10.3, "y": 200.6, "text": "Hi"})).unwrap()["id"].as_u64().unwrap(); + assert!(!aligned(&s, text)); + // A duplicate and a paste of art that is not pixel-aligned keep it so. + s.execute("select.set", &json!({"ids": [old]})).unwrap(); + s.execute("edit.duplicate", &json!({"dx": 100.3, "dy": 0.4})).unwrap(); + let copy = s.doc().unwrap().selection.objects[0].0; + assert!(copy != old && !aligned(&s, copy)); + s.execute("select.set", &json!({"ids": [old]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("edit.paste", &json!({})).unwrap(); + let pasted = s.doc().unwrap().selection.objects[0].0; + assert!(pasted != old && pasted != copy && !aligned(&s, pasted)); + // The object's own setting turns off while the document's stays on. + s.execute("object.setPixelAligned", &json!({"ids": [rect], "on": false})).unwrap(); + assert!(!aligned(&s, rect) && align_new(&s)); + // Off: the next rectangle is drawn as it is given, and the first one stays pixel-aligned. + s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": false})).unwrap(); + let plain = s.execute("shape.rectangle", &json!({"x": 10.3, "y": 20.6, "width": 30.4, "height": 9.7})).unwrap()["id"].as_u64().unwrap(); + assert!(!aligned(&s, plain)); + let drawn = [(10.3, 20.6), (40.7, 20.6), (40.7, 30.3), (10.3, 30.3)]; + assert!(points(&s, plain).iter().zip(drawn).all(|(a, b)| close(*a, b)), "{:?}", points(&s, plain)); + assert!(aligned(&s, line)); + // A value that is not true or false changes nothing. + let steps = undo_len(&s); + assert!(s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": "yes"})).is_err()); + assert!(!align_new(&s)); + assert_eq!(undo_len(&s), steps); +} + +/// While Align New Objects to Pixel Grid is on, the paths of a new rectangular grid, polar grid +/// and flare are pixel-aligned (the group is not), and a new 3D Box add-on shape is snapped as +/// Align to Pixel Grid snaps the same box drawn without it. +#[test] +fn align_new_objects_reaches_grids_flares_and_add_on_shapes() { + let mut s = new_doc(); + s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap(); + let doc = |s: &Session| s.doc().unwrap().doc.clone(); + let children = |s: &Session, id: u64| -> Vec { doc(s).node(NodeId(id)).unwrap().children().unwrap().iter().map(|c| c.id.0).collect() }; + let grid = s.execute("shape.rectangularGrid", &json!({"x": 10.3, "y": 20.6, "width": 100.4, "height": 50.7})).unwrap()["id"].as_u64().unwrap(); + assert!(!aligned(&s, grid)); + let lines = children(&s, grid); + assert!(!lines.is_empty() && lines.iter().all(|id| aligned(&s, *id))); + // Under the 1 pt stroke, a divider sits on a half point across its length, and the frame + // has every corner on half points. + let half = |v: f64| ((v - 0.5) - (v - 0.5).round()).abs() < 1e-9; + let snapped = + |p: &[(f64, f64)]| halves(p) || (p.iter().all(|q| q.1 == p[0].1) && half(p[0].1)) || (p.iter().all(|q| q.0 == p[0].0) && half(p[0].0)); + assert!(lines.iter().all(|id| snapped(&points(&s, *id))), "{:?}", lines.iter().map(|id| points(&s, *id)).collect::>()); + let polar = s.execute("shape.polarGrid", &json!({"x": 200.3, "y": 20.6, "width": 80.4, "height": 80.7})).unwrap()["id"].as_u64().unwrap(); + assert!(!aligned(&s, polar) && children(&s, polar).iter().all(|id| aligned(&s, *id))); + let flare = s.execute("shape.flare", &json!({"cx": 100.3, "cy": 200.6})).unwrap()["id"].as_u64().unwrap(); + assert!(!aligned(&s, flare) && children(&s, flare).iter().all(|id| aligned(&s, *id))); + // Seen straight on, the box's front face has horizontal and vertical edges to snap. + let params = json!({"x": 20.3, "y": 300.6, "width": 60.4, "height": 40.7, "angleX": 0, "angleY": 0, "angleZ": 0}); + let drawn = s.execute("addon.shapes.box3d", ¶ms).unwrap()["id"].as_u64().unwrap(); + assert!(aligned(&s, drawn)); + s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": false})).unwrap(); + let later = s.execute("addon.shapes.box3d", ¶ms).unwrap()["id"].as_u64().unwrap(); + assert!(!aligned(&s, later)); + let unaligned = points(&s, later); + s.execute("object.setPixelAligned", &json!({"ids": [later]})).unwrap(); + assert_eq!(points(&s, drawn), points(&s, later)); + assert_ne!(points(&s, drawn), unaligned, "the box has segments to snap"); +} + +/// The document's Align New Objects to Pixel Grid is saved in the native file only when on and +/// read back; a file from before it opens with it off. +#[test] +fn align_new_objects_is_saved_and_read_back() { + let mut s = new_doc(); + let off = serde_json::to_value(&s.doc().unwrap().doc.setup).unwrap(); + assert!(off.get("alignNewObjectsToPixelGrid").is_none(), "{off}"); + let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + assert!(!back.setup.align_new_objects_to_pixel_grid); + s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap(); + let on = serde_json::to_value(&s.doc().unwrap().doc.setup).unwrap(); + assert_eq!(on["alignNewObjectsToPixelGrid"], true); + let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + assert!(back.setup.align_new_objects_to_pixel_grid); + let mut older = on; + older.as_object_mut().unwrap().remove("alignNewObjectsToPixelGrid"); + assert!(!serde_json::from_value::(older).unwrap().align_new_objects_to_pixel_grid); +} + fn selected_ids(s: &Session) -> Vec { let mut ids: Vec = s.doc().unwrap().selection.objects.iter().map(|i| i.0).collect(); ids.sort_unstable(); @@ -834,3 +959,202 @@ fn not_aligned_to_pixel_grid_leaves_out_what_cant_be_selected() { assert_eq!(s.execute("select.object.notAlignedToPixelGrid", &json!({})).unwrap()["count"], 1); assert_eq!(selected_ids(&s), vec![inside]); } + +/// Run Not Aligned to Pixel Grid with `before` selected, check that it makes no undo step and that +/// its count is the number of objects it selected → the selected ids, sorted. +fn not_aligned(s: &mut Session, before: &[u64]) -> Vec { + s.execute("select.set", &json!({ "ids": before })).unwrap(); + let steps = undo_len(s); + let r = s.execute("select.object.notAlignedToPixelGrid", &json!({})).unwrap(); + let ids = selected_ids(s); + assert_eq!(r["count"], json!(ids.len()), "{r}"); + assert_eq!(undo_len(s), steps); + ids +} + +fn sorted(mut ids: Vec) -> Vec { + ids.sort_unstable(); + ids +} + +/// What Select All selects, sorted. +fn all_ids(s: &mut Session) -> Vec { + s.execute("select.all", &json!({})).unwrap(); + selected_ids(s) +} + +fn kind(s: &Session, id: u64) -> NodeKind { + s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind.clone() +} + +/// Images, symbol instances, point type, area type and type on a path cannot take the property, so +/// Not Aligned to Pixel Grid leaves them out though Select All selects them; the path a symbol was +/// made from is the symbol's art, not an object of the document. +#[test] +fn not_aligned_to_pixel_grid_leaves_out_images_symbol_instances_and_type() { + let mut s = new_doc(); + let p = path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 1.0); + let png = crate::tests_links::png(4, 4, [255, 0, 0]); + s.execute("file.place", &json!({"name": "red.png", "dataBase64": vectorcraft_format::base64_encode(&png), "link": false})).unwrap(); + let image = s.doc().unwrap().selection.objects[0].0; + let art = path(&mut s, "M60.5 60 L80 60 L80 80 L60.5 80 Z", 1.0); + let made = s.execute("symbol.new", &json!({"name": "Mark", "ids": [art]})).unwrap()["id"].as_u64().unwrap(); + let placed = s.execute("symbol.place", &json!({"name": "Mark", "x": 200.3, "y": 200.3})).unwrap()["id"].as_u64().unwrap(); + let point = s.execute("text.create", &json!({"x": 100, "y": 100, "text": "point"})).unwrap()["id"].as_u64().unwrap(); + let frame = json!({"width": 80.5, "height": 40.5}); + let area = s.execute("text.create", &json!({"x": 100, "y": 150, "text": "area", "area": frame})).unwrap()["id"].as_u64().unwrap(); + let on_path = path(&mut s, "M10.5 300 C100 250 200 350 300.5 300", 1.0); + let on_path = s.execute("text.createInPath", &json!({"path": on_path, "mode": "onPath", "text": "on a path"})).unwrap()["id"].as_u64().unwrap(); + let in_path = path(&mut s, "M250.5 20.5 L350 20.5 L350 90 L250.5 90 Z", 1.0); + let in_path = s.execute("text.createInPath", &json!({"path": in_path, "mode": "area", "text": "in a path"})).unwrap()["id"].as_u64().unwrap(); + assert!(matches!(kind(&s, image), NodeKind::Image(_))); + for id in [made, placed] { + assert!(matches!(kind(&s, id), NodeKind::SymbolInstance { .. }), "{id}"); + } + for id in [point, area, on_path, in_path] { + assert!(matches!(kind(&s, id), NodeKind::Text(_)), "{id}"); + } + assert!(s.doc().unwrap().doc.node(NodeId(art)).is_none()); + assert_eq!(all_ids(&mut s), sorted(vec![p, image, made, placed, point, area, on_path, in_path])); + assert_eq!(not_aligned(&mut s, &[image, made, point]), vec![p]); + // With the path aligned, nothing is left to select. + s.execute("object.setPixelAligned", &json!({"ids": [p]})).unwrap(); + assert_eq!(not_aligned(&mut s, &[placed]), Vec::::new()); +} + +/// Paths on a template layer, in a hidden or locked sublayer or on a locked artboard are left out, +/// as Select All leaves them out; paths in an unlocked visible sublayer are selected. +#[test] +fn not_aligned_to_pixel_grid_leaves_out_template_layers_locked_sublayers_and_locked_artboards() { + let mut s = new_doc(); + s.execute("artboard.new", &json!({"x": 500, "y": 0, "width": 100, "height": 100})).unwrap(); + let main = s.doc().unwrap().doc.layers[0].id.0; + let free = path(&mut s, "M10 10 L20 10 L20 20 L10 20 Z", 1.0); + let on_locked_board = path(&mut s, "M510 10 L520 10 L520 20 L510 20 Z", 1.0); + let template = s.execute("layer.new", &json!({"name": "Trace"})).unwrap()["id"].as_u64().unwrap(); + let traced = path(&mut s, "M30 10 L40 10 L40 20 L30 20 Z", 1.0); + s.execute("layer.setProps", &json!({"id": template, "template": true})).unwrap(); + let sub = |s: &mut Session, name: &str, d: &str| { + let l = s.execute("layer.newSublayer", &json!({"parent": main, "name": name})).unwrap()["id"].as_u64().unwrap(); + s.execute("layer.setCurrent", &json!({"id": l})).unwrap(); + (l, path(s, d, 1.0)) + }; + let (_, in_sublayer) = sub(&mut s, "Open", "M50 10 L60 10 L60 20 L50 20 Z"); + let (hidden, in_hidden) = sub(&mut s, "Hidden", "M70 10 L80 10 L80 20 L70 20 Z"); + let (locked, in_locked) = sub(&mut s, "Locked", "M90 10 L100 10 L100 20 L90 20 Z"); + s.execute("layer.setProps", &json!({"id": hidden, "visible": false})).unwrap(); + s.execute("layer.setProps", &json!({"id": locked, "locked": true})).unwrap(); + s.execute("artboard.setProps", &json!({"index": 1, "locked": true})).unwrap(); + let all = all_ids(&mut s); + for id in [traced, in_hidden, in_locked, on_locked_board] { + assert!(!all.contains(&id), "{id}"); + } + assert_eq!(not_aligned(&mut s, &[free]), sorted(vec![free, in_sublayer])); + // Unlocked, the artboard's path is selected again. + s.execute("artboard.setProps", &json!({"index": 1, "locked": false})).unwrap(); + assert_eq!(not_aligned(&mut s, &[free]), sorted(vec![free, in_sublayer, on_locked_board])); +} + +/// A clipping path and the paths it clips are selected, not their clip group; a path with a drop +/// shadow or a Gaussian Blur is selected as the path it is, and its effects are not objects. +#[test] +fn not_aligned_to_pixel_grid_selects_clipping_paths_and_paths_with_effects() { + let mut s = new_doc(); + let clipped = path(&mut s, "M10.5 10 L60 10 L60 60 L10.5 60 Z", 1.0); + let clip = path(&mut s, "M20.5 20 L50 20 L50 50 L20.5 50 Z", 1.0); + s.execute("select.set", &json!({"ids": [clipped, clip]})).unwrap(); + let group = s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + let shadowed = path(&mut s, "M100.5 10 L150 10 L150 60 L100.5 60 Z", 1.0); + s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "ids": [shadowed]})).unwrap(); + let blurred = path(&mut s, "M200.5 10 L250 10 L250 60 L200.5 60 Z", 1.0); + s.execute("effect.apply", &json!({"effect": "blur.gaussian", "params": {"radius": 3}, "ids": [blurred]})).unwrap(); + assert!(matches!(kind(&s, group), NodeKind::Group { .. })); + for id in [shadowed, blurred] { + assert!(!s.doc().unwrap().doc.node(NodeId(id)).unwrap().appearance.effects.is_empty(), "{id}"); + } + let want = sorted(vec![clipped, clip, shadowed, blurred]); + assert_eq!(not_aligned(&mut s, &[group]), want); + // Object › Align to Pixel Grid takes each object selected; then nothing is left to select. + s.execute("object.setPixelAligned", &json!({"ids": want})).unwrap(); + assert_eq!(not_aligned(&mut s, &[group]), Vec::::new()); +} + +/// The filter looks into blends, envelopes, repeats and Intertwine groups and selects the paths +/// they are made of, not the objects that hold them; Align to Pixel Grid takes that selection, and +/// then nothing is left to select. +#[test] +fn not_aligned_to_pixel_grid_selects_the_paths_of_blends_envelopes_repeats_and_intertwines() { + let mut s = new_doc(); + let b1 = path(&mut s, "M10.5 10 L30 10 L30 30 L10.5 30 Z", 1.0); + let b2 = path(&mut s, "M80.5 10 L100 10 L100 30 L80.5 30 Z", 1.0); + s.execute("select.set", &json!({"ids": [b1, b2]})).unwrap(); + let blend = s.execute("object.blend.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + let warped = path(&mut s, "M10.5 100 L100 100 L100 150 L10.5 150 Z", 1.0); + let envelope = s.execute("object.envelope.makeWithWarp", &json!({"ids": [warped]})).unwrap()["id"].as_u64().unwrap(); + let tile = path(&mut s, "M200.5 10 L220 10 L220 30 L200.5 30 Z", 1.0); + let repeat = s.execute("object.repeat.grid", &json!({"ids": [tile], "rows": 2, "cols": 2})).unwrap()["id"].as_u64().unwrap(); + let i1 = path(&mut s, "M200.5 200 L260 200 L260 230 L200.5 230 Z", 1.0); + let i2 = path(&mut s, "M220.5 180 L240 180 L240 250 L220.5 250 Z", 1.0); + let intertwine = s.execute("object.intertwine.make", &json!({"ids": [i1, i2]})).unwrap()["id"].as_u64().unwrap(); + assert!(matches!(kind(&s, blend), NodeKind::Blend { .. })); + assert!(matches!(kind(&s, envelope), NodeKind::Envelope { .. })); + assert!(matches!(kind(&s, repeat), NodeKind::Repeat(_))); + assert!(matches!(kind(&s, intertwine), NodeKind::Intertwine { .. })); + let want = sorted(vec![b1, b2, warped, tile, i1, i2]); + assert_eq!(not_aligned(&mut s, &[blend, envelope]), want); + s.execute("object.setPixelAligned", &json!({})).unwrap(); + for id in &want { + assert!(aligned(&s, *id), "{id}"); + } + assert_eq!(not_aligned(&mut s, &[repeat, intertwine]), Vec::::new()); +} + +/// Gradient meshes, placed documents and ruler guides are left out; a live shape is a path and is +/// selected. +#[test] +fn not_aligned_to_pixel_grid_leaves_out_meshes_placed_documents_and_guides_but_takes_live_shapes() { + let mut s = new_doc(); + let filled = path(&mut s, "M10.5 10 L60 10 L60 60 L10.5 60 Z", 1.0); + s.execute("paint.setFill", &json!({"color": "#3366cc"})).unwrap(); + let mesh = s.execute("object.mesh.create", &json!({"ids": [filled], "rows": 2, "cols": 2})).unwrap()["ids"][0].as_u64().unwrap(); + let dir = crate::tests_links::Folder::new("pixelalign-placed"); + let file = dir.file("placed.vectorcraft"); + let mut d = vectorcraft_doc::Document::new(50.0, 50.0); + let layer = d.layers[0].id; + let id = d.alloc_id(); + let rect = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.5, 0.5, 40.0, 40.0)); + let paint = vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb8(20, 20, 230)); + let look = vectorcraft_doc::Appearance::basic(paint, vectorcraft_color::Paint::None, 0.0); + d.insert(Some(layer), 0, vectorcraft_doc::Node::path(id, rect, look)).unwrap(); + crate::tests_links::write(&file, &vectorcraft_format::save_file(&d)); + let placed = s.execute("file.place", &json!({"path": file, "at": [200, 200]})).unwrap()["ids"][0].as_u64().unwrap(); + let guide = path(&mut s, "M0 300.5 L400 300.5", 1.0); + s.execute("view.guides.make", &json!({})).unwrap(); + let live = s.execute("shape.rectangle", &json!({"x": 100.3, "y": 20.6, "width": 30.4, "height": 9.7})).unwrap()["id"].as_u64().unwrap(); + assert!(matches!(kind(&s, mesh), NodeKind::Mesh(_))); + assert!(matches!(kind(&s, placed), NodeKind::PlacedDocument(_))); + assert!(matches!(kind(&s, guide), NodeKind::Path { guide: true, .. })); + assert!(s.doc().unwrap().doc.node(NodeId(live)).unwrap().live_shape().is_some()); + let all = all_ids(&mut s); + assert!(all.contains(&mesh) && all.contains(&placed), "{all:?}"); + assert_eq!(not_aligned(&mut s, &[mesh, placed]), vec![live]); +} + +/// A compound path goes by its own property, whatever the property of the paths in it (a file can +/// hold paths with the property on inside a compound path): off, it is selected as one object and +/// the paths in it are not; on, it is not selected, though a path in it has the property off. +#[test] +fn not_aligned_to_pixel_grid_takes_a_compound_path_by_its_own_property() { + let mut s = new_doc(); + let on = path(&mut s, "M10.5 10 L30 10 L30 30 L10.5 30 Z", 1.0); + let off = path(&mut s, "M50.5 10 L70 10 L70 30 L50.5 30 Z", 1.0); + s.execute("select.set", &json!({"ids": [on, off]})).unwrap(); + let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(NodeId(on)).unwrap().extras_mut().pixel_aligned = true; + assert!(aligned(&s, on) && !aligned(&s, off) && !aligned(&s, compound)); + let other = path(&mut s, "M100 100 L110 100 L110 110 L100 110 Z", 1.0); + assert_eq!(not_aligned(&mut s, &[other]), sorted(vec![compound, other])); + s.execute("object.setPixelAligned", &json!({"ids": [compound]})).unwrap(); + assert!(!aligned(&s, off)); + assert_eq!(not_aligned(&mut s, &[compound]), vec![other]); +} diff --git a/crates/engine/src/tests/place.rs b/crates/engine/src/tests/place.rs index a0a8ededa0..8dbe06f349 100644 --- a/crates/engine/src/tests/place.rs +++ b/crates/engine/src/tests/place.rs @@ -365,6 +365,95 @@ fn a_file_read_apart_from_the_session_replaces_what_was_selected_when_place_star } } +/// Every open document with its art, selection and undo steps, and the journal, tool and tool +/// options: what a refused hand-off leaves as it was. +type Snapshot = (Vec<(u64, Arc, Vec, usize)>, usize, &'static str, Value); + +fn snapshot(s: &Session) -> Snapshot { + let docs = s.documents().iter().map(|d| (d.uid, d.doc.clone(), d.selection.objects.clone(), d.history.undo.len())).collect(); + (docs, s.journal.len(), s.tool_id(), s.tool_options()) +} + +/// A file read apart from the session is placed only in the document Place started in: with +/// another document active, Replace included when that document holds the same object under the +/// same id, or after the document closed, nothing changes in any document; with the document +/// active again, the file is placed in it. +#[test] +fn a_file_read_apart_from_the_session_is_placed_only_in_the_document_it_was_read_for() { + let blue = file("blue.png", &png(8, 8, [0, 0, 255, 255], None)); + let not_active = "the document it was prepared for is no longer active"; + for replace in [false, true] { + let p = with(blue.clone(), json!({"replace": replace})); + let mut s = session(); + let square = json!({"x": 10, "y": 10, "width": 20, "height": 20}); + let a = s.execute("shape.rectangle", &square).unwrap()["id"].clone(); + let read = s.prepare_place(&p).unwrap().read().unwrap(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let b = s.execute("shape.rectangle", &square).unwrap()["id"].clone(); + assert_eq!(a, b, "the other document holds an object with the same id"); + assert!(node(&s, &b) == s.documents()[0].doc.node(NodeId(a.as_u64().unwrap())).unwrap().clone(), "and the same content"); + let before = snapshot(&s); + let err = s.place_read(read).unwrap_err(); + assert!(err.to_string().contains(not_active), "replace {replace}: {err}"); + assert!(snapshot(&s) == before, "replace {replace}: nothing placed, selected or journaled in either document"); + // Active again, the document Place started in takes the file. + let read = { + s.execute("document.activate", &json!({"index": 0})).unwrap(); + s.prepare_place(&p).unwrap().read().unwrap() + }; + s.execute("document.activate", &json!({"index": 1})).unwrap(); + s.execute("document.activate", &json!({"index": 0})).unwrap(); + let r = s.place_read(read).unwrap(); + assert_eq!(s.active_index(), Some(0)); + assert!(s.doc().unwrap().doc.node(NodeId(r["ids"][0].as_u64().unwrap())).is_some(), "replace {replace}: placed in the first document"); + let others = s.documents()[1].doc.layers.last().unwrap().children().unwrap().len(); + assert_eq!(others, 1, "replace {replace}: the other document keeps its one object"); + } + // The document Place started in closed: refused in the document left open, and with none left. + let mut s = session(); + let read = s.prepare_place(&blue).unwrap().read().unwrap(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("file.close", &json!({"index": 0})).unwrap(); + let before = snapshot(&s); + assert!(s.place_read(read).unwrap_err().to_string().contains(not_active)); + assert!(snapshot(&s) == before, "nothing placed in the document left open"); + let read = s.prepare_place(&blue).unwrap().read().unwrap(); + s.execute("file.close", &json!({})).unwrap(); + let journal = s.journal.len(); + assert!(s.place_read(read).is_err() && s.journal.len() == journal, "no document left: refused"); +} + +/// Files read for the place cursor apart from the session load it only in the document they were +/// read for: with another document active, or after that document closed, its tool and queue stay +/// as they were; with the document active again, the cursor is loaded. +#[test] +fn files_read_for_the_place_cursor_apart_from_the_session_load_it_only_in_their_document() { + let p = json!({"files": [file("a.png", &png(40, 20, [9, 9, 9, 255], None))], "link": false}); + let not_active = "the document it was prepared for is no longer active"; + let mut s = session(); + let read = s.prepare_place_queue(&p).unwrap().read().unwrap(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let before = snapshot(&s); + assert!(s.place_queue_read(read).unwrap_err().to_string().contains(not_active)); + assert!(snapshot(&s) == before && s.tool_id() == "selection", "the other document's tool and queue stay"); + let read = { + s.execute("document.activate", &json!({"index": 0})).unwrap(); + s.prepare_place_queue(&p).unwrap().read().unwrap() + }; + s.execute("document.activate", &json!({"index": 1})).unwrap(); + s.execute("document.activate", &json!({"index": 0})).unwrap(); + assert_eq!(s.place_queue_read(read).unwrap()["count"], 1); + assert_eq!(s.tool_id(), "place"); + // The document they were read for closed. + let mut s = session(); + let read = s.prepare_place_queue(&p).unwrap().read().unwrap(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("file.close", &json!({"index": 0})).unwrap(); + let before = snapshot(&s); + assert!(s.place_queue_read(read).unwrap_err().to_string().contains(not_active)); + assert!(snapshot(&s) == before, "the document left open keeps its tool"); +} + /// A linked image keeps the preview its file was read with ([`cmd::place::PlaceJob::read`] makes /// it), so placing the read file does not decode the image again; an embedded image has none. #[test] @@ -662,6 +751,101 @@ fn placed_art_brings_its_symbols_and_swatches_renaming_on_conflict() { assert!(linked, "still linked to the swatch it brought"); } +/// The symbol and pattern art placed art brings takes ids of the document's own: the file's ids +/// already name other objects there, and the Links panel names linked art in symbols by its id. +#[test] +fn placed_art_brings_its_symbols_and_patterns_with_ids_of_the_documents_own() { + let mut src = session(); + src.execute("shape.ellipse", &json!({"x": 50, "y": 10, "width": 20, "height": 20})).unwrap(); + src.execute("symbol.new", &json!({"name": "Star"})).unwrap(); + src.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 8, "height": 8})).unwrap(); + let tile = src.doc().unwrap().selection.objects[0]; + src.execute("object.pattern.make", &json!({"ids": [tile.0], "edit": false, "name": "Dots"})).unwrap(); + src.execute("paint.setFill", &json!({"ids": [tile.0], "swatch": "Dots"})).unwrap(); + let bytes = serialize(&mut src, "vectorcraft"); + // The document's objects take the same ids the file's do. + let mut s = session(); + for x in [0, 20, 40, 60] { + s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 5, "height": 5})).unwrap(); + } + s.execute("symbol.new", &json!({"name": "Box"})).unwrap(); + place(&mut s, "logo.vectorcraft", &bytes, json!({})); + let doc = &s.doc().unwrap().doc; + assert!(doc.symbols.iter().any(|x| x.name == "Star") && doc.pattern("Dots").is_some()); + let mut ids = vec![]; + doc.visit_stored(|n, _| ids.push(n.id.0)); + let unique: std::collections::BTreeSet = ids.iter().copied().collect(); + assert_eq!(unique.len(), ids.len(), "{ids:?}"); +} + +/// Placing the same file again shares the symbols and patterns the first placement brought: their +/// art differs from the file's only in its ids, so no `Star 2` or `Dots 2` joins the document. +#[test] +fn placing_the_same_art_again_shares_its_symbols_and_patterns() { + let mut src = session(); + src.execute("shape.ellipse", &json!({"x": 50, "y": 10, "width": 20, "height": 20})).unwrap(); + src.execute("symbol.new", &json!({"name": "Star"})).unwrap(); + src.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 8, "height": 8})).unwrap(); + let tile = src.doc().unwrap().selection.objects[0]; + src.execute("object.pattern.make", &json!({"ids": [tile.0], "edit": false, "name": "Dots"})).unwrap(); + src.execute("paint.setFill", &json!({"ids": [tile.0], "swatch": "Dots"})).unwrap(); + let bytes = serialize(&mut src, "vectorcraft"); + let mut s = session(); + let counts = |s: &Session| { + let doc = &s.doc().unwrap().doc; + (doc.symbols.len(), doc.patterns.len()) + }; + place(&mut s, "logo.vectorcraft", &bytes, json!({})); + let once = counts(&s); + for _ in 0..2 { + place(&mut s, "logo.vectorcraft", &bytes, json!({})); + } + assert_eq!(counts(&s), once); + let doc = &s.doc().unwrap().doc; + assert!(!doc.symbols.iter().any(|x| x.name == "Star 2") && doc.pattern("Dots 2").is_none()); +} + +/// A symbol whose art matches the document's own but uses a pattern the document defines +/// differently is not shared: it comes in under a free name, using the pattern it brings. +#[test] +fn placed_art_does_not_share_a_symbol_whose_pattern_moves() { + let mut src = session(); + src.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 8, "height": 8})).unwrap(); + let tile = src.doc().unwrap().selection.objects[0]; + src.execute("object.pattern.make", &json!({"ids": [tile.0], "edit": false, "name": "Dots"})).unwrap(); + src.execute("paint.setFill", &json!({"ids": [tile.0], "swatch": "Dots"})).unwrap(); + src.execute("symbol.new", &json!({"name": "Star", "ids": [tile.0]})).unwrap(); + let bytes = serialize(&mut src, "vectorcraft"); + let mut s = session(); + place(&mut s, "logo.vectorcraft", &bytes, json!({})); + // The document's "Dots" changes; its "Star" still matches the file's. + let st = s.doc_mut().unwrap(); + let d = Arc::make_mut(&mut st.doc); + let dots = d.pattern_mut("Dots").unwrap(); + dots.tile = Rect::new(0.0, 0.0, 50.0, 50.0); + let r = place(&mut s, "logo.vectorcraft", &bytes, json!({})); + let mut symbol = None; + node(&s, &r["ids"][0]).walk(&mut |n| { + if let NodeKind::SymbolInstance { symbol: name, .. } = &n.kind { + symbol = Some(name.clone()); + } + }); + assert_eq!(symbol.as_deref(), Some("Star 2")); + let doc = &s.doc().unwrap().doc; + let star2 = doc.symbols.iter().find(|x| x.name == "Star 2").unwrap(); + let mut fills = vec![]; + star2.art.walk(&mut |n| { + fills.extend(n.appearance.items.iter().filter_map(|i| match i { + AppearanceItem::Fill(f) => match &f.paint { + Paint::Pattern { pattern, .. } => Some(pattern.clone()), + _ => None, + }, + _ => None, + })) + }); + assert_eq!(fills, ["Dots 2"]); +} + #[test] fn placed_art_brings_its_brushes_renaming_on_conflict() { // The file: a path with its own brush, and one with a brush the defaults hold. diff --git a/crates/engine/src/tests/placed_document.rs b/crates/engine/src/tests/placed_document.rs index 5871b85a31..2420ef265c 100644 --- a/crates/engine/src/tests/placed_document.rs +++ b/crates/engine/src/tests/placed_document.rs @@ -1060,6 +1060,135 @@ fn link_info_gives_the_artboards_size_not_pixels() { ); } +/// A confined caller's Link Info of a placed document whose file is outside its read roots has no +/// `link`, `path` or `location`, and keeps the file's name. +#[test] +fn link_info_leaves_out_a_placed_documents_path_outside_the_read_roots() { + let away = Folder::new("placed-lrr-away"); + let home = Folder::new("placed-lrr-home"); + let src = away.file("logo.vectorcraft"); + source(&src, 100.0, 50.0, RED, 0); + let mut s = session(); + let id = place(&mut s, &src); + let roots = crate::file_access::AutomationRoots::new(&[&home.0], &[]).unwrap().unwrap(); + let i = crate::file_access::confine(Some(&roots), || s.execute("links.info", &json!({"id": id.0}))).unwrap(); + assert!(!i.to_string().contains("placed-lrr-away"), "{i}"); + assert_eq!( + (i["fileName"].as_str(), i["document"].as_bool(), i["status"].as_str()), + (Some("logo.vectorcraft"), Some(true), Some("missing")), + "{i}" + ); + let l = crate::file_access::confine(Some(&roots), || s.execute("links.list", &json!({}))).unwrap(); + assert!(!l.to_string().contains("placed-lrr-away") && l["links"][0]["name"] == "logo.vectorcraft", "{l}"); + let i = s.execute("links.info", &json!({"id": id.0})).unwrap(); + assert_eq!((&i["link"], &i["path"]), (&json!(src), &json!(src)), "unconfined: {i}"); +} + +/// `document.inspect` and `document.json` for a confined caller: the document's file, a placed +/// document and a linked image outside the read roots are not named by path, and the document +/// keeps its links. +#[test] +fn document_replies_leave_out_paths_outside_the_read_roots() { + let away = Folder::new("doc-lrr-away"); + let home = Folder::new("doc-lrr-home"); + let src = away.file("logo.vectorcraft"); + source(&src, 100.0, 50.0, RED, 0); + let pic = away.file("photo.png"); + write(&pic, &crate::tests_links::png(60, 30, BLUE)); + let mut s = session(); + let id = place(&mut s, &src); + let r = s.execute("file.place", &json!({"path": pic, "at": [50, 50]})).unwrap(); + assert_eq!(r["linked"], true, "{r}"); + s.execute("variable.define", &json!({"name": "Photo", "kind": "image"})).unwrap(); + s.execute("dataset.new", &json!({"name": "Row", "values": {"Photo": pic}})).unwrap(); + let image = r["ids"][0].as_u64().unwrap(); + // A linked JavaScript file outside the read roots, and one given as a URL. + let script = away.file("menu.js"); + write(&script, b"void 0;"); + let url = "https://example.com/scripts/menu.js"; + for file in [script.as_str(), url] { + s.execute("svgInteractivity.addFile", &json!({"file": file})).unwrap(); + } + let poster = away.file("poster.vectorcraft"); + save(&mut s, &poster); + // The folder Export for Screens wrote to, and a pattern of the linked image being edited: its + // definition before editing is kept beside the tile art. + let out = away.file("out"); + s.execute("document.exportForScreens", &json!({"folder": out, "formats": [{"format": "svg"}]})).unwrap(); + let pattern = s.execute("object.pattern.make", &json!({"ids": [image], "edit": false})).unwrap()["name"].clone(); + s.execute("object.pattern.edit", &json!({"name": pattern})).unwrap(); + assert!(s.doc().unwrap().doc.pattern_edit.as_ref().is_some_and(|e| e.original.is_some())); + let ask = |s: &mut Session, root: &std::path::Path, cmd: &str| { + let roots = crate::file_access::AutomationRoots::new(&[root], &[]).unwrap().unwrap(); + crate::file_access::confine(Some(&roots), || s.execute(cmd, &json!({}))).unwrap() + }; + let inspect = ask(&mut s, &home.0, "document.inspect"); + assert!(!inspect.to_string().contains("doc-lrr-away"), "{inspect}"); + assert!(inspect["path"].is_null() && inspect["uid"].is_u64(), "{inspect}"); + let model = ask(&mut s, &home.0, "document.json").to_string(); + assert!(!model.contains("doc-lrr-away"), "{model}"); + for name in ["logo.vectorcraft", "photo.png"] { + assert!(model.contains(&format!("\"path\":\"{name}\"")), "{name}: {model}"); + } + assert!(model.contains("{\"image\":\"photo.png\"}"), "{model}"); + assert!(model.contains(&format!("\"svg_scripts\":[\"menu.js\",\"{url}\"]")), "{model}"); + // The document keeps its links, and a caller whose read roots hold the files sees every path. + assert_eq!(placed(&s, id).link.path, src); + assert_eq!(s.doc().unwrap().doc.svg_scripts, [script.as_str(), url]); + for model in [ask(&mut s, &away.0, "document.json"), s.execute("document.json", &json!({})).unwrap()] { + let model = model.to_string(); + for path in [&src, &pic, &out, &script] { + assert!(model.contains(&json!(path).to_string()), "{path}: {model}"); + } + } + assert_eq!(ask(&mut s, &away.0, "document.inspect")["path"], json!(poster)); + assert_eq!(s.execute("document.inspect", &json!({})).unwrap()["path"], json!(poster)); +} + +/// `document.json` for a confined caller: a linked image in a brush's art outside the read roots +/// is named by its file name, a stored brush entry that does not read as a brush is left out, and a +/// link inside them whose stored relative path leads outside them loses that relative path. +#[test] +fn document_json_checks_brush_art_and_relative_paths_against_the_read_roots() { + let away = Folder::new("doc-brr-away"); + let home = Folder::new("doc-brr-home"); + let pic = away.file("photo.png"); + write(&pic, &crate::tests_links::png(60, 30, BLUE)); + let near_pic = home.file("near.png"); + write(&near_pic, &crate::tests_links::png(20, 10, RED)); + let mut s = session(); + let r = s.execute("file.place", &json!({"path": pic, "at": [50, 50]})).unwrap(); + assert_eq!(r["linked"], true, "{r}"); + let image = r["ids"][0].as_u64().unwrap(); + let r = s.execute("file.place", &json!({"path": near_pic, "at": [150, 50]})).unwrap(); + assert_eq!(r["linked"], true, "{r}"); + s.execute("brush.new", &json!({"type": "art", "name": "Photo Band", "ids": [image]})).unwrap(); + save(&mut s, &home.file("poster.vectorcraft")); + { + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let lib = d.unknown.get_mut(vectorcraft_brush::DOC_KEY).and_then(Value::as_array_mut).unwrap(); + lib.push(json!({"name": "Broken Band", "type": "unknown kind", "note": pic})); + d.update_links(|l| { + if l.name() == "near.png" { + l.relative = Some("../doc-brr-away/near.png".into()); + } + }); + } + let unconfined = s.execute("document.json", &json!({})).unwrap().to_string(); + for part in [json!(pic).to_string(), "Broken Band".into(), "../doc-brr-away/near.png".into()] { + assert!(unconfined.contains(&part), "{part}: {unconfined}"); + } + let roots = crate::file_access::AutomationRoots::new(&[&home.0], &[]).unwrap().unwrap(); + let model = crate::file_access::confine(Some(&roots), || s.execute("document.json", &json!({}))).unwrap(); + let text = model.to_string(); + assert!(!text.contains("doc-brr-away") && !text.contains("Broken Band"), "{text}"); + assert!(text.contains("\"path\":\"photo.png\"") && text.contains("Photo Band"), "{text}"); + assert!(text.contains(&json!(near_pic).to_string()), "{text}"); + // The document keeps its brushes and links. + let stored = s.doc().unwrap().doc.unknown.get(vectorcraft_brush::DOC_KEY).unwrap().to_string(); + assert!(stored.contains("Broken Band") && stored.contains(&json!(pic).to_string()), "{stored}"); +} + /// Save As reads its defaults from the catalog; using them must retain current editable links. #[test] fn native_save_catalog_defaults_keep_placed_documents_editable() { diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index f8738eb547..499f2d15c6 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -235,8 +235,16 @@ fn live_effect_plugins_reshape_editable_art_and_expand() { run(&mut s, "select.all", json!({})); run(&mut s, "object.move", json!({"dx": 50, "dy": 0})); assert_eq!(effected(&s), *node(&s, a).path_data().unwrap()); + // A parameter of another type than the manifest gives it is refused. + let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + let wrong = json!({"ids": [a.0], "effect": "plugin.test.engine.tri", "params": {"size": "4 pt"}}); + let e = s.execute("effect.apply", &wrong).unwrap_err().to_string(); + assert!(e.contains("`size` must be a number"), "{e}"); + assert_eq!((s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()), before); run(&mut s, "effect.apply", json!({"ids": [a.0], "effect": "plugin.test.engine.tri", "params": {"size": 4}})); assert_eq!(effected(&s), triangle()); + let e = s.execute("effect.setParams", &json!({"ids": [a.0], "index": 1, "params": {"size": true}})).unwrap_err().to_string(); + assert!(e.contains("`size` must be a number"), "{e}"); assert_eq!(node(&s, a).appearance.effects[1].params, json!({"size": 4})); // Uninstalled: the geometry is drawn as it is. run(&mut s, "plugin.remove", json!({"id": "test.engine.tri"})); @@ -329,6 +337,29 @@ fn expanding_a_fill_gives_its_plug_in_effect_the_fill_it_sits_on() { assert_eq!(clip.path_data().unwrap().bounds(), triangle().bounds(), "the triangle the canvas fills"); } +/// A plug-in effect on a fill, before the fill's own 3D Revolve, is given the fill it sits on +/// (`_context.item`), so the fill revolves the shape the plug-in returns for it. +#[test] +fn a_fills_revolve_gives_the_plug_in_effect_before_it_the_fill_it_sits_on() { + let mut s = session(); + let id = rect(&mut s, 10.0, "#ff0000"); + let tri = json!({"objects": [{"path": triangle()}]}).to_string(); + let on_fill = tpl::when_given(&tpl::manifest("test.engine.revolvefill", "effect", "{}"), tpl::Given::Params, r#""item":{"fill":0}"#, &tri); + install_wat(&mut s, &on_fill); + let fill = node(&s, id).appearance.items.iter().position(|i| i.is_fill()).unwrap(); + run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "plugin.test.engine.revolvefill", "item": fill})); + run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "threeD.revolve", "item": fill})); + let n = node(&s, id); + // The same object with the triangle as its path and only the Revolve on its fill. + let mut expected = n.clone(); + if let vectorcraft_doc::NodeKind::Path { path, .. } = &mut expected.kind { + *path = triangle(); + } + expected.appearance.items[fill].effects_mut().retain(|e| e.id == "threeD.revolve"); + let art = vectorcraft_render::effects::revolve_art(&n).unwrap(); + assert_eq!(art, vectorcraft_render::effects::revolve_art(&expected).unwrap(), "the fill revolves the triangle"); +} + /// The manifest of a test live effect `id` that declares `paintOutput` (at `api` 2), or that /// doesn't (`paints` off). fn painting(id: &str, paints: bool) -> String { @@ -452,6 +483,60 @@ fn a_painted_effect_on_a_fill_and_refused_results() { } } +/// A fill's Drop Shadow before a painted effect that returns two fills, and a 200% Transform effect +/// after it: the shadow of each returned fill follows the Transform effect. The square the effect +/// returns spans 30 to 70 pt once scaled, so both half-opaque shadows, 20 pt to the right, cover +/// 85 pt as they cover 75 pt. +#[test] +fn a_shadow_on_each_fill_a_painted_effect_returns_follows_the_transform_after_it() { + let mut s = session(); + let id = rect(&mut s, 10.0, "#ff0000"); + let out = json!({"objects": [{"path": square_at(40.0), "fills": [solid("#00ff00"), solid("#0000ff")]}]}).to_string(); + install_wat(&mut s, &tpl::returning(&painting("test.engine.shadowedfills", true), &out)); + let fill = node(&s, id).appearance.items.iter().position(|i| i.is_fill()).unwrap(); + for (effect, params) in [ + ("stylize.dropShadow", json!({"x": 10, "y": 0, "blur": 0, "opacity": 50})), + ("plugin.test.engine.shadowedfills", json!({})), + ("distort.transform", json!({"scaleH": 200, "scaleV": 200})), + ] { + run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": effect, "params": params, "item": fill})); + } + let img = drawn(&s); + let (near, far) = (img.pixel(75, 50), img.pixel(85, 50)); + assert_ne!(near, WHITE, "the shadows reach past the square"); + assert_eq!(far, near, "both shadows at 20 pt"); +} + +/// A Transform effect with Scale Strokes & Effects on after a painted effect on a fill leaves the +/// Drop Shadow after it as it is on every paint the piece is drawn with. +#[test] +fn a_transform_after_a_painted_fill_effect_leaves_the_later_shadow_on_every_paint() { + let mut s = session(); + let id = rect(&mut s, 10.0, "#ff0000"); + let two = json!({"objects": [{"path": square_at(40.0), "fills": [solid("#00ff00"), solid("#0000ff")]}]}).to_string(); + install_wat(&mut s, &tpl::returning(&painting("test.engine.twopaints", true), &two)); + let fill = node(&s, id).appearance.items.iter().position(|i| i.is_fill()).unwrap(); + run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "plugin.test.engine.twopaints", "item": fill})); + let mut n = node(&s, id); + let later = [ + vectorcraft_doc::Effect { id: "distort.transform".into(), params: json!({"scaleH": 200, "scaleV": 200, "strokes": true}), visible: true }, + vectorcraft_doc::Effect { id: "stylize.dropShadow".into(), params: json!({"x": 10.0, "y": 0.0, "blur": 0.0}), visible: true }, + ]; + n.appearance.items[fill].effects_mut().extend(later); + let art = vectorcraft_render::effects::reshape(Some(&s.doc().unwrap().doc), &n, None).unwrap(); + let mut offsets = vec![]; + art.walk(&mut |m| { + for item in &m.appearance.items { + for r in vectorcraft_render::effects::raster_effects(item.effects()) { + if let vectorcraft_render::effects::RasterFx::DropShadow { dx, dy, .. } = r { + offsets.push((dx, dy)); + } + } + } + }); + assert_eq!(offsets, [(10.0, 0.0), (10.0, 0.0)], "one shadow on each of the piece's two fills"); +} + /// A result refused for a swatch the document doesn't have stays cached: once the document has the /// swatch, the next check of that result clears the error. #[test] @@ -505,6 +590,30 @@ fn a_painted_group_effect_links_to_the_document_s_swatches() { assert_eq!((img.pixel(50, 50), img.pixel(15, 15)), (GREEN, WHITE), "the group's piece, green"); } +/// A painted effect on a group leaves the group's art as it is when a path in it has a linked +/// opacity mask, which can't take the pieces as the path does: the mask still covers the path. +#[test] +fn a_painted_group_effect_leaves_art_with_a_linked_mask_as_it_is() { + let mut s = session(); + let a = rect(&mut s, 10.0, "#ff0000"); + let m = rect(&mut s, 10.0, "#ffffff"); + run(&mut s, "select.set", json!({"ids": [a.0, m.0]})); + run(&mut s, "transparency.makeOpacityMask", json!({})); + rect(&mut s, 100.0, "#0000ff"); + run(&mut s, "select.all", json!({})); + let g = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap()); + let out = json!({"objects": [{"path": square_at(40.0), "fills": [solid("#00ff00")]}]}).to_string(); + install_wat(&mut s, &tpl::returning(&painting("test.engine.maskedpaint", true), &out)); + run(&mut s, "effect.apply", json!({"ids": [g.0], "effect": "plugin.test.engine.maskedpaint"})); + let art = vectorcraft_render::effects::evaluate_container(Some(&s.doc().unwrap().doc), &node(&s, g)).unwrap(); + let mut masked = vec![]; + art.walk(&mut |c| masked.extend(c.extras().mask.as_ref().map(|k| (c.geometric_bounds(), k.art.geometric_bounds())))); + assert!(!masked.is_empty(), "the masked path"); + for (path, mask) in masked { + assert_eq!(path, mask, "the mask covers the path"); + } +} + /// The output of a painted effect that returns one green square linked to swatch `Leaf`. fn leaf_square() -> String { let mut leaf = solid("#00ff00"); @@ -644,6 +753,27 @@ fn expanding_a_gradient_fill_keeps_each_piece_s_own_paint() { } } +/// `object.expand.info` measures each piece a painted effect returns: a piece whose repeating +/// gradient needs more runs across it than are written (1,000) reports no gradient to expand, as +/// Expand leaves it a gradient, and the same gradient in 10 runs reports one. +#[test] +fn expand_info_measures_the_gradient_on_each_painted_piece() { + for (end, expands) in [(120.0, true), (100.2, false)] { + let mut s = session(); + let id = rect(&mut s, 10.0, "#ff0000"); + let gradient = json!({"kind": "linear", "spread": "repeat", "repeats": 10, "start": [100, 50], "end": [end, 50]}); + run(&mut s, "paint.setFill", json!({"ids": [id.0], "gradient": gradient})); + let out = json!({"objects": [{"path": square_at(100.0)}]}).to_string(); + install_wat(&mut s, &tpl::returning(&painting("test.engine.expandruns", true), &out)); + run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "plugin.test.engine.expandruns"})); + run(&mut s, "select.set", json!({"ids": [id.0]})); + let info = s.execute("object.expand.info", &json!({})).unwrap(); + assert_eq!((info["gradient"].clone(), info["fill"].clone()), (json!(expands), json!(expands)), "{end}"); + let only_fill = s.execute("object.expand", &json!({"object": false, "fill": true, "stroke": false})); + assert_eq!(only_fill.is_ok(), expands, "{end}: {only_fill:?}"); + } +} + /// Object › Expand of a pattern fill works piece by piece: a piece that keeps the pattern has its /// tiles expanded, and a piece with a paint of its own keeps that paint. #[test] @@ -666,30 +796,269 @@ fn expanding_a_pattern_fill_keeps_each_piece_s_own_paint() { assert_eq!(patterns, 0, "the tiles are objects"); } -/// Two painted effects on one fill, the first returning a piece with two fills: the second replaces -/// the first of them and the other fill stays over it. +/// A path's bounds and the paints of its fills and strokes, each stroke with its weight. +type PaintedPath = (Option, Vec<(Paint, Option)>); + +/// The paths of `id`'s reshaped art that paint, in paint order, each with the fills and strokes of +/// it that paint. +fn painted_paths(s: &Session, id: NodeId) -> Vec { + let st = s.doc().unwrap(); + let art = vectorcraft_render::effects::reshape(Some(&st.doc), st.doc.node(id).unwrap(), None).unwrap(); + let mut paths = vec![]; + art.walk(&mut |n| { + if let Some(p) = n.path_data() { + let items: Vec<_> = n + .appearance + .items + .iter() + .map(|i| match i { + vectorcraft_doc::AppearanceItem::Fill(f) => (f.paint.clone(), None), + vectorcraft_doc::AppearanceItem::Stroke(st) => (st.paint.clone(), Some(st.width)), + }) + .filter(|(paint, _)| !paint.is_none()) + .collect(); + if !items.is_empty() { + paths.push((p.bounds(), items)); + } + } + }); + paths +} + +fn paint(hex: &str) -> Paint { + Paint::solid(Color::from_hex(hex).unwrap()) +} + +/// Two painted effects on one fill, the first returning a piece with two fills: the second runs on +/// each of them, told which fill it is on. On the second fill it returns a blue square at 80 pt; on +/// the first it returns a result that is refused, which leaves only that fill, red, on the square at +/// 40 pt. #[test] -fn a_second_painted_effect_on_a_fill_keeps_the_piece_s_other_fills() { +fn a_later_painted_effect_runs_on_every_fill_a_piece_returns() { let mut s = session(); let id = rect(&mut s, 10.0, "#ff0000"); let two = json!({"objects": [{"path": square_at(40.0), "fills": [solid("#ff0000"), solid("#00ff00")]}]}).to_string(); - let one = json!({"objects": [{"path": square_at(40.0), "fills": [solid("#0000ff")]}]}).to_string(); + let blue = json!({"objects": [{"path": square_at(80.0), "fills": [solid("#0000ff")]}]}).to_string(); install_wat(&mut s, &tpl::returning(&painting("test.engine.twofills", true), &two)); - install_wat(&mut s, &tpl::returning(&painting("test.engine.onefill", true), &one)); + install_wat(&mut s, &tpl::when_given(&painting("test.engine.onsecond", true), tpl::Given::Params, r#""item":{"fill":1}"#, &blue)); let fill = node(&s, id).appearance.items.iter().position(|i| i.is_fill()).unwrap(); run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "plugin.test.engine.twofills", "item": fill})); - run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "plugin.test.engine.onefill", "item": fill})); - assert_eq!(drawn(&s).pixel(50, 50), GREEN, "the other fill paints over the replaced one"); + run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "plugin.test.engine.onsecond", "item": fill})); + let img = drawn(&s); + assert_eq!((img.pixel(50, 50), img.pixel(90, 50)), (RED, BLUE), "the first fill as it was, the second moved and blue"); + let (a, b) = (square_at(40.0).bounds(), square_at(80.0).bounds()); + assert_eq!(painted_paths(&s, id), [(a, vec![(paint("#ff0000"), None)]), (b, vec![(paint("#0000ff"), None)])]); + // The same result for both fills: each is replaced. + let one = json!({"objects": [{"path": square_at(40.0), "fills": [solid("#0000ff")]}]}).to_string(); + install_wat(&mut s, &tpl::returning(&painting("test.engine.onsecond", true), &one)); + assert_eq!(painted_paths(&s, id), [(a, vec![(paint("#0000ff"), None)]), (a, vec![(paint("#0000ff"), None)])]); +} + +/// On a stroke, a later painted effect runs on each stroke the first returns, with its own weight +/// and place among them, and keeps their order. +#[test] +fn a_later_painted_effect_runs_on_every_stroke_a_piece_returns() { + let mut s = session(); + let id = rect(&mut s, 10.0, "#ff0000"); + run(&mut s, "paint.setStroke", json!({"ids": [id.0], "color": "#000000"})); + let two = json!({"objects": [{"path": square_at(40.0), "strokes": [{"paint": solid("#ff0000"), "width": 2}, {"paint": solid("#00ff00"), "width": 6}]}]}) + .to_string(); + let blue = json!({"objects": [{"path": square_at(80.0), "strokes": [{"paint": solid("#0000ff"), "width": 4}]}]}).to_string(); + install_wat(&mut s, &tpl::returning(&painting("test.engine.twostrokes", true), &two)); + install_wat(&mut s, &tpl::when_given(&painting("test.engine.onsecondstroke", true), tpl::Given::Params, r#""item":{"stroke":1}"#, &blue)); + let stroke = node(&s, id).appearance.items.iter().position(|i| !i.is_fill()).unwrap(); + for effect in ["plugin.test.engine.twostrokes", "plugin.test.engine.onsecondstroke"] { + run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": effect, "item": stroke})); + } + let stroked: Vec<_> = painted_paths(&s, id).into_iter().filter(|(_, items)| items.iter().any(|(_, w)| w.is_some())).collect(); + let (a, b) = (square_at(40.0).bounds(), square_at(80.0).bounds()); + assert_eq!(stroked, [(a, vec![(paint("#ff0000"), Some(2.0))]), (b, vec![(paint("#0000ff"), Some(4.0))])]); +} + +/// A third painted effect runs on every fill the second returned, for each fill the first returned. +#[test] +fn a_third_painted_effect_visits_every_fill_from_the_second() { + let mut s = session(); + let id = rect(&mut s, 10.0, "#ff0000"); + let first = json!({"objects": [{"path": square_at(40.0), "fills": [solid("#ff0000"), solid("#00ff00")]}]}).to_string(); + let second = json!({"objects": [{"path": square_at(40.0), "fills": [solid("#0000ff"), solid("#00ffff")]}]}).to_string(); + let third = json!({"objects": [{"path": square_at(80.0), "fills": [solid("#ffff00")]}]}).to_string(); + install_wat(&mut s, &tpl::returning(&painting("test.engine.third.a", true), &first)); + install_wat(&mut s, &tpl::returning(&painting("test.engine.third.b", true), &second)); + install_wat(&mut s, &tpl::when_given(&painting("test.engine.third.c", true), tpl::Given::Params, r#""item":{"fill":1}"#, &third)); + let fill = node(&s, id).appearance.items.iter().position(|i| i.is_fill()).unwrap(); + for effect in ["a", "b", "c"] { + run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": format!("plugin.test.engine.third.{effect}"), "item": fill})); + } + let (a, b) = (square_at(40.0).bounds(), square_at(80.0).bounds()); + let pair = [(a, vec![(paint("#0000ff"), None)]), (b, vec![(paint("#ffff00"), None)])]; + assert_eq!(painted_paths(&s, id), [pair.clone(), pair].concat()); +} + +/// A later live effect that changes geometry only runs on each fill a painted effect returned, told +/// which fill it is on: on the second it moves the square to 80 pt, and the first stays at 40 pt. +#[test] +fn a_later_geometry_effect_uses_each_generated_fill_s_context() { + let mut s = session(); + let id = rect(&mut s, 10.0, "#ff0000"); + let two = json!({"objects": [{"path": square_at(40.0), "fills": [solid("#ff0000"), solid("#00ff00")]}]}).to_string(); + let moved = json!({"objects": [{"path": square_at(80.0)}]}).to_string(); + install_wat(&mut s, &tpl::returning(&painting("test.engine.geomfills", true), &two)); + install_wat(&mut s, &tpl::when_given(&painting("test.engine.geomsecond", false), tpl::Given::Params, r#""item":{"fill":1}"#, &moved)); + let fill = node(&s, id).appearance.items.iter().position(|i| i.is_fill()).unwrap(); + for effect in ["plugin.test.engine.geomfills", "plugin.test.engine.geomsecond"] { + run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": effect, "item": fill})); + } + let (a, b) = (square_at(40.0).bounds(), square_at(80.0).bounds()); + assert_eq!(painted_paths(&s, id), [(a, vec![(paint("#ff0000"), None)]), (b, vec![(paint("#00ff00"), None)])]); +} + +/// A later Outline Stroke effect runs on each stroke a painted effect returned, with that stroke's +/// weight: the 2 pt stroke's outline is 22 pt wide and the 6 pt stroke's 26 pt, in their order. +#[test] +fn a_later_outline_stroke_uses_each_generated_stroke_s_weight() { + let mut s = session(); + let id = rect(&mut s, 10.0, "#ff0000"); + run(&mut s, "paint.setStroke", json!({"ids": [id.0], "color": "#000000"})); + let two = json!({"objects": [{"path": square_at(40.0), "strokes": [{"paint": solid("#ff0000"), "width": 2}, {"paint": solid("#00ff00"), "width": 6}]}]}) + .to_string(); + install_wat(&mut s, &tpl::returning(&painting("test.engine.outlinestrokes", true), &two)); + let stroke = node(&s, id).appearance.items.iter().position(|i| !i.is_fill()).unwrap(); + run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "plugin.test.engine.outlinestrokes", "item": stroke})); + run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "path.outlineStroke", "params": {}, "item": stroke})); let st = s.doc().unwrap(); let art = vectorcraft_render::effects::reshape(Some(&st.doc), st.doc.node(id).unwrap(), None).unwrap(); - let mut paints = vec![]; + // Each outline is a compound path (the ring around the square): its width and its strokes. + let mut outlines = vec![]; art.walk(&mut |n| { - if n.path_data().is_some() { - paints.push(n.appearance.items.iter().filter(|i| i.is_fill()).map(|i| i.paint().clone()).collect::>()); + if let vectorcraft_doc::NodeKind::Compound { children, .. } = &n.kind { + let bounds = children.iter().filter_map(|c| c.path_data().and_then(PathData::bounds)).reduce(|a, b| a.union(b)); + let strokes: Vec<_> = n + .appearance + .items + .iter() + .filter_map(|i| match i { + vectorcraft_doc::AppearanceItem::Stroke(st) => Some((st.paint.clone(), st.width)), + vectorcraft_doc::AppearanceItem::Fill(_) => None, + }) + .collect(); + outlines.push((bounds.map(|b| (b.width() * 1000.0).round() / 1000.0), strokes)); } }); - let fill = |hex: &str| Paint::solid(Color::from_hex(hex).unwrap()); - assert!(paints.contains(&vec![fill("#0000ff"), fill("#00ff00")]), "{paints:?}"); + assert_eq!( + outlines, + [(Some(22.0), vec![(paint("#ff0000"), 2.0)]), (Some(26.0), vec![(paint("#00ff00"), 6.0)])], + "each stroke is outlined at its own weight" + ); +} + +/// A later painted effect's runs on the fills a piece returned share the effects' budget: each run +/// that fits gives all its pieces, and once the budget is spent the remaining fills stay together +/// on the piece's path, with none of their run's pieces. +#[test] +fn painted_fills_share_the_budget_without_partial_results() { + let mut s = session(); + let id = rect(&mut s, 10.0, "#ff0000"); + let fills = vec![solid("#ff0000"); vectorcraft_plugins::objects::MAX_ITEMS]; + let first = json!({"objects": [{"path": square_at(40.0), "fills": fills}]}).to_string(); + let tiny = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(0.1, 0.0), Point::new(0.0, 0.1)], true)); + let many = json!({"objects": vec![json!({"path": tiny}); 400]}).to_string(); + install_wat(&mut s, &tpl::returning(&painting("test.engine.budget.fills", true), &first)); + install_wat(&mut s, &tpl::returning(&painting("test.engine.budget.many", true), &many)); + let fill = node(&s, id).appearance.items.iter().position(|i| i.is_fill()).unwrap(); + for effect in ["plugin.test.engine.budget.fills", "plugin.test.engine.budget.many"] { + run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": effect, "item": fill})); + } + let paths = painted_paths(&s, id); + let tinies = paths.iter().filter(|(b, _)| *b == tiny.bounds()).count(); + let kept: Vec<_> = paths.iter().filter(|(b, _)| *b == square_at(40.0).bounds()).collect(); + assert_eq!(kept.len(), 1, "the fills left out stay together"); + let ran = vectorcraft_plugins::objects::MAX_ITEMS - kept[0].1.len(); + assert!(ran > 1 && !kept[0].1.is_empty(), "{ran} runs gave their pieces"); + assert_eq!(tinies, ran * 400, "every run that fit gave all its pieces"); + assert!(paths.len() <= vectorcraft_plugins::objects::MAX_OBJECTS, "{} paths", paths.len()); +} + +/// A later painted effect runs on each of 256 fills a painted effect returned on an 8,000-anchor +/// path, although 256 copies of that path would pass the effects' budget, when what it returns +/// fits. +#[test] +fn a_later_painted_effect_runs_on_many_fills_of_a_large_piece_when_its_results_fit() { + let mut s = session(); + let id = rect(&mut s, 10.0, "#ff0000"); + let zigzag: Vec = (0..8_000).map(|i| Point::new(40.0 + f64::from(i) * 20.0 / 8_000.0, if i % 2 == 0 { 40.0 } else { 60.0 })).collect(); + let large = PathData::single(SubPath::polyline(&zigzag, true)); + let fills = vec![solid("#ff0000"); vectorcraft_plugins::objects::MAX_ITEMS]; + let first = json!({"objects": [{"path": large, "fills": fills}]}).to_string(); + let tiny = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(0.1, 0.0), Point::new(0.0, 0.1)], true)); + let small = json!({"objects": [{"path": tiny}]}).to_string(); + install_wat(&mut s, &tpl::returning(&painting("test.engine.large.fills", true), &first)); + install_wat(&mut s, &tpl::returning(&painting("test.engine.large.small", true), &small)); + let fill = node(&s, id).appearance.items.iter().position(|i| i.is_fill()).unwrap(); + for effect in ["plugin.test.engine.large.fills", "plugin.test.engine.large.small"] { + run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": effect, "item": fill})); + } + let paths = painted_paths(&s, id); + let tinies = paths.iter().filter(|(b, _)| *b == tiny.bounds()).count(); + assert_eq!(tinies, vectorcraft_plugins::objects::MAX_ITEMS, "every fill's run"); + assert!(paths.iter().all(|(b, _)| *b != large.bounds()), "no fill left on the large path"); +} + +/// An open path of `curves` tall curves, each drawn with about 5,200 lines. +fn tall_curves(curves: u32) -> PathData { + let h = 3_000_000.0; + let anchors = (0..=curves) + .map(|i| { + let x = 40.0 + f64::from(i); + vectorcraft_geom::Anchor::with_handles(Point::new(x, 0.0), Point::new(x, -h), Point::new(x, h)) + }) + .collect(); + PathData::single(SubPath::new(anchors, false)) +} + +/// A later painted effect's run on the first of two fills a painted effect returned on a path that +/// takes most of the effects' budget gives its result when it and the second fill's result fit +/// together, although the result and another copy of the path would not. +#[test] +fn a_later_painted_run_counts_the_results_after_it_before_keeping_room_for_its_input() { + let mut s = session(); + let id = rect(&mut s, 10.0, "#ff0000"); + let (large, result) = (tall_curves(1_000), tall_curves(600)); + let tiny = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(0.1, 0.0), Point::new(0.0, 0.1)], true)); + let two = json!({"objects": [{"path": large, "fills": [solid("#ff0000"), solid("#00ff00")]}]}).to_string(); + let on_first = json!({"objects": [{"path": result}]}).to_string(); + let on_second = json!({"objects": [{"path": tiny}]}).to_string(); + install_wat(&mut s, &tpl::returning(&painting("test.engine.tall.fills", true), &two)); + let second = painting("test.engine.tall.each", true); + install_wat(&mut s, &tpl::when_given_else(&second, tpl::Given::Params, r#""item":{"fill":0}"#, &on_first, &on_second)); + let fill = node(&s, id).appearance.items.iter().position(|i| i.is_fill()).unwrap(); + for effect in ["plugin.test.engine.tall.fills", "plugin.test.engine.tall.each"] { + run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": effect, "item": fill})); + } + let want = [(result.bounds(), vec![(paint("#ff0000"), None)]), (tiny.bounds(), vec![(paint("#00ff00"), None)])]; + assert_eq!(painted_paths(&s, id), want, "both runs give their results"); +} + +/// When the results of a later painted effect's runs on the two fills of a large path do not fit +/// together, and the first fill's result and another copy of the path do not fit either, the first +/// fill stays on the path and the second fill's result, which fits beside the path, is drawn. +#[test] +fn a_later_painted_run_that_did_not_fit_beside_an_earlier_result_fits_once_that_is_left_out() { + let mut s = session(); + let id = rect(&mut s, 10.0, "#ff0000"); + let (large, first, second) = (tall_curves(577), tall_curves(1_058), tall_curves(770)); + let two = json!({"objects": [{"path": large, "fills": [solid("#ff0000"), solid("#00ff00")]}]}).to_string(); + let on_first = json!({"objects": [{"path": first}]}).to_string(); + let on_second = json!({"objects": [{"path": second}]}).to_string(); + install_wat(&mut s, &tpl::returning(&painting("test.engine.refit.fills", true), &two)); + let each = painting("test.engine.refit.each", true); + install_wat(&mut s, &tpl::when_given_else(&each, tpl::Given::Params, r#""item":{"fill":0}"#, &on_first, &on_second)); + let fill = node(&s, id).appearance.items.iter().position(|i| i.is_fill()).unwrap(); + for effect in ["plugin.test.engine.refit.fills", "plugin.test.engine.refit.each"] { + run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": effect, "item": fill})); + } + let want = [(large.bounds(), vec![(paint("#ff0000"), None)]), (second.bounds(), vec![(paint("#00ff00"), None)])]; + assert_eq!(painted_paths(&s, id), want, "the second fill's result is drawn"); } /// A Transform effect before a painted effect on a fill moves the fill's placed gradient: a piece @@ -1053,6 +1422,39 @@ fn the_first_view_defers_plug_in_effects_past_its_budget() { assert_eq!(fx_c.take_report(), Some(0)); } +/// A later painted effect deferred on the fills a piece returned is listed once, at its place among +/// the object's fill's effects, and a refresh of the object runs it on each of them. +#[test] +fn deferred_runs_on_the_fills_a_piece_returned_keep_the_fill_s_stage() { + let mut s = session(); + let id = rect(&mut s, 10.0, "#ff0000"); + let two = json!({"objects": [{"path": square_at(40.0), "fills": [solid("#ff0000"), solid("#00ff00")]}]}).to_string(); + let blue = json!({"objects": [{"path": square_at(80.0), "fills": [solid("#0000ff")]}]}).to_string(); + install_wat(&mut s, &tpl::returning(&painting("test.engine.deferred.two", true), &two)); + install_wat(&mut s, &tpl::returning(&painting("test.engine.deferred.later", true), &blue)); + let fill = node(&s, id).appearance.items.iter().position(|i| i.is_fill()).unwrap(); + run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "plugin.test.engine.deferred.two", "item": fill})); + // The first effect's result is kept from a drawing outside a view's budget. + assert_eq!(drawn(&s).pixel(50, 50), GREEN); + run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "plugin.test.engine.deferred.later", "item": fill})); + let step = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(3_000)); + let fx = vectorcraft_plugins::deferred::Deferrals::with_clock(stepping_clock(&step)); + s.doc_mut().unwrap().plugin_effects = fx.clone(); + let img = fx.view(|| drawn(&s)); + assert_eq!((img.pixel(50, 50), img.pixel(90, 50)), (GREEN, WHITE), "the fills on the first effect's piece"); + let places = run(&mut s, "effect.deferredStatus", json!({}))["effects"] + .as_array() + .unwrap() + .iter() + .map(|e| (e["objectId"].as_u64().unwrap(), e["item"].as_u64(), e["effectIndex"].as_u64().unwrap())) + .collect::>(); + assert_eq!(places, [(id.0, Some(fill as u64), 1)], "the fill's stage, listed once"); + step.store(0, std::sync::atomic::Ordering::Relaxed); + assert_eq!(run(&mut s, "effect.refreshDeferred", json!({"ids": [id.0]})), json!({"refreshed": 1, "stillDeferred": 0, "failed": 0})); + let img = fx.view(|| drawn(&s)); + assert_eq!((img.pixel(50, 50), img.pixel(90, 50)), (WHITE, BLUE), "both fills replaced"); +} + /// Deferred stages are listed where their effects are: after an effect that changes no geometry, /// and on a fill after a Transform effect that reaches its appearance, each of two instances of /// one plug-in at its own place. @@ -1153,6 +1555,98 @@ fn deferred_stages_in_symbol_art_are_listed_and_refreshed() { assert_eq!(run(&mut s, "effect.deferredStatus", json!({}))["effects"], json!([])); } +/// `effect.refreshDeferred` takes the id of an object in the art of a symbol, pattern, brush or +/// opacity mask, as `effect.deferredStatus` lists it: one with a deferred stage is refreshed, and +/// one without (or whose stage is gone) adds nothing to the counts. The id of art that is no +/// longer in the document is an error. +#[test] +fn refresh_takes_objects_in_definition_art() { + let mut s = session(); + const FX: &str = "plugin.test.engine.deferred.nested"; + let out = json!({"objects": [{"path": square_at(110.0)}]}).to_string(); + install_wat(&mut s, &tpl::returning(&tpl::manifest("test.engine.deferred.nested", "effect", "{}"), &out)); + // A symbol whose art holds an object with the effect and one without. + let staged = rect(&mut s, 10.0, "#ff0000"); + let plain = rect(&mut s, 30.0, "#ff0000"); + run(&mut s, "effect.apply", json!({"ids": [staged.0], "effect": FX})); + run(&mut s, "select.set", json!({"ids": [staged.0, plain.0]})); + run(&mut s, "symbol.new", json!({"name": "Nested"})); + // A pattern, an art brush (its source deleted) and an opacity mask, none with a stage. + let tile = rect(&mut s, 50.0, "#00ff00"); + run(&mut s, "select.set", json!({"ids": [tile.0]})); + run(&mut s, "object.pattern.make", json!({"name": "Tile", "width": 20, "height": 20})); + run(&mut s, "object.pattern.done", json!({})); + let bar = rect(&mut s, 70.0, "#0000ff"); + run(&mut s, "select.set", json!({"ids": [bar.0]})); + run(&mut s, "brush.new", json!({"type": "art", "name": "Bar"})); + run(&mut s, "edit.clear", json!({"ids": [bar.0]})); + let masked = rect(&mut s, 90.0, "#ff0000"); + let mask = rect(&mut s, 90.0, "#ffffff"); + run(&mut s, "select.set", json!({"ids": [masked.0, mask.0]})); + run(&mut s, "transparency.makeOpacityMask", json!({})); + // A layer object with a stage that stays deferred, and one without. + let kept = rect(&mut s, 130.0, "#ff0000"); + run(&mut s, "effect.apply", json!({"ids": [kept.0], "effect": FX})); + let bare = rect(&mut s, 150.0, "#ff0000"); + + // The ids of the objects of `art` that are not in the layers. + let nested = |s: &Session, art: &vectorcraft_doc::Node| { + let d = &s.doc().unwrap().doc; + let mut ids = Vec::new(); + vectorcraft_doc::swatches::walk_with_masks(art, &mut |n| { + if d.node(n.id).is_none() { + ids.push(n.id.0); + } + }); + ids + }; + let d = s.doc().unwrap().doc.clone(); + let in_symbol = nested(&s, &d.symbols[0].art); + let in_pattern = d.patterns.iter().flat_map(|p| p.art.iter().flat_map(|a| nested(&s, a))).collect::>(); + let brushes = vectorcraft_brush::library(&d); + let in_brush = brushes.iter().flat_map(|b| b.art().into_iter().flat_map(|a| nested(&s, a)).collect::>()).collect::>(); + let in_mask = d.node(masked).and_then(|n| n.extras().mask.as_ref()).map(|m| nested(&s, &m.art)).unwrap_or_default(); + for (what, ids) in [("symbol", &in_symbol), ("pattern", &in_pattern), ("brush", &in_brush), ("opacity mask", &in_mask)] { + assert!(!ids.is_empty(), "the {what} art has an object outside the layers"); + } + + let step = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(3_000)); + let fx = vectorcraft_plugins::deferred::Deferrals::with_clock(stepping_clock(&step)); + s.doc_mut().unwrap().plugin_effects = fx.clone(); + fx.view(|| drawn(&s)); + fx.first_view_done(); + let listed = |s: &mut Session| { + run(s, "effect.deferredStatus", json!({}))["effects"].as_array().unwrap().iter().map(|e| e["objectId"].as_u64().unwrap()).collect::>() + }; + let deferred = listed(&mut s); + let [nested_staged, last] = deferred[..] else { panic!("two stages: {deferred:?}") }; + assert!(in_symbol.contains(&nested_staged) && last == kept.0, "{deferred:?} {in_symbol:?}"); + let Some(&nested_plain) = in_symbol.iter().find(|i| **i != nested_staged) else { panic!("{in_symbol:?}") }; + + // Objects without a stage, each on its own and together: nothing to refresh. + let none = json!({"refreshed": 0, "stillDeferred": 0, "failed": 0}); + let mut plain_ids = vec![nested_plain, in_pattern[0], in_brush[0], in_mask[0], bare.0]; + for id in &plain_ids { + assert_eq!(run(&mut s, "effect.refreshDeferred", json!({"id": id})), none, "object {id}"); + } + assert_eq!(run(&mut s, "effect.refreshDeferred", json!({"ids": plain_ids})), none); + assert_eq!(listed(&mut s), [nested_staged, kept.0]); + + // The staged object of the symbol's art, by its id, with the others. + step.store(0, std::sync::atomic::Ordering::Relaxed); + plain_ids.push(nested_staged); + assert_eq!(run(&mut s, "effect.refreshDeferred", json!({"ids": plain_ids})), json!({"refreshed": 1, "stillDeferred": 0, "failed": 0})); + assert_eq!(listed(&mut s), [kept.0]); + // Its stage is gone; the object is still there. + assert_eq!(run(&mut s, "effect.refreshDeferred", json!({"id": nested_staged})), none); + + // Art no longer in the document, and an id of no object. + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).patterns.clear(); + assert!(s.execute("effect.refreshDeferred", &json!({"id": in_pattern[0]})).is_err(), "the pattern is gone"); + assert!(s.execute("effect.refreshDeferred", &json!({"ids": [nested_plain, 999_999]})).is_err(), "not an object of the document"); + assert_eq!(listed(&mut s), [kept.0]); +} + /// `CRAFT_PLUGIN_PAINTS_WASM=` saves a test live effect to try in the app /// (`stroke-width-test-effect.wasm`): it draws a triangle over the area 100,80–300,230 while its /// object's stroke is 5 pt wide, and hands the geometry back otherwise. @@ -1341,6 +1835,92 @@ fn plugins_folder_set_again_after_clearing_installs_its_plugins() { run(&mut s, "plugin.remove", json!({"id": id})); } +/// Under automation read roots, `plugin.list` names the plug-in folder last loaded, its failed +/// files and a plug-in's source file only inside them: a folder outside is `null`, and a file +/// outside is named by its file name. +#[test] +fn plugin_list_leaves_out_paths_outside_the_read_root() { + use crate::file_access::{AutomationRoots, confine}; + let _folder = PREFS_FOLDER.lock().unwrap_or_else(|e| e.into_inner()); + let base = crate::tests_links::Folder::new("plugin-list-read-root"); + let (inside, outside) = (base.0.join("in"), base.0.join("out")); + std::fs::create_dir_all(&inside).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + let id = "test.engine.listroots"; + let src = tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#); + std::fs::write(outside.join("hidden.wasm"), wat::parse_str(src).unwrap()).unwrap(); + std::fs::write(outside.join("broken.wasm"), b"\0asm?").unwrap(); + let folder = outside.to_string_lossy().to_string(); + let mut s = session(); + let r = run(&mut s, "plugin.reload", json!({"path": folder})); + assert_eq!(r["loaded"], json!([id]), "{r}"); + let broken = outside.join("broken.wasm").to_string_lossy().to_string(); + let source = outside.join("hidden.wasm").to_string_lossy().to_string(); + let entry = |list: &Value| list["plugins"].as_array().unwrap().iter().find(|p| p["id"] == id).cloned().unwrap(); + + // The person sees the paths. + let person = run(&mut s, "plugin.list", json!({})); + assert_eq!((&person["folder"]["folder"], &person["folder"]["failed"][0]["file"]), (&json!(folder), &json!(broken)), "{person}"); + assert_eq!(entry(&person)["source"], json!(source)); + + // The client sees their names. + let roots = AutomationRoots::new(&[&inside], &[]).unwrap(); + let listed = confine(roots.as_ref(), || s.execute("plugin.list", &json!({}))).unwrap(); + let report = &listed["folder"]; + assert_eq!((&report["folder"], &report["loaded"], &report["failed"][0]["file"]), (&Value::Null, &json!([id]), &json!("broken.wasm")), "{listed}"); + assert_eq!(entry(&listed)["source"], "hidden.wasm"); + let info = confine(roots.as_ref(), || s.execute("plugin.info", &json!({"id": id}))).unwrap(); + assert_eq!(info["source"], "hidden.wasm"); + let outside_text = json!(folder).to_string(); + for reply in [&listed, &info] { + assert!(!reply.to_string().contains(outside_text.trim_matches('"')), "no path outside the root: {reply}"); + } + + // A read root holding the folder shows it whole. + let wider = AutomationRoots::new(&[&outside], &[]).unwrap(); + let listed = confine(wider.as_ref(), || s.execute("plugin.list", &json!({}))).unwrap(); + assert_eq!(listed["folder"]["folder"], json!(folder), "{listed}"); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// Under automation read roots, a plug-in turned off for the next launch is listed with a file +/// outside them named by its file name, and `plugin.setEnabled` turns it on by that name. +#[test] +fn disabled_plugins_name_files_outside_the_read_root_by_their_names() { + if !in_own_process("disabled_plugins_name_files_outside_the_read_root_by_their_names") { + return; + } + use crate::file_access::{AutomationRoots, confine}; + let base = crate::tests_links::Folder::new("plugin-disabled-read-root"); + let (inside, outside) = (base.0.join("in"), base.0.join("out")); + std::fs::create_dir_all(&inside).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + let id = "test.engine.disabledroots"; + let src = tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#); + let file = outside.join("off.wasm"); + std::fs::write(&file, wat::parse_str(src).unwrap()).unwrap(); + let file = file.to_string_lossy().to_string(); + let mut s = session(); + run(&mut s, "plugin.install", json!({"path": file})); + let roots = AutomationRoots::new(&[&inside], &[]).unwrap(); + // The client turns it off by the source plugin.list shows. + let listed = confine(roots.as_ref(), || s.execute("plugin.list", &json!({}))).unwrap(); + let source = listed["plugins"].as_array().unwrap().iter().find(|p| p["id"] == id).unwrap()["source"].clone(); + assert_eq!(source, "off.wasm", "{listed}"); + confine(roots.as_ref(), || s.execute("plugin.setEnabled", &json!({"file": source, "enabled": false}))).unwrap(); + assert_eq!(run(&mut s, "plugin.safeMode", json!({}))["disabled"][0]["file"], json!(file), "the person sees the path"); + + let outside_text = json!(outside.to_string_lossy()).to_string(); + for cmd in ["plugin.list", "plugin.safeMode"] { + let r = confine(roots.as_ref(), || s.execute(cmd, &json!({}))).unwrap(); + assert_eq!(r["disabled"][0]["file"], "off.wasm", "{cmd}: {r}"); + assert!(!r.to_string().contains(outside_text.trim_matches('"')), "{cmd}: no path outside the root: {r}"); + } + let r = confine(roots.as_ref(), || s.execute("plugin.setEnabled", &json!({"file": "off.wasm", "enabled": true}))).unwrap(); + assert_eq!((&r["changed"], &r["disabled"]), (&json!(true), &json!([])), "{r}"); + run(&mut s, "plugin.remove", json!({"id": id})); +} + /// #2541: a plug-in installed in a session with a plug-in store is installed again in the next /// session that attaches the store, and Remove Plug-in takes it out of the store. #[test] @@ -1587,7 +2167,7 @@ fn a_module_without_permissions_ends_the_grant_of_its_id() { /// that holds such a module and a grant for its id has that grant forgotten when it is attached. #[test] fn a_module_without_permissions_ends_the_grant_kept_in_the_store() { - use vectorcraft_plugins::permissions::{Grant, Permission, sha256_hex}; + use vectorcraft_plugins::permissions::{Grant, GrantToken, Permission, sha256_hex}; let folder = crate::tests_links::Folder::new("plugin-store-stale-grant"); let id = "test.engine.permissions.storedstale"; let other = "test.engine.permissions.storedother"; @@ -1634,7 +2214,11 @@ fn a_module_without_permissions_ends_the_grant_kept_in_the_store() { let future = json!({"id": id, "hash": "00", "permissions": ["doc.read", "ui.panel"]}); std::fs::write(&grants, serde_json::to_vec(&json!([future, other_entry])).unwrap()).unwrap(); vectorcraft_plugins::registry::remove(id); - vectorcraft_plugins::registry::grant(Grant { id: id.into(), hash: sha256_hex(&approved), permissions: vec![Permission::DocRead] }); + vectorcraft_plugins::registry::grant(GrantToken::after_engine_approval(Grant { + id: id.into(), + hash: sha256_hex(&approved), + permissions: vec![Permission::DocRead], + })); let mut fourth = session(); fourth.attach_plugin_store(folder.0.clone()); assert_eq!(ids(), vec![other.to_string()]); @@ -1816,11 +2400,11 @@ fn a_grant_that_cannot_be_removed_and_has_no_stored_module_stops_counting() { run(&mut s, "plugin.remove", json!({"id": id})); } -/// A grant that a load of the plug-in store should forget and can't stays out of the approvals for -/// the session: both when `grants.json` can't be rewritten and when it can't be read at the load. -/// A grant recorded later counts again, and another store starts with nothing ignored. +/// A grant that a load of the plug-in store should forget and can't stays out of the approvals in +/// the process: both when `grants.json` can't be rewritten and when it can't be read at the load. +/// A grant recorded later counts again, and another store's grant for the id counts. #[test] -fn a_grant_the_load_cannot_remove_stops_counting_for_the_session() { +fn a_grant_the_load_cannot_remove_stops_counting_in_the_process() { use vectorcraft_plugins::permissions::sha256_hex; let folder = crate::tests_links::Folder::new("plugin-store-load-forget"); let elsewhere = crate::tests_links::Folder::new("plugin-store-load-forget-other"); @@ -1852,8 +2436,12 @@ fn a_grant_the_load_cannot_remove_stops_counting_for_the_session() { next.attach_plugin_store(elsewhere.0.clone()); assert_eq!(run(&mut next, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "that store's grant counts"); + // A load that can rewrite the file forgets the grant, and the store has nothing ignored again. + std::fs::write(&grants, &recorded).unwrap(); + next.attach_plugin_store(folder.0.clone()); + assert!(!grants.exists(), "the load removes the grant"); + // A directory at the file's path gives a read error on every platform. - std::fs::remove_file(&grants).unwrap(); std::fs::create_dir(&grants).unwrap(); vectorcraft_plugins::registry::remove(id); let mut third = session(); @@ -1879,6 +2467,180 @@ fn a_grant_the_load_cannot_remove_stops_counting_for_the_session() { run(&mut third, "plugin.remove", json!({"id": id})); } +/// A grant one session stops counting stops counting for every session in the process attached to +/// the same folder, by any path to it: one attached before, one attached after with no stored module +/// to try the removal for, and one that comes back from another folder. A successful write of the +/// grant in any of them makes it count in all of them again. +#[test] +fn an_ignored_stored_grant_is_shared_by_sessions_on_the_same_folder() { + use vectorcraft_plugins::permissions::sha256_hex; + let folder = crate::tests_links::Folder::new("plugin-store-shared-ignore"); + let elsewhere = crate::tests_links::Folder::new("plugin-store-shared-ignore-other"); + let id = "test.engine.permissions.sharedignore"; + let empty = json!({"objects": []}); + let approved = asking(id, r#"["doc.read"]"#, &empty); + let approved_data = vectorcraft_format::base64_encode(&approved); + let plain = asking(id, "null", &empty); + let needs_approval = json!({"dataBase64": approved_data}); + let grants = folder.0.join("grants.json"); + let entry = json!({"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}); + let recorded = serde_json::to_vec(&json!([entry])).unwrap(); + std::fs::write(&grants, &recorded).unwrap(); + let mut first = session(); + first.attach_plugin_store(folder.0.clone()); + let inside = folder.0.join("inside"); + std::fs::create_dir(&inside).unwrap(); + let mut other = session(); + other.attach_plugin_store(inside.join("..")); + assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "the recorded grant counts"); + + // `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read. + let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + std::fs::write(&grants, &full).unwrap(); + run(&mut first, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&plain)})); + let file = first.stored_plugin_file(id).unwrap(); + assert!(!std::path::Path::new(&file).exists(), "the store keeps no module"); + assert_eq!(std::fs::read(&grants).unwrap(), full); + + assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], true, "the other session doesn't count it"); + let refused = other.execute("plugin.install", &json!({"dataBase64": approved_data, "replace": true})).unwrap_err().to_string(); + assert!(refused.contains("doc.read"), "{refused}"); + std::fs::write(&file, &approved).unwrap(); + vectorcraft_plugins::registry::remove(id); + other.load_stored_plugins(); + assert!(vectorcraft_plugins::registry::get(id).is_none(), "the formerly approved module isn't loaded"); + std::fs::remove_file(&file).unwrap(); + + let mut later = session(); + later.attach_plugin_store(folder.0.clone()); + assert_eq!(run(&mut later, "plugin.inspect", needs_approval.clone())["needsApproval"], true, "a session attached later doesn't count it"); + + std::fs::write(elsewhere.0.join("grants.json"), &recorded).unwrap(); + other.attach_plugin_store(elsewhere.0.clone()); + assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "that store's grant counts"); + other.attach_plugin_store(folder.0.clone()); + assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], true, "back on the folder, it doesn't"); + + std::fs::write(&grants, &recorded).unwrap(); + assert!(later.store_grant(id, Some(serde_json::from_value(entry).unwrap())), "the file can be written"); + for s in [&mut first, &mut other, &mut later] { + assert_eq!(run(s, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "it counts again"); + } + std::fs::remove_file(&grants).unwrap(); +} + +/// A plug-in folder that doesn't exist yet gets the key it gets once it is made, and every path to a +/// folder gets the same key. +#[test] +fn a_plugin_folder_has_one_key_for_every_path_to_it() { + use crate::store::plugin_store_key; + let folder = crate::tests_links::Folder::new("plugin-store-key"); + let dir = folder.0.join("Plug-ins"); + let before = plugin_store_key(&dir); + assert_eq!(plugin_store_key(&dir.join("sub").join("..")), before); + assert_eq!(plugin_store_key(&folder.0.join(".").join("Plug-ins")), before); + std::fs::create_dir(&dir).unwrap(); + assert_eq!(plugin_store_key(&dir), before, "the key stays when the folder is made"); + assert_eq!(plugin_store_key(&dir.join(".")), before); + #[cfg(windows)] + { + let plain = std::path::absolute(&dir).unwrap(); + let verbatim = std::path::PathBuf::from(format!(r"\\?\{}", plain.display())); + assert_eq!(plugin_store_key(&verbatim), before, "a verbatim path names the same folder"); + } +} + +/// Sessions attached to a plug-in folder before it exists, by paths that only name the same folder +/// once it is made, share the grants the process doesn't count for it. A grant that one session +/// writes while another fails to remove it keeps counting. +#[test] +fn sessions_attached_before_the_folder_exists_share_its_ignored_grants() { + use vectorcraft_plugins::permissions::sha256_hex; + let folder = crate::tests_links::Folder::new("plugin-store-late-folder"); + let id = "test.engine.permissions.latefolder"; + let approved = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let needs_approval = json!({"dataBase64": vectorcraft_format::base64_encode(&approved)}); + let entry = json!({"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}); + std::fs::create_dir_all(folder.0.join("a").join("b")).unwrap(); + let dir = folder.0.join("a").join("Plug-ins"); + // On disk `link/..` is `a`, so `link/../Plug-ins` is the folder; by name it is a `Plug-ins` beside `a`. + // On Windows the folder is named in other letter case. + #[cfg(unix)] + let alias = { + std::os::unix::fs::symlink(folder.0.join("a").join("b"), folder.0.join("link")).unwrap(); + folder.0.join("link").join("..").join("Plug-ins") + }; + #[cfg(windows)] + let alias = folder.0.join("A").join("PLUG-INS"); + #[cfg(not(any(unix, windows)))] + let alias = dir.clone(); + let mut first = session(); + first.attach_plugin_store(dir.clone()); + let mut other = session(); + other.attach_plugin_store(alias); + std::fs::create_dir(&dir).unwrap(); + std::fs::write(dir.join("grants.json"), serde_json::to_vec(&json!([entry])).unwrap()).unwrap(); + assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "the recorded grant counts"); + + first.ignore_stored_grant(id, first.grant_writes()); + assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], true, "the other session doesn't count it"); + assert!(other.store_grant(id, Some(serde_json::from_value(entry.clone()).unwrap())), "the file can be written"); + assert_eq!(run(&mut first, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "it counts again"); + + // A write that fails in one session while another writes the grant for the id leaves the grant + // counting. + let before = first.grant_writes(); + assert!(other.store_grant(id, Some(serde_json::from_value(entry).unwrap())), "the other session writes the grant"); + first.ignore_stored_grant(id, before); + assert_eq!(run(&mut first, "plugin.inspect", needs_approval)["needsApproval"], false, "the written grant counts"); + std::fs::remove_file(dir.join("grants.json")).unwrap(); +} + +/// Grant writes that change nothing, each for another id, don't grow what the process keeps past its +/// limit. +#[test] +fn the_process_keeps_a_bounded_number_of_grant_writes() { + let folder = crate::tests_links::Folder::new("plugin-store-writes-kept"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + for n in 0..300 { + assert!(s.store_grant(&format!("test.engine.permissions.unknown{n}"), None), "nothing to remove is a success"); + } + assert!(Session::grant_writes_kept() <= 256, "{}", Session::grant_writes_kept()); +} + +/// A session attached by a link to a plug-in folder matches the grants the process doesn't count +/// with the folder the link leads to now, not the one it led to when the session was attached. +#[cfg(unix)] +#[test] +fn a_linked_plugin_folder_uses_the_ignored_grants_of_where_the_link_leads() { + use vectorcraft_plugins::permissions::sha256_hex; + let folder = crate::tests_links::Folder::new("plugin-store-relinked"); + let id = "test.engine.permissions.relinked"; + let approved = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let needs_approval = json!({"dataBase64": vectorcraft_format::base64_encode(&approved)}); + let entry = json!({"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}); + let recorded = serde_json::to_vec(&json!([entry])).unwrap(); + let (old, new, link) = (folder.0.join("old"), folder.0.join("new"), folder.0.join("Plug-ins")); + for dir in [&old, &new] { + std::fs::create_dir(dir).unwrap(); + std::fs::write(dir.join("grants.json"), &recorded).unwrap(); + } + std::os::unix::fs::symlink(&old, &link).unwrap(); + let mut linked = session(); + linked.attach_plugin_store(link.clone()); + assert_eq!(run(&mut linked, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "the recorded grant counts"); + + std::fs::remove_file(&link).unwrap(); + std::os::unix::fs::symlink(&new, &link).unwrap(); + let mut direct = session(); + direct.attach_plugin_store(new.clone()); + direct.ignore_stored_grant(id, direct.grant_writes()); + assert_eq!(run(&mut linked, "plugin.inspect", needs_approval.clone())["needsApproval"], true, "the link leads to the ignored grant"); + assert!(linked.store_grant(id, Some(serde_json::from_value(entry).unwrap())), "the file can be written"); + assert_eq!(run(&mut direct, "plugin.inspect", needs_approval)["needsApproval"], false, "it counts again"); +} + /// A grants file that can't be opened or read may name the old module once it reads again, so /// neither a module listing no permissions nor `plugin.remove` gets past it. A directory at the /// file's path gives a read error on every platform. @@ -2119,6 +2881,35 @@ fn a_grants_file_that_cannot_be_deleted_keeps_the_stored_module() { run(&mut s, "plugin.remove", json!({"id": id})); } +/// When the last grant can't be removed because `grants.json` can't be deleted, a replacing module +/// that asks for no permissions doesn't stay in the store: the store gets back the module the grant +/// still covers, and the grant is left as it was. +#[test] +fn a_grants_file_whose_deletion_fails_keeps_the_stored_module() { + let folder = crate::tests_links::Folder::new("plugin-store-undeletable-grants"); + let id = "test.engine.permissions.undeletablegrants"; + let empty = json!({"objects": []}); + let approved = asking(id, r#"["doc.read"]"#, &empty); + let approved_data = vectorcraft_format::base64_encode(&approved); + let plain = asking(id, "null", &empty); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": approved_data, "grant": ["doc.read"]})); + let file = s.stored_plugin_file(id).unwrap(); + let recorded = std::fs::read(&grants).unwrap(); + + crate::store::GRANTS_DELETE_FAILS.set(true); + run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&plain), "replace": true})); + crate::store::GRANTS_DELETE_FAILS.set(false); + assert_eq!(std::fs::read(&file).unwrap(), approved, "the store gets the module the grant covers back"); + assert_eq!(std::fs::read(&grants).unwrap(), recorded, "the grant stays as it was"); + assert_eq!(run(&mut s, "plugin.inspect", json!({"dataBase64": approved_data}))["needsApproval"], false, "the grant still covers the module"); + + run(&mut s, "plugin.remove", json!({"id": id})); + assert!(!grants.exists(), "a removal that can delete the file forgets the grant"); +} + /// A plug-in folder that leaves a module listing no permissions under an id forgets the process's /// grant for it, unless a later file in the folder leaves a granted module there. A grant kept in /// the plug-in store stays, with the stored module it covers. @@ -2165,7 +2956,7 @@ fn a_plugin_folder_ends_the_process_grant_of_an_id_it_replaces() { /// With a store attached, a matching grant held only by the process doesn't count. #[test] fn a_stored_grant_covers_only_the_stored_module_it_recorded() { - use vectorcraft_plugins::permissions::{Grant, Permission, sha256_hex}; + use vectorcraft_plugins::permissions::{Grant, GrantToken, Permission, sha256_hex}; let folder = crate::tests_links::Folder::new("plugin-store-recorded-module"); let id = "test.engine.permissions.storedbytes"; let first = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); @@ -2210,7 +3001,11 @@ fn a_stored_grant_covers_only_the_stored_module_it_recorded() { assert!(starts()); let mut attached = session(); attached.attach_plugin_store(folder.0.clone()); - vectorcraft_plugins::registry::grant(Grant { id: id.into(), hash: sha256_hex(&changed), permissions: vec![Permission::DocRead] }); + vectorcraft_plugins::registry::grant(GrantToken::after_engine_approval(Grant { + id: id.into(), + hash: sha256_hex(&changed), + permissions: vec![Permission::DocRead], + })); let inspected = run(&mut attached, "plugin.inspect", json!({"dataBase64": vectorcraft_format::base64_encode(&changed)})); assert_eq!(inspected["needsApproval"], true, "a grant held only by the process doesn't count with a store attached"); run(&mut attached, "plugin.remove", json!({"id": id})); @@ -2297,6 +3092,376 @@ fn a_failed_store_write_keeps_the_stored_module_with_its_grant() { vectorcraft_plugins::registry::revoke(id); } +/// An install refused because another session revoked the grant its checks relied on writes +/// nothing: a store that kept the grant and lost the module gets no module back, its grants stay as +/// they were, and the plug-in installed with the id and the other session's revoke stand. `grant` +/// approves the module by itself. +#[test] +fn a_grant_revoked_while_installing_leaves_the_store_as_it_was() { + use vectorcraft_plugins::permissions::sha256_hex; + use vectorcraft_plugins::registry; + let folder = crate::tests_links::Folder::new("plugin-store-revoked-while-installing"); + let id = "test.engine.permissions.revokedwhileinstalling"; + let bytes = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let data = vectorcraft_format::base64_encode(&bytes); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + let grants = folder.0.join("grants.json"); + let recorded = std::fs::read(&grants).unwrap(); + let module = std::path::PathBuf::from(s.stored_plugin_file(id).unwrap()); + std::fs::remove_file(&module).unwrap(); + + crate::cmd::plugin::BEFORE_INSTALL.set(Some(Box::new(move || { + registry::revoke(id); + }))); + let e = s.execute("plugin.install", &json!({"dataBase64": data})).unwrap_err().to_string(); + assert!(e.contains("asks for the permissions doc.read"), "{e}"); + assert!(!module.exists(), "no module is stored"); + assert_eq!(std::fs::read(&grants).unwrap(), recorded, "the grants stay as they were"); + assert!(registry::granted(id).is_none(), "the other session's revoke stands"); + assert_eq!(registry::get(id).map(|p| p.hash().to_string()), Some(sha256_hex(&bytes)), "the installed plug-in stays"); + + crate::cmd::plugin::BEFORE_INSTALL.set(Some(Box::new(move || { + registry::revoke(id); + }))); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + assert_eq!(std::fs::read(&module).unwrap(), bytes, "a module `grant` approves is stored"); + assert!(registry::granted(id).is_some_and(|g| g.hash == sha256_hex(&bytes))); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A plug-in another session installs with the id while a module is checked takes the place the +/// checks found free. Without `replace`, or with `replace: false`, the install is refused, writes no +/// module and leaves that plug-in installed; with `replace: true` the module takes its place. +#[test] +fn a_plug_in_installed_while_installing_needs_replace() { + use vectorcraft_plugins::permissions::sha256_hex; + use vectorcraft_plugins::registry; + let folder = crate::tests_links::Folder::new("plugin-store-installed-while-installing"); + let id = "test.engine.installedwhileinstalling"; + let ours = asking(id, "[]", &json!({"objects": []})); + let theirs = asking(id, "[]", &json!({"objects": [], "documentData": null})); + let data = vectorcraft_format::base64_encode(&ours); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + let module = std::path::PathBuf::from(s.stored_plugin_file(id).unwrap()); + let installed = || registry::get(id).map(|p| p.hash().to_string()); + let meanwhile = |theirs: Vec| -> Option> { + Some(Box::new(move || { + registry::install_bytes(&theirs).unwrap(); + })) + }; + + for (replace, why) in [(Value::Null, "is another module than"), (json!(false), "is already installed")] { + crate::cmd::plugin::BEFORE_INSTALL.set(meanwhile(theirs.clone())); + let e = s.execute("plugin.install", &json!({"dataBase64": data, "replace": replace})).unwrap_err().to_string(); + assert!(e.contains(why), "{replace}: {e}"); + assert!(!module.exists(), "{replace}: no module is stored"); + assert_eq!(installed(), Some(sha256_hex(&theirs)), "{replace}: the other plug-in stays installed"); + registry::remove(id); + } + + crate::cmd::plugin::BEFORE_INSTALL.set(meanwhile(theirs)); + run(&mut s, "plugin.install", json!({"dataBase64": data, "replace": true})); + assert_eq!(std::fs::read(&module).unwrap(), ours); + assert_eq!(installed(), Some(sha256_hex(&ours))); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// Without a plug-in store, the install's approval comes from the grant it read first, the one it +/// checks again before it installs: a grant another session records after that read approves +/// nothing, so a revoke that follows it can't be undone by the install recording it again. +#[test] +fn a_grant_recorded_and_revoked_while_installing_approves_nothing() { + use vectorcraft_plugins::permissions::{Grant, GrantToken, Permission, sha256_hex}; + use vectorcraft_plugins::registry; + let id = "test.engine.permissions.recordedwhileinstalling"; + let bytes = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let data = vectorcraft_format::base64_encode(&bytes); + let mut s = session(); + let g = Grant { id: id.into(), hash: sha256_hex(&bytes), permissions: vec![Permission::DocRead] }; + crate::cmd::plugin::AFTER_GRANT_READ.set(Some(Box::new(move || { + registry::grant(GrantToken::after_engine_approval(g)); + }))); + let e = s.execute("plugin.install", &json!({"dataBase64": data})).unwrap_err().to_string(); + assert!(e.contains("asks for the permissions doc.read"), "{e}"); + assert!(registry::get(id).is_none(), "nothing is installed"); + registry::revoke(id); +} + +/// A `plugin.remove` in another session while a module is installed waits until the install has +/// written the store, then removes the module, its grant and the plug-in: nothing of it stays in +/// the store for the next launch. +#[test] +fn a_removal_while_installing_leaves_nothing_in_the_store() { + use vectorcraft_plugins::registry; + let folder = crate::tests_links::Folder::new("plugin-store-removed-while-installing"); + let id = "test.engine.permissions.removedwhileinstalling"; + let bytes = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let data = vectorcraft_format::base64_encode(&bytes); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + let module = std::path::PathBuf::from(s.stored_plugin_file(id).unwrap()); + let grants = folder.0.join("grants.json"); + + let (said, heard) = std::sync::mpsc::channel::<&'static str>(); + let (handed, remover) = std::sync::mpsc::channel(); + let dir = folder.0.clone(); + crate::cmd::plugin::BEFORE_STORE.set(Some(Box::new(move || { + let thread = std::thread::spawn(move || { + let tell = said.clone(); + crate::cmd::plugin::WHILE_WAITING.set(Some(Box::new(move || { + let _ = tell.send("waiting"); + }))); + let mut other = session(); + other.attach_plugin_store(dir); + let removed = other.execute("plugin.remove", &json!({"id": id})).map(|_| ()).map_err(|e| e.to_string()); + let _ = said.send("removed"); + removed + }); + // The removal has finished, or waits for this install. + let first = heard.recv().unwrap_or("gone"); + let _ = handed.send((first, thread)); + }))); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + let (first, thread) = remover.recv().unwrap(); + assert_eq!(thread.join().unwrap(), Ok(())); + assert!(registry::get(id).is_none() && registry::granted(id).is_none(), "the plug-in and its grant are gone"); + assert!(!module.exists(), "no module stays in the store"); + assert!(!std::fs::read_to_string(&grants).is_ok_and(|g| g.contains(id)), "no grant stays in the store"); + assert_eq!(first, "waiting", "the removal waits for the install"); +} + +/// Another session that attaches the plug-in store while a new version is installed loads the +/// stored plug-ins once the install has written the store: the version that runs is the one the +/// store keeps for the next launch. +#[test] +fn a_store_loaded_while_installing_loads_the_new_version() { + use vectorcraft_plugins::permissions::sha256_hex; + use vectorcraft_plugins::registry; + let folder = crate::tests_links::Folder::new("plugin-store-loaded-while-installing"); + let id = "test.engine.permissions.loadedwhileinstalling"; + let old = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let new = asking(id, r#"["doc.read"]"#, &json!({"objects": [], "documentData": null})); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&old), "grant": ["doc.read"]})); + + let (said, heard) = std::sync::mpsc::channel::<&'static str>(); + let (handed, loader) = std::sync::mpsc::channel(); + let dir = folder.0.clone(); + crate::cmd::plugin::BEFORE_STORE.set(Some(Box::new(move || { + let thread = std::thread::spawn(move || { + let tell = said.clone(); + crate::cmd::plugin::WHILE_WAITING.set(Some(Box::new(move || { + let _ = tell.send("waiting"); + }))); + session().attach_plugin_store(dir); + let _ = said.send("loaded"); + }); + // The load has finished, or waits for this install. + let first = heard.recv().unwrap_or("gone"); + let _ = handed.send((first, thread)); + }))); + let data = vectorcraft_format::base64_encode(&new); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"], "replace": true})); + let (first, thread) = loader.recv().unwrap(); + thread.join().unwrap(); + assert_eq!(registry::get(id).map(|p| p.hash().to_string()), Some(sha256_hex(&new)), "the new version runs"); + assert_eq!(std::fs::read(s.stored_plugin_file(id).unwrap()).unwrap(), new, "the store keeps the new version"); + assert_eq!(first, "waiting", "the load waits for the install"); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// Runs the test `name` of this module again in a process of its own → whether this is that +/// process. The list of disabled plug-ins is kept for the whole process, and the other tests here +/// read it again each time they attach a plug-in store. +fn in_own_process(name: &str) -> bool { + const CHILD: &str = "VECTORCRAFT_TEST_PLUGIN_DISABLED_LIST"; + if std::env::var_os(CHILD).is_some() { + return true; + } + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", &format!("tests::plugins::{name}"), "--nocapture"]) + .env(CHILD, "1") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"), + "{name} failed in its own process:\n{stdout}\n{}", + String::from_utf8_lossy(&output.stderr), + ); + false +} + +/// An update whose grant can't be written, and whose old module can't be put back either, stays in +/// the store: a disabled plug-in is turned on, as for any update the store holds. The old grant +/// doesn't cover the new module, so the next start skips it until it is approved. +#[test] +fn an_update_left_in_the_store_by_a_failed_put_back_turns_a_disabled_plugin_on() { + if !in_own_process("an_update_left_in_the_store_by_a_failed_put_back_turns_a_disabled_plugin_on") { + return; + } + use vectorcraft_plugins::{permissions::sha256_hex, registry, safe_mode}; + let folder = crate::tests_links::Folder::new("plugin-store-failed-put-back-update"); + let id = "test.engine.permissions.putbackupdate"; + let first = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let changed = asking(id, r#"["doc.read","doc.write"]"#, &json!({"objects": []})); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&first), "grant": ["doc.read"]})); + run(&mut s, "plugin.setEnabled", json!({"id": id, "enabled": false})); + let grants = folder.0.join("grants.json"); + let recorded = std::fs::read(&grants).unwrap(); + std::fs::remove_file(&grants).unwrap(); + std::fs::create_dir_all(grants.join("block")).unwrap(); + + crate::store::PUT_BACK_FAILS.set(true); + let update = json!({"dataBase64": vectorcraft_format::base64_encode(&changed), "grant": ["doc.read", "doc.write"], "replace": true}); + let installed = s.execute("plugin.install", &update); + crate::store::PUT_BACK_FAILS.set(false); + assert_eq!(installed.unwrap()["hash"], sha256_hex(&changed), "the new module runs in this session"); + assert_eq!(registry::get(id).map(|p| p.hash().to_string()), Some(sha256_hex(&changed))); + assert_eq!(std::fs::read(s.stored_plugin_file(id).unwrap()).unwrap(), changed, "the store holds the new module"); + assert!(safe_mode::disabled().is_empty(), "the module the store holds is turned on"); + let saved = std::fs::read(folder.0.join(crate::store::DISABLED_FILE)).unwrap(); + assert!(safe_mode::parse_disabled_file(&saved).is_empty(), "nothing disabled is saved"); + + std::fs::remove_dir_all(&grants).unwrap(); + std::fs::write(&grants, &recorded).unwrap(); + registry::remove(id); + registry::revoke(id); + let mut next = session(); + next.attach_plugin_store(folder.0.clone()); + assert!(registry::get(id).is_none(), "the old grant doesn't cover the new module"); + safe_mode::set_disabled(vec![]); +} + +/// An update whose grant can't be written, and whose put-back writes the old module and then +/// reports a failure, leaves the old module in the store: a disabled plug-in stays disabled, and the +/// next start doesn't load it. +#[test] +fn an_update_put_back_that_fails_after_writing_keeps_a_disabled_plugin_off() { + if !in_own_process("an_update_put_back_that_fails_after_writing_keeps_a_disabled_plugin_off") { + return; + } + use vectorcraft_plugins::{registry, safe_mode}; + let folder = crate::tests_links::Folder::new("plugin-store-put-back-fails-after-write"); + let id = "test.engine.permissions.putbacklate"; + let first = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let changed = asking(id, r#"["doc.read","doc.write"]"#, &json!({"objects": []})); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&first), "grant": ["doc.read"]})); + run(&mut s, "plugin.setEnabled", json!({"id": id, "enabled": false})); + let disabled = safe_mode::disabled(); + assert!(!disabled.is_empty()); + let grants = folder.0.join("grants.json"); + let recorded = std::fs::read(&grants).unwrap(); + std::fs::remove_file(&grants).unwrap(); + std::fs::create_dir_all(grants.join("block")).unwrap(); + + crate::store::PUT_BACK_FAILS_AFTER_WRITE.set(true); + let update = json!({"dataBase64": vectorcraft_format::base64_encode(&changed), "grant": ["doc.read", "doc.write"], "replace": true}); + let installed = s.execute("plugin.install", &update); + crate::store::PUT_BACK_FAILS_AFTER_WRITE.set(false); + installed.unwrap(); + assert_eq!(std::fs::read(s.stored_plugin_file(id).unwrap()).unwrap(), first, "the store holds the old module"); + assert_eq!(safe_mode::disabled(), disabled, "the plug-in stays disabled"); + let saved = std::fs::read(folder.0.join(crate::store::DISABLED_FILE)).unwrap(); + assert!(!safe_mode::parse_disabled_file(&saved).is_empty(), "the disabled list on disk is kept"); + + std::fs::remove_dir_all(&grants).unwrap(); + std::fs::write(&grants, &recorded).unwrap(); + registry::remove(id); + registry::revoke(id); + let mut next = session(); + next.attach_plugin_store(folder.0.clone()); + assert!(registry::get(id).is_none(), "the disabled old module doesn't load"); + safe_mode::set_disabled(vec![]); +} + +/// A module without permissions whose install can't remove the old grant, and whose put-back writes +/// the old module and then reports a failure, leaves the old module in the store: a disabled plug-in +/// stays disabled. +#[test] +fn a_plain_update_put_back_that_fails_after_writing_keeps_a_disabled_plugin_off() { + if !in_own_process("a_plain_update_put_back_that_fails_after_writing_keeps_a_disabled_plugin_off") { + return; + } + use vectorcraft_plugins::safe_mode; + let folder = crate::tests_links::Folder::new("plugin-store-plain-put-back-fails-after-write"); + let id = "test.engine.permissions.plainputbacklate"; + let empty = json!({"objects": []}); + let approved = asking(id, r#"["doc.read"]"#, &empty); + let plain = asking(id, "null", &empty); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&approved), "grant": ["doc.read"]})); + run(&mut s, "plugin.setEnabled", json!({"id": id, "enabled": false})); + let disabled = safe_mode::disabled(); + assert!(!disabled.is_empty()); + let file = s.stored_plugin_file(id).unwrap(); + // `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read. + let entry = serde_json::from_slice::>(&std::fs::read(&grants).unwrap()).unwrap().remove(0); + let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + std::fs::write(&grants, &full).unwrap(); + + crate::store::PUT_BACK_FAILS_AFTER_WRITE.set(true); + let installed = s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&plain), "replace": true})); + crate::store::PUT_BACK_FAILS_AFTER_WRITE.set(false); + installed.unwrap(); + assert_eq!(std::fs::read(&file).unwrap(), approved, "the store holds the old module"); + assert_eq!(safe_mode::disabled(), disabled, "the plug-in stays disabled"); + let saved = std::fs::read(folder.0.join(crate::store::DISABLED_FILE)).unwrap(); + assert!(!safe_mode::parse_disabled_file(&saved).is_empty(), "the disabled list on disk is kept"); + + std::fs::remove_file(&grants).unwrap(); + run(&mut s, "plugin.remove", json!({"id": id})); + safe_mode::set_disabled(vec![]); +} + +/// A first install whose grant can't be written, and whose module can't be taken out of the store +/// again, stays in the store: the plug-in's file is turned on. No grant covers the module, so the +/// next start skips it until it is approved. +#[test] +fn a_first_install_left_in_the_store_by_a_failed_put_back_turns_its_file_on() { + if !in_own_process("a_first_install_left_in_the_store_by_a_failed_put_back_turns_its_file_on") { + return; + } + use vectorcraft_plugins::{registry, safe_mode}; + let folder = crate::tests_links::Folder::new("plugin-store-failed-put-back-first"); + let id = "test.engine.permissions.putbackfirst"; + let first = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + let module = s.stored_plugin_file(id).unwrap(); + run(&mut s, "plugin.setEnabled", json!({"file": module, "enabled": false})); + let grants = folder.0.join("grants.json"); + std::fs::create_dir_all(grants.join("block")).unwrap(); + + crate::store::PUT_BACK_FAILS.set(true); + let installed = s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&first), "grant": ["doc.read"]})); + crate::store::PUT_BACK_FAILS.set(false); + installed.unwrap(); + assert!(registry::get(id).is_some(), "the module runs in this session"); + assert_eq!(std::fs::read(&module).unwrap(), first, "the store holds the module"); + assert!(safe_mode::disabled().is_empty(), "the file the store holds is turned on"); + let saved = std::fs::read(folder.0.join(crate::store::DISABLED_FILE)).unwrap(); + assert!(safe_mode::parse_disabled_file(&saved).is_empty(), "nothing disabled is saved"); + + std::fs::remove_dir_all(&grants).unwrap(); + registry::remove(id); + registry::revoke(id); + let mut next = session(); + next.attach_plugin_store(folder.0.clone()); + assert!(registry::get(id).is_none(), "no grant covers the module"); + safe_mode::set_disabled(vec![]); +} + /// A plug-in folder reports a changed module as needing approval and still loads the other files; /// granted on its own, the changed module loads from the folder. A session without a store uses the /// grants held by the process. @@ -2480,8 +3645,15 @@ fn a_run_past_the_memory_budget_fails_before_the_plugin_starts() { params.join(",") ); let module = wat::parse_str(tpl::module(&manifest, "unreachable", "", 1)).unwrap(); - // One page of memory: the input and the parameters share 32 KiB. - registry::install(Plugin::load(&module, Limits { max_memory_bytes: 1 << 16, ..Limits::default() }).unwrap()); + // One page of memory: the input and the parameters share 32 KiB. The module lists permissions, + // so its grant is recorded first. + let plugin = Plugin::load(&module, Limits { max_memory_bytes: 1 << 16, ..Limits::default() }).unwrap(); + registry::grant(vectorcraft_plugins::permissions::GrantToken::after_engine_approval(vectorcraft_plugins::permissions::Grant { + id: id.into(), + hash: plugin.hash().to_string(), + permissions: plugin.manifest().permissions(), + })); + registry::install(plugin).unwrap(); let mut s = session(); let small = rect(&mut s, 10.0, "#ff0000"); let long = rect(&mut s, 30.0, "#00ff00"); @@ -2522,7 +3694,7 @@ fn a_run_past_the_memory_budget_fails_before_the_plugin_starts() { assert!(e.contains(says), "{says}: {e}"); assert_eq!((s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()), before, "{says}"); } - assert!(registry::remove(id)); + assert!(registry::remove(id) && registry::revoke(id)); } /// What the user granted is kept in the plug-in store with the module: the next session installs @@ -2613,6 +3785,41 @@ fn granted_permissions_are_kept_and_folders_skip_the_rest() { run(&mut granted, "plugin.remove", json!({"id": id})); } +/// The registry installs a module that lists permissions only under a grant the process holds, so +/// a start and a `plugin.reload` record the store's grant for the module they load. A module in the +/// folder that nobody granted is reported and skipped, and records nothing. +#[test] +fn stored_and_reload_grants_still_install() { + let _folder = PREFS_FOLDER.lock().unwrap_or_else(|e| e.into_inner()); + let store = crate::tests_links::Folder::new("plugin-store-grants-reload"); + let id = "test.engine.permissions.reload"; + let lone = "test.engine.permissions.reload.lone"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let mut s = session(); + s.attach_plugin_store(store.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": ["doc.read"]})); + let forget = || { + vectorcraft_plugins::registry::remove(id); + vectorcraft_plugins::registry::revoke(id); + }; + forget(); + let mut next = session(); + next.attach_plugin_store(store.0.clone()); + assert!(vectorcraft_plugins::registry::get(id).is_some(), "installed again from the store"); + assert_eq!(vectorcraft_plugins::registry::granted(id).map(|g| g.hash), Some(vectorcraft_plugins::permissions::sha256_hex(&wasm))); + forget(); + let dir = crate::tests_links::Folder::new("plugin-folder-grants-reload"); + std::fs::write(dir.0.join("granted.wasm"), &wasm).unwrap(); + std::fs::write(dir.0.join("lone.wasm"), asking(lone, r#"["doc.read"]"#, &json!({"objects": []}))).unwrap(); + let r = run(&mut next, "plugin.reload", json!({"path": dir.0.display().to_string()})); + assert_eq!(r["loaded"], json!([id]), "{r}"); + assert!(vectorcraft_plugins::registry::granted(id).is_some(), "the store's grant is the process's too"); + let why = r["failed"][0]["error"].as_str().unwrap(); + assert!(why.contains("needs approval") && r["failed"][0]["file"].as_str().unwrap().ends_with("lone.wasm"), "{r}"); + assert!(vectorcraft_plugins::registry::get(lone).is_none() && vectorcraft_plugins::registry::granted(lone).is_none()); + run(&mut next, "plugin.remove", json!({"id": id})); +} + /// A grant covers the module it was given to: another module under the id, listing the same /// permissions, isn't installed from the store at the next start, a folder load reports it as /// needing approval, and `plugin.install` asks for `grant` again, even with `replace: true`. It @@ -3784,3 +4991,60 @@ fn a_filter_that_calls_commands_is_given_the_edit_in_progress() { assert_eq!(x, json!(17.0), "undoing the filter brings back the moved rectangle"); run(&mut s, "plugin.remove", json!({"id": id})); } + +/// Installs a filter `id` that calls commands and hands back what it is given, with `commands` (a +/// JSON list of command specs) in its manifest. +fn install_echo_calling(s: &mut Session, id: &str, commands: &str) { + let grant = json!(["doc.read", "doc.write", "commands"]); + let manifest = format!( + r#"{{"id":"{id}","name":"Test {id}","kind":"filter","api":2,"permissions":{grant},"commandAllowlist":["select.all"],"commands":{commands}}}"# + ); + let wasm = wat::parse_str(tpl::module(&manifest, tpl::ECHO, "", 1)).unwrap(); + run(s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true})); +} + +/// With Real-time Drawing off, a 50 × 50 rectangle at (10, 10) whose move by 7 pt is still being +/// dragged: the tool has stored the move, which the document does not hold yet. +fn deferred_move(s: &mut Session) -> NodeId { + let r = NodeId(run(s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50}))["id"].as_u64().unwrap()); + run(s, "prefs.set", json!({"key": "realTimeDrawing", "value": false})); + let move_by = vectorcraft_tools::Action::Preview("object.move".into(), json!({"dx": 7, "dy": 0})); + s.apply_actions(vec![vectorcraft_tools::Action::Begin("Move".into()), move_by]).unwrap(); + assert_eq!(node(s, r).geometric_bounds().unwrap().x0, 10.0, "the move is not applied while it is dragged"); + r +} + +/// The rectangle a run named `label` during [`deferred_move`] left: moved, with the interaction +/// ended and the move an undo step of its own before the run's. +fn assert_moved_once(s: &Session, r: NodeId, label: &str) { + assert!(!s.in_interaction()); + assert_eq!(node(s, r).geometric_bounds().unwrap().x0, 17.0, "the filter was given the moved rectangle"); + let labels: Vec<&str> = s.doc().unwrap().history.undo.iter().rev().take(2).map(|e| e.label.as_str()).collect(); + assert_eq!(labels, [label, "Move"]); +} + +/// With Real-time Drawing off, `plugin.run` of a filter that calls commands during a drag applies +/// the dragged move first and gives the filter the moved rectangle, which it hands back as it was. +#[test] +fn a_filter_that_calls_commands_is_given_a_deferred_move() { + let id = "test.engine.callsdeferred"; + let mut s = session(); + install_echo_calling(&mut s, id, "[]"); + let r = deferred_move(&mut s); + run(&mut s, "plugin.run", json!({"id": id})); + assert_moved_once(&s, r, &format!("Test {id}")); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A plug-in command that calls commands, run with Real-time Drawing off during a drag, is given +/// the moved rectangle as `plugin.run` is. +#[test] +fn a_plugin_command_that_calls_commands_is_given_a_deferred_move() { + let id = "test.engine.callsdeferredcmd"; + let mut s = session(); + install_echo_calling(&mut s, id, r#"[{"id":"same","label":"Same"}]"#); + let r = deferred_move(&mut s); + run(&mut s, &format!("plugin.{id}.same"), json!({})); + assert_moved_once(&s, r, "Same"); + run(&mut s, "plugin.remove", json!({"id": id})); +} diff --git a/crates/engine/src/tests/prefs.rs b/crates/engine/src/tests/prefs.rs index ed37d09695..37127f686a 100644 --- a/crates/engine/src/tests/prefs.rs +++ b/crates/engine/src/tests/prefs.rs @@ -753,6 +753,12 @@ fn precise_cursors_replace_every_pen_state() { Cursor::ShapeBuilderErase, Cursor::AnchorPoint, Cursor::Curvature, + Cursor::LivePaintBucket, + Cursor::LivePaintBucketFace, + Cursor::LivePaintBucketEdge, + Cursor::LivePaintSelectFace, + Cursor::LivePaintSelectEdge, + Cursor::LivePaintSelectOutside, ] { assert_eq!(c.precise(), Cursor::Crosshair, "{c:?}"); } @@ -2047,6 +2053,42 @@ fn real_time_drawing_turned_on_mid_drag_still_commits_deferred_preview() { assert_eq!(paths(&s), 1, "the deferred rectangle is committed"); } +/// With Real-time Drawing off, Undo during a drag keeps the dragged move as its own step and takes +/// back only that: the rectangle drawn before stays, and Redo brings the move back. +#[test] +fn undo_during_a_deferred_drag_takes_back_only_the_drag() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let r = NodeId(s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap()); + set_pref(&mut s, "realTimeDrawing", json!(false)); + let x = |s: &Session| s.doc().unwrap().doc.node(r).and_then(vectorcraft_doc::Node::geometric_bounds).map(|b| b.x0); + let move_by = vectorcraft_tools::Action::Preview("object.move".into(), json!({"dx": 7, "dy": 0})); + s.apply_actions(vec![vectorcraft_tools::Action::Begin("Move".into()), move_by]).unwrap(); + assert_eq!(x(&s), Some(10.0)); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(!s.in_interaction()); + assert_eq!(x(&s), Some(10.0), "the rectangle stays"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(x(&s), Some(17.0), "Redo brings the move back"); +} + +/// Undo during a drag whose stored preview fails cancels the drag, as its release would, and then +/// takes back the step before it. +#[test] +fn undo_during_a_deferred_drag_that_fails_cancels_it() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + set_pref(&mut s, "realTimeDrawing", json!(false)); + let bad = vectorcraft_tools::Action::Preview("no.such.command".into(), json!({})); + s.apply_actions(vec![vectorcraft_tools::Action::Begin("Bad".into()), bad]).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(!s.in_interaction()); + let d = s.doc().unwrap(); + assert_eq!(d.doc.layers.iter().map(|l| l.children().map_or(0, |c| c.len())).sum::(), 0, "the rectangle is undone"); + assert!(d.history.undo.iter().all(|e| e.label != "Bad")); +} + /// Repeated overlay redraws with Real-time Drawing off reuse the cached deferred feedback. #[test] fn deferred_preview_overlays_are_cached_across_redraws() { @@ -2437,6 +2479,65 @@ fn deferred_commit_forwards_preview_warnings() { assert!(ui.iter().any(|r| matches!(r, UiRequest::Status(m) if m.contains("type"))), "{ui:?}"); } +/// A session with a rectangle selected, and type too with `with_type`, tool `tool` chosen, +/// Real-time Drawing off, and an interaction labeled `label` whose deferred Bloat preview warns +/// that type is skipped when type is selected. +fn deferred_bloat(label: &str, with_type: bool, tool: &str) -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let rect = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 200, "height": 200})).unwrap(); + let text = s.execute("text.create", &json!({"x": 300, "y": 200, "text": "Hi"})).unwrap(); + let ids = if with_type { json!([rect["id"], text["id"]]) } else { json!([rect["id"]]) }; + s.execute("select.set", &json!({ "ids": ids })).unwrap(); + s.select_tool(tool, ViewInfo::default()).unwrap(); + set_pref(&mut s, "realTimeDrawing", json!(false)); + s.begin_interaction(label).unwrap(); + let p = json!({"tool": "bloat", "points": [[290.0, 200.0]], "width": 200.0, "height": 200.0}); + s.doc_mut().unwrap().interaction.as_mut().unwrap().preview = Some(("object.liquify".into(), p)); + s +} + +/// A command that applies a deferred preview before it runs (Undo, Clear History) reports the +/// preview's warning in its result, as the tool's own commit reports it; the preview is its own +/// step, which Undo takes back. A preview without a warning adds none. +#[test] +fn settling_a_deferred_preview_keeps_its_warning() { + let mut s = deferred_bloat("Bloat", true, "selection"); + let before = s.doc().unwrap().history.undo.len(); + let r = s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(r["undone"], "Bloat", "{r}"); + assert!(r["warning"].as_str().is_some_and(|w| w.contains("type")), "{r}"); + assert_eq!(r["previewWarning"], r["warning"], "{r}"); + assert_eq!(s.doc().unwrap().history.undo.len(), before, "the preview was a step of its own, and Undo took it back"); + let r = s.execute("edit.redo", &json!({})).unwrap(); + assert!(r.get("warning").is_none() && r.get("previewWarning").is_none(), "nothing was settled: {r}"); + + let mut s = deferred_bloat("Bloat", true, "selection"); + let r = s.execute("edit.clearHistory", &json!({})).unwrap(); + assert!(r["warning"].as_str().is_some_and(|w| w.contains("type")), "{r}"); + + let mut s = deferred_bloat("Bloat", false, "selection"); + let r = s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(r, json!({"undone": "Bloat"})); +} + +/// Typing kept as its own step when a tool's drag begins, or when a Cmd press lends the Selection +/// tool, shows its applied preview's warning in the status bar. +#[test] +fn settling_typing_for_a_tool_shows_its_preview_warning() { + use vectorcraft_tools::{Action, Mods}; + let warned = |ui: &[UiRequest]| ui.iter().any(|r| matches!(r, UiRequest::Status(m) if m.contains("type"))); + let mut s = deferred_bloat("Typing", true, "selection"); + let ui = s.apply_actions(vec![Action::Begin("Move".into())]).unwrap(); + assert!(warned(&ui), "{ui:?}"); + + let mut s = deferred_bloat("Typing", true, "rectangle"); + let cmd = Mods { cmd: true, ..Default::default() }; + let ui = s.pointer(&PointerEvent::new(PointerKind::Down, 50.0, 380.0).with_mods(cmd), ViewInfo::default()).unwrap(); + assert!(warned(&ui), "{ui:?}"); + s.pointer(&PointerEvent::new(PointerKind::Up, 50.0, 380.0).with_mods(cmd), ViewInfo::default()).unwrap(); +} + /// File Handling › Use Low Resolution Proxy for Linked EPS (#394): off by default; toggling it does /// not replace full-resolution pixels already in the document. #[test] @@ -2700,3 +2801,33 @@ fn snap_to_glyph_options_read_set_and_reset() { s.execute("prefs.reset", &json!({})).unwrap(); assert_eq!(s.execute("view.snapToGlyph.options", &json!({})).unwrap(), all); } + +/// Pixel Snapping Options: `view.snapToPixel.options` reads and sets While Drawing, While Moving +/// and While Scaling, all on by default, kept as the `pixelSnap` preference group; bad keys and +/// values change nothing, preferences saved without the group read it as all on, and resetting the +/// preferences turns them all back on. +#[test] +fn pixel_snapping_options_read_set_and_reset() { + let mut s = Session::new(); + let all = json!({"drawing": true, "moving": true, "scaling": true}); + assert_eq!(s.execute("view.snapToPixel.options", &json!({})).unwrap(), all); + let set = json!({"drawing": true, "moving": false, "scaling": true}); + assert_eq!(s.execute("view.snapToPixel.options", &json!({"moving": false})).unwrap(), set); + assert_eq!(s.execute("prefs.get", &json!({"key": "pixelSnap"})).unwrap(), set); + assert!(!s.prefs.pixel_snap.moving && s.prefs.pixel_snap.drawing && s.prefs.pixel_snap.scaling); + for bad in [json!({"moving": 1}), json!({"rotating": false})] { + assert!(s.execute("view.snapToPixel.options", &bad).is_err(), "{bad}"); + assert!(s.execute("prefs.set", &json!({"key": "pixelSnap", "value": bad})).is_err(), "{bad}"); + assert_eq!(s.execute("view.snapToPixel.options", &json!({})).unwrap(), set, "{bad}"); + } + s.execute("prefs.set", &json!({"key": "pixelSnap", "value": {"scaling": false}})).unwrap(); + let both = json!({"drawing": true, "moving": false, "scaling": false}); + assert_eq!(s.execute("view.snapToPixel.options", &json!({})).unwrap(), both); + // Preferences written before the group existed, and a group that names only some options. + let older: Prefs = serde_json::from_value(json!({"keyboardIncrement": 4})).unwrap(); + assert_eq!(older.pixel_snap, vectorcraft_tools::PixelSnap::default()); + let partial: Prefs = serde_json::from_value(json!({"pixelSnap": {"drawing": false}})).unwrap(); + assert_eq!(partial.pixel_snap, vectorcraft_tools::PixelSnap { drawing: false, moving: true, scaling: true }); + s.execute("prefs.reset", &json!({})).unwrap(); + assert_eq!(s.execute("view.snapToPixel.options", &json!({})).unwrap(), all); +} diff --git a/crates/engine/src/tests/prefs_roots.rs b/crates/engine/src/tests/prefs_roots.rs new file mode 100644 index 0000000000..b9818949f1 --- /dev/null +++ b/crates/engine/src/tests/prefs_roots.rs @@ -0,0 +1,107 @@ +//! The preferences commands under automation roots: a confined request sees a folder preference and +//! an export preset's folder only inside its read roots. + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; + +use crate::cmd::fileio::ScreenExportPreset; +use crate::file_access::{AutomationRoots, confine}; +use crate::*; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")) +} + +fn text(p: &Path) -> String { + p.to_string_lossy().to_string() +} + +/// A fresh scratch folder for one test, with the folders `in` and `out`. +fn folder(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("vc-prefs-roots-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + for sub in ["in", "out"] { + std::fs::create_dir_all(dir.join(sub)).unwrap(); + } + dir +} + +/// The folder preferences that name the folder outside the read root. +const OUTSIDE: [&str; 3] = ["pluginsFolder", "scratchPrimary", "templatesFolder"]; + +/// A session whose folder preferences name `inside` (fonts, and the Data Recovery folder with +/// spaces around it) and `outside` (the [`OUTSIDE`] ones, the Templates folder with spaces around +/// it), with a scratch disk choice and an export preset kept with each folder. +fn session(inside: &str, outside: &str) -> Session { + let mut s = Session::new(); + s.prefs.fonts_folder = inside.to_string(); + s.prefs.recovery_folder = format!(" {inside} "); + s.prefs.plugins_folder = outside.to_string(); + s.prefs.scratch_primary = outside.to_string(); + s.prefs.scratch_secondary = "None".to_string(); + s.prefs.templates_folder = format!(" {outside} "); + for (name, folder) in [("Inside", inside), ("Outside", outside)] { + let settings = json!({"formats": [{"format": "svg"}], "folder": folder}); + s.prefs.screen_export_presets.push(ScreenExportPreset { name: name.into(), settings: settings.as_object().cloned().unwrap_or_default() }); + } + s +} + +/// Does a string anywhere in `v` hold `path`? +fn holds(v: &Value, path: &str) -> bool { + v.to_string().contains(&path.replace('\\', "\\\\")) +} + +#[test] +fn prefs_commands_leave_out_folders_outside_the_read_root() { + let base = folder("get"); + let (inside, outside) = (text(&base.join("in").join("fonts")), text(&base.join("out"))); + let roots = AutomationRoots::new(&[&base.join("in")], &[]).unwrap(); + let mut s = session(&inside, &outside); + + let all = confine(roots.as_ref(), || run(&mut s, "prefs.get", json!({}))); + let prefs = &all["prefs"]; + assert_eq!(prefs["fontsFolder"], json!(inside), "a folder inside the root is shown"); + assert_eq!(prefs["recoveryFolder"], json!(format!(" {inside} ")), "checked without the spaces, shown as kept"); + assert_eq!(prefs["scratchSecondary"], json!("None"), "a scratch disk choice is shown"); + for key in OUTSIDE { + assert_eq!(prefs[key], Value::Null, "{key}: {all}"); + } + let presets = prefs["screenExportPresets"].as_array().unwrap(); + assert_eq!(presets[0]["settings"]["folder"], json!(inside)); + assert_eq!(presets[1]["name"], json!("Outside"), "the preset stays"); + assert!(presets[1]["settings"].get("folder").is_none(), "{all}"); + assert!(!holds(&all, &outside), "{all}"); + + for key in OUTSIDE { + let one = confine(roots.as_ref(), || run(&mut s, "prefs.get", json!({"key": key}))); + assert_eq!(one, Value::Null, "{key}"); + } + assert_eq!(confine(roots.as_ref(), || run(&mut s, "prefs.get", json!({"key": "fontsFolder"}))), json!(inside)); + + let list = confine(roots.as_ref(), || run(&mut s, "prefs.list", json!({}))); + assert!(!holds(&list, &outside), "{list}"); + let row = |key: &str| list.as_array().unwrap().iter().find(|r| r["key"] == key).cloned().unwrap(); + assert_eq!(row("fontsFolder")["value"], json!(inside)); + assert_eq!(row("pluginsFolder")["value"], Value::Null); + assert_eq!(row("pluginsFolder")["kind"], json!("text"), "the row stays"); + + // A request that sets another preference, or resets a category without folders. + let set = confine(roots.as_ref(), || run(&mut s, "prefs.set", json!({"values": {"keyboardIncrement": 2, "pluginsFolder": outside}}))); + assert_eq!(set, json!({"keyboardIncrement": 2.0, "pluginsFolder": null}), "a folder kept as it was is left out too"); + let reset = confine(roots.as_ref(), || run(&mut s, "prefs.reset", json!({"category": "General"}))); + assert!(!holds(&reset, &outside), "{reset}"); + assert_eq!(reset["prefs"]["fontsFolder"], json!(inside)); + + // Unconfined and with only a write root. + let all = run(&mut s, "prefs.get", json!({})); + assert_eq!(all["prefs"]["pluginsFolder"], json!(outside), "unconfined, the folder is shown"); + assert_eq!(all["prefs"]["screenExportPresets"][1]["settings"]["folder"], json!(outside)); + let write_only = AutomationRoots::new(&[], &[&base.join("in")]).unwrap(); + let all = confine(write_only.as_ref(), || run(&mut s, "prefs.get", json!({}))); + assert_eq!(all["prefs"]["fontsFolder"], Value::Null, "without a read root no folder is shown"); + assert_eq!(all["prefs"]["recoveryFolder"], Value::Null); + assert_eq!(s.prefs.plugins_folder, outside, "the preferences are unchanged"); + let _ = std::fs::remove_dir_all(&base); +} diff --git a/crates/engine/src/tests/previewbounds.rs b/crates/engine/src/tests/previewbounds.rs index 773b2b7842..e395c708bc 100644 --- a/crates/engine/src/tests/previewbounds.rs +++ b/crates/engine/src/tests/previewbounds.rs @@ -581,11 +581,13 @@ fn set_bounds_measures_paths_turned_together_square_to_their_box() { fn a_size_below_what_the_kept_strokes_of_several_paths_add_gives_them_no_width() { // With no width, the paths have a visual box 10 pt wide, the width of the thick stroke. A width // of 0 or more below 10 gives both paths no width, and the left edge of the visual box stays at - // -2. A negative width turns the paths over, as it does one path. + // -2. With no width each path turns back at its top and bottom, where the miter join bevels, + // so the visual box runs from y 100 to 150. A negative width turns the paths over, as it does + // one path. let mut wrong = vec![]; for (width, paths, visual) in [ - (8.0, [Rect::new(3.0, 100.0, 3.0, 150.0); 2], Rect::new(-2.0, 95.0, 8.0, 155.0)), - (0.0, [Rect::new(3.0, 100.0, 3.0, 150.0); 2], Rect::new(-2.0, 95.0, 8.0, 155.0)), + (8.0, [Rect::new(3.0, 100.0, 3.0, 150.0); 2], Rect::new(-2.0, 100.0, 8.0, 150.0)), + (0.0, [Rect::new(3.0, 100.0, 3.0, 150.0); 2], Rect::new(-2.0, 100.0, 8.0, 150.0)), (-37.0, [Rect::new(-44.0, 100.0, 0.0, 150.0), Rect::new(-44.0, 100.0, -13.2, 150.0)], Rect::new(-49.0, 95.0, 1.0, 155.0)), ] { let (mut s, ids) = thin_and_thick(); @@ -666,6 +668,35 @@ fn set_bounds_gives_a_butt_path_with_slanted_corners_the_size_out_of_proportion( assert!((v.width() - 60.0).abs() < 1e-6 && (v.height() - 20.0).abs() < 1e-6, "{v:?}"); } +#[test] +fn set_bounds_gives_a_closed_path_with_beveled_or_mitered_corners_the_size_out_of_proportion() { + // The bevel at the triangle's tip, the miter the limit bevels there and the miter spikes it + // keeps reach past the path by margins that follow the slanted segments' directions, which a + // scale out of proportion changes. The miter spikes of a stroke whose dashes have round or + // projecting caps reach past the path too. + let mut wrong = vec![]; + for (join, limit, cap, dash) in [ + ("bevel", 10.0, "round", Value::Null), + ("miter", 2.0, "round", Value::Null), + ("miter", 10.0, "round", Value::Null), + ("miter", 10.0, "round", json!([6, 3])), + ("miter", 10.0, "projecting", json!([6, 3])), + ] { + let mut s = session(); + let anchors = json!([{"x": 100, "y": 150}, {"x": 110, "y": 100}, {"x": 120, "y": 150}]); + let id = NodeId(run(&mut s, "path.create", json!({"anchors": anchors, "closed": true}))["id"].as_u64().unwrap()); + run(&mut s, "stroke.set", json!({"weight": 2, "cap": cap, "join": join, "miterLimit": limit, "dash": dash})); + preview(&mut s, true); + run(&mut s, "select.set", json!({"ids": [id.0]})); + run(&mut s, "object.setBounds", json!({"width": 60, "height": 20, "reference": 0, "strokes": false})); + let v = s.transform_bounds(&[id]).unwrap(); + if (v.width() - 60.0).abs() > 1e-6 || (v.height() - 20.0).abs() > 1e-6 { + wrong.push(format!("{join} {limit} {cap} {dash}: {v:?}")); + } + } + assert!(wrong.is_empty(), "{wrong:?}"); +} + #[test] fn set_bounds_gives_a_symbol_instance_of_a_diagonal_butt_line_the_size_out_of_proportion() { let mut s = session(); diff --git a/crates/engine/src/tests/print.rs b/crates/engine/src/tests/print.rs index 8ccd76deba..f10bf65c94 100644 --- a/crates/engine/src/tests/print.rs +++ b/crates/engine/src/tests/print.rs @@ -254,6 +254,35 @@ fn type_in_a_missing_family_warns_as_pdf_export_does() { } } +/// The warnings of `file.print` (PDF and PostScript) and `print.preview` list what the job +/// leaves out of the document or prints differently first, then the notes on the options. +#[test] +fn what_a_print_loses_comes_before_the_notes_on_the_options() { + let (mut s, _) = session(); + s.execute("text.create", &json!({"x": 10, "y": 100, "text": "Ab", "font": "Nonexistent Sans Probe"})).unwrap(); + let notes = |v: &Value| -> Vec { v["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).map(str::to_string).collect() }; + // A fixed flatness isn't written to a PDF: a note on the options, made before the type's. + let fixed = json!({"settings": {"graphics": {"autoFlatness": false}}}); + for v in [print(&mut s, fixed.clone()).1, s.execute("print.preview", &fixed).unwrap()] { + let n = notes(&v); + assert!(n.iter().any(|w| w.contains("Nonexistent Sans Probe")), "{n:?}"); + assert!(n.last().is_some_and(|w| w.starts_with("a fixed flatness")), "{n:?}"); + } + // PostScript doesn't apply the printer profile. + let profile = json!({"format": "postscript", "settings": {"color": {"profile": vectorcraft_color::cms::SRGB}}}); + let n = notes(&s.execute("file.print", &profile).unwrap()); + assert!(n.iter().any(|w| w.contains("Nonexistent Sans Probe")), "{n:?}"); + assert!(n.last().is_some_and(|w| w.starts_with("the printer profile")), "{n:?}"); + // An artboard larger than Letter: copies per sheet that don't fit come after the art that + // doesn't print. + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 700, "height": 900})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 700, "height": 900})).unwrap(); + let n = notes(&print(&mut s, json!({"settings": {"copiesPerSheet": true}})).1); + assert!(n.iter().any(|w| w.contains("part of it doesn't print")), "{n:?}"); + assert!(n.last().is_some_and(|w| w.ends_with("it prints one copy per sheet")), "{n:?}"); +} + #[test] fn type_that_does_not_fit_its_frame_is_named() { let (mut s, _) = session(); diff --git a/crates/engine/src/tests/rastersettings.rs b/crates/engine/src/tests/rastersettings.rs index 2110e611ea..75659faf32 100644 --- a/crates/engine/src/tests/rastersettings.rs +++ b/crates/engine/src/tests/rastersettings.rs @@ -455,3 +455,50 @@ fn rasterize_to_cmyk_makes_a_cmyk_image() { assert_eq!((alpha.get_pixel(1, 1).0, alpha.get_pixel(25, 25).0), ([0], [255])); assert!(mask.clip); } + +/// Rasterize with the Grayscale or Bitmap colour model makes a grayscale image (#6969): the +/// image says Grayscale, its file holds one gray channel (one bit a pixel for an opaque Bitmap, +/// gray and alpha over a transparent background), in a CMYK document too, and a fill color +/// colorizes it. +#[test] +fn rasterize_to_grayscale_or_bitmap_makes_a_grayscale_image() { + for mode in ["rgb", "cmyk"] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "colorMode": mode})).unwrap(); + let r = id(&s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#ff0000", "ids": [r.0]})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true, "ids": [r.0]})).unwrap(); + let mut rasterize = |model: &str, background: &str| { + s.execute("select.set", &json!({"ids": [r.0]})).unwrap(); + let p = json!({"ppi": 72, "colorModel": model, "background": background, "addAround": 5}); + let img = id(&s.execute("object.rasterize", &p).unwrap()); + let info = s.execute("image.info", &json!({"id": img.0})).unwrap(); + let d = &s.doc().unwrap().doc; + let n = d.node(img).unwrap(); + assert!(n.extras().mask.is_none(), "{mode} {model} {background}: no opacity mask"); + let NodeKind::Image(im) = &n.kind else { panic!("an image") }; + let blob = d.images[&im.key].clone(); + let pixels = image::load_from_memory(&blob.bytes).unwrap().to_luma_alpha8(); + assert_eq!(pixels.dimensions(), (50, 50)); + let at = |x, y| pixels.get_pixel(x, y).0; + s.execute("edit.undo", &json!({})).unwrap(); + (info["colorMode"].clone(), blob.gray_source(), at(25, 25), at(1, 1)) + }; + let gray = |one_bit, alpha| Some(vectorcraft_doc::GraySource { one_bit, alpha }); + let (info, source, [level, alpha], corner) = rasterize("grayscale", "white"); + assert_eq!((info, source, alpha, corner), (json!("Grayscale"), gray(false, false), 255, [255, 255]), "{mode}"); + if mode == "rgb" { + assert_eq!(level, 54, "red's Rec. 709 luma"); + } else { + assert!((1..=254).contains(&level), "the CMYK red's screen color as a gray: {level}"); + } + assert_eq!(rasterize("grayscale", "transparent"), (json!("Grayscale"), gray(false, true), [level, 255], [255, 0]), "{mode}"); + assert_eq!(rasterize("bitmap", "white"), (json!("Grayscale"), gray(true, false), [0, 255], [255, 255]), "{mode}"); + assert_eq!(rasterize("bitmap", "transparent"), (json!("Grayscale"), gray(false, true), [0, 255], [255, 0]), "{mode}"); + // A fill color colorizes the image, as it does any grayscale image. + s.execute("select.set", &json!({"ids": [r.0]})).unwrap(); + let img = id(&s.execute("object.rasterize", &json!({"ppi": 72, "colorModel": "grayscale"})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#0000ff", "ids": [img.0]})).unwrap(); + assert!(s.doc().unwrap().doc.node(img).unwrap().extras().colorize.is_some(), "{mode}: colorized"); + } +} diff --git a/crates/engine/src/tests/recolor.rs b/crates/engine/src/tests/recolor.rs index 37464de71d..90e7822ef8 100644 --- a/crates/engine/src/tests/recolor.rs +++ b/crates/engine/src/tests/recolor.rs @@ -1079,3 +1079,428 @@ fn global_adjust_refuses_params_of_the_wrong_form() { run(&mut s, "recolor.apply", json!({"map": map, "globalAdjust": {"saturation": null, "temperature": -100}})); assert_ne!(fill(&s, art).to_hex(), "#ff0000", "an amount at the end of the range applies"); } + +/// A placed `w` × `h` px image whose left half is `left` and right half `right` (RGBA), and its +/// bounds on the page. +fn halves_image(s: &mut Session, w: u32, h: u32, left: [u8; 4], right: [u8; 4]) -> (NodeId, vectorcraft_geom::Rect) { + let img = image::RgbaImage::from_fn(w, h, |x, _| image::Rgba(if x < w / 2 { left } else { right })); + let mut png = Vec::new(); + img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let r = run(s, "file.place", json!({"name": "halves.png", "dataBase64": vectorcraft_format::base64_encode(&png)})); + let id = NodeId(r["ids"][0].as_u64().unwrap()); + let b = s.doc().unwrap().doc.node(id).unwrap().visual_bounds().unwrap(); + (id, b) +} + +fn pick_theme(s: &mut Session, p: Value) -> Vec { + keys(&run(s, "recolor.pickTheme", p)["colors"]) +} + +/// A click takes the palette of the object a Selection tool click takes (a whole group), the most +/// used color first, each in its own model; a click on empty canvas or on a hidden object takes +/// nothing. Locked objects are read. Picking changes nothing. +#[test] +fn theme_picker_click_takes_the_palette_of_the_whole_object() { + let mut s = session(); + let a = rect(&mut s, json!("#ff0000")); + let b = rect(&mut s, json!({"c": 0, "m": 0, "y": 100, "k": 0})); + let c = rect(&mut s, json!("#ff0000")); + run(&mut s, "paint.setStroke", json!({"ids": [c.0], "color": "#0000ff"})); + // x 70 to 85 and 90 to 105. + let hidden = rect(&mut s, json!("#00ff00")); + let locked = rect(&mut s, json!("#ff00ff")); + run(&mut s, "select.set", json!({"ids": [a.0, b.0, c.0]})); + run(&mut s, "object.group", json!({})); + run(&mut s, "object.hide", json!({"ids": [hidden.0]})); + run(&mut s, "object.lock", json!({"ids": [locked.0]})); + let undo = s.doc().unwrap().history.undo.len(); + let doc = s.doc().unwrap().doc.clone(); + // A click on `b` (x 30 to 45): the group's three rectangles, red the most used. + let r = run(&mut s, "recolor.pickTheme", json!({"picks": [{"at": [37, 17]}]})); + assert_eq!(keys(&r["colors"]), ["rgb 255 0 0", "cmyk 0 0 100 0", "rgb 0 0 255"], "{r}"); + assert_eq!(r["objects"], 3); + assert_eq!(pick_theme(&mut s, json!({"picks": [{"at": [37, 17]}], "colors": 2})).len(), 2, "at most `colors`"); + assert!(pick_theme(&mut s, json!({"picks": [{"at": [300, 150]}]})).is_empty(), "empty canvas"); + assert!(pick_theme(&mut s, json!({"picks": [{"at": [77, 17]}]})).is_empty(), "a hidden object"); + assert_eq!(pick_theme(&mut s, json!({"picks": [{"at": [97, 17]}]})), ["rgb 255 0 255"], "a locked object"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step"); + assert!(std::sync::Arc::ptr_eq(&s.doc().unwrap().doc, &doc), "the document stays as it was"); +} + +/// A marquee takes the part of an image inside it and every painted object it touches; several +/// picks (Shift) add up. A click on an image takes all its pixels. +#[test] +fn theme_picker_marquee_takes_the_area_and_picks_add_up() { + let mut s = session(); + let (_, b) = halves_image(&mut s, 64, 32, [255, 0, 0, 255], [0, 0, 255, 255]); + let (mid, y) = ((b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0); + let left = json!({"rect": [b.x0 + 1.0, b.y0 + 1.0, mid - 1.0, b.y1 - 1.0]}); + assert_eq!(pick_theme(&mut s, json!({"picks": [left]})), ["rgb 255 0 0"], "the left half alone"); + let right_backwards = json!({"rect": [b.x1 - 1.0, b.y1 - 1.0, mid + 1.0, b.y0 + 1.0]}); + assert_eq!(pick_theme(&mut s, json!({"picks": [right_backwards]})), ["rgb 0 0 255"], "a marquee drawn backwards"); + let both = pick_theme(&mut s, json!({"picks": [left, right_backwards]})); + assert_eq!(both.len(), 2, "Shift adds a second area: {both:?}"); + assert_eq!(pick_theme(&mut s, json!({"picks": [{"at": [mid, y]}]})).len(), 2, "a click takes the whole image"); + // Two rectangles away from the image: a marquee touching both takes both. + let r1 = rect(&mut s, json!("#00ff00")); + let r2 = rect(&mut s, json!("#ffff00")); + let (b1, b2) = { + let d = &s.doc().unwrap().doc; + (d.node(r1).unwrap().visual_bounds().unwrap(), d.node(r2).unwrap().visual_bounds().unwrap()) + }; + let over = json!({"rect": [b1.x1 - 2.0, b1.y0 + 2.0, b2.x0 + 2.0, b1.y0 + 4.0]}); + let mut got = pick_theme(&mut s, json!({"picks": [over]})); + got.sort(); + assert_eq!(got, ["rgb 0 255 0", "rgb 255 255 0"]); +} + +/// Pixels less than half opaque are left out, and so is an image whose pixels can't be read. +#[test] +fn theme_picker_leaves_out_clear_pixels_and_unreadable_images() { + let mut s = session(); + let (_, b) = halves_image(&mut s, 8, 8, [255, 0, 0, 255], [0, 0, 255, 100]); + let all = json!({"rect": [b.x0, b.y0, b.x1, b.y1]}); + assert_eq!(pick_theme(&mut s, json!({"picks": [all]})), ["rgb 255 0 0"]); + let cut = super::menucmds::place_undecodable_png(&mut s); + let cb = s.doc().unwrap().doc.node(cut).unwrap().visual_bounds().unwrap(); + let r = run(&mut s, "recolor.pickTheme", json!({"picks": [{"rect": [cb.x0, cb.y0, cb.x1, cb.y1]}]})); + assert!(r["colors"].as_array().unwrap().iter().all(|k| k == "rgb 255 0 0"), "the undecodable image adds nothing: {r}"); +} + +/// A large image is read through about 65,536 pixels: its palette still holds both halves. +#[test] +fn theme_picker_reads_a_large_image_within_its_pixel_budget() { + let mut s = session(); + let (_, b) = halves_image(&mut s, 2000, 1000, [10, 200, 30, 255], [250, 240, 10, 255]); + let (mid, y) = ((b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0); + let mut got = pick_theme(&mut s, json!({"picks": [{"at": [mid, y]}]})); + got.sort(); + assert_eq!(got, ["rgb 10 200 30", "rgb 250 240 10"]); +} + +/// A symbol instance gives the colors of the art it shows, by a click or a marquee; a pattern fill +/// gives the colors of its tile and of the patterns the tile uses. +#[test] +fn theme_picker_reads_symbol_art_and_nested_patterns() { + let mut s = session(); + let r = rect(&mut s, json!("#00ff00")); + run(&mut s, "select.set", json!({"ids": [r.0]})); + let inst = NodeId(run(&mut s, "symbol.new", json!({"name": "Dot"}))["id"].as_u64().unwrap()); + let b = s.doc().unwrap().doc.node(inst).unwrap().visual_bounds().unwrap(); + let (cx, cy) = ((b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0); + assert_eq!(pick_theme(&mut s, json!({"picks": [{"at": [cx, cy]}]})), ["rgb 0 255 0"], "a click on the instance"); + assert_eq!(pick_theme(&mut s, json!({"picks": [{"rect": [cx, cy, cx + 1.0, cy + 1.0]}]})), ["rgb 0 255 0"], "a marquee"); + select_all(&mut s); + run(&mut s, "edit.clear", json!({})); + // Pattern "inner" of a red square fills a square, which becomes pattern "outer". + let red = rect(&mut s, json!("#ff0000")); + let inner = run(&mut s, "object.pattern.make", json!({"ids": [red.0], "edit": false}))["name"].as_str().unwrap().to_string(); + let tile = rect(&mut s, json!("#0000ff")); + run(&mut s, "paint.setFill", json!({"ids": [tile.0], "swatch": inner})); + let outer = run(&mut s, "object.pattern.make", json!({"ids": [tile.0], "edit": false}))["name"].as_str().unwrap().to_string(); + let art = rect(&mut s, json!("#0000ff")); + run(&mut s, "paint.setFill", json!({"ids": [art.0], "swatch": outer})); + let b = s.doc().unwrap().doc.node(art).unwrap().visual_bounds().unwrap(); + let got = pick_theme(&mut s, json!({"picks": [{"at": [(b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0]}]})); + assert!(got.contains(&"rgb 255 0 0".to_string()), "the inner pattern's red: {got:?}"); +} + +/// A grayscale image that a fill color colorizes gives that color, not its grays. +#[test] +fn theme_picker_reads_the_color_of_a_colorized_image() { + let mut s = session(); + let mut png = Vec::new(); + image::GrayImage::from_pixel(8, 8, image::Luma([90])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let r = run(&mut s, "file.place", json!({"name": "gray.png", "dataBase64": vectorcraft_format::base64_encode(&png)})); + let id = NodeId(r["ids"][0].as_u64().unwrap()); + let b = s.doc().unwrap().doc.node(id).unwrap().visual_bounds().unwrap(); + let at = json!({"picks": [{"at": [(b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0]}]}); + assert_eq!(pick_theme(&mut s, at.clone()), ["rgb 90 90 90"], "uncolorized: its grays"); + run(&mut s, "paint.setFill", json!({"ids": [id.0], "color": "#ff0000"})); + assert!(s.doc().unwrap().doc.node(id).unwrap().extras().colorize.is_some(), "the fill colorizes the image"); + assert_eq!(pick_theme(&mut s, at), ["rgb 255 0 0"]); +} + +/// A hidden fill gives no color, and a marquee in a clip group reads only what the clipping path +/// lets through. +#[test] +fn theme_picker_leaves_out_hidden_fills_and_clipped_art() { + let mut s = session(); + let shape = |s: &mut Session, x: f64, w: f64, fill: &str| { + let id = NodeId(run(s, "shape.rectangle", json!({"x": x, "y": 10, "width": w, "height": 15}))["id"].as_u64().unwrap()); + run(s, "paint.setFill", json!({"ids": [id.0], "color": fill})); + run(s, "paint.setStroke", json!({"ids": [id.0], "none": true})); + id + }; + let hidden = shape(&mut s, 200.0, 15.0, "#ff00ff"); + run(&mut s, "select.set", json!({"ids": [hidden.0]})); + run(&mut s, "appearance.setItem", json!({"index": 0, "visible": false})); + assert!(pick_theme(&mut s, json!({"picks": [{"rect": [205, 12, 210, 20]}]})).is_empty(), "a hidden fill"); + // A marquee inside an outlined square without a fill misses it; inside a filled one it takes it. + let outline = shape(&mut s, 250.0, 40.0, "#00ffff"); + run(&mut s, "paint.setFill", json!({"ids": [outline.0], "none": true})); + run(&mut s, "paint.setStroke", json!({"ids": [outline.0], "color": "#ffff00"})); + assert!(pick_theme(&mut s, json!({"picks": [{"rect": [260, 13, 270, 20]}]})).is_empty(), "inside the outline"); + assert_eq!(pick_theme(&mut s, json!({"picks": [{"rect": [245, 13, 260, 20]}]})), ["rgb 255 255 0"], "across the outline"); + run(&mut s, "paint.setFill", json!({"ids": [outline.0], "color": "#00ffff"})); + assert_eq!(pick_theme(&mut s, json!({"picks": [{"rect": [260, 13, 270, 20]}]})).len(), 2, "inside the fill"); + // Red runs from x 10 to 110 and green from 50 to 60; the clipping path lets x 10 to 40 through. + let red = shape(&mut s, 10.0, 100.0, "#ff0000"); + let green = shape(&mut s, 50.0, 10.0, "#00ff00"); + let clip = shape(&mut s, 10.0, 30.0, "#0000ff"); + run(&mut s, "select.set", json!({"ids": [red.0, green.0, clip.0]})); + run(&mut s, "object.clippingMask.make", json!({})); + assert_eq!(pick_theme(&mut s, json!({"picks": [{"rect": [30, 12, 55, 20]}]})), ["rgb 255 0 0"]); +} + +/// An image in a clip group gives only the pixels inside its clipping path, by a click or a +/// marquee. +#[test] +fn theme_picker_reads_an_image_inside_its_clipping_path() { + let mut s = session(); + // Red, with blue 6 × 3 px blocks in the corners, which an ellipse inscribed in the image leaves out. + let (w, h) = (64, 32); + let img = image::RgbaImage::from_fn(w, h, |x, y| { + let corner = (x < 6 || x >= w - 6) && (y < 3 || y >= h - 3); + image::Rgba(if corner { [0, 0, 255, 255] } else { [255, 0, 0, 255] }) + }); + let mut png = Vec::new(); + img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let r = run(&mut s, "file.place", json!({"name": "corners.png", "dataBase64": vectorcraft_format::base64_encode(&png)})); + let id = NodeId(r["ids"][0].as_u64().unwrap()); + let b = s.doc().unwrap().doc.node(id).unwrap().visual_bounds().unwrap(); + let all = json!({"picks": [{"rect": [b.x0, b.y0, b.x1, b.y1]}]}); + assert_eq!(pick_theme(&mut s, all.clone()).len(), 2, "unclipped: red and blue"); + let e = NodeId(run(&mut s, "shape.ellipse", json!({"x": b.x0, "y": b.y0, "width": b.width(), "height": b.height()}))["id"].as_u64().unwrap()); + run(&mut s, "select.set", json!({"ids": [id.0, e.0]})); + run(&mut s, "object.clippingMask.make", json!({})); + assert_eq!(pick_theme(&mut s, all), ["rgb 255 0 0"], "a marquee"); + let center = json!({"picks": [{"at": [(b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0]}]}); + assert_eq!(pick_theme(&mut s, center), ["rgb 255 0 0"], "a click"); +} + +/// An object in a clip group that its clipping path hides gives no color, even inside the +/// clipping path's box. +#[test] +fn theme_picker_leaves_out_art_a_curved_clipping_path_hides() { + let mut s = session(); + let shape = |s: &mut Session, x: f64, y: f64, w: f64, h: f64, fill: &str| { + let id = NodeId(run(s, "shape.rectangle", json!({"x": x, "y": y, "width": w, "height": h}))["id"].as_u64().unwrap()); + run(s, "paint.setFill", json!({"ids": [id.0], "color": fill})); + run(s, "paint.setStroke", json!({"ids": [id.0], "none": true})); + id + }; + // A red square in the middle of a 100 × 100 ellipse, and a green one in its top left corner. + let red = shape(&mut s, 40.0, 40.0, 20.0, 20.0, "#ff0000"); + let green = shape(&mut s, 0.0, 0.0, 8.0, 8.0, "#00ff00"); + let e = NodeId(run(&mut s, "shape.ellipse", json!({"x": 0, "y": 0, "width": 100, "height": 100}))["id"].as_u64().unwrap()); + let all = json!({"picks": [{"rect": [-5, -5, 105, 105]}]}); + let mut both = pick_theme(&mut s, all.clone()); + both.retain(|k| k == "rgb 255 0 0" || k == "rgb 0 255 0"); + assert_eq!(both.len(), 2, "unclipped: both squares"); + run(&mut s, "select.set", json!({"ids": [red.0, green.0, e.0]})); + run(&mut s, "object.clippingMask.make", json!({})); + assert_eq!(pick_theme(&mut s, all), ["rgb 255 0 0"], "the corner square is hidden"); +} + +/// In isolation mode a click and a marquee read only the isolated art. +#[test] +fn theme_picker_reads_only_the_isolated_art() { + let mut s = session(); + let a = rect(&mut s, json!("#ff0000")); + let b = rect(&mut s, json!("#0000ff")); + run(&mut s, "select.set", json!({"ids": [a.0, b.0]})); + let g = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap()); + // Green on top of the blue square (x 30 to 45). + let green = NodeId(run(&mut s, "shape.rectangle", json!({"x": 30, "y": 10, "width": 15, "height": 15}))["id"].as_u64().unwrap()); + run(&mut s, "paint.setFill", json!({"ids": [green.0], "color": "#00ff00"})); + run(&mut s, "paint.setStroke", json!({"ids": [green.0], "none": true})); + assert_eq!(pick_theme(&mut s, json!({"picks": [{"at": [37, 17]}]})), ["rgb 0 255 0"], "outside isolation: the top object"); + run(&mut s, "object.isolate", json!({"id": g.0})); + let got = pick_theme(&mut s, json!({"picks": [{"at": [37, 17]}]})); + assert_eq!(got, ["rgb 0 0 255"], "a click reaches the isolated blue square under the green one"); + let mut got = pick_theme(&mut s, json!({"picks": [{"rect": [5, 5, 60, 30]}]})); + got.sort(); + assert_eq!(got, ["rgb 0 0 255", "rgb 255 0 0"], "a marquee leaves out the green square"); +} + +/// Bad parameters are refused with an error naming them. +#[test] +fn theme_picker_refuses_bad_params() { + let mut s = session(); + rect(&mut s, json!("#ff0000")); + let many: Vec = (0..257).map(|_| json!({"at": [0, 0]})).collect(); + for (p, msg) in [ + (json!({}), "missing `picks`"), + (json!({"picks": {"at": [0, 0]}}), "`picks` must be an array"), + (json!({"picks": []}), "`picks` must hold 1 to 256 picks (got 0)"), + (json!({"picks": many}), "`picks` must hold 1 to 256 picks (got 257)"), + (json!({"picks": [{"at": [0]}]}), "`at` must be [x, y]"), + (json!({"picks": [{"at": ["1", 2]}]}), "`at` must be [x, y]"), + (json!({"picks": [{"rect": [0, 0, 10]}]}), "`rect` must be [x0, y0, x1, y1]"), + (json!({"picks": [{"at": [0, 0], "rect": [0, 0, 1, 1]}]}), "each pick is"), + (json!({"picks": [{"point": [0, 0]}]}), "each pick is"), + (json!({"picks": [{"at": [0, 0]}], "colors": 0}), "`colors` must be between 1 and 64 (got 0)"), + (json!({"picks": [{"at": [0, 0]}], "colors": 65}), "`colors` must be between 1 and 64 (got 65)"), + (json!({"picks": [{"at": [0, 0]}], "colors": 2.5}), "`colors` must be a whole number"), + ] { + let e = s.execute("recolor.pickTheme", &p).unwrap_err().to_string(); + assert!(e.contains(msg), "{p}: {e}"); + } +} + +const RED: &str = "rgb 255 0 0"; +const PURPLE: &str = "rgb 128 0 204"; +const BLUE: &str = "rgb 0 0 255"; + +/// Two red rectangles, a purple one and a blue one, selected. +fn prominent_art(s: &mut Session) -> [NodeId; 4] { + let ids = [rect(s, json!("#ff0000")), rect(s, json!("#ff0000")), rect(s, json!("#8000cc")), rect(s, json!("#0000ff"))]; + select_all(s); + ids +} + +#[test] +fn weigh_gives_each_rows_share_of_the_uses() { + let mut s = session(); + prominent_art(&mut s); + let map = json!([{"from": [RED, PURPLE], "to": "#00ff00"}, {"from": BLUE, "to": null, "tint": 50}]); + let r = run(&mut s, "recolor.weigh", json!({"map": map})); + assert_eq!(r["shares"], json!([75.0, 25.0])); + assert_eq!( + r["map"], + json!([{"from": [RED, PURPLE], "to": "#00ff00"}, {"from": [BLUE], "to": null, "tint": 50}]), + "rows as given, from as a list" + ); + // An excluded row has no share, and the others share the uses. + let excl = json!([{"from": [RED, PURPLE], "to": null}, {"from": [BLUE], "to": null, "exclude": true}]); + assert_eq!(run(&mut s, "recolor.weigh", json!({"map": excl}))["shares"], json!([100.0, 0.0])); + // An excluded row before another that lists the same colour doesn't take its uses. + let first = json!([{"from": [RED], "exclude": true}, {"from": [RED]}, {"from": [BLUE, PURPLE]}]); + assert_eq!(run(&mut s, "recolor.weigh", json!({"map": first}))["shares"], json!([0.0, 50.0, 50.0])); + // A current colour that no art uses counts nothing, and a use counts for the first row only. + let twice = json!({"map": [{"from": [RED, "#123456"]}, {"from": [RED, PURPLE, BLUE]}]}); + assert_eq!(run(&mut s, "recolor.weigh", twice)["shares"], json!([50.0, 50.0])); + // As recolor.apply matches them: an exact colour before a hex one, a row with a new colour first. + let exact = json!({"map": [{"from": ["#ff0000", PURPLE], "to": "#00ff00"}, {"from": [RED, BLUE], "to": "#ffff00"}]}); + assert_eq!(run(&mut s, "recolor.weigh", exact)["shares"], json!([25.0, 75.0])); + let recolored = json!({"map": [{"from": [RED, PURPLE]}, {"from": [RED, BLUE], "to": "#ffff00"}]}); + assert_eq!(run(&mut s, "recolor.weigh", recolored)["shares"], json!([25.0, 75.0])); +} + +#[test] +fn weigh_moves_colors_to_the_rows_weights_and_changes_nothing() { + let mut s = session(); + let [_, _, purple, blue] = prominent_art(&mut s); + let map = json!([{"from": [RED, PURPLE], "to": "#00ff00"}, {"from": [BLUE], "to": "#ffff00"}]); + let r = run(&mut s, "recolor.weigh", json!({"map": map, "weights": [1, 1]})); + assert_eq!(r["map"], json!([{"from": [RED], "to": "#00ff00"}, {"from": [BLUE, PURPLE], "to": "#ffff00"}])); + assert_eq!(r["shares"], json!([50.0, 50.0])); + assert_eq!(fill(&s, purple).to_hex(), "#8000cc", "a query leaves the art alone"); + // Recoloring with the weighed rows gives the moved colour its new row's colour. + select_all(&mut s); + run(&mut s, "recolor.apply", json!({"map": r["map"]})); + assert_eq!(fill(&s, purple).to_hex(), "#ffff00"); + assert_eq!(fill(&s, blue).to_hex(), "#ffff00"); + // A row's first colour stays, however small its weight. + let mut s = session(); + prominent_art(&mut s); + let r = run(&mut s, "recolor.weigh", json!({"map": map, "weights": [0, 1]})); + assert_eq!(r["map"][0]["from"], json!([RED])); + assert_eq!(r["shares"], json!([50.0, 50.0])); + // Excluded rows keep their colours and take none; their weights are ignored. + let three = + json!([{"from": [RED, PURPLE], "to": "#000000"}, {"from": [BLUE], "to": "#000000", "exclude": true}, {"from": ["#00ff00"], "to": "#000000"}]); + let r = run(&mut s, "recolor.weigh", json!({"map": three, "weights": [1, 50, 1]})); + assert_eq!(r["map"][1]["from"], json!([BLUE])); + assert_eq!(r["map"][2]["from"], json!(["#00ff00", PURPLE])); + // A row without a new colour recolors nothing, so it neither gives nor takes colours. + let keep = json!([{"from": [RED, PURPLE], "to": "#000000"}, {"from": [BLUE]}, {"from": ["#00ff00"], "to": "#000000"}]); + let r = run(&mut s, "recolor.weigh", json!({"map": keep, "weights": [0, 1, 1]})); + assert_eq!(r["map"][1]["from"], json!([BLUE])); + assert_eq!(r["map"][2]["from"], json!(["#00ff00", PURPLE])); +} + +/// A colour that two rows list moves only where recolor.apply recolors it with the row it moved +/// to, so the shares describe the recolor. +#[test] +fn weigh_keeps_a_moved_color_from_rows_that_also_list_it() { + const GREEN: &str = "rgb 0 255 0"; + let mut s = session(); + let [_, _, purple, _] = prominent_art(&mut s); + rect(&mut s, json!("#00ff00")); + select_all(&mut s); + // The purple moves from the first row to the third; the second row's entry for it goes. + let map = json!([{"from": [RED, PURPLE], "to": "#000000"}, {"from": [BLUE, PURPLE], "to": "#ffffff"}, {"from": [GREEN], "to": "#ffff00"}]); + let r = run(&mut s, "recolor.weigh", json!({"map": map, "weights": [2, 1, 2]})); + assert_eq!(r["map"][0]["from"], json!([RED])); + assert_eq!(r["map"][1]["from"], json!([BLUE])); + assert_eq!(r["map"][2]["from"], json!([GREEN, PURPLE])); + assert_eq!(r["shares"], json!([40.0, 20.0, 40.0])); + run(&mut s, "recolor.apply", json!({"map": r["map"], "method": "exact"})); + assert_eq!(fill(&s, purple).to_hex(), "#ffff00", "the purple takes the row it moved to"); + // A colour that another row lists first stays: that row would take it back. + let mut s = session(); + let [_, _, purple, _] = prominent_art(&mut s); + rect(&mut s, json!("#00ff00")); + select_all(&mut s); + let map = json!([{"from": [RED, PURPLE], "to": "#000000"}, {"from": [PURPLE, BLUE], "to": "#ffffff"}, {"from": [GREEN], "to": "#ffff00"}]); + let r = run(&mut s, "recolor.weigh", json!({"map": map, "weights": [2, 1, 2]})); + assert_eq!(r["map"][0]["from"], json!([RED, PURPLE])); + assert_eq!(r["map"][1]["from"], json!([PURPLE, BLUE])); + assert_eq!(r["shares"], json!([60.0, 20.0, 20.0])); + run(&mut s, "recolor.apply", json!({"map": r["map"], "method": "exact"})); + assert_eq!(fill(&s, purple).to_hex(), "#000000", "the purple keeps the first row's colour"); +} + +#[test] +fn weigh_moves_the_tints_of_a_global_swatch_together() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Brand", "color": {"c": 0, "m": 80, "y": 90, "k": 0}, "global": true})); + rect(&mut s, json!("#ff0000")); + let full = rect(&mut s, json!("#00ff00")); + let tint = rect(&mut s, json!("#00ff00")); + rect(&mut s, json!("#0000ff")); + run(&mut s, "paint.setFill", json!({"ids": [full.0], "swatch": "Brand"})); + run(&mut s, "paint.setFill", json!({"ids": [tint.0], "swatch": "Brand", "tint": 50})); + select_all(&mut s); + let brand: Vec = run(&mut s, "recolor.colors", json!({}))["colors"] + .as_array() + .unwrap() + .iter() + .filter(|c| c["swatch"] == "Brand") + .map(|c| c["key"].clone()) + .collect(); + assert_eq!(brand.len(), 2); + let map = json!([{"from": [RED, brand[0], brand[1]], "to": "#000000"}, {"from": [BLUE], "to": "#ffffff"}]); + // Even weights would take one tint alone, which would split the swatch: nothing moves. + let r = run(&mut s, "recolor.weigh", json!({"map": map, "weights": [1, 1]})); + assert_eq!(r["map"][1]["from"], json!([BLUE])); + // The swatch's two colours move to the blue row as one. + let r = run(&mut s, "recolor.weigh", json!({"map": map, "weights": [1, 3]})); + assert_eq!(r["map"][1]["from"], json!([BLUE, brand[0], brand[1]])); + assert_eq!(r["shares"], json!([25.0, 75.0])); + // Colours that stay keep their order, a swatch's colours with another between them included. + let split = json!([{"from": [brand[0], RED, brand[1]], "to": "#000000"}, {"from": [BLUE], "to": "#ffffff"}]); + let r = run(&mut s, "recolor.weigh", json!({"map": split, "weights": [3, 1]})); + assert_eq!(r["map"][0]["from"], json!([brand[0], RED, brand[1]])); +} + +#[test] +fn weigh_refuses_bad_weights() { + let mut s = session(); + prominent_art(&mut s); + let map = json!([{"from": [RED]}, {"from": [BLUE], "exclude": true}]); + for (p, msg) in [ + (json!({"map": map, "weights": [1]}), "`weights` must be a list of 2 numbers, one per row"), + (json!({"map": map, "weights": "1, 1"}), "`weights` must be a list of 2 numbers"), + (json!({"map": map, "weights": [1, -1]}), "each weight must be a number of 0 or more (got -1)"), + (json!({"map": map, "weights": [1, "2"]}), "each weight must be a number of 0 or more"), + (json!({"map": map, "weights": [0, 5]}), "at least one row that isn't excluded needs a weight above 0"), + (json!({"weights": [1, 1]}), "missing `map`"), + (json!({"map": [{"to": "#ff0000"}]}), "each row needs `from`"), + ] { + let e = s.execute("recolor.weigh", &p).unwrap_err().to_string(); + assert!(e.contains(msg), "{p}: {e}"); + } +} diff --git a/crates/engine/src/tests/recovery.rs b/crates/engine/src/tests/recovery.rs index 9fe2d846ce..976d217833 100644 --- a/crates/engine/src/tests/recovery.rs +++ b/crates/engine/src/tests/recovery.rs @@ -483,6 +483,802 @@ fn the_folder_store_reads_no_linked_entries() { let _ = std::fs::remove_dir_all(&base); } +/// A file where a folder of the store's path should be: the error names that file, not the area +/// folder or the copy below it, for a write, a lock, a read, a listing, a removal and a recovery +/// save. +#[cfg(unix)] +#[test] +fn folder_errors_name_a_file_in_the_way() { + let base = std::env::temp_dir().join(format!("vc-recovery-file-in-way-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(&base).unwrap(); + let file = base.join("file"); + std::fs::write(&file, b"").unwrap(); + let folder = file.join("recovery"); + let store = FolderStore::new(&folder); + let mut s = Session::new(); + s.prefs.recovery_folder = folder.to_string_lossy().to_string(); + s.execute("file.new", &json!({"width": 50, "height": 50})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap(); + let errors = [ + ("write", store.write("1-1/Untitled-1-1.vectorcraft", b"copy").err()), + ("lock", store.lock("1-2").err()), + ("read", store.read("1-1/Untitled-1-1.vectorcraft").err()), + ("list", store.list().err()), + ("remove", store.remove("1-1/Untitled-1-1.vectorcraft").err()), + ("save", s.execute("file.recovery.save", &json!({})).err().map(|e| e.to_string())), + ]; + let _ = std::fs::remove_dir_all(&base); + let named = format!("{} is not a folder: ", file.display()); + let wrong: Vec<_> = errors.iter().filter(|(_, e)| !e.as_deref().is_some_and(|e| e.contains(&named))).collect(); + assert!(wrong.is_empty(), "{wrong:?}"); +} + +/// A removal that finds the copy missing because a file is on the way to it (how Windows reports a +/// file in the way) names that file. A copy that is just not there still counts as removed. +#[test] +fn a_removal_reported_missing_names_a_file_in_the_way() { + let base = std::env::temp_dir().join(format!("vc-recovery-remove-in-way-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(&base).unwrap(); + let file = base.join("file"); + std::fs::write(&file, b"").unwrap(); + let missing = || std::io::Error::from(std::io::ErrorKind::NotFound); + let behind = FolderStore::removed(&file.join("recovery").join("1-1").join("Untitled-1-1.vectorcraft"), Err(missing())); + let gone = FolderStore::removed(&base.join("recovery").join("1-1").join("Untitled-1-1.vectorcraft"), Err(missing())); + let _ = std::fs::remove_dir_all(&base); + let named = format!("{} is not a folder: ", file.display()); + assert!(behind.as_ref().is_err_and(|e| e.starts_with(&named)), "{behind:?}"); + assert_eq!(gone, Ok(())); +} + +/// A folder of the store's path that is missing and can't be made: a write or a lock names it as +/// the folder it couldn't make, and a read names it as missing. An area folder that can't be made +/// in a store folder that is there is named the same way. +#[cfg(unix)] +#[test] +fn folder_errors_name_a_missing_folder_that_cannot_be_made() { + use std::os::unix::fs::PermissionsExt as _; + let base = std::env::temp_dir().join(format!("vc-recovery-missing-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let closed = base.join("closed"); + std::fs::create_dir_all(&closed).unwrap(); + std::fs::set_permissions(&closed, std::fs::Permissions::from_mode(0o500)).unwrap(); + let gone = closed.join("gone"); + let store = FolderStore::new(gone.join("recovery")); + let unmade = format!("couldn't make {}: ", gone.display()); + let area = FolderStore::new(&closed).write("1-1/Untitled-1-1.vectorcraft", b"copy").err(); + let errors = [ + ("write", store.write("1-1/Untitled-1-1.vectorcraft", b"copy").err(), unmade.clone()), + ("lock", store.lock("1-2").err(), unmade), + ("read", store.read("1-1/Untitled-1-1.vectorcraft").err(), format!("{} is missing", gone.display())), + ("area", area, format!("couldn't make {}: ", closed.join("1-1").display())), + ]; + std::fs::set_permissions(&closed, std::fs::Permissions::from_mode(0o700)).unwrap(); + let _ = std::fs::remove_dir_all(&base); + // An account that can write anywhere (root) makes the folders, so the test has nothing to check. + if errors[0].1.is_none() { + return; + } + let wrong: Vec<_> = errors.iter().filter(|(_, e, named)| !e.as_deref().is_some_and(|e| e.starts_with(named.as_str()))).collect(); + assert!(wrong.is_empty(), "{wrong:?}"); +} + +/// When every folder on the way is there, an error names the folder it happened on. +#[cfg(unix)] +#[test] +fn folder_errors_name_the_folder_when_every_folder_is_there() { + use std::os::unix::fs::PermissionsExt as _; + let base = std::env::temp_dir().join(format!("vc-recovery-unreadable-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let unreadable = base.join("unreadable"); + std::fs::create_dir_all(&unreadable).unwrap(); + std::fs::set_permissions(&unreadable, std::fs::Permissions::from_mode(0o300)).unwrap(); + let listed = FolderStore::new(&unreadable).list(); + std::fs::set_permissions(&unreadable, std::fs::Permissions::from_mode(0o700)).unwrap(); + let _ = std::fs::remove_dir_all(&base); + // An account that can read any folder (root) lists it, so the test has nothing to check. + let Err(err) = listed else { return }; + assert!(err.starts_with(&format!("{}: ", unreadable.display())), "{err}"); +} + +/// A store in memory that notes each removal of an area (its lock file and folder, then its empty +/// folder) and whether the area was still held then. +#[derive(Default)] +struct Tidying { + inner: MemoryStore, + removals: std::sync::Mutex>, +} + +impl Tidying { + fn note(&self, what: &'static str, area: &str) { + let held = matches!(self.inner.lock(area), Ok(cmd::recovery::Lock::Busy)); + self.removals.lock().unwrap().push((what, held)); + } +} + +impl RecoveryStore for Tidying { + fn list(&self) -> std::result::Result, String> { + self.inner.list() + } + fn read(&self, name: &str) -> std::result::Result, String> { + self.inner.read(name) + } + fn write(&self, name: &str, bytes: &[u8]) -> std::result::Result<(), String> { + self.inner.write(name, bytes) + } + fn remove(&self, name: &str) -> std::result::Result<(), String> { + self.inner.remove(name) + } + fn location(&self) -> String { + self.inner.location() + } + fn lock(&self, area: &str) -> std::result::Result { + self.inner.lock(area) + } + fn remove_area(&self, area: &str) { + self.note("area", area); + } + fn remove_empty_area(&self, area: &str) { + self.note("empty folder", area); + } + fn now(&self) -> Option { + self.inner.now() + } +} + +/// An app tidying an area away (a crashed app's, or its own when it quits) removes it while it +/// still holds it, so another app taking a new area of that name can't lock it in between. Once it +/// let the area go, it removes the folder again if that is empty. +#[test] +fn areas_are_removed_while_still_held() { + let store = Arc::new(Tidying::default()); + let app = || { + let mut s = Session::new(); + s.recovery.set_store(store.clone()); + s.execute("file.new", &json!({"width": 50, "height": 50})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap(); + s + }; + let mut a = app(); + a.execute("file.recovery.save", &json!({})).unwrap(); + drop(a); + let mut b = app(); + assert_eq!(b.execute("file.recovery.discard", &json!({})).unwrap()["discarded"].as_array().unwrap().len(), 1); + b.execute("file.recovery.save", &json!({})).unwrap(); + b.execute("file.close", &json!({})).unwrap(); + cmd::recovery::forget_all(&mut b); + let tidy = [("area", true), ("empty folder", false)]; + assert_eq!(*store.removals.lock().unwrap(), [tidy, tidy].concat(), "discard's tidy, then quitting"); +} + +/// Another app tidied an empty area away between this app making it and locking it: the area is +/// busy, not held and not an error. +#[test] +fn an_area_tidied_away_before_it_is_locked_is_busy() { + use cmd::recovery::Lock; + let base = std::env::temp_dir().join(format!("vc-recovery-tidied-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let store = FolderStore::new(&base); + drop(store.lock("5-1").unwrap()); + let area = base.join("5-1"); + let path = area.join(".lock"); + let open = |create: bool| std::fs::OpenOptions::new().read(true).write(true).create(create).truncate(false).open(&path).unwrap(); + // The lock file was opened, then removed before it was locked. + let opened = open(false); + std::fs::remove_file(&path).unwrap(); + assert!(matches!(FolderStore::take(opened, &path), Ok(Lock::Busy))); + // The folder went before it was checked or its lock file opened. + std::fs::remove_dir(&area).unwrap(); + assert!(matches!(FolderStore::lock_area(&area), Ok(Lock::Busy))); + // A lock file made again under the same name is not the one opened, also where it keeps the + // removed one's creation time (NTFS does within 15 seconds). + #[cfg(any(unix, windows))] + { + std::fs::create_dir_all(&area).unwrap(); + let opened = open(true); + std::fs::remove_file(&path).unwrap(); + std::fs::write(&path, b"").unwrap(); + assert!(matches!(FolderStore::take(opened, &path), Ok(Lock::Busy))); + assert!(matches!(FolderStore::take(open(false), &path), Ok(Lock::Held(_)))); + } + let _ = std::fs::remove_dir_all(&base); +} + +/// Opening an area's lock file failed. When the folder went after it was checked, or the lock file +/// is there but can't be opened (a removed lock file that another app still has open, on file +/// systems that keep it until it is closed), the area is busy. A lock file that can't be made is an +/// error. +#[test] +fn a_lock_file_that_is_gone_or_cannot_be_opened_is_busy() { + use cmd::recovery::Lock; + use std::io::ErrorKind::{NotFound, PermissionDenied}; + let base = std::env::temp_dir().join(format!("vc-recovery-unopened-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(&base).unwrap(); + let path = base.join(".lock"); + let failed = |kind: std::io::ErrorKind| FolderStore::open_failed(kind.into(), &path); + assert!(matches!(failed(NotFound), Ok(Lock::Busy))); + assert!(failed(PermissionDenied).is_err()); + std::fs::write(&path, b"").unwrap(); + assert!(matches!(failed(PermissionDenied), Ok(Lock::Busy))); + #[cfg(unix)] + if !rustix::process::geteuid().is_root() { + use std::os::unix::fs::PermissionsExt as _; + let mode = |p: &std::path::Path, m: u32| std::fs::set_permissions(p, std::fs::Permissions::from_mode(m)).unwrap(); + // A lock file that is there but can't be opened. + let area = base.join("5-1"); + std::fs::create_dir(&area).unwrap(); + std::fs::write(area.join(".lock"), b"").unwrap(); + mode(&area.join(".lock"), 0o400); + assert!(matches!(FolderStore::lock_area(&area), Ok(Lock::Busy))); + // A folder in which no lock file can be made. + let area = base.join("5-2"); + std::fs::create_dir(&area).unwrap(); + mode(&area, 0o500); + let r = FolderStore::lock_area(&area); + mode(&area, 0o700); + assert!(r.is_err()); + } + let _ = std::fs::remove_dir_all(&base); +} + +/// A folder store in which another app tidies the first area away as soon as it is made. +struct TidiedFirst { + inner: FolderStore, + dir: std::path::PathBuf, + first: std::sync::atomic::AtomicBool, +} + +impl RecoveryStore for TidiedFirst { + fn list(&self) -> std::result::Result, String> { + self.inner.list() + } + fn read(&self, name: &str) -> std::result::Result, String> { + self.inner.read(name) + } + fn write(&self, name: &str, bytes: &[u8]) -> std::result::Result<(), String> { + self.inner.write(name, bytes) + } + fn remove(&self, name: &str) -> std::result::Result<(), String> { + self.inner.remove(name) + } + fn location(&self) -> String { + self.inner.location() + } + fn areas(&self) -> std::result::Result, String> { + self.inner.areas() + } + fn lock(&self, area: &str) -> std::result::Result { + if !self.first.swap(false, std::sync::atomic::Ordering::SeqCst) { + return self.inner.lock(area); + } + let dir = self.dir.join(area); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::remove_dir(&dir).unwrap(); + FolderStore::lock_area(&dir) + } + fn remove_area(&self, area: &str) { + self.inner.remove_area(area); + } +} + +#[test] +fn a_recovery_save_takes_the_next_area_when_the_first_is_tidied_away() { + let dir = std::env::temp_dir().join(format!("vc-recovery-next-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let store = Arc::new(TidiedFirst { inner: FolderStore::new(&dir), dir: dir.clone(), first: true.into() }); + let mut s = Session::new(); + s.recovery.set_store(store.clone()); + s.execute("file.new", &json!({"width": 50, "height": 50})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap(); + let r = s.execute("file.recovery.save", &json!({})).unwrap(); + let area = s.recovery.own_area().unwrap().to_string(); + assert!(area.ends_with("-2"), "{area}"); + assert_eq!(r["saved"][0]["file"], format!("{area}/Untitled-1-1").as_str(), "{r}"); + assert!(dir.join(&area).join("Untitled-1-1.vectorcraft").is_file()); + drop(s); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A session keeping its copies in folder `dir`, with one modified document whose copy is written. +fn saved_in(dir: &std::path::Path) -> (Session, String) { + let mut s = Session::new(); + s.prefs.recovery_folder = dir.to_string_lossy().to_string(); + s.execute("file.new", &json!({"width": 50, "height": 50})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap(); + s.execute("file.recovery.save", &json!({})).unwrap(); + let area = s.recovery.own_area().unwrap().to_string(); + (s, area) +} + +/// A new app over folder `dir`, with nothing open. +#[cfg(unix)] +fn other_app(dir: &std::path::Path) -> Session { + let mut s = Session::new(); + s.prefs.recovery_folder = dir.to_string_lossy().to_string(); + s +} + +/// The area's lock file was removed while its app runs: the next recovery save locks the area +/// again, so another app neither offers nor discards its copy. +#[cfg(unix)] +#[test] +fn a_recovery_save_locks_the_area_again_when_its_lock_file_was_removed() { + use cmd::recovery::Lock; + let dir = std::env::temp_dir().join(format!("vc-recovery-relock-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let (mut a, area) = saved_in(&dir); + std::fs::remove_file(dir.join(&area).join(".lock")).unwrap(); + a.execute("file.recovery.save", &json!({})).unwrap(); + assert_eq!(a.recovery.own_area(), Some(area.as_str())); + let mut b = other_app(&dir); + assert!(offered(&mut b).is_empty()); + assert!(b.execute("file.recovery.discard", &json!({})).unwrap()["discarded"].as_array().unwrap().is_empty()); + assert!(dir.join(&area).join("Untitled-1-1.vectorcraft").is_file()); + assert!(matches!(FolderStore::new(&dir).lock(&area), Ok(Lock::Busy))); + drop(a); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The whole area was removed while its app runs: the next recovery save makes it again, locked, +/// with the copy written again. +#[cfg(unix)] +#[test] +fn a_recovery_save_makes_the_area_again_when_it_was_removed() { + use cmd::recovery::Lock; + let dir = std::env::temp_dir().join(format!("vc-recovery-remade-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let (mut a, area) = saved_in(&dir); + std::fs::remove_dir_all(dir.join(&area)).unwrap(); + let r = a.execute("file.recovery.save", &json!({})).unwrap(); + assert_eq!(r["saved"][0]["file"], format!("{area}/Untitled-1-1").as_str(), "{r}"); + assert!(dir.join(&area).join("Untitled-1-1.vectorcraft").is_file()); + assert!(matches!(FolderStore::new(&dir).lock(&area), Ok(Lock::Busy))); + assert!(offered(&mut other_app(&dir)).is_empty()); + drop(a); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Another app locked the area after its lock file was removed: the next heartbeat takes a new +/// area, and the document is to be copied again there. Its copy in the old area stays until then. +#[cfg(unix)] +#[test] +fn an_area_another_app_locked_meanwhile_is_left_for_a_new_one() { + use cmd::recovery::Lock; + let dir = std::env::temp_dir().join(format!("vc-recovery-moved-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let (mut a, area) = saved_in(&dir); + std::fs::remove_file(dir.join(&area).join(".lock")).unwrap(); + let store = FolderStore::new(&dir); + let Ok(Lock::Held(other)) = store.lock(&area) else { panic!("the other app locks the area") }; + let uid = a.doc().unwrap().uid; + assert_eq!(cmd::recovery::heartbeat(&mut a), [uid]); + let mine = a.recovery.own_area().unwrap().to_string(); + assert_ne!(mine, area); + assert!(a.doc().unwrap().recovery.is_none()); + assert!(dir.join(&area).join("Untitled-1-1.vectorcraft").is_file(), "kept until the new copy is written"); + let r = a.execute("file.recovery.save", &json!({})).unwrap(); + assert_eq!(r["saved"][0]["file"], format!("{mine}/Untitled-1-1").as_str(), "{r}"); + assert!(!dir.join(&area).join("Untitled-1-1.vectorcraft").exists(), "the copy left there goes"); + assert!(matches!(store.lock(&mine), Ok(Lock::Busy))); + drop(other); + assert!(offered(&mut other_app(&dir)).is_empty()); + drop(a); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A copy written in the background into the area the session left meanwhile is not the +/// document's copy: it stays only until the document is copied again in the new area. +#[cfg(unix)] +#[test] +fn a_copy_written_into_an_area_left_meanwhile_goes_once_copied_again() { + use cmd::recovery::Lock; + let dir = std::env::temp_dir().join(format!("vc-recovery-inflight-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let (mut a, area) = saved_in(&dir); + a.execute("shape.ellipse", &json!({"x": 10, "y": 10, "width": 5, "height": 5})).unwrap(); + let store: Arc = Arc::new(FolderStore::new(&dir)); + let (jobs, _) = cmd::recovery::jobs(&mut a, &store).unwrap(); + assert_eq!(jobs.len(), 1); + std::fs::remove_file(dir.join(&area).join(".lock")).unwrap(); + let Ok(Lock::Held(other)) = store.lock(&area) else { panic!("the other app locks the area") }; + cmd::recovery::heartbeat(&mut a); + for j in jobs { + j.write().unwrap(); + j.finish(&mut a); + } + assert!(a.doc().unwrap().recovery.is_none()); + assert!(dir.join(&area).join("Untitled-1-1.vectorcraft").is_file()); + let uid = a.doc().unwrap().uid; + assert_eq!(cmd::recovery::heartbeat(&mut a), [uid], "the next heartbeat has it copied again"); + let r = a.execute("file.recovery.save", &json!({})).unwrap(); + assert_eq!(r["saved"].as_array().unwrap().len(), 1, "{r}"); + assert!(!dir.join(&area).join("Untitled-1-1.vectorcraft").exists()); + assert!(cmd::recovery::heartbeat(&mut a).is_empty()); + drop(other); + assert!(offered(&mut other_app(&dir)).is_empty()); + drop(a); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Another app locked the area meanwhile and the document is unchanged since its copy: the next +/// recovery save still writes the copy, in the new area. +#[cfg(unix)] +#[test] +fn a_recovery_save_copies_unchanged_documents_into_the_new_area() { + use cmd::recovery::Lock; + let dir = std::env::temp_dir().join(format!("vc-recovery-unchanged-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let (mut a, area) = saved_in(&dir); + std::fs::remove_file(dir.join(&area).join(".lock")).unwrap(); + let Ok(Lock::Held(other)) = FolderStore::new(&dir).lock(&area) else { panic!("the other app locks the area") }; + let r = a.execute("file.recovery.save", &json!({})).unwrap(); + let mine = a.recovery.own_area().unwrap().to_string(); + assert_ne!(mine, area); + assert_eq!(r["saved"][0]["file"], format!("{mine}/Untitled-1-1").as_str(), "{r}"); + assert!(dir.join(&mine).join("Untitled-1-1.vectorcraft").is_file()); + assert!(!dir.join(&area).join("Untitled-1-1.vectorcraft").exists()); + drop(other); + drop(a); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A copy left in an area the session had to leave goes at once when its document is saved, +/// reverted or closed, and every one goes when the app quits with nothing unsaved. +#[cfg(unix)] +#[test] +fn copies_left_behind_go_when_their_document_is_saved_reverted_or_closed() { + use cmd::recovery::Lock; + let base = std::env::temp_dir().join(format!("vc-recovery-leftgo-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let dir = base.join("recovery"); + let path = base.join("doc.vectorcraft").to_string_lossy().to_string(); + let left = |area: &str| std::fs::read_dir(dir.join(area)).unwrap().flatten().any(|e| e.path().extension().is_some_and(|x| x == "vectorcraft")); + for how in ["save", "revert", "close", "quit"] { + let (mut a, _) = saved_in(&dir); + a.execute("document.save", &json!({"path": path})).unwrap(); + a.execute("shape.ellipse", &json!({"x": 10, "y": 10, "width": 5, "height": 5})).unwrap(); + a.execute("file.recovery.save", &json!({})).unwrap(); + let area = a.recovery.own_area().unwrap().to_string(); + std::fs::remove_file(dir.join(&area).join(".lock")).unwrap(); + let Ok(Lock::Held(other)) = FolderStore::new(&dir).lock(&area) else { panic!("the other app locks the area") }; + cmd::recovery::heartbeat(&mut a); + assert!(left(&area), "{how}"); + match how { + "save" => a.execute("document.save", &json!({"path": path})).map(drop).unwrap(), + "revert" => a.execute("file.revert", &json!({})).map(drop).unwrap(), + "close" => a.execute("file.close", &json!({})).map(drop).unwrap(), + _ => cmd::recovery::forget_all(&mut a), + } + assert!(!left(&area), "{how}"); + drop(other); + drop(a); + } + let _ = std::fs::remove_dir_all(&base); +} + +/// The lock file was removed: the next heartbeat locks the area again, before any recovery save. +#[cfg(unix)] +#[test] +fn a_heartbeat_locks_the_area_again_when_its_lock_file_was_removed() { + use cmd::recovery::Lock; + let dir = std::env::temp_dir().join(format!("vc-recovery-beatlock-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let (mut a, area) = saved_in(&dir); + std::fs::remove_file(dir.join(&area).join(".lock")).unwrap(); + assert!(cmd::recovery::heartbeat(&mut a).is_empty(), "the copy is still there"); + assert_eq!(a.recovery.own_area(), Some(area.as_str())); + assert!(matches!(FolderStore::new(&dir).lock(&area), Ok(Lock::Busy))); + assert!(offered(&mut other_app(&dir)).is_empty()); + drop(a); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The lock file was removed and can't be made again (the area folder can't be written to now): +/// the session takes a new area and writes its copy there. +#[cfg(unix)] +#[test] +fn an_area_whose_lock_file_cannot_be_made_again_is_left_for_a_new_one() { + use std::os::unix::fs::PermissionsExt as _; + + use cmd::recovery::Lock; + // Permissions don't stop the superuser. + if rustix::process::geteuid().is_root() { + return; + } + let dir = std::env::temp_dir().join(format!("vc-recovery-readonly-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let (mut a, area) = saved_in(&dir); + std::fs::remove_file(dir.join(&area).join(".lock")).unwrap(); + std::fs::set_permissions(dir.join(&area), std::fs::Permissions::from_mode(0o500)).unwrap(); + let r = a.execute("file.recovery.save", &json!({})).unwrap(); + let mine = a.recovery.own_area().unwrap().to_string(); + assert_ne!(mine, area); + assert_eq!(r["saved"][0]["file"], format!("{mine}/Untitled-1-1").as_str(), "{r}"); + assert!(matches!(FolderStore::new(&dir).lock(&mine), Ok(Lock::Busy))); + std::fs::set_permissions(dir.join(&area), std::fs::Permissions::from_mode(0o700)).unwrap(); + drop(a); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A copy left behind that can't be removed when its document is saved (its area can't be written +/// to now) stays the session's own: it isn't offered here, and a later heartbeat removes it. +#[cfg(unix)] +#[test] +fn a_copy_left_behind_that_cannot_be_removed_yet_stays_the_sessions_own() { + use std::os::unix::fs::PermissionsExt as _; + + use cmd::recovery::Lock; + // Permissions don't stop the superuser. + if rustix::process::geteuid().is_root() { + return; + } + let base = std::env::temp_dir().join(format!("vc-recovery-leftstuck-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let dir = base.join("recovery"); + let path = base.join("doc.vectorcraft").to_string_lossy().to_string(); + let (mut a, area) = saved_in(&dir); + std::fs::remove_file(dir.join(&area).join(".lock")).unwrap(); + let Ok(Lock::Held(other)) = FolderStore::new(&dir).lock(&area) else { panic!("the other app locks the area") }; + cmd::recovery::heartbeat(&mut a); + std::fs::set_permissions(dir.join(&area), std::fs::Permissions::from_mode(0o500)).unwrap(); + a.execute("document.save", &json!({"path": path})).unwrap(); + std::fs::set_permissions(dir.join(&area), std::fs::Permissions::from_mode(0o700)).unwrap(); + let copy = dir.join(&area).join("Untitled-1-1.vectorcraft"); + assert!(copy.is_file()); + drop(other); + assert!(offered(&mut a).is_empty()); + cmd::recovery::heartbeat(&mut a); + assert!(!copy.exists()); + drop(a); + let _ = std::fs::remove_dir_all(&base); +} + +/// A copy left in an area the session had to leave is still the session's own after the app that +/// locked that area is gone: the session neither offers nor discards it. +#[cfg(unix)] +#[test] +fn a_copy_left_behind_is_not_offered_by_its_own_app() { + use cmd::recovery::Lock; + let dir = std::env::temp_dir().join(format!("vc-recovery-leftmine-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let (mut a, area) = saved_in(&dir); + std::fs::remove_file(dir.join(&area).join(".lock")).unwrap(); + let Ok(Lock::Held(other)) = FolderStore::new(&dir).lock(&area) else { panic!("the other app locks the area") }; + cmd::recovery::heartbeat(&mut a); + drop(other); + assert!(offered(&mut a).is_empty()); + let r = a.execute("file.recovery.discard", &json!({})).unwrap(); + assert!(r["discarded"].as_array().unwrap().is_empty(), "{r}"); + assert!(a.execute("file.recovery.discard", &json!({"file": format!("{area}/Untitled-1-1")})).is_err()); + assert!(dir.join(&area).join("Untitled-1-1.vectorcraft").is_file()); + drop(a); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A copy left in an area the session had to leave is not another app's to offer, restore or +/// discard while the session runs, even after the app that locked that area let it go: an entry in +/// the session's new area says it keeps it. Once the copy is written again in the new area, the +/// entry goes; after a crash before that, the copy is offered. +#[cfg(unix)] +#[test] +fn a_copy_left_behind_is_not_offered_by_another_app_while_its_app_runs() { + use cmd::recovery::Lock; + let dir = std::env::temp_dir().join(format!("vc-recovery-leftother-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let left_behind = |area: &str| dir.join(area).join("Untitled-1-1.vectorcraft"); + let leave = |a: &mut Session, area: &str| { + std::fs::remove_file(dir.join(area).join(".lock")).unwrap(); + let Ok(Lock::Held(other)) = FolderStore::new(&dir).lock(area) else { panic!("the other app locks the area") }; + cmd::recovery::heartbeat(a); + drop(other); + a.recovery.own_area().unwrap().to_string() + }; + let (mut a, area) = saved_in(&dir); + let mine = leave(&mut a, &area); + assert_ne!(mine, area); + assert!(dir.join(&mine).join(format!("keeps-{area}")).is_file()); + // Removed meanwhile: the next heartbeat writes it again. + std::fs::remove_file(dir.join(&mine).join(format!("keeps-{area}"))).unwrap(); + cmd::recovery::heartbeat(&mut a); + assert!(dir.join(&mine).join(format!("keeps-{area}")).is_file()); + let mut b = other_app(&dir); + assert!(offered(&mut b).is_empty()); + assert_eq!(restored(b.execute("file.recovery.restore", &json!({})).unwrap()), 0); + assert!(b.execute("file.recovery.discard", &json!({})).unwrap()["discarded"].as_array().unwrap().is_empty()); + assert!(b.execute("file.recovery.discard", &json!({"file": format!("{area}/Untitled-1-1")})).is_err()); + assert!(left_behind(&area).is_file()); + // Written again in the new area: the copy left behind and the entry go. + a.execute("file.recovery.save", &json!({})).unwrap(); + assert!(!left_behind(&area).exists()); + assert!(!dir.join(&mine).join(format!("keeps-{area}")).exists()); + assert!(offered(&mut b).is_empty()); + drop(a); + let _ = std::fs::remove_dir_all(&dir); + // A crash before the copy is written again: the copy left behind is offered. + let (mut a, area) = saved_in(&dir); + leave(&mut a, &area); + drop(a); + assert_eq!(offered(&mut other_app(&dir)).len(), 1); + assert!(left_behind(&area).is_file()); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A store in memory whose areas named `foreign-…` can't be locked by this account (as another +/// account's folder in a shared recovery folder). +#[derive(Default)] +struct ForeignAreas(MemoryStore); + +impl RecoveryStore for ForeignAreas { + fn list(&self) -> std::result::Result, String> { + self.0.list() + } + fn read(&self, name: &str) -> std::result::Result, String> { + self.0.read(name) + } + fn write(&self, name: &str, bytes: &[u8]) -> std::result::Result<(), String> { + self.0.write(name, bytes) + } + fn remove(&self, name: &str) -> std::result::Result<(), String> { + self.0.remove(name) + } + fn location(&self) -> String { + self.0.location() + } + fn lock(&self, area: &str) -> std::result::Result { + if area.starts_with("foreign-") { + return Err(format!("{area}: belongs to another account")); + } + self.0.lock(area) + } + fn now(&self) -> Option { + self.0.now() + } +} + +/// An entry `/keeps-` in an area this account can't lock keeps nothing: a crashed +/// app's copies in the left area are still offered. +#[test] +fn a_keeps_entry_in_an_area_that_cannot_be_locked_keeps_nothing() { + let store = Arc::new(ForeignAreas::default()); + let app = || { + let mut s = Session::new(); + s.recovery.set_store(store.clone()); + s + }; + let mut a = app(); + a.execute("file.new", &json!({"width": 50, "height": 50})).unwrap(); + a.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap(); + a.execute("file.recovery.save", &json!({})).unwrap(); + let area = a.recovery.own_area().unwrap().to_string(); + drop(a); + store.write(&format!("foreign-1/keeps-{area}"), b"").unwrap(); + let mut b = app(); + assert_eq!(offered(&mut b).len(), 1); + assert_eq!(restored(b.execute("file.recovery.restore", &json!({})).unwrap()), 1); +} + +/// An entry `/keeps-` in a running app's area keeps a crashed app's copies in the +/// left area until that app is gone too. +#[test] +fn a_keeps_entry_in_a_running_apps_area_keeps_the_copies() { + let store = Arc::new(MemoryStore::default()); + let mut a = session_in(&store); + a.execute("file.recovery.save", &json!({})).unwrap(); + let area = a.recovery.own_area().unwrap().to_string(); + drop(a); + let mut c = session_in(&store); + c.execute("file.recovery.save", &json!({})).unwrap(); + let keeper = c.recovery.own_area().unwrap().to_string(); + store.write(&format!("{keeper}/keeps-{area}"), b"").unwrap(); + let mut b = relaunch(&store); + assert!(offered(&mut b).is_empty()); + assert_eq!(restored(b.execute("file.recovery.restore", &json!({})).unwrap()), 0); + drop(c); + assert_eq!(offered(&mut b).len(), 2); +} + +/// An entry `/keeps-` in a crashed app's area keeps nothing while restore or +/// discard holds that area: both crashed apps' copies are restored, and discarded. +#[test] +fn a_keeps_entry_in_a_crashed_apps_area_held_by_the_same_command_keeps_nothing() { + let crashed = |store: &Arc| { + let mut s = session_in(store); + s.execute("file.recovery.save", &json!({})).unwrap(); + s.recovery.own_area().unwrap().to_string() + }; + for cmd in ["file.recovery.restore", "file.recovery.discard"] { + let store = Arc::new(MemoryStore::default()); + let a = crashed(&store); + let c = crashed(&store); + assert_ne!(a, c); + // The area that sorts first, which the command holds first, keeps the other one's copies. + let (first, second) = if a < c { (a, c) } else { (c, a) }; + store.write(&format!("{first}/keeps-{second}"), b"").unwrap(); + let mut b = relaunch(&store); + assert_eq!(offered(&mut b).len(), 2); + let r = b.execute(cmd, &json!({})).unwrap(); + let done = if cmd == "file.recovery.restore" { restored(r) } else { r["discarded"].as_array().unwrap().len() }; + assert_eq!(done, 2, "{cmd}"); + } +} + +/// An entry `/keeps-` in a folder whose lock file can't be opened keeps nothing. +#[cfg(unix)] +#[test] +fn a_keeps_entry_in_a_folder_whose_lock_cannot_be_checked_keeps_nothing() { + let dir = std::env::temp_dir().join(format!("vc-recovery-keepsunlocked-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let (a, area) = saved_in(&dir); + drop(a); + std::fs::create_dir_all(dir.join("keeper").join(".lock")).unwrap(); + std::fs::write(dir.join("keeper").join(format!("keeps-{area}")), b"").unwrap(); + assert_eq!(offered(&mut other_app(&dir)).len(), 1); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A complex document (Data Recovery off for those) gets no new copy after the session left its +/// area: it keeps the copy it left there, and the heartbeat asks for it only once. +#[cfg(unix)] +#[test] +fn a_complex_documents_copy_left_behind_is_asked_for_once() { + use cmd::recovery::Lock; + let dir = std::env::temp_dir().join(format!("vc-recovery-leftcomplex-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut a = other_app(&dir); + let mut d = vectorcraft_doc::Document::new(1000.0, 1000.0); + let layer = d.layers[0].id; + for i in 0..cmd::recovery::COMPLEX_OBJECTS { + let id = d.alloc_id(); + let r = vectorcraft_geom::Rect::new((i % 200) as f64, (i / 200) as f64, (i % 200) as f64 + 1.0, (i / 200) as f64 + 1.0); + let n = vectorcraft_doc::Node::path(id, vectorcraft_geom::shapes::rectangle(r), vectorcraft_doc::Appearance::default_art()); + d.insert(Some(layer), i, n).unwrap(); + } + a.add_document(d, None); + a.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap(); + let r = a.execute("file.recovery.save", &json!({})).unwrap(); + let copy = r["saved"][0]["file"].as_str().unwrap().to_string(); + let area = a.recovery.own_area().unwrap().to_string(); + a.prefs.recovery_off_for_complex = true; + std::fs::remove_file(dir.join(&area).join(".lock")).unwrap(); + let Ok(Lock::Held(other)) = FolderStore::new(&dir).lock(&area) else { panic!("the other app locks the area") }; + let uid = a.doc().unwrap().uid; + assert_eq!(cmd::recovery::heartbeat(&mut a), [uid]); + let r = a.execute("file.recovery.save", &json!({})).unwrap(); + assert!(r["saved"].as_array().unwrap().is_empty(), "{r}"); + assert!(cmd::recovery::heartbeat(&mut a).is_empty(), "asked for once"); + assert!(dir.join(format!("{copy}.vectorcraft")).is_file(), "its copy stays"); + drop(other); + drop(a); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The preference named another folder while a copy was written in the background: the copy goes +/// from the folder it was written to, and the document keeps its copy in the new folder. +#[test] +fn a_copy_finished_after_the_folder_changed_goes_from_its_own_folder() { + let base = std::env::temp_dir().join(format!("vc-recovery-refolder-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let (old, new) = (base.join("old"), base.join("new")); + let (mut a, area) = saved_in(&old); + a.execute("shape.ellipse", &json!({"x": 10, "y": 10, "width": 5, "height": 5})).unwrap(); + let store: Arc = Arc::new(FolderStore::new(&old)); + let (jobs, _) = cmd::recovery::jobs(&mut a, &store).unwrap(); + a.prefs.recovery_folder = new.to_string_lossy().to_string(); + a.execute("file.recovery.save", &json!({})).unwrap(); + let mine = a.doc().unwrap().recovery.as_ref().unwrap().file.clone(); + for j in jobs { + j.write().unwrap(); + j.finish(&mut a); + } + assert!(!old.join(&area).join("Untitled-1-1.vectorcraft").exists()); + assert_eq!(a.doc().unwrap().recovery.as_ref().unwrap().file, mine); + assert!(new.join(format!("{mine}.vectorcraft")).is_file()); + drop(a); + let _ = std::fs::remove_dir_all(&base); +} + #[test] fn saving_reverting_or_closing_removes_the_copy() { let dir = std::env::temp_dir().join(format!("vc-recovery-save-{}", std::process::id())); @@ -774,6 +1570,71 @@ impl RecoveryStore for DiesAfterDocument { } } +/// Under automation read roots, `file.recovery.save`, `file.recovery.list` and +/// `file.recovery.restore` name a document's file and the recovery folder only inside them. +#[test] +fn recovery_replies_leave_out_paths_outside_the_read_root() { + use crate::file_access::{AutomationRoots, confine}; + use serde_json::Value; + let base = crate::tests_links::Folder::new("recovery-read-root"); + let (inside, outside) = (base.0.join("in"), base.0.join("out")); + std::fs::create_dir_all(&inside).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + let store: Arc = Arc::new(FolderStore::new(outside.join("recovery"))); + let location = outside.join("recovery").to_string_lossy().to_string(); + let kept = inside.join("kept.vectorcraft").to_string_lossy().to_string(); + let hidden = outside.join("hidden.vectorcraft").to_string_lossy().to_string(); + let mut s = Session::new(); + s.recovery.set_store(store.clone()); + for path in [&kept, &hidden] { + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + s.execute("file.saveAs", &json!({"path": path})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap(); + } + let roots = AutomationRoots::new(&[&inside], &[]).unwrap(); + let saved = confine(roots.as_ref(), || s.execute("file.recovery.save", &json!({}))).unwrap(); + assert_eq!(saved["location"], Value::Null, "{saved}"); + s.execute("shape.ellipse", &json!({"x": 80, "y": 20, "width": 20, "height": 20})).unwrap(); + assert_eq!(s.execute("file.recovery.save", &json!({})).unwrap()["location"], json!(location), "the person sees the folder"); + + let sorted = |v: &Value, key: &str| -> Vec { + let mut out: Vec = v[key].as_array().unwrap().iter().map(|c| c["path"].to_string()).collect(); + out.sort(); + out + }; + let both = |first: Value| { + let mut out = vec![first.to_string(), json!(kept).to_string()]; + out.sort(); + out + }; + assert_eq!(sorted(&s.execute("file.recovery.list", &json!({})).unwrap(), "copies"), both(json!(hidden))); + let listed = confine(roots.as_ref(), || s.execute("file.recovery.list", &json!({}))).unwrap(); + assert_eq!((sorted(&listed, "copies"), &listed["location"]), (both(Value::Null), &Value::Null), "{listed}"); + let outside_text = json!(outside.to_string_lossy()).to_string(); + assert!(!listed.to_string().contains(outside_text.trim_matches('"')), "no path outside the root: {listed}"); + // A relative recovery folder is checked as the file system reads it; a store that is no folder + // keeps its name. + let mut relative = Session::new(); + relative.recovery.set_store(Arc::new(FolderStore::new("vc-recovery-relative-folder"))); + let l = confine(roots.as_ref(), || relative.execute("file.recovery.list", &json!({}))).unwrap(); + assert_eq!(l["location"], Value::Null, "{l}"); + let (mut memory, _) = session(); + let l = confine(roots.as_ref(), || memory.execute("file.recovery.list", &json!({}))).unwrap(); + assert_eq!(l["location"], "memory", "{l}"); + + // After a crash, the copies restored. + drop(s); + let mut s = Session::new(); + s.recovery.set_store(store.clone()); + let r = confine(roots.as_ref(), || s.execute("file.recovery.restore", &json!({}))).unwrap(); + assert_eq!(sorted(&r, "restored"), both(Value::Null), "{r}"); + let mut opened: Vec> = s.documents().iter().map(|d| d.path.clone()).collect(); + opened.sort(); + let mut files = vec![Some(hidden), Some(kept)]; + files.sort(); + assert_eq!(opened, files, "the documents keep their files"); +} + /// A crash between writing a copy's document and its details restores the new document with /// every image, the one placed since the last copy too (and the first copy likewise). #[test] diff --git a/crates/engine/src/tests/save.rs b/crates/engine/src/tests/save.rs index d92365a356..99febca6b2 100644 --- a/crates/engine/src/tests/save.rs +++ b/crates/engine/src/tests/save.rs @@ -40,6 +40,99 @@ fn objects(s: &Session) -> usize { s.doc().unwrap().doc.node_count() } +/// A client confined by automation roots: a save without a path writes the document's own file, and +/// when that file is outside the read roots the reply leaves out its `path` and names the files +/// written beside it by their file names. A reply without a path leaves out a suggested `folder` +/// outside them. A path inside the read roots, and one the client gives, stay whole. +#[test] +fn a_confined_save_leaves_out_paths_outside_the_read_root() { + use crate::file_access::{AutomationRoots, confine}; + + let d = dir("roots"); + let (inside, outside) = (d.join("in"), d.join("out")); + for f in [&inside, &outside] { + std::fs::create_dir_all(f).unwrap(); + } + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap(); + rect(&mut s); + let own = path(&outside, "doc.vectorcraft"); + s.execute("document.save", &json!({"path": own})).unwrap(); + let person = s.execute("document.save", &json!({"separateArtboards": true})).unwrap(); + let files: Vec = person["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap().to_string()).collect(); + assert_eq!((files.len(), files[0].as_str()), (3, own.as_str()), "{person}"); + + let write_only = AutomationRoots::new(&[inside.as_path()], &[outside.as_path()]).unwrap(); + let both = AutomationRoots::new(&[inside.as_path(), outside.as_path()], &[outside.as_path()]).unwrap(); + let run = |s: &mut Session, roots: &Option>, id: &str, p: Value| { + confine(roots.as_ref(), || s.execute(id, &p)).unwrap_or_else(|e| panic!("{id} {p}: {e}")) + }; + let hidden = outside.to_string_lossy().into_owned(); + let r = run(&mut s, &write_only, "document.save", json!({})); + assert!(r.get("path").is_none() && r["bytes"].as_u64().is_some_and(|n| n > 0), "{r}"); + assert!(!r.to_string().contains(&hidden), "{r}"); + let r = run(&mut s, &write_only, "document.save", json!({"separateArtboards": true})); + let names: Vec = files.iter().map(|f| json!(std::path::Path::new(f).file_name().unwrap().to_string_lossy())).collect(); + assert_eq!((r.get("path"), r["files"].as_array()), (None, Some(&names)), "{r}"); + // Inside the read roots, or given by the client: whole. + assert_eq!(run(&mut s, &both, "document.save", json!({}))["path"], json!(own)); + assert_eq!(run(&mut s, &write_only, "document.save", json!({"path": own}))["path"], json!(own)); + // A save without a path known suggests the document's folder. + let r = run(&mut s, &write_only, "file.saveCopy", json!({})); + assert!(r.get("folder").is_none() && r["name"] == "doc copy.vectorcraft" && r.get("dataBase64").is_some(), "{r}"); + assert_eq!(run(&mut s, &both, "file.saveCopy", json!({}))["folder"], json!(hidden)); + let _ = std::fs::remove_dir_all(d); +} + +/// A save without a path, and Revert, refused because the document's own file is outside a confined +/// client's roots: the error keeps the root and the reason and names the file by its file name, also +/// for the files a save writes beside it. A path the client gives stays whole in the error. +#[test] +fn pathless_save_rejection_hides_document_folder() { + use crate::file_access::{AutomationRoots, confine}; + + let d = dir("roots-error"); + let (inside, outside) = (d.join("in"), d.join("kept-out")); + for f in [&inside, &outside] { + std::fs::create_dir_all(f).unwrap(); + } + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap(); + rect(&mut s); + let own = path(&outside, "doc.vectorcraft"); + s.execute("document.save", &json!({"path": own})).unwrap(); + rect(&mut s); + let roots = AutomationRoots::new(&[inside.as_path()], &[inside.as_path()]).unwrap(); + let root = crate::cmd::findfiles::plain(std::fs::canonicalize(&inside).unwrap()).display().to_string(); + let hidden = outside.to_string_lossy().into_owned(); + let mut refused = |id: &str, p: Value| confine(roots.as_ref(), || s.execute(id, &p)).unwrap_err().to_string(); + + let e = refused("document.save", json!({})); + assert_eq!(e, format!("automation path rejected: outside the write root {root}: doc.vectorcraft")); + let e = refused("document.save", json!({"separateArtboards": true})); + assert!(e.starts_with(&format!("automation path rejected: outside the write root {root}: ")) && !e.contains(&hidden), "{e}"); + let e = refused("file.revert", json!({})); + assert_eq!(e, format!("automation path rejected: outside the read root {root}: doc.vectorcraft")); + // Given by the client: whole. + let e = refused("document.save", json!({"path": own})); + assert_eq!(e, format!("automation path rejected: outside the write root {root}: {own}")); + // Without read roots, a write refusal still names the file by its file name. + let write_only = AutomationRoots::new(&[], &[inside.as_path()]).unwrap(); + let e = confine(write_only.as_ref(), || s.execute("document.save", &json!({}))).unwrap_err().to_string(); + assert_eq!(e, format!("automation path rejected: outside the write root {root}: doc.vectorcraft")); + assert!(s.doc().unwrap().is_dirty(), "nothing was saved"); + // Read with losses from its own file: the refusal to write over it names the file by its file name. + let st = s.doc_mut().unwrap(); + st.imported_from = Some(own.clone()); + st.import_losses = vec!["hidden text".into()]; + let e = confine(roots.as_ref(), || s.execute("document.save", &json!({}))).unwrap_err().to_string(); + assert!(e.starts_with("invalid parameters for `document.save`: doc.vectorcraft is the file this document was read from"), "{e}"); + assert!(!e.contains(&hidden), "{e}"); + let e = confine(roots.as_ref(), || s.execute("document.save", &json!({"path": own}))).unwrap_err().to_string(); + assert!(e.contains(&format!("{own} is the file this document was read from")), "{e}"); + let _ = std::fs::remove_dir_all(d); +} + #[test] fn an_svg_path_writes_svg_and_save_writes_it_back() { let d = dir("svg"); @@ -425,8 +518,16 @@ fn transparency_grid_round_trips_without_dirtying() { let _ = std::fs::remove_dir_all(d); } +/// The `%%BoundingBox` of an EPS file's PostScript. +fn bounding_box(eps: &[u8]) -> [i64; 4] { + let ps = std::str::from_utf8(vectorcraft_eps::sections(eps).unwrap().0).unwrap(); + let line = ps.lines().find_map(|l| l.strip_prefix("%%BoundingBox:")).expect("a bounding box"); + let v: Vec = line.split_whitespace().map(|n| n.parse().unwrap()).collect(); + [v[0], v[1], v[2], v[3]] +} + #[test] -fn opened_eps_saves_to_its_own_file_with_editable_data_and_page_margins() { +fn opened_eps_saves_to_its_own_file_around_its_art_or_on_its_page() { let d = dir("eps-original-format"); let eps_path = path(&d, "Artwork.eps"); // Original, contributor-authored PostScript: the artwork occupies only part of the page. @@ -440,11 +541,16 @@ fn opened_eps_saves_to_its_own_file_with_editable_data_and_page_margins() { assert_eq!((board.width(), board.height()), (200.0, 100.0)); rect(&mut s); let edited_layers = s.doc().unwrap().doc.layers.clone(); - let r = s.execute("document.save", &json!({"options": {"previewFormat": "none", "thumbnails": false}})).unwrap(); + // Without Use Artboards the bounding box fits the art, as Export draws it; the editing data + // keeps the page. + let quiet = json!({"previewFormat": "none", "thumbnails": false}); + let r = s.execute("document.save", &json!({"options": quiet})).unwrap(); assert_eq!((r["path"].as_str(), r["format"].as_str()), (Some(eps_path.as_str()), Some("eps"))); let bytes = std::fs::read(&eps_path).unwrap(); assert!(bytes.starts_with(b"%!PS-Adobe-3.0 EPSF-3.0")); - assert!(std::str::from_utf8(vectorcraft_eps::sections(&bytes).unwrap().0).unwrap().contains("%%BoundingBox: 0 0 200 100")); + let exported = b64(&s.execute("document.export", &json!({"format": "eps", "previewFormat": "none", "thumbnails": false})).unwrap()); + assert_eq!(bounding_box(&bytes), bounding_box(&exported)); + assert_ne!(bounding_box(&bytes), [0, 0, 200, 100], "the art does not fill the page"); let editing = vectorcraft_format::load(&vectorcraft_eps::native(&bytes).unwrap()).unwrap(); assert_eq!(editing.artboards[0].rect, board); assert_eq!(editing.layers, edited_layers); @@ -453,26 +559,125 @@ fn opened_eps_saves_to_its_own_file_with_editable_data_and_page_margins() { assert_eq!(opened["restored"], true); assert_eq!(s.doc().unwrap().doc.layers, edited_layers); assert_eq!(s.doc().unwrap().doc.artboards[0].rect, board); + // Use Artboards keeps the opened file's page. + rect(&mut s); + s.execute("document.save", &json!({"options": {"useArtboards": true, "previewFormat": "none", "thumbnails": false}})).unwrap(); + assert_eq!(s.doc().unwrap().path.as_deref(), Some(eps_path.as_str())); + assert_eq!(bounding_box(&std::fs::read(&eps_path).unwrap()), [0, 0, 200, 100]); + // Save remembers it. rect(&mut s); s.execute("document.save", &json!({})).unwrap(); - assert_eq!(s.doc().unwrap().path.as_deref(), Some(eps_path.as_str())); + assert_eq!(bounding_box(&std::fs::read(&eps_path).unwrap()), [0, 0, 200, 100]); std::fs::remove_dir_all(d).unwrap(); } #[test] -fn eps_save_keeps_all_editing_artboards_while_printing_one_page() { +fn eps_save_without_use_artboards_fits_the_box_to_art_past_the_artboard() { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": -50, "y": 20, "width": 300, "height": 40})).unwrap(); + let quiet = json!({"previewFormat": "none", "thumbnails": false}); + let r = s.execute("document.save", &json!({"format": "eps", "options": quiet})).unwrap(); + let [x0, y0, x1, y1] = bounding_box(&b64(&r)); + assert!(x0 <= -50 && x1 >= 250 && y0 >= 0 && y1 <= 100, "{:?}", [x0, y0, x1, y1]); + for (use_artboards, expected) in [(false, [x0, y0, x1, y1]), (true, [0, 0, 200, 100])] { + let options = json!({"useArtboards": use_artboards, "previewFormat": "none", "thumbnails": false}); + let r = s.execute("document.save", &json!({"format": "eps", "options": options})).unwrap(); + assert_eq!(bounding_box(&b64(&r)), expected, "useArtboards: {use_artboards}"); + } +} + +#[test] +fn eps_save_keeps_all_editing_artboards_in_the_file_of_one_page() { let mut s = Session::new(); s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap(); rect(&mut s); let r = s.execute("document.save", &json!({"format": "eps", "artboard": 1, "previewFormat": "none", "thumbnails": false})).unwrap(); let bytes = b64(&r); + assert!(r.get("files").is_none(), "{r}"); + let board = s.doc().unwrap().doc.artboards[1].rect; + let [x0, y0, x1, y1] = bounding_box(&bytes); + assert_eq!(((x1 - x0) as f64, (y1 - y0) as f64), (board.width(), board.height())); let native = vectorcraft_format::load(&vectorcraft_eps::native(&bytes).unwrap()).unwrap(); assert_eq!(native.artboards.len(), 2); assert_eq!(native.layers, s.doc().unwrap().doc.layers); - assert!(s.execute("document.save", &json!({"format": "eps", "range": "all"})).is_err(), "EPS is one printed page"); - for options in [json!({"useArtboards": false}), json!({"selectedOnly": true})] { - assert!(s.execute("document.save", &json!({"format": "eps", "options": options})).is_err(), "cropping is Export's job"); + assert!(s.execute("document.save", &json!({"format": "eps", "options": {"selectedOnly": true}})).is_err(), "selected-only is Export's job"); +} + +#[test] +fn eps_save_with_use_artboards_and_a_named_artboard_reports_it_as_the_range() { + let d = dir("eps-named-artboard"); + let eps_path = path(&d, "Art.eps"); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap(); + rect(&mut s); + let options = json!({"useArtboards": true, "artboard": 1, "previewFormat": "none", "thumbnails": false}); + s.execute("document.save", &json!({"path": eps_path, "options": options})).unwrap(); + let o = s.execute("file.formatOptions", &json!({})).unwrap(); + assert_eq!(o["options"]["useArtboards"]["value"], true); + assert_eq!(o["options"]["range"]["value"], "2", "the saved artboard, not All"); + std::fs::remove_dir_all(d).unwrap(); +} + +#[test] +fn eps_save_with_use_artboards_refuses_to_replace_the_file_read_from_before_writing_any_file() { + let d = dir("eps-artboards-lossy-sibling"); + let eps_path = path(&d, "Art.eps"); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap(); + rect(&mut s); + let options = json!({"useArtboards": true, "previewFormat": "none", "thumbnails": false}); + let r = s.execute("document.save", &json!({"path": eps_path, "options": options})).unwrap(); + let sibling = r["files"][1].as_str().unwrap().to_string(); + let original = std::fs::read(&sibling).unwrap(); + std::fs::remove_file(&eps_path).unwrap(); + let st = s.doc_mut().unwrap(); + st.imported_from = Some(sibling.clone()); + st.import_losses.push("test import omitted artwork".into()); + let err = s.execute("document.save", &json!({"path": eps_path, "options": options})).unwrap_err().to_string(); + assert!(err.contains("acknowledgeLoss") && err.contains(&sibling), "{err}"); + assert_eq!(std::fs::read(&sibling).unwrap(), original); + assert!(!std::path::Path::new(&eps_path).exists(), "no file of the set is written when one is refused"); + s.execute("document.save", &json!({"path": eps_path, "options": options, "acknowledgeLoss": true})).unwrap(); + assert!(std::path::Path::new(&eps_path).exists()); + std::fs::remove_dir_all(d).unwrap(); +} + +#[test] +fn eps_save_with_use_artboards_writes_the_central_file_and_one_per_artboard() { + let d = dir("eps-artboards"); + let eps_path = path(&d, "Art.eps"); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap(); + rect(&mut s); + let options = json!({"useArtboards": true, "previewFormat": "none", "thumbnails": false}); + let r = s.execute("document.save", &json!({"path": eps_path, "options": options})).unwrap(); + let files: Vec = r["files"].as_array().expect("files").iter().map(|f| f.as_str().unwrap().to_string()).collect(); + assert_eq!(files.len(), 3, "{r}"); + assert_eq!(files[0], eps_path, "the file the document becomes comes first"); + assert!(files[1..].iter().all(|f| f.starts_with(&path(&d, "Art_")) && f.ends_with(".eps")), "{files:?}"); + // The central file: the visible art and the whole document. + let central = std::fs::read(&eps_path).unwrap(); + let exported = b64(&s.execute("document.export", &json!({"format": "eps", "previewFormat": "none", "thumbnails": false})).unwrap()); + assert_eq!(bounding_box(¢ral), bounding_box(&exported)); + assert_eq!(vectorcraft_format::load(&vectorcraft_eps::native(¢ral).unwrap()).unwrap().artboards.len(), 2); + // Each artboard's file: its artboard as the page, holding that artboard. + let boards = s.doc().unwrap().doc.artboards.clone(); + for (f, board) in files[1..].iter().zip(&boards) { + let bytes = std::fs::read(f).unwrap(); + let [x0, y0, x1, y1] = bounding_box(&bytes); + assert_eq!(((x1 - x0) as f64, (y1 - y0) as f64), (board.rect.width(), board.rect.height()), "{f}"); + let native = vectorcraft_format::load(&vectorcraft_eps::native(&bytes).unwrap()).unwrap(); + assert_eq!(native.artboards.iter().map(|a| a.rect).collect::>(), [board.rect], "{f}"); } + let st = s.doc().unwrap(); + assert_eq!((st.path.as_deref(), st.is_dirty()), (Some(eps_path.as_str()), false)); + // With no visible art the central file is still written, on the first artboard. + s.execute("select.all", &json!({})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + std::fs::remove_file(&eps_path).unwrap(); + s.execute("document.save", &json!({})).unwrap(); + assert_eq!(bounding_box(&std::fs::read(&eps_path).unwrap()), [0, 0, 200, 100]); + std::fs::remove_dir_all(d).unwrap(); } #[test] @@ -550,7 +755,7 @@ fn eps_save_bounds_large_page_preview_without_cropping_vector_or_editing_data() s.execute("file.new", &json!({"width": 4000, "height": 4000})).unwrap(); rect(&mut s); // Explicit colour preview remains a colour preview; Save bounds its resolution, not the art. - let r = s.execute("document.save", &json!({"format": "eps", "previewFormat": "tiffColor"})).unwrap(); + let r = s.execute("document.save", &json!({"format": "eps", "useArtboards": true, "previewFormat": "tiffColor"})).unwrap(); let bytes = b64(&r); let (ps, tiff) = vectorcraft_eps::sections(&bytes).unwrap(); let tiff = tiff.unwrap(); @@ -584,3 +789,29 @@ fn units_and_ruler_guides_survive_save_and_reopen() { } let _ = std::fs::remove_dir_all(d); } + +/// A ruler guide hidden or locked on its own (the Layers panel's eye and lock on its row, +/// `layer.setProps` on its node) stays so through Save, Close and Open, and the other guide stays +/// visible and unlocked. +#[test] +fn a_guide_hidden_or_locked_on_its_own_survives_save_and_reopen() { + let d = dir("guide-flags"); + for ext in ["vectorcraft", "pdf", "ai", "eps"] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + for pos in [10, 20, 30] { + s.execute("guide.add", &json!({"vertical": true, "pos": pos})).unwrap(); + } + rect(&mut s); + let ids: Vec = s.doc().unwrap().doc.ruler_guides().iter().map(|g| g.id.unwrap().0).collect(); + s.execute("layer.setProps", &json!({"ids": [ids[1]], "visible": false})).unwrap(); + s.execute("layer.setProps", &json!({"ids": [ids[2]], "locked": true})).unwrap(); + let p = path(&d, &format!("a.{ext}")); + s.execute("document.save", &json!({"path": p})).unwrap(); + s.execute("file.close", &json!({})).unwrap(); + s.execute("document.open", &json!({"path": p})).unwrap(); + let flags: Vec<_> = s.doc().unwrap().doc.ruler_guides().iter().map(|g| (g.pos, g.hidden, g.locked)).collect(); + assert_eq!(flags, [(10.0, false, false), (20.0, true, false), (30.0, false, true)], "{ext}"); + } + let _ = std::fs::remove_dir_all(d); +} diff --git a/crates/engine/src/tests/script_console.rs b/crates/engine/src/tests/script_console.rs index 27f53cef07..48d5c8ed0a 100644 --- a/crates/engine/src/tests/script_console.rs +++ b/crates/engine/src/tests/script_console.rs @@ -265,3 +265,31 @@ fn the_slowest_commands_are_the_longest_in_all_then_by_id() { assert_eq!(ids, ["b.two", "a.one", "c.three", "f", "e"]); assert_eq!((slow[0].calls, slow[0].total_ms, slow[0].max_ms), (3, 9, 4)); } + +/// Under automation read roots, the error lines of a failed run name the included file it stopped +/// in by its file name also when the console cut a line inside the file's path. +#[test] +fn a_cut_error_line_leaves_out_an_included_files_folder_outside_the_read_root() { + use crate::file_access::{AutomationRoots, confine}; + let base = crate::tests_links::Folder::new("script-report-cut-line"); + let inside = base.0.join("in"); + std::fs::create_dir_all(&inside).unwrap(); + // A path longer than a console line, as the report of a failed run names it. + let file = base.0.join("out").join("d".repeat(MAX_LINE_BYTES)).join("bad.jsxinc").to_string_lossy().to_string(); + let mut report = json!({"ok": false, "name": "t.js", "file": file, "line": 2, "column": 7, "message": format!("Error: stopped\nin {file}")}); + let error = script::error_lines(&report); + assert!(error.len() == 2 && error.iter().all(|l| l.len() <= MAX_LINE_BYTES && l.ends_with(CUT_MARK)), "both lines are cut: {error:?}"); + let written: Vec = std::iter::once("written by the script".to_string()).chain(error).collect(); + report["console"] = json!({"lines": written, "droppedLines": 0, "truncatedLines": 2}); + let mut s = Session::new(); + s.script_report = Some(report.clone()); + + let roots = AutomationRoots::new(&[&inside], &[]).unwrap(); + let shown = confine(roots.as_ref(), || s.shown_script_report()).unwrap(); + assert_eq!((&shown["file"], &shown["message"]), (&json!("bad.jsxinc"), &json!("Error: stopped\nin bad.jsxinc")), "{shown}"); + assert_eq!(shown["console"]["lines"], json!(["written by the script", "t.js: bad.jsxinc:2:7: Error: stopped", "in bad.jsxinc"]), "{shown}"); + let outside = json!(base.0.join("out").to_string_lossy()).to_string(); + assert!(!shown.to_string().contains(outside.trim_matches('"')), "no path outside the root: {shown}"); + // The person sees the report as it is. + assert_eq!(s.shown_script_report(), Some(report)); +} diff --git a/crates/engine/src/tests/script_dialogs.rs b/crates/engine/src/tests/script_dialogs.rs index 7572ca52f0..f955a6fdb3 100644 --- a/crates/engine/src/tests/script_dialogs.rs +++ b/crates/engine/src/tests/script_dialogs.rs @@ -217,6 +217,26 @@ fn dialog_loop_stops_or_exhausts() { assert_eq!(art(&s), before); } +#[test] +fn a_run_waiting_at_a_dialog_stops_at_the_next_slice_once_its_work_is_canceled() { + let mut s = one_doc(); + let before = art(&s); + let token = crate::cancel::CancelToken::new(); + s.script_frames = true; + let source = "vc.run('shape.rectangle', {x: 20, y: 0, width: 5, height: 5}); alert('x'); vc.log('answered');"; + assert_eq!(s.execute("script.run", &json!({"source": source, "name": "d.js"})).unwrap()["running"], true); + assert!(crate::cancel::scope(&token, None, || s.script_pump()).is_none()); + assert!(s.script_dialog().is_some()); + token.cancel(); + let ended = crate::cancel::scope(&token, None, || s.script_pump()); + assert!(ended.expect("the run goes on waiting for an answer").is_err()); + let report = s.script_report().unwrap(); + assert_eq!((report["kind"].as_str(), &report["log"]), (Some("stopped"), &json!([])), "{report}"); + assert_eq!(report["dialogs"][0]["answer"], "stop"); + assert_eq!(s.script_dialog(), None); + assert_eq!(art(&s), before); +} + #[test] fn dialog_text_limits_and_controls() { let mut s = one_doc(); diff --git a/crates/engine/src/tests/script_dollar.rs b/crates/engine/src/tests/script_dollar.rs index d5b9624500..849d5b9080 100644 --- a/crates/engine/src/tests/script_dollar.rs +++ b/crates/engine/src/tests/script_dollar.rs @@ -5,6 +5,7 @@ use std::time::Duration; use serde_json::{Value, json}; +use crate::cancel::{self, CancelToken}; use crate::script::{TEST_ELAPSED, TEST_NO_CLOCK}; use crate::*; @@ -62,7 +63,7 @@ fn each_member_has_its_value() { ("$.memCache", json!(0)), ("$.os", json!(os)), ("$.screens.length", json!(0)), - ("$.stack", json!("[global]:1\n")), + ("$.stack", json!("[global]@t.js:1\n")), ("$.strict", json!(false)), ("$.version", json!(version)), ("typeof $.getenv + typeof $.setenv + typeof $.sleep", json!("functionfunctionfunction")), @@ -164,7 +165,7 @@ fn getenv_reads_only_its_names_and_setenv_changes_only_the_run() { fn error_line_and_stack_follow_the_running_code() { let mut s = Session::new(); let source = "try { null.x; } catch (e) {}\nfunction where() {\n return [$.line, $.stack, $.error instanceof TypeError];\n}\nvc.log(where());"; - assert_eq!(logged(&mut s, source)[0], json!([3, "[global]:5\nwhere:3\n", true])); + assert_eq!(logged(&mut s, source)[0], json!([3, "[global]@t.js:5\nwhere@t.js:3\n", true])); assert_eq!(value(&mut s, "$.error"), json!(null), "each run starts without one"); } @@ -204,6 +205,36 @@ fn a_sleeping_run_stops_when_asked() { TEST_ELAPSED.set(None); } +#[test] +fn a_sleeping_run_stops_at_the_next_slice_once_its_work_is_canceled() { + for (asleep_until, when) in + [(None, "before its first slice"), (Some(Duration::ZERO), "while it sleeps"), (Some(Duration::from_secs(1)), "at its wake time")] + { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let before = (format!("{:?}", s.documents()[0].doc.layers), s.documents()[0].history.undo.len()); + s.script_frames = true; + TEST_ELAPSED.set(Some(Duration::ZERO)); + let source = "vc.run('shape.rectangle', {x: 0, y: 0, width: 5, height: 5}); $.sleep(1000); vc.log('woke'); \ + vc.run('shape.rectangle', {x: 9, y: 0, width: 5, height: 5});"; + s.execute("script.run", &json!({"source": source, "name": "t.js"})).unwrap(); + let token = CancelToken::new(); + if let Some(at) = asleep_until { + assert!(cancel::scope(&token, None, || s.script_pump()).is_none(), "{when}"); + assert_eq!(s.script_sleep_left(), Some(Duration::from_secs(1)), "{when}"); + TEST_ELAPSED.set(Some(at)); + } + token.cancel(); + let ended = cancel::scope(&token, None, || s.script_pump()); + TEST_ELAPSED.set(None); + assert!(ended.unwrap_or_else(|| panic!("{when}: the run goes on waiting")).is_err(), "{when}"); + let report = s.script_report().unwrap(); + assert_eq!((report["kind"].as_str(), &report["log"]), (Some("stopped"), &json!([])), "{when}: {report}"); + assert!(!s.script_running(), "{when}"); + assert_eq!((format!("{:?}", s.documents()[0].doc.layers), s.documents()[0].history.undo.len()), before, "{when}"); + } +} + #[test] fn sleep_takes_milliseconds_from_0_to_1000() { let mut s = Session::new(); diff --git a/crates/engine/src/tests/script_engines.rs b/crates/engine/src/tests/script_engines.rs new file mode 100644 index 0000000000..a25b0489ba --- /dev/null +++ b/crates/engine/src/tests/script_engines.rs @@ -0,0 +1,639 @@ +//! `#targetengine`: named engines whose globals last between the runs that name them, their names +//! and places, their limits, `script.engines` and `script.engine.drop`. + +use std::path::PathBuf; +use std::sync::Arc; + +use serde_json::{Value, json}; + +use crate::script::{PANIC_IN_SLICE, TEST_ENGINE_HEAP, TEST_KEPT_MAP_BYTES, engines_on_this_thread, releases_kept_for}; +use crate::*; + +fn run(s: &mut Session, source: &str) -> Result { + s.execute("script.run", &json!({"source": source, "name": "t.js"})) +} + +fn log(s: &mut Session, source: &str) -> Value { + run(s, source).unwrap()["log"].clone() +} + +/// A session with one document holding one rectangle. +fn one_doc() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + s +} + +fn objects(s: &Session) -> usize { + s.documents()[0].doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum() +} + +fn names(s: &mut Session) -> Vec { + let r = s.execute("script.engines", &json!({})).unwrap(); + r["engines"].as_array().unwrap().iter().map(|e| e["name"].as_str().unwrap().to_string()).collect() +} + +const RECT: &str = "{x: 100, y: 0, width: 5, height: 5}"; + +#[test] +fn a_named_engine_keeps_its_globals_and_functions_between_runs() { + let mut s = Session::new(); + assert_eq!(log(&mut s, "#targetengine \"session\"\nvar n = 41;\nfunction f() { return n + 1; }\nvc.log($.engineName);"), json!(["session"])); + assert_eq!(log(&mut s, "//@targetengine session\nvc.log(f()); n = 1;"), json!([42])); + assert_eq!(log(&mut s, "#targetengine 'session'\nvc.log(n);"), json!([1]), "single quotes name the same engine"); + assert_eq!(log(&mut s, "#targetengine Session\nvc.log(typeof n);"), json!(["undefined"]), "names are matched as written"); + assert_eq!(log(&mut s, "#targetengine other\nvc.log(typeof f);"), json!(["undefined"])); + assert_eq!(log(&mut s, "vc.log(typeof n, $.engineName);\nvc.log($.engineName);"), json!(["undefined", "VectorCraft"])); + // `main` is new for each run, as a script without the line is. + log(&mut s, "#targetengine main\nvar m = 1;"); + assert_eq!(log(&mut s, "#targetengine main\nvc.log(typeof m, $.engineName);\nvc.log($.engineName);"), json!(["undefined", "main"])); + assert_eq!(names(&mut s), ["session", "Session", "other"]); + assert_eq!(log(&mut s, "#targetengine \"Ünï cödé 1\"\nvc.log($.engineName);"), json!(["Ünï cödé 1"])); + let r = s.execute("script.run", &json!({"source": "#targetengine session\n$.engineName = 'x'; vc.log($.engineName);"})).unwrap(); + assert_eq!(r["log"], json!(["session"]), "$.engineName is read-only"); +} + +#[test] +fn engine_names_and_places_are_checked_before_anything_runs() { + let mut s = Session::new(); + let long = "a".repeat(65); + let control = "#targetengine \"a\u{1}b\""; + let cases: Vec<(String, &str, u64)> = vec![ + ("#targetengine".into(), "#targetengine needs a name", 1), + ("#targetengine \"\"".into(), "#targetengine needs a name", 1), + ("#targetengine a b".into(), "#targetengine needs a name of letters, digits and _", 1), + ("#targetengine 9a".into(), "#targetengine needs a name of letters, digits and _", 1), + ("#targetengine \"a\" \"b\"".into(), "#targetengine takes one name", 1), + (format!("#targetengine \"{long}\""), "#targetengine needs a name of at most 64 bytes", 1), + (format!("#targetengine {long}"), "#targetengine needs a name of at most 64 bytes", 1), + (control.into(), "#targetengine needs a name without control characters", 1), + ("#targetengine a\n//@targetengine a".into(), "the script has more than one //@targetengine line", 2), + ("var x;\n#targetengine a".into(), "#targetengine must come before the script's code and #include lines", 2), + ("/* a */ 1;\n#targetengine a".into(), "#targetengine must come before the script's code and #include lines", 2), + ]; + for (source, message, line) in &cases { + let e = run(&mut s, &format!("{source}\nvc.log(1);")).unwrap_err().to_string(); + assert!(e.contains(message), "{source}: {e}"); + assert_eq!(s.script_report().unwrap()["line"], *line, "{source}"); + assert_eq!(s.script_report().unwrap()["log"], json!([]), "{source}"); + } + assert!(names(&mut s).is_empty(), "no failed line made an engine"); + let ok = format!( + "// a comment\n/* and\n another */\n#target vectorcraft\n#script \"Named\"\n #targetengine \"{}\"\nvc.log($.engineName.length);", + "b".repeat(64) + ); + assert_eq!(log(&mut s, &ok), json!([64])); + // A script that does not start: an engine it would make is not kept. + assert!(run(&mut s, "#targetengine broken\nvar = 1;").is_err()); + assert_eq!(names(&mut s), ["b".repeat(64)]); +} + +#[test] +fn only_the_script_itself_names_its_engine() { + let base: PathBuf = std::env::temp_dir().join(format!("vc-script-engines-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(&base).unwrap(); + std::fs::write(base.join("lib.jsxinc"), "#targetengine lib\nvar a = 1;").unwrap(); + let main = base.join("main.jsx"); + let mut s = Session::new(); + for text in ["#include \"lib.jsxinc\"\n", "$.evalFile('lib.jsxinc');\n"] { + std::fs::write(&main, text).unwrap(); + let e = s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap_err().to_string(); + assert!(e.contains("#targetengine may only be in the script itself, not in a file it runs"), "{text}: {e}"); + assert!(s.script_report().unwrap()["file"].as_str().unwrap().ends_with("lib.jsxinc"), "{text}"); + } + std::fs::write(base.join("ok.jsxinc"), "var a = 1;").unwrap(); + std::fs::write(&main, "#include \"ok.jsxinc\"\n#targetengine e\n").unwrap(); + let e = s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap_err().to_string(); + assert!(e.contains("#targetengine must come before the script's code and #include lines"), "{e}"); + assert_eq!(s.script_report().unwrap()["line"], 2); + // An error in a file $.evalFile runs is at that file's place in a kept engine's later runs too. + std::fs::write(base.join("bad.jsxinc"), "var b;\nthrow new Error('here');").unwrap(); + std::fs::write(&main, "#targetengine e\n$.evalFile('ok.jsxinc');").unwrap(); + s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap(); + std::fs::write(&main, "#targetengine e\n$.evalFile('bad.jsxinc');").unwrap(); + assert!(s.execute("script.run", &json!({"path": main.to_string_lossy()})).is_err()); + let report = s.script_report().unwrap().clone(); + assert!(report["file"].as_str().is_some_and(|f| f.ends_with("bad.jsxinc")), "{report}"); + assert_eq!(report["line"], 2, "{report}"); + assert_eq!(names(&mut s), ["e"]); + let _ = std::fs::remove_dir_all(base); + // An error in a function an earlier run defined is at that run's line; a script given as text + // is named by its run's name. + run(&mut s, "#targetengine e\n\n\n\nfunction bad() { throw new Error('kept'); }").unwrap(); + let e = run(&mut s, "#targetengine e\nbad();").unwrap_err().to_string(); + let report = s.script_report().unwrap().clone(); + assert_eq!((report["name"].as_str(), report["file"].as_str(), report["line"].as_u64()), (Some("t.js"), Some("t.js"), Some(5)), "{report}"); + let column = report["column"].as_u64().unwrap(); + assert_eq!(error_lines(&report), [format!("t.js: t.js:5:{column}: Error: kept")]); + assert!(e.contains(&format!("line 5, column {column} of t.js")), "{e}"); +} + +/// The console error lines of a run's report. +fn error_lines(report: &Value) -> Vec { + let lines = report["console"]["lines"].as_array().unwrap(); + lines.iter().filter_map(Value::as_str).filter(|l| l.contains("Error: ")).map(str::to_string).collect() +} + +/// The file, line and column of the last run's error. +fn place(s: &Session) -> (Option, u64, u64) { + let r = s.script_report().unwrap(); + (r["file"].as_str().map(str::to_string), r["line"].as_u64().unwrap(), r["column"].as_u64().unwrap()) +} + +/// An error in code an earlier run of a named engine compiled is at the place of that code: in that +/// run's script, a file it included or a file `$.evalFile` gave, while the report and the console +/// line keep the calling run's name. +#[test] +fn an_error_in_code_an_earlier_run_kept_is_at_that_runs_file_and_line() { + let base: PathBuf = std::env::temp_dir().join(format!("vc-script-engines-places-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(&base).unwrap(); + std::fs::write(base.join("inc.jsxinc"), "\nfunction fromInclude() { throw new Error('inc'); }").unwrap(); + std::fs::write(base.join("ev.jsxinc"), "\n\n\nfunction fromEval() { throw new Error('ev'); }").unwrap(); + let def = base.join("def.jsx"); + let text = "#targetengine e\n#include \"inc.jsxinc\"\n$.evalFile('ev.jsxinc');\nfunction fromMain() {\n throw new Error('main');\n}\n\ + function spin() {\n while (true) {}\n}\nfunction badEval() {\n eval('var = 1');\n}"; + std::fs::write(&def, text).unwrap(); + let mut s = Session::new(); + s.execute("script.run", &json!({"path": def.to_string_lossy()})).unwrap(); + let call = |s: &mut Session, code: &str| { + let e = s.execute("script.run", &json!({"source": format!("#targetengine e\n\n{code}"), "name": "caller.js"})); + assert!(e.is_err(), "{code}"); + }; + let shown = def.to_string_lossy().to_string(); + let ends = |p: &(Option, u64, u64), file: &str, line: u64| p.0.as_deref().is_some_and(|f| f.ends_with(file)) && p.1 == line && p.2 > 0; + call(&mut s, "fromMain();"); + let p = place(&s); + assert!(ends(&p, "def.jsx", 5), "{p:?}"); + let report = s.script_report().unwrap().clone(); + assert_eq!(report["name"], "caller.js"); + assert_eq!(error_lines(&report), [format!("caller.js: {}:5:{}: Error: main", p.0.as_deref().unwrap(), p.2)]); + call(&mut s, "fromInclude();"); + assert!(ends(&place(&s), "inc.jsxinc", 2), "{:?}", place(&s)); + call(&mut s, "fromEval();"); + assert!(ends(&place(&s), "ev.jsxinc", 4), "{:?}", place(&s)); + call(&mut s, "badEval();"); + assert!(ends(&place(&s), "def.jsx", 11), "a syntax error eval raises is at its call: {:?}", place(&s)); + let e = s.execute("script.run", &json!({"source": "#targetengine e\nspin();", "name": "caller.js", "maxFuel": 100_000})); + assert!(e.is_err()); + assert_eq!(s.script_report().unwrap()["kind"], "limit"); + assert!(ends(&place(&s), "def.jsx", 8), "the fuel ran out in spin: {:?}", place(&s)); + // A caught error thrown again is where that throw is, in the calling run. + call(&mut s, "try { fromMain(); } catch (x) {\n throw x;\n}"); + assert_eq!(place(&s), (None, 4, 3)); + // A run that fails before it starts compiles nothing, and the kept places stay. + assert!(run(&mut s, "#targetengine e\n#include \"missing.jsxinc\"").is_err()); + call(&mut s, "fromMain();"); + assert!(ends(&place(&s), "def.jsx", 5), "{:?}", place(&s)); + assert!(place(&s).0.is_some_and(|f| f == shown)); + // A dropped engine takes its places with it: the new one has its own. + s.execute("script.engine.drop", &json!({"name": "e"})).unwrap(); + run(&mut s, "#targetengine e\nfunction fromMain() { throw new Error('new'); }").unwrap(); + call(&mut s, "fromMain();"); + assert_eq!(place(&s).0.as_deref(), Some("t.js")); + assert_eq!(place(&s).1, 2); + // The name stands for the earlier script as that run's report gave it, not as console lines + // show it. + s.execute("script.run", &json!({"source": "#targetengine e\nfunction named() { throw 1; }", "name": "a\u{1}b.js"})).unwrap(); + call(&mut s, "named();"); + assert_eq!(place(&s).0.as_deref(), Some("a\u{1}b.js")); + let _ = std::fs::remove_dir_all(base); +} + +/// `$.fileName` in code an earlier run of a named engine kept names the file that code is in: that +/// run's script, a file it included or a file `$.evalFile` gave, not the file of the run that calls +/// it. Code from a script given as text, and code whose place the engine no longer keeps, has no +/// name; a dropped engine takes its functions with it. +#[test] +fn a_kept_function_reads_the_file_name_of_the_file_it_is_in() { + let base: PathBuf = std::env::temp_dir().join(format!("vc-script-engines-file-name-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + for dir in ["a", "b"] { + std::fs::create_dir_all(base.join(dir)).unwrap(); + } + std::fs::write(base.join("a/inc.jsxinc"), "function fromInclude() { return $.fileName; }").unwrap(); + std::fs::write(base.join("a/ev.jsxinc"), "\nfunction fromEval() { return $.fileName; }").unwrap(); + let def = base.join("a/def.jsx"); + std::fs::write(&def, "#targetengine e\nfunction where() { return $.fileName; }\n#include \"inc.jsxinc\"\n$.evalFile('ev.jsxinc');").unwrap(); + let caller = base.join("b/caller.jsx"); + let call = |s: &mut Session, text: &str| -> Vec { + std::fs::write(&caller, text).unwrap(); + let r = s.execute("script.run", &json!({"path": caller.to_string_lossy()})).unwrap(); + r["log"][0].as_array().unwrap().iter().map(|v| v.as_str().unwrap().replace('\\', "/")).collect() + }; + let mut s = Session::new(); + s.execute("script.run", &json!({"path": def.to_string_lossy()})).unwrap(); + let from_file = call(&mut s, "#targetengine e\nvc.log([where(), fromInclude(), fromEval(), $.fileName]);"); + let from_text = log(&mut s, "#targetengine e\nvc.log([where(), $.fileName, eval('where()'), eval('$.fileName')]);"); + run(&mut s, "#targetengine e\nfunction fromText() { return $.fileName; }").unwrap(); + let text_kept = call(&mut s, "#targetengine e\nvc.log([fromText(), $.fileName]);"); + // Each run's own place takes the room of the ones before, so def.jsx's places go. + TEST_KEPT_MAP_BYTES.with(|b| b.set(Some(300))); + for _ in 0..20 { + run(&mut s, "#targetengine e\nvar x = 1;").unwrap(); + } + let evicted = call(&mut s, "#targetengine e\nvc.log([where(), fromEval(), $.fileName]);"); + TEST_KEPT_MAP_BYTES.with(|b| b.set(None)); + s.execute("script.engine.drop", &json!({"name": "e"})).unwrap(); + let dropped = log(&mut s, "#targetengine e\nvc.log(typeof where);"); + let _ = std::fs::remove_dir_all(&base); + let ends = |names: &[String], ends: &[&str]| names.len() == ends.len() && names.iter().zip(ends).all(|(n, e)| n.ends_with(e)); + assert!(ends(&from_file, &["a/def.jsx", "a/inc.jsxinc", "a/ev.jsxinc", "b/caller.jsx"]), "{from_file:?}"); + let shown: Vec = from_text[0].as_array().unwrap().iter().map(|v| v.as_str().unwrap().replace('\\', "/")).collect(); + assert!(ends(&shown, &["a/def.jsx", "", "a/def.jsx", ""]) && shown[1].is_empty() && shown[3].is_empty(), "{shown:?}"); + assert!(text_kept[0].is_empty() && text_kept[1].ends_with("b/caller.jsx"), "{text_kept:?}"); + assert!(evicted[0].is_empty() && evicted[1].is_empty() && evicted[2].ends_with("b/caller.jsx"), "{evicted:?}"); + assert_eq!(dropped, json!(["undefined"])); +} + +/// A named engine keeps the places of its earlier runs' code within its budget, the oldest going +/// first, and the code still runs once its place is gone. +#[test] +fn an_engine_keeps_the_newest_places_within_its_budget() { + let mut s = Session::new(); + run(&mut s, "#targetengine e\nfunction a() { throw new Error('a'); }").unwrap(); + TEST_KEPT_MAP_BYTES.with(|b| b.set(Some(300))); + run(&mut s, "#targetengine e\n\nfunction b() { throw new Error('b'); }").unwrap(); + for _ in 0..20 { + run(&mut s, "#targetengine e\nvar x = 1;").unwrap(); + } + run(&mut s, "#targetengine e\n\n\nfunction c() { throw new Error('c'); }").unwrap(); + // Each run's own map takes the room of the one before, so c is called first. + assert!(run(&mut s, "#targetengine e\nc();").is_err()); + let c_place = place(&s); + let a = run(&mut s, "#targetengine e\na();").map(drop); + let a_place = place(&s); + TEST_KEPT_MAP_BYTES.with(|b| b.set(Some(1))); + run(&mut s, "#targetengine e\n\n\n\nfunction d() { throw new Error('d'); }").unwrap(); + assert!(run(&mut s, "#targetengine e\nd();").is_err()); + let d_place = place(&s); + TEST_KEPT_MAP_BYTES.with(|b| b.set(None)); + assert!(a.is_err()); + assert_eq!((a_place.0, a_place.1, a_place.2), (None, 0, 0), "a's place went to make room"); + assert_eq!((c_place.0.as_deref(), c_place.1), (Some("t.js"), 4)); + assert_eq!((d_place.0, d_place.1, d_place.2), (None, 0, 0), "a map larger than the budget is not kept"); +} + +/// `$.line` and `$.stack` in code an earlier run of a named engine compiled give the line of that +/// run's file: its script, or a file it included; a script given as text is named by that run's +/// name. Code `eval` and `Function` compiled keeps its own line, in `[eval]`, and code whose place +/// the engine did not keep is at line 0 of `[unknown]`. +#[test] +fn the_line_and_the_stack_of_code_an_earlier_run_kept_are_at_that_runs_files() { + use super::script_include::short_stack; + let base: PathBuf = std::env::temp_dir().join(format!("vc-script-engines-line-stack-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(&base).unwrap(); + std::fs::write(base.join("inc.jsxinc"), "\n\nfunction fromInclude() {\n return [$.line, $.stack];\n}").unwrap(); + let def = base.join("def.jsx"); + std::fs::write(&def, "#targetengine e\nvar pad = 1;\n#include \"inc.jsxinc\"\nfunction fromMain() {\n return fromInclude();\n}").unwrap(); + let mut s = Session::new(); + s.execute("script.run", &json!({"path": def.to_string_lossy()})).unwrap(); + run(&mut s, "#targetengine e\n\nfunction fromText() {\n return $.stack;\n}").unwrap(); + let call = |s: &mut Session, code: &str| { + let r = s.execute("script.run", &json!({"source": format!("#targetengine e\n\n{code}"), "name": "caller.js"})); + r.unwrap_or_else(|e| panic!("{code}: {e}"))["log"][0].clone() + }; + let r = call(&mut s, "vc.log(fromMain());"); + assert_eq!(r[0], 4, "{r}"); + assert_eq!(short_stack(&r[1]), "[global]@caller.js:3\nfromMain@def.jsx:5\nfromInclude@inc.jsxinc:4\n"); + assert_eq!(short_stack(&call(&mut s, "vc.log(fromText());")), "[global]@caller.js:3\nfromText@t.js:4\n"); + assert_eq!(call(&mut s, "vc.log(eval('\\n\\n$.line'));"), 3); + assert_eq!(call(&mut s, "vc.log(eval('\\n$.stack'));"), "[global]@caller.js:3\n[global]@[eval]:2\n"); + let r = call(&mut s, "vc.log(new Function('\\nreturn $.stack;')());"); + assert_eq!(r, "[global]@caller.js:3\n[anonymous]@[eval]:4\n", "the line of the function source `Function` compiles"); + // A map larger than the budget is not kept. + TEST_KEPT_MAP_BYTES.with(|b| b.set(Some(1))); + let lost = run(&mut s, "#targetengine e\n\n\nfunction lost() {\n return [$.line, $.stack];\n}"); + let r = lost.map(|_| call(&mut s, "vc.log(lost());")); + TEST_KEPT_MAP_BYTES.with(|b| b.set(None)); + let r = r.unwrap(); + assert_eq!(r, json!([0, "[global]@caller.js:3\nlost@[unknown]:0\n"])); + let _ = std::fs::remove_dir_all(base); +} + +/// A run of a named engine whose script does not compile defines no code, so it keeps no place +/// and pushes out none of the places kept before. An included file without a preprocessor line is +/// first parsed with the script it joins, so its syntax error ends the run as it starts. +#[test] +fn a_run_that_does_not_compile_keeps_no_place() { + let base: PathBuf = std::env::temp_dir().join(format!("vc-script-engines-uncompiled-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(&base).unwrap(); + // A kept place counts the names of the files the run read: four places of the failed run's size + // would not fit in the budget. + let mut text = String::from("#targetengine e\n"); + for k in 0..10 { + std::fs::write(base.join(format!("ok{k}.jsxinc")), "var ok = 1;").unwrap(); + text.push_str(&format!("#include \"ok{k}.jsxinc\"\n")); + } + std::fs::write(base.join("bad.jsxinc"), "var = ;").unwrap(); + text.push_str("#include \"bad.jsxinc\""); + let bad = base.join("bad.jsx"); + std::fs::write(&bad, text).unwrap(); + let mut s = Session::new(); + run(&mut s, "#targetengine e\nvar x = 1;").unwrap(); + TEST_KEPT_MAP_BYTES.with(|b| b.set(Some(3000))); + run(&mut s, "#targetengine e\n\n\nfunction c() { throw new Error('c'); }").unwrap(); + let mut kinds = vec![]; + for _ in 0..5 { + assert!(s.execute("script.run", &json!({"path": bad.to_string_lossy()})).is_err()); + kinds.push(s.script_report().unwrap()["kind"].clone()); + } + assert!(run(&mut s, "#targetengine e\nc();").is_err()); + let c_place = place(&s); + TEST_KEPT_MAP_BYTES.with(|b| b.set(None)); + let _ = std::fs::remove_dir_all(base); + assert!(kinds.iter().all(|k| k == "syntax"), "{kinds:?}"); + assert_eq!((c_place.0.as_deref(), c_place.1), (Some("t.js"), 4)); +} + +/// A `$.evalFile` an earlier run kept reads files the way the run that calls it does: relative to +/// that run's script, and as `$.evalFile` does in a run given as text. +#[test] +fn a_kept_eval_file_reads_in_the_calling_run_scope() { + let base: PathBuf = std::env::temp_dir().join(format!("vc-script-engines-scope-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + for dir in ["a", "b"] { + std::fs::create_dir_all(base.join(dir)).unwrap(); + std::fs::write(base.join(dir).join("lib.jsxinc"), format!("'{dir}'")).unwrap(); + } + let mut s = Session::new(); + let a = base.join("a").join("main.jsx"); + std::fs::write(&a, "#targetengine e\nvar ev = $.evalFile;\nvc.log(ev('lib.jsxinc'));").unwrap(); + assert_eq!(s.execute("script.run", &json!({"path": a.to_string_lossy()})).unwrap()["log"], json!(["a"])); + let b = base.join("b").join("main.jsx"); + std::fs::write(&b, "#targetengine e\nvc.log(ev('lib.jsxinc'));").unwrap(); + assert_eq!(s.execute("script.run", &json!({"path": b.to_string_lossy()})).unwrap()["log"], json!(["b"]), "the kept function reads beside b"); + let kept = run(&mut s, "#targetengine e\nvc.log(ev('lib.jsxinc'));").map_err(|e| e.to_string()); + let direct = run(&mut s, "vc.log($.evalFile('lib.jsxinc'));").map_err(|e| e.to_string()); + let _ = std::fs::remove_dir_all(base); + assert!(direct.is_err(), "{direct:?}"); + assert_eq!(kept.unwrap_err().split(": ").last(), direct.unwrap_err().split(": ").last(), "a run given as text reads no file beside a"); +} + +/// `File` and `Folder` objects an earlier run kept read in the folder of the run that calls them, +/// `Folder.current` starts at each run's script, and a file an earlier run left open is not open: +/// it takes the encoding it is given, as a closed file does. +#[test] +fn kept_file_objects_read_in_the_calling_run_folder() { + let base: PathBuf = std::env::temp_dir().join(format!("vc-script-engines-files-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + for dir in ["a", "b"] { + std::fs::create_dir_all(base.join(dir)).unwrap(); + std::fs::write(base.join(dir).join("data.txt"), dir.to_uppercase()).unwrap(); + } + let mut s = Session::new(); + let a = base.join("a").join("main.jsx"); + std::fs::write(&a, "#targetengine e\nvar keep = new File('data.txt');\nkeep.open('r');\nvc.log([Folder.current.name, keep.read(1)]);").unwrap(); + assert_eq!(s.execute("script.run", &json!({"path": a.to_string_lossy()})).unwrap()["log"], json!([["a", "A"]])); + let b = base.join("b").join("main.jsx"); + let text = "#targetengine e\nvar g = new File('data.txt');\ng.open('r');\nvc.log([Folder.current.name, g.read(), keep.read(), keep.error, keep.exists]);\n\ + var before = keep.encoding;\nkeep.encoding = 'BINARY';\nkeep.open('r');\nvc.log([before, keep.encoding]);"; + std::fs::write(&b, text).unwrap(); + let log = s.execute("script.run", &json!({"path": b.to_string_lossy()})).unwrap()["log"].clone(); + let _ = std::fs::remove_dir_all(base); + assert_eq!(log, json!([["b", "B", "", "Script file is not open", false], ["UTF-8", "BINARY"]])); +} + +#[test] +fn a_failed_or_stopped_run_keeps_the_globals_it_set_and_puts_the_documents_back() { + let mut s = one_doc(); + let undo = s.documents()[0].history.undo.len(); + let e = run(&mut s, &format!("#targetengine e\nvar n = 1;\nvc.run('shape.rectangle', {RECT});\nthrow new Error('boom');")); + assert!(e.is_err()); + assert_eq!((objects(&s), s.documents()[0].history.undo.len()), (1, undo), "the documents went back"); + assert_eq!(log(&mut s, "#targetengine e\nvc.log(n);"), json!([1])); + // A stop. + s.script_frames = true; + assert_eq!(run(&mut s, &format!("#targetengine e\nn = 10;\nvc.run('shape.rectangle', {RECT});\nwhile (true) {{}}")).unwrap()["running"], true); + assert!(s.script_pump().is_none()); + assert_eq!(s.execute("script.stop", &json!({})).unwrap()["stopped"], true); + assert!(s.script_pump().unwrap().is_err()); + s.script_frames = false; + assert_eq!(objects(&s), 1); + // An error in another engine leaves this one as it was. + assert!(run(&mut s, "#targetengine f\nvar n = 99;\nthrow 1;").is_err()); + assert_eq!(log(&mut s, "#targetengine e\nvc.log(n);"), json!([10])); + // A run that ends well is one undo step. + run(&mut s, &format!("#targetengine e\nvc.run('shape.rectangle', {RECT});")).unwrap(); + assert_eq!((objects(&s), s.documents()[0].history.undo.len()), (2, undo + 1)); + assert_eq!(s.documents()[0].history.undo.last().unwrap().label, "Run Script"); +} + +/// A run stopped at a dialog, or left paused, ends where it was: the engine keeps its globals and +/// the next run starts afresh. +#[test] +fn a_run_stopped_at_a_dialog_or_left_paused_ends_where_it_was() { + let mut s = Session::new(); + s.script_frames = true; + run(&mut s, "#targetengine e\nvar n = 20;\nfunction f() { var big = new Array(4000001).join('x'); alert('x'); n = big.length; }\nf();").unwrap(); + for _ in 0..1_000 { + if s.script_dialog().is_some() { + break; + } + assert!(s.script_pump().is_none()); + } + assert!(s.script_dialog().is_some()); + s.execute("script.stop", &json!({})).unwrap(); + assert!(s.script_pump().unwrap().is_err()); + let heap = s.execute("script.engines", &json!({})).unwrap()["engines"][0]["heapBytes"].as_u64().unwrap(); + assert!(heap < 4 << 20, "the stopped run's frames, and the string they held, are gone: {heap} bytes"); + run(&mut s, "#targetengine e\nn += 1;\nwhile (true) {}").unwrap(); + assert!(s.script_pump().is_none()); + assert!(s.script_abandon()); + s.script_frames = false; + for _ in 0..3 { + assert_eq!(log(&mut s, "#targetengine e\nvc.log(n);"), json!([21])); + } +} + +#[test] +fn a_kept_host_function_acts_for_the_run_that_calls_it() { + let mut s = one_doc(); + run(&mut s, "#targetengine e\nvar oldRun = vc.run, oldVc = vc, oldWrite = $.writeln, oldAlert = alert;").unwrap(); + // The functions an earlier run kept work in this run's transaction, which goes back. + let e = run(&mut s, &format!("#targetengine e\noldRun('shape.rectangle', {RECT});\noldVc.log('kept');\nthrow new Error('x');")); + assert!(e.is_err()); + assert_eq!(objects(&s), 1, "the kept vc.run's change went back with the run"); + assert_eq!(s.script_report().unwrap()["log"], json!(["kept"])); + let r = s + .execute( + "script.run", + &json!({"source": format!("#targetengine e\noldRun('shape.rectangle', {RECT});\noldWrite('out');\noldAlert('hi');"), "answers": [{"kind": "alert", "value": "ok"}]}), + ) + .unwrap(); + assert_eq!((objects(&s), r["dialogCount"].as_u64()), (2, Some(1))); + assert!(r["console"]["lines"].as_array().unwrap().iter().any(|l| l == "out"), "{r}"); + assert_eq!(s.documents()[0].history.undo.last().unwrap().label, "Run Script"); + let r = s + .execute( + "script.run", + &json!({"source": "#targetengine e\nvc.log([oldVc.args.n, vc === oldVc, Object.isFrozen(vc.args)]);", "args": {"n": 2}}), + ) + .unwrap(); + assert_eq!(r["log"], json!([[2, true, true]]), "a kept vc gives the calling run's args, frozen"); +} + +/// The values a run sets on `$` in a named engine end with that run, as in a run without one, and +/// a `$` an earlier run kept gives the values of the run that reads it. +#[test] +fn the_values_of_the_dollar_object_belong_to_each_run_of_a_named_engine() { + let mut s = Session::new(); + let read = "vc.log([$.getenv('OS'), $.getenv('LANG'), $.localize, $.flags, $.locale]);"; + let fresh = log(&mut s, read); + let set = "$.setenv('OS', 'set_here');\n$.setenv('LANG', 'set_here');\n$.localize = true;\n$.locale = 'fr_FR';"; + run(&mut s, &format!("#targetengine e\nvar d = $;\n{set}\n{read}")).unwrap(); + assert_eq!(log(&mut s, &format!("#targetengine e\n{read}")), fresh); + let os = fresh[0][0].clone(); + assert_eq!(log(&mut s, "#targetengine e\nvc.log([d === $, d.engineName, d.getenv('OS'), d.localize]);"), json!([[true, "e", os, false]])); + assert_eq!(log(&mut s, "#targetengine e\nd.setenv('OS', 'again');\nvc.log(d.getenv('OS'));"), json!(["again"])); + assert_eq!(log(&mut s, &format!("#targetengine e\n{read}")), fresh); +} + +#[test] +fn an_engine_does_not_keep_a_closed_document() { + let mut s = one_doc(); + let name = s.documents()[0].title(); + run(&mut s, "#targetengine e\nvar snap = vc.document;\nvar read = function () { return vc.document; };").unwrap(); + let weak = Arc::downgrade(&s.documents()[0].doc); + s.execute("file.close", &json!({})).unwrap(); + assert!(weak.upgrade().is_none(), "nothing holds the closed document"); + assert_eq!(log(&mut s, "#targetengine e\nvc.log(read());\nvc.log(snap.name);"), json!([null, name])); +} + +#[test] +fn a_session_keeps_eight_engines_and_drops_them_on_request() { + let mut s = Session::new(); + for i in 0..8 { + run(&mut s, &format!("#targetengine e{i}\nvar v = {i};")).unwrap(); + } + let e = run(&mut s, "#targetengine e8\nvc.log(1);").unwrap_err().to_string(); + assert!(e.contains("a session keeps at most 8 script engines"), "{e}"); + assert_eq!((s.script_report().unwrap()["kind"].as_str(), s.script_report().unwrap()["log"].clone()), (Some("limit"), json!([]))); + assert_eq!(log(&mut s, "#targetengine e3\nvc.log(v);"), json!([3]), "the eight still run"); + let list = s.execute("script.engines", &json!({})).unwrap(); + assert_eq!((list["limit"].as_u64(), list["heapLimit"].as_u64()), (Some(8), Some(64 << 20))); + for (i, e) in list["engines"].as_array().unwrap().iter().enumerate() { + assert_eq!(e["name"], format!("e{i}")); + assert_eq!(e["running"], false); + assert!(e["heapBytes"].as_u64().unwrap() > 0, "{e}"); + } + assert_eq!(s.execute("script.engine.drop", &json!({"name": "e2"})).unwrap(), json!({"dropped": true, "name": "e2"})); + assert_eq!(names(&mut s), ["e0", "e1", "e3", "e4", "e5", "e6", "e7"]); + run(&mut s, "#targetengine e8\nvar v = 8;").unwrap(); + assert!(run(&mut s, "#targetengine e2\n1").unwrap_err().to_string().contains("at most 8")); + s.execute("script.engine.drop", &json!({"name": "e8"})).unwrap(); + assert_eq!(log(&mut s, "#targetengine e2\nvc.log(typeof v);"), json!(["undefined"]), "a dropped engine comes back new"); + for (params, message) in [ + (json!({"name": "main"}), "the main script engine is new for each run"), + (json!({"name": "nope"}), "there is no script engine named \"nope\""), + (json!({}), "`name` must be the name of a script engine"), + (json!({"name": 3}), "`name` must be the name of a script engine"), + ] { + let e = s.execute("script.engine.drop", ¶ms).unwrap_err().to_string(); + assert!(e.contains(message), "{params}: {e}"); + } + // The running script's engine cannot be dropped; another one can. + s.script_frames = true; + assert_eq!(run(&mut s, "#targetengine e0\nwhile (true) {}").unwrap()["running"], true); + assert!(s.script_pump().is_none()); + assert!(matches!(s.execute("script.engine.drop", &json!({"name": "e0"})), Err(EngineError::Busy))); + let list = s.execute("script.engines", &json!({})).unwrap(); + assert_eq!(list["engines"][0]["running"], true); + s.execute("script.engine.drop", &json!({"name": "e1"})).unwrap(); + s.execute("script.stop", &json!({})).unwrap(); + assert!(s.script_pump().unwrap().is_err()); + assert_eq!(names(&mut s), ["e0", "e3", "e4", "e5", "e6", "e7", "e2"]); + // A script cannot drop or list engines itself. + s.script_frames = false; + let e = run(&mut s, "vc.run('script.engine.drop', {name: 'e0'});").unwrap_err().to_string(); + assert!(e.contains("a script cannot run `script.engine.drop`"), "{e}"); +} + +#[test] +fn a_named_engine_has_its_own_heap_limit_and_stays_usable() { + TEST_ENGINE_HEAP.with(|h| h.set(Some(8 << 20))); + let mut s = Session::new(); + let big = run(&mut s, "#targetengine big\nvar marker = 'set', keep = [];\nfor (var i = 0; i < 10000000; i++) keep.push('item ' + i);"); + // The next run starts on the nearly full heap even with large `args`, and can free memory. + let big_args = json!({"big": "x".repeat(1 << 19)}); + let free = json!({"source": "#targetengine big\nkeep = null;\nvc.log(marker);", "name": "t.js", "args": big_args}); + let kept = s.execute("script.run", &free).unwrap()["log"].clone(); + let after = s.execute("script.engines", &json!({})).unwrap(); + TEST_ENGINE_HEAP.with(|h| h.set(None)); + assert!(big.unwrap_err().to_string().contains("Heap")); + assert_eq!(kept, json!(["set"]), "the globals set before the limit stay, and the engine still runs"); + assert!(after["engines"][0]["heapBytes"].as_u64().unwrap() < 8 << 20, "{after}"); + // A run without #targetengine keeps the larger heap of one run. + assert_eq!(log(&mut s, "var keep = [];\nfor (var i = 0; i < 300000; i++) keep.push('item ' + i);\nvc.log(keep.length);"), json!([300000])); +} + +/// The engines stay on the thread that made them: a session used on another thread starts there +/// with none, and the engines it left, or that a session dropped elsewhere held, are dropped on +/// their own thread when it next uses its engines. +#[test] +fn a_session_moved_to_another_thread_starts_with_no_engines_and_lets_the_old_ones_go() { + let mut s = Session::new(); + run(&mut s, "#targetengine e\nvar kept = 1;").unwrap(); + assert_eq!(engines_on_this_thread(), 1); + let (mut s, there, listed, thread) = std::thread::spawn(move || { + let there = log(&mut s, "#targetengine e\nvc.log(typeof kept);"); + let listed = names(&mut s); + (s, there, listed, std::thread::current().id()) + }) + .join() + .unwrap(); + assert_eq!((there, listed), (json!(["undefined"]), vec!["e".to_string()])); + assert!(!releases_kept_for(thread), "a thread that ended keeps no list of engines to let go"); + // Back here, the first engine has been let go: the run gets a new one. + assert_eq!(log(&mut s, "#targetengine e\nvc.log(typeof kept);"), json!(["undefined"])); + assert_eq!(engines_on_this_thread(), 1); + assert!(!releases_kept_for(thread), "letting go of the ended thread's engines adds nothing for it"); + std::thread::spawn(move || drop(s)).join().unwrap(); + let mut other = Session::new(); + assert!(names(&mut other).is_empty()); + assert_eq!(engines_on_this_thread(), 0, "the engine of the session dropped on another thread is dropped here"); +} + +#[test] +fn an_internal_error_drops_the_engine() { + let mut s = Session::new(); + assert_eq!(log(&mut s, "#targetengine p\nvar a = 1;\nvc.log(a);"), json!([1])); + assert_eq!(log(&mut s, "#targetengine p\nvc.log(a);"), json!([1])); + s.script_frames = true; + run(&mut s, "#targetengine p\nwhile (true) {}").unwrap(); + PANIC_IN_SLICE.with(|p| p.set(true)); + let r = s.script_pump().unwrap(); + PANIC_IN_SLICE.with(|p| p.set(false)); + assert!(r.is_err()); + assert!(names(&mut s).is_empty()); + s.script_frames = false; + assert_eq!(log(&mut s, "#targetengine p\nvc.log(typeof a);"), json!(["undefined"])); +} + +/// A run whose job is gone took its engine's realm with it: the engine is dropped, so the next run +/// that names it starts it new and other engines stay. +#[test] +fn a_run_whose_job_is_gone_drops_its_engine() { + for abandon in [true, false] { + let mut s = Session::new(); + run(&mut s, "#targetengine kept\nvar k = 1;").unwrap(); + run(&mut s, "#targetengine lost\nvar a = 1;").unwrap(); + s.script_frames = true; + run(&mut s, "#targetengine lost\nwhile (true) {}").unwrap(); + assert!(s.script_pump().is_none()); + assert!(crate::script::forget_job(&s)); + if abandon { + assert!(s.script_abandon()); + } else { + assert!(s.script_pump().unwrap().is_err()); + } + s.script_frames = false; + assert_eq!(names(&mut s), ["kept"], "abandon: {abandon}"); + assert_eq!(log(&mut s, "#targetengine lost\nvc.log(typeof a);"), json!(["undefined"]), "abandon: {abandon}"); + assert_eq!(log(&mut s, "#targetengine kept\nvc.log(k);"), json!([1]), "abandon: {abandon}"); + } +} diff --git a/crates/engine/src/tests/script_folder.rs b/crates/engine/src/tests/script_folder.rs index b176b4f143..312db3e0fc 100644 --- a/crates/engine/src/tests/script_folder.rs +++ b/crates/engine/src/tests/script_folder.rs @@ -311,7 +311,9 @@ fn the_automation_read_root_keeps_an_agent_out_of_the_scripts_folder() { s.attach_scripts_dir(root.clone()); let roots = crate::file_access::AutomationRoots::new(&[&work], &[]).unwrap().unwrap(); let e = crate::file_access::confine(Some(&roots), || s.execute("script.listInstalled", &json!({}))).unwrap_err(); - assert!(e.to_string().contains("outside the read root"), "{e}"); + // The Scripts folder is the app's: the error keeps the root and names the folder by its name. + let shown_root = crate::cmd::findfiles::plain(std::fs::canonicalize(&work).unwrap()).display().to_string(); + assert_eq!(e.to_string(), format!("automation path rejected: outside the read root {shown_root}: Scripts")); let e = crate::file_access::confine(Some(&roots), || s.installed_script(&script.to_string_lossy())).unwrap_err(); assert!(e.to_string().contains("outside the read root"), "{e}"); // A read root that holds the folder lets both through. diff --git a/crates/engine/src/tests/script_include.rs b/crates/engine/src/tests/script_include.rs index 124407f6b0..1ad659cfdd 100644 --- a/crates/engine/src/tests/script_include.rs +++ b/crates/engine/src/tests/script_include.rs @@ -192,7 +192,7 @@ fn script_target_other_app_does_not_route() { assert_eq!(r["log"], json!([1])); for (source, message) in [ ("#target\nvc.log(1);", "#target needs a value"), - ("#targetengine \"session\"", "unsupported script directive: #targetengine"), + ("#targetengine \"session\"", "#targetengine must come before the script's code and #include lines"), ("#engine \"main\"", "unsupported script directive: #engine"), ("#strict maybe", "#strict takes on or off"), ("#frobnicate 1", "unknown script directive: #frobnicate"), @@ -374,6 +374,48 @@ fn script_eval_file_returns_last_value_and_shares_globals() { let _ = std::fs::remove_dir_all(base); } +/// `$.fileName` names the file the code reading it is in: a function `$.evalFile` gave names its +/// file after the file has returned, through nested files, and code an included file inserted names +/// that file. Code that `eval` compiled names the file being run. +#[test] +fn script_file_name_names_the_file_of_the_code_that_reads_it() { + let base = folder("filename"); + write(&base.join("main/inc.jsxinc"), "function fromInclude() { return $.fileName; }\nvar includedTop = $.fileName;"); + write( + &base.join("main/sub/outer.jsx"), + "function fromOuter() { return $.fileName; }\nvar before = $.fileName;\n$.evalFile('inner.jsx');\nvar after = $.fileName;\nfromInner();", + ); + write(&base.join("main/sub/inner.jsx"), "function fromInner() { return $.fileName; }\n$.fileName;"); + let r = run( + &base, + "#include \"inc.jsxinc\"\nvar nested = $.evalFile('sub/outer.jsx');\n\ + vc.log([fromInclude(), includedTop, before, after, nested, fromOuter(), fromInner(), $.fileName, eval('$.fileName')]);", + ) + .unwrap(); + let names: Vec = r["log"][0].as_array().unwrap().iter().map(|v| v.as_str().unwrap().replace('\\', "/")).collect(); + let ends = [ + "main/inc.jsxinc", + "main/inc.jsxinc", + "sub/outer.jsx", + "sub/outer.jsx", + "sub/inner.jsx", + "sub/outer.jsx", + "sub/inner.jsx", + "main/main.jsx", + "main/main.jsx", + ]; + assert_eq!(names.len(), ends.len(), "{names:?}"); + for (name, end) in names.iter().zip(ends) { + assert!(name.ends_with(end), "{name} ends with {end}: {names:?}"); + } + // A script given as text has no name, and neither have the functions it defines. + let r = Session::new() + .execute("script.run", &json!({"source": "function f() { return $.fileName; }\nvc.log([f(), $.fileName]);", "name": "t.js"})) + .unwrap(); + assert_eq!(r["log"], json!([["", ""]])); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn script_eval_file_outside_scope_refused() { let base = folder("evaloutside"); @@ -454,6 +496,49 @@ fn script_included_error_has_local_file_and_line() { let _ = std::fs::remove_dir_all(base); } +/// `$.stack`'s text with each frame's file cut to its name: `function@name:line` a line. +pub(crate) fn short_stack(stack: &Value) -> String { + let stack = stack.as_str().unwrap_or_else(|| panic!("a stack: {stack}")); + stack + .lines() + .map(|frame| match (frame.split_once('@'), frame.rsplit_once(':')) { + (Some((name, _)), Some((place, line))) => { + let file = place.split_once('@').map_or(place, |(_, f)| f).rsplit(['/', '\\']).next().unwrap_or_default(); + format!("{name}@{file}:{line}\n") + } + _ => format!("{frame}\n"), + }) + .collect() +} + +/// `$.line` and `$.stack` give the line of the file the running code is in: the script, a file it +/// included (and a file that one included) or a file `$.evalFile` gave and the files it included, +/// whatever lines come before it in the run's expanded source. +#[test] +fn script_line_and_stack_are_at_the_line_of_each_file() { + let base = folder("line-stack"); + write( + &base.join("main/lib.jsxinc"), + "\nfunction libWhere() {\n return [$.line, $.stack];\n}\nvar libLine = $.line;\n#include \"deep.jsxinc\"\n", + ); + write(&base.join("main/deep.jsxinc"), "\n\nvar deepLine = $.line;\nfunction deepStack() {\n return $.stack;\n}"); + write(&base.join("main/sub/ev.jsx"), "#include \"inc.jsxinc\"\nfunction evWhere() {\n return incWhere();\n}\nevWhere();"); + write(&base.join("main/sub/inc.jsxinc"), "\n\nfunction incWhere() {\n return [$.line, $.stack];\n}"); + let text = "var a = 1;\nvar b = 2;\n#include \"lib.jsxinc\"\nvar mainLine = $.line;\nvc.log([libLine, deepLine, mainLine]);\n\ + vc.log(libWhere());\nvc.log(deepStack());\nvc.log($.evalFile('sub/ev.jsx'));"; + let log = run(&base, text).unwrap()["log"].clone(); + assert_eq!(log[0], json!([5, 3, 4]), "{log}"); + assert_eq!(log[1][0], 3, "{log}"); + assert_eq!(short_stack(&log[1][1]), "[global]@main.jsx:6\nlibWhere@lib.jsxinc:3\n"); + assert_eq!(short_stack(&log[2]), "[global]@main.jsx:7\ndeepStack@deep.jsxinc:5\n"); + assert_eq!(log[3][0], 4, "{log}"); + assert_eq!(short_stack(&log[3][1]), "[global]@main.jsx:8\n[global]@ev.jsx:5\nevWhere@ev.jsx:3\nincWhere@inc.jsxinc:4\n"); + // The file a frame names is the one `$.fileName` gives while that file runs. + let log = run(&base, "vc.log($.stack.slice(9, -3) === $.fileName);").unwrap()["log"].clone(); + assert_eq!(log, json!([true])); + let _ = std::fs::remove_dir_all(base); +} + /// Pumps the run in the app until it ends or waits at a dialog (`None`). fn pump(s: &mut Session) -> Option> { for _ in 0..10_000 { diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 4f9f193f51..e056ea2f7c 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -55,6 +55,42 @@ fn file_constructor_identity_and_folder_path() { let _ = std::fs::remove_dir_all(base); } +/// `exists` is true only when the path names an entry of the object's own kind. +#[test] +fn script_file_exists_checks_the_kind() { + let base = folder("kind"); + write(&base.join("main/data.txt"), b"x"); + std::fs::create_dir_all(base.join("main/sub")).unwrap(); + let log = + logged(&base, "vc.log([new File('sub').exists, new Folder('data.txt').exists, new File('data.txt').exists, new Folder('sub').exists]);"); + assert_eq!(log, json!([[false, false, true, true]])); + let _ = std::fs::remove_dir_all(base); +} + +/// A property a script puts on `Object.prototype` is not read as part of what the app returns. +#[test] +fn script_file_ignores_inherited_result_fields() { + let base = folder("inherited"); + write(&base.join("main/data.txt"), b"data"); + let log = logged( + &base, + "Object.prototype.error = 'inherited'; Object.prototype.exists = true;\n\ + var f = new File('data.txt'); var opened = f.open('r');\n\ + vc.log([f.exists, new File('nope').exists, opened, f.error, f.read()]);", + ); + assert_eq!(log, json!([[true, false, true, "", "data"]])); + let _ = std::fs::remove_dir_all(base); +} + +/// `File.encode`, `File.decode`, `File.isEncodingAvailable` and the `Folder` locations are counted as +/// calls to the app. +#[test] +fn script_file_class_functions_are_counted() { + let source = "File.encode('x'); File.decode('y'); Folder.isEncodingAvailable('UTF-8'); Folder.temp;"; + let r = Session::new().execute("script.run", &json!({"source": source})).unwrap(); + assert_eq!(r["hostCallCounts"]["fileCalls"], 4, "{r}"); +} + #[test] fn file_names_are_uri_encoded_and_current_relative() { let base = folder("names"); @@ -74,7 +110,7 @@ fn file_names_are_uri_encoded_and_current_relative() { assert_eq!( log, json!([ - ["caf%C3%A9%20x.txt", "caf\u{e9} x.txt", "caf%C3%A9%20x.txt", true, "%C3%A9%20%2F", "\u{e9}", "sub/y.txt", true, true], + ["caf%C3%A9%20x.txt", "caf\u{e9} x.txt", "caf%C3%A9%20x.txt", true, "%C3%A9%20/", "\u{e9}", "sub/y.txt", true, true], ["sub", "w", "w"], ["literal%20name.txt", "literal%2520name.txt", "literal%2520name.txt", true, "p%41", "p%41"] ]) @@ -194,7 +230,7 @@ fn script_file_link_escape_refused() { /// not matter, and outside it where case matters, whether or not the file is there. #[test] fn script_file_case_variant_folder() { - let base = folder("case"); + let base = crate::cmd::findfiles::plain(folder("case").canonicalize().unwrap()); write(&base.join("main/own.txt"), b"own"); let upper = base.join("MAIN"); let source = |name: &str| { diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 8294aa638a..d272fea167 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -166,10 +166,20 @@ fn an_error_names_the_script_its_place_and_kind() { let e = run(&mut s, "var = 1;").unwrap_err().to_string(); assert!(e.starts_with("t.js: line 1,") && e.ends_with("(syntax)"), "{e}"); assert!(run(&mut s, "app.activeDocument;").unwrap_err().to_string().contains("`vc`")); - assert!(run(&mut s, "#targetengine x\n1").unwrap_err().to_string().contains("unsupported script directive: #targetengine")); + assert!(run(&mut s, "#targetengine 9x\n1").unwrap_err().to_string().contains("#targetengine needs a name of letters, digits and _")); assert_eq!(s.script_report().unwrap()["line"], 1); } +/// An error raised where the run has no place for it, such as in code `eval` compiled, is named +/// with the script and its kind alone, with one colon after the script's name. +#[test] +fn an_error_without_a_place_names_the_script_and_kind() { + let mut s = two_docs(); + let e = run(&mut s, "eval(\"throw new TypeError('no')\");").unwrap_err().to_string(); + assert_eq!(s.script_report().unwrap()["line"], 0); + assert_eq!(e, "t.js: TypeError: no (thrown)"); +} + #[test] fn bad_parameters_are_refused_before_anything_runs() { let mut s = two_docs(); @@ -845,6 +855,30 @@ fn a_person_can_let_a_growing_run_go_on_or_stop_it() { assert_eq!(state(&s), before); } +#[test] +fn a_run_waiting_to_grow_stops_at_the_next_slice_once_its_work_is_canceled() { + TEST_GROWTH.with(|g| g.set(Some(20))); + let mut s = two_docs(); + let before = state(&s); + s.script_frames = true; + run(&mut s, "for (var i = 0; i < 25; i++) vc.run('shape.rectangle', {x:i,y:1,width:1,height:1});").unwrap(); + let token = crate::cancel::CancelToken::new(); + for _ in 0..1_000 { + if s.script_waiting() { + break; + } + assert!(crate::cancel::scope(&token, None, || s.script_pump()).is_none()); + } + assert!(s.script_waiting()); + token.cancel(); + let ended = crate::cancel::scope(&token, None, || s.script_pump()); + TEST_GROWTH.with(|g| g.set(None)); + assert!(ended.expect("the run goes on waiting for Continue").is_err()); + assert_eq!(s.script_report().unwrap()["kind"], "stopped"); + assert!(!s.script_running()); + assert_eq!(state(&s), before); +} + #[test] fn a_file_saved_before_a_failure_stays_written_and_is_named() { let path = std::env::temp_dir().join(format!("vc-script-save-{}.svg", std::process::id())); diff --git a/crates/engine/src/tests/select_effects.rs b/crates/engine/src/tests/select_effects.rs new file mode 100644 index 0000000000..d2160fba34 --- /dev/null +++ b/crates/engine/src/tests/select_effects.rs @@ -0,0 +1,393 @@ +//! Clicks, hovers and marquees with the selection tools leave out the area that raster effects +//! (drop shadows, glows, blurs) paint beyond an object: there they reach the object under the +//! effect, or nothing. + +use serde_json::{Value, json}; +use vectorcraft_doc::NodeId; +use vectorcraft_geom::{Point, Rect}; +use vectorcraft_tools::{Cursor, Mods, PointerEvent, PointerKind}; + +use crate::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + s +} + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")) +} + +fn id_of(v: &Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +/// A rectangle filled with `color`. +fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64, color: &str) -> NodeId { + let id = id_of(&run(s, "shape.rectangle", json!({"x": x, "y": y, "width": w, "height": h}))); + run(s, "select.set", json!({"ids": [id.0]})); + run(s, "paint.setFill", json!({"color": color})); + id +} + +/// A drop shadow on the whole of `id`, `dx` to the right, with no blur. +fn shadow(s: &mut Session, id: NodeId, dx: f64) { + run(s, "effect.apply", json!({"effect": "stylize.dropShadow", "ids": [id.0], "params": {"x": dx, "y": 0, "blur": 0}, "item": null})); +} + +fn pixel(s: &Session, x: u32, y: u32) -> [u8; 4] { + let doc = s.doc().unwrap().doc.clone(); + let opts = vectorcraft_render::RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + vectorcraft_render::Renderer::new().render(&doc, 200, 200, vectorcraft_geom::Affine::IDENTITY, &opts).pixel(x, y) +} + +fn press(s: &mut Session, tool: &str, from: (f64, f64), to: (f64, f64), mods: Mods) -> Vec { + let v = ViewInfo::default(); + s.select_tool(tool, v).unwrap(); + for (k, (x, y)) in [(PointerKind::Down, from), (PointerKind::Drag, to), (PointerKind::Up, to)] { + if k == PointerKind::Drag && from == to { + continue; + } + s.pointer(&PointerEvent::new(k, x, y).with_mods(mods), v).unwrap(); + } + s.active().unwrap().selection.objects.clone() +} + +/// Click with the Selection tool at (x, y) on a 100% view: what is selected afterwards. +fn click(s: &mut Session, x: f64, y: f64) -> Vec { + press(s, "selection", (x, y), (x, y), Mods::default()) +} + +fn bounds(s: &Session, id: NodeId) -> Rect { + s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap() +} + +const WHITE: [u8; 4] = [255; 4]; +const BLUE: [u8; 4] = [0, 0, 255, 255]; + +/// Blue B at x 100 to 160, red A over its left edge's side at x 20 to 80, and A's shadow +/// 40 pt to the right, from x 60 to 120: over the canvas from 80 to 100 and over B from 100 to 120. +fn shadow_over_b(s: &mut Session) -> (NodeId, NodeId) { + let b = rect(s, 100.0, 20.0, 60.0, 60.0, "#0000ff"); + let a = rect(s, 20.0, 20.0, 60.0, 60.0, "#ff0000"); + shadow(s, a, 40.0); + (a, b) +} + +#[test] +fn a_click_on_a_drop_shadow_selects_the_object_under_it() { + let mut s = session(); + let (a, b) = shadow_over_b(&mut s); + // The shadow paints over B and over the canvas. + assert_ne!(pixel(&s, 110, 50), BLUE); + assert_ne!(pixel(&s, 90, 50), WHITE); + run(&mut s, "select.none", json!({})); + assert_eq!(click(&mut s, 110.0, 50.0), [b]); + assert_eq!(click(&mut s, 50.0, 50.0), [a]); +} + +#[test] +fn a_click_on_a_drop_shadow_over_the_canvas_selects_nothing_and_clears_the_selection() { + let mut s = session(); + let (a, _) = shadow_over_b(&mut s); + run(&mut s, "select.set", json!({"ids": [a.0]})); + assert!(click(&mut s, 90.0, 50.0).is_empty()); +} + +#[test] +fn a_click_on_an_outer_glow_or_a_gaussian_blur_outside_the_path_selects_what_is_under_it() { + let mut s = session(); + let a = rect(&mut s, 20.0, 20.0, 60.0, 60.0, "#ff0000"); + run(&mut s, "effect.apply", json!({"effect": "stylize.outerGlow", "ids": [a.0], "params": {"blur": 20, "mode": "normal"}, "item": null})); + assert_ne!(pixel(&s, 88, 50), WHITE); + run(&mut s, "select.none", json!({})); + assert!(click(&mut s, 88.0, 50.0).is_empty()); + // A red square whose blur reaches over the canvas and over the left edge of a blue one. + let mut s = session(); + let b = rect(&mut s, 92.0, 20.0, 60.0, 60.0, "#0000ff"); + let a = rect(&mut s, 20.0, 20.0, 60.0, 60.0, "#ff0000"); + run(&mut s, "effect.apply", json!({"effect": "blur.gaussian", "ids": [a.0], "params": {"radius": 20}, "item": null})); + assert_ne!(pixel(&s, 98, 50), BLUE); + assert_ne!(pixel(&s, 87, 50), WHITE); + run(&mut s, "select.none", json!({})); + assert_eq!(click(&mut s, 98.0, 50.0), [b]); + // (With B deselected, so that the press does not take its bounding box handle.) + run(&mut s, "select.none", json!({})); + assert!(click(&mut s, 87.0, 50.0).is_empty()); +} + +/// The first point of `area` (x0, y0, x1, y1) that the canvas paints, scanning rows. +fn painted_in(s: &Session, (x0, y0, x1, y1): (u32, u32, u32, u32)) -> Option<(f64, f64)> { + let doc = s.doc().unwrap().doc.clone(); + let opts = vectorcraft_render::RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let img = vectorcraft_render::Renderer::new().render(&doc, 200, 200, vectorcraft_geom::Affine::IDENTITY, &opts); + (y0..y1) + .flat_map(|y| (x0..x1).map(move |x| (x, y))) + .find(|&(x, y)| img.pixel(x, y) != WHITE) + .map(|(x, y)| (f64::from(x) + 0.5, f64::from(y) + 0.5)) +} + +#[test] +fn a_click_on_the_drop_shadow_of_a_group_or_of_point_type_selects_neither() { + let mut s = session(); + let a = rect(&mut s, 20.0, 20.0, 30.0, 30.0, "#ff0000"); + let b = rect(&mut s, 60.0, 20.0, 30.0, 30.0, "#ff0000"); + run(&mut s, "select.set", json!({"ids": [a.0, b.0]})); + let g = id_of(&run(&mut s, "object.group", json!({}))); + shadow(&mut s, g, 80.0); + // The group's shadow lies from x 100 to 170. + assert_ne!(pixel(&s, 110, 35), WHITE); + run(&mut s, "select.none", json!({})); + assert!(click(&mut s, 110.0, 35.0).is_empty()); + assert_eq!(click(&mut s, 35.0, 35.0), [g]); + // Type 40 pt high at y 150 with its shadow 90 pt to the right. + let t = id_of(&run(&mut s, "text.create", json!({"x": 20, "y": 150, "text": "HH", "size": 40}))); + shadow(&mut s, t, 90.0); + let right = bounds(&s, t).x1; + assert!(right < 100.0, "{right}"); + let at = painted_in(&s, (right.ceil() as u32 + 10, 110, 199, 160)).expect("the type's shadow paints"); + run(&mut s, "select.none", json!({})); + assert!(click(&mut s, at.0, at.1).is_empty(), "{at:?}"); +} + +#[test] +fn a_click_on_the_drop_shadow_of_a_symbols_art_does_not_select_the_instance() { + let mut s = session(); + let a = rect(&mut s, 20.0, 20.0, 60.0, 60.0, "#ff0000"); + shadow(&mut s, a, 40.0); + run(&mut s, "select.set", json!({"ids": [a.0]})); + let inst = id_of(&run(&mut s, "symbol.new", json!({"name": "Shadowed"}))); + assert_ne!(pixel(&s, 100, 50), WHITE); + run(&mut s, "select.none", json!({})); + assert!(click(&mut s, 100.0, 50.0).is_empty()); + assert_eq!(click(&mut s, 50.0, 50.0), [inst]); +} + +#[test] +fn a_click_on_the_drop_shadow_of_an_image_outside_its_frame_does_not_select_it() { + let mut s = session(); + let mut png = vec![]; + image::RgbaImage::from_pixel(30, 30, image::Rgba([255, 0, 0, 255])) + .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .unwrap(); + let r = run(&mut s, "file.place", json!({"name": "red.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [65, 65]})); + let im = NodeId(r["ids"][0].as_u64().unwrap()); + // The frame lies from x 50 to 80 and the shadow from 90 to 120. + shadow(&mut s, im, 40.0); + assert_ne!(pixel(&s, 105, 65), WHITE); + run(&mut s, "select.none", json!({})); + assert!(click(&mut s, 105.0, 65.0).is_empty()); + assert_eq!(click(&mut s, 65.0, 65.0), [im]); +} + +#[test] +fn shift_click_direct_selection_and_hover_on_a_drop_shadow_pass_through_it() { + let mut s = session(); + let (a, b) = shadow_over_b(&mut s); + // Shift-click on the shadow over B adds B and keeps A. + run(&mut s, "select.set", json!({"ids": [a.0]})); + let shift = Mods { shift: true, ..Mods::default() }; + let mut sel = press(&mut s, "selection", (110.0, 50.0), (110.0, 50.0), shift); + sel.sort_by_key(|n| n.0); + let mut both = vec![a, b]; + both.sort_by_key(|n| n.0); + assert_eq!(sel, both); + // Direct Selection takes B through the shadow, and nothing over the canvas. + run(&mut s, "select.none", json!({})); + let sel = press(&mut s, "directSelection", (110.0, 50.0), (110.0, 50.0), Mods::default()); + assert!(sel.contains(&b) && !sel.contains(&a), "{sel:?}"); + run(&mut s, "select.none", json!({})); + assert!(press(&mut s, "directSelection", (90.0, 50.0), (90.0, 50.0), Mods::default()).is_empty()); + // With A selected, the pointer over its shadow is the plain arrow, and over A the move pointer. + run(&mut s, "select.set", json!({"ids": [a.0]})); + let v = ViewInfo::default(); + s.select_tool("selection", v).unwrap(); + assert_eq!(s.cursor(Point::new(50.0, 50.0), Mods::default(), v), Cursor::Move); + assert_eq!(s.cursor(Point::new(110.0, 50.0), Mods::default(), v), Cursor::Arrow); + assert_eq!(s.cursor(Point::new(92.0, 50.0), Mods::default(), v), Cursor::Arrow); +} + +#[test] +fn a_drag_from_the_drop_shadow_of_a_selected_object_does_not_move_it() { + let mut s = session(); + let (a, b) = shadow_over_b(&mut s); + run(&mut s, "select.set", json!({"ids": [a.0]})); + let before = bounds(&s, a); + // From the shadow over the canvas: a marquee that touches nothing. + assert!(press(&mut s, "selection", (92.0, 50.0), (96.0, 60.0), Mods::default()).is_empty()); + assert_eq!(bounds(&s, a), before); + // From the shadow over B: B moves, A stays. + run(&mut s, "select.set", json!({"ids": [a.0]})); + let b_before = bounds(&s, b); + assert_eq!(press(&mut s, "selection", (110.0, 50.0), (110.0, 60.0), Mods::default()), [b]); + assert_eq!(bounds(&s, a), before); + assert!((bounds(&s, b).y0 - b_before.y0 - 10.0).abs() < 1e-6, "{:?}", bounds(&s, b)); +} + +#[test] +fn a_marquee_that_touches_only_a_drop_shadow_does_not_select_its_object() { + let mut s = session(); + let (_, b) = shadow_over_b(&mut s); + run(&mut s, "select.none", json!({})); + assert!(press(&mut s, "selection", (85.0, 40.0), (95.0, 60.0), Mods::default()).is_empty()); + // From above B, over B and the shadow: B only. + assert_eq!(press(&mut s, "selection", (105.0, 5.0), (115.0, 30.0), Mods::default()), [b]); +} + +/// The selection after a drag with `tool` from `from` to `to`. +fn marquee(s: &mut Session, tool: &str, from: (f64, f64), to: (f64, f64)) -> vectorcraft_doc::Selection { + press(s, tool, from, to, Mods::default()); + s.doc().unwrap().selection.clone() +} + +/// The point of anchor `(si, ai)` of path `id`. +fn anchor_point(s: &Session, id: NodeId, (si, ai): vectorcraft_doc::AnchorRef) -> Point { + let path = s.doc().unwrap().doc.node(id).and_then(|n| n.path_data()).unwrap(); + path.anchors().find(|(s, i, _)| (*s, *i) == (si, ai)).map(|(.., a)| a.p).unwrap() +} + +/// The anchors a marquee or a click picked on `id`, as points. +fn picked_points(s: &Session, id: NodeId) -> Vec { + let refs: Vec<_> = s.doc().unwrap().selection.partial(id).into_iter().flatten().copied().collect(); + refs.into_iter().map(|r| anchor_point(s, id, r)).collect() +} + +/// The anchors the tool marks as hovered. +fn anchor_marks(s: &mut Session) -> Vec { + s.overlays(ViewInfo::default()) + .into_iter() + .filter_map(|o| if let vectorcraft_tools::Overlay::Anchor { p, .. } = o { Some(p) } else { None }) + .collect() +} + +fn hover(s: &mut Session, x: f64, y: f64) -> Cursor { + let v = ViewInfo::default(); + s.pointer(&PointerEvent::new(PointerKind::Move, x, y), v).unwrap(); + s.cursor(Point::new(x, y), Mods::default(), v) +} + +#[test] +fn a_direct_selection_marquee_leaves_out_a_drop_shadow() { + let mut s = session(); + let (a, b) = shadow_over_b(&mut s); + let (a_before, b_before) = (bounds(&s, a), bounds(&s, b)); + assert_ne!(pixel(&s, 90, 50), WHITE); + run(&mut s, "select.none", json!({})); + // Over the shadow alone: no object, no anchor, no segment. + let sel = marquee(&mut s, "directSelection", (85.0, 40.0), (95.0, 60.0)); + assert!(sel.objects.is_empty() && sel.anchors.is_empty() && sel.segments.is_empty(), "{sel:?}"); + // Over the shadow and B's upper left corner: that anchor of B, and nothing of A. + let sel = marquee(&mut s, "directSelection", (90.0, 5.0), (105.0, 30.0)); + assert_eq!(sel.objects, [b]); + assert_eq!(picked_points(&s, b), [Point::new(100.0, 20.0)]); + // Across B's top edge under the shadow, with neither of its anchors inside: that segment. + run(&mut s, "select.none", json!({})); + assert_ne!(pixel(&s, 112, 25), BLUE); + let sel = marquee(&mut s, "directSelection", (110.0, 5.0), (115.0, 30.0)); + assert_eq!(sel.objects, [b]); + assert!(sel.segments.contains_key(&b) && !sel.segments.contains_key(&a), "{sel:?}"); + assert_eq!((bounds(&s, a), bounds(&s, b)), (a_before, b_before)); +} + +#[test] +fn direct_selection_hover_leaves_out_a_drop_shadow_and_marks_the_anchor_under_it() { + let mut s = session(); + let (_, b) = shadow_over_b(&mut s); + // B's upper left corner lies under the shadow. + assert_ne!(pixel(&s, 101, 21), BLUE); + run(&mut s, "select.none", json!({})); + s.select_tool("directSelection", ViewInfo::default()).unwrap(); + for (x, y) in [(90.0, 50.0), (110.0, 50.0)] { + assert_eq!(hover(&mut s, x, y), Cursor::ArrowHollow, "({x}, {y})"); + assert!(anchor_marks(&mut s).is_empty(), "({x}, {y})"); + } + assert_eq!(hover(&mut s, 101.0, 21.0), Cursor::DirectAnchor); + assert_eq!(anchor_marks(&mut s), [Point::new(100.0, 20.0)]); + // A press there picks that anchor of B. + assert_eq!(press(&mut s, "directSelection", (101.0, 21.0), (101.0, 21.0), Mods::default()), [b]); + assert_eq!(picked_points(&s, b), [Point::new(100.0, 20.0)]); +} + +#[test] +fn a_group_selection_click_on_a_drop_shadow_selects_the_object_under_it() { + let mut s = session(); + let (a, b) = shadow_over_b(&mut s); + run(&mut s, "select.none", json!({})); + assert_eq!(press(&mut s, "groupSelection", (110.0, 50.0), (110.0, 50.0), Mods::default()), [b]); + assert!(press(&mut s, "groupSelection", (90.0, 50.0), (90.0, 50.0), Mods::default()).is_empty()); + assert_eq!(press(&mut s, "groupSelection", (50.0, 50.0), (50.0, 50.0), Mods::default()), [a]); +} + +#[test] +fn group_selection_clicks_on_a_drop_shadow_climb_the_groups_of_the_object_under_it() { + let mut s = session(); + // B and C in one group, A and D in another above it, and A's shadow over B. + let b = rect(&mut s, 100.0, 20.0, 60.0, 60.0, "#0000ff"); + let c = rect(&mut s, 170.0, 20.0, 20.0, 20.0, "#0000ff"); + run(&mut s, "select.set", json!({"ids": [b.0, c.0]})); + let gb = id_of(&run(&mut s, "object.group", json!({}))); + let a = rect(&mut s, 20.0, 20.0, 60.0, 60.0, "#ff0000"); + let d = rect(&mut s, 20.0, 120.0, 20.0, 20.0, "#ff0000"); + run(&mut s, "select.set", json!({"ids": [a.0, d.0]})); + let ga = id_of(&run(&mut s, "object.group", json!({}))); + shadow(&mut s, a, 40.0); + assert_ne!(pixel(&s, 110, 50), BLUE); + assert_ne!(pixel(&s, 90, 50), WHITE); + run(&mut s, "select.none", json!({})); + let click = |s: &mut Session, x, y| { + let mut sel = press(s, "groupSelection", (x, y), (x, y), Mods::default()); + sel.sort_by_key(|n| n.0); + sel + }; + assert_eq!(click(&mut s, 110.0, 50.0), [b]); + let mut both = vec![b, gb]; + both.sort_by_key(|n| n.0); + assert_eq!(click(&mut s, 110.0, 50.0), both); + // With A selected, a click on its shadow over the canvas does not add A's group. + run(&mut s, "select.set", json!({"ids": [a.0]})); + assert!(click(&mut s, 90.0, 50.0).is_empty()); + // On A itself the second click adds it. + assert_eq!(click(&mut s, 50.0, 50.0), [a]); + let mut both = vec![a, ga]; + both.sort_by_key(|n| n.0); + assert_eq!(click(&mut s, 50.0, 50.0), both); +} + +#[test] +fn a_group_selection_marquee_leaves_out_a_drop_shadow() { + let mut s = session(); + let (a, b) = shadow_over_b(&mut s); + run(&mut s, "select.none", json!({})); + let sel = marquee(&mut s, "groupSelection", (85.0, 40.0), (95.0, 60.0)); + assert!(sel.objects.is_empty() && sel.anchors.is_empty(), "{sel:?}"); + // Over the shadow and B's upper left corner: that anchor of B. + let sel = marquee(&mut s, "groupSelection", (90.0, 5.0), (105.0, 30.0)); + assert_eq!(sel.objects, [b]); + assert_eq!(picked_points(&s, b), [Point::new(100.0, 20.0)]); + // With E, a marquee around B that crosses A's shadow selects B whole, and not A. + run(&mut s, "select.none", json!({})); + let v = ViewInfo::default(); + s.select_tool("groupSelection", v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 95.0, 10.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 130.0, 50.0), v).unwrap(); + s.tool_key(vectorcraft_tools::ToolKey::Letter('e'), Mods::default(), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 165.0, 90.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 165.0, 90.0), v).unwrap(); + let sel = s.doc().unwrap().selection.clone(); + assert_eq!(sel.objects, [b]); + assert!(sel.partial(b).is_none() && sel.partial(a).is_none(), "{sel:?}"); +} + +#[test] +fn group_selection_hover_over_a_drop_shadow_marks_nothing() { + let mut s = session(); + let (_, b) = shadow_over_b(&mut s); + run(&mut s, "select.none", json!({})); + s.select_tool("groupSelection", ViewInfo::default()).unwrap(); + for (x, y) in [(90.0, 50.0), (110.0, 50.0), (101.0, 21.0)] { + assert_eq!(hover(&mut s, x, y), Cursor::GroupSelection, "({x}, {y})"); + assert!(anchor_marks(&mut s).is_empty(), "({x}, {y})"); + } + assert_eq!(press(&mut s, "groupSelection", (110.0, 50.0), (110.0, 50.0), Mods::default()), [b]); +} diff --git a/crates/engine/src/tests/shaper.rs b/crates/engine/src/tests/shaper.rs index 891d03e7a7..38e61241f0 100644 --- a/crates/engine/src/tests/shaper.rs +++ b/crates/engine/src/tests/shaper.rs @@ -259,6 +259,93 @@ fn shaper_double_click_selects_an_original_for_construction_editing() { assert_eq!(s.doc().unwrap().selection.objects, vec![g]); } +/// With a Shaper Group or one of its faces selected, a Shaper click on an original shape's outline +/// enters Construction mode with that shape selected, even where the outline lies inside a merged +/// face. A click away from every outline still selects a face, and a click on an outline of a group +/// that is not selected selects the group. +#[test] +fn shaper_click_on_an_original_outline_enters_construction_mode() { + let mut s = session(); + let a = rectangle(&mut s, 0.0, "#ff0000"); + let b = rectangle(&mut s, 50.0, "#0000ff"); + let g = scribble(&mut s, &[[25.0, 20.0], [75.0, 35.0], [30.0, 50.0], [125.0, 65.0]]); + let sources = node(&s, g).children().unwrap()[0].id; + let v = ViewInfo { smart_guides: false, ..Default::default() }; + s.select_tool("shaper", v).unwrap(); + let click = |s: &mut Session, x: f64, y: f64| { + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, x, y), v).unwrap(); + } + }; + s.execute("select.none", &json!({})).unwrap(); + click(&mut s, 101.0, 50.0); + assert_eq!(s.doc().unwrap().selection.objects, vec![g]); + assert_eq!(s.doc().unwrap().isolation, None); + // The right side of the back shape runs through the merged face. + click(&mut s, 101.0, 50.0); + assert_eq!(s.doc().unwrap().selection.objects, vec![a]); + assert_eq!(s.doc().unwrap().isolation, Some(sources)); + s.execute("object.exitIsolation", &json!({})).unwrap(); + // A click inside the face, away from the outlines, selects the face. + click(&mut s, 75.0, 50.0); + let face = s.doc().unwrap().selection.objects.clone(); + assert_eq!(face.len(), 1); + assert_ne!(face, vec![g]); + assert_eq!(s.doc().unwrap().isolation, None); + // With the face selected, a click on the front shape's outline picks that shape. + click(&mut s, 149.0, 50.0); + assert_eq!(s.doc().unwrap().selection.objects, vec![b]); + assert_eq!(s.doc().unwrap().isolation, Some(sources)); + s.execute("object.exitIsolation", &json!({})).unwrap(); + let undo = s.doc().unwrap().history.undo.len(); + for tolerance in [json!("3"), json!(-1), json!(1e9)] { + assert!(s.execute("shaper.select", &json!({"point": [101, 50], "tolerance": tolerance})).is_err(), "{tolerance}"); + assert_eq!(s.doc().unwrap().selection.objects, vec![g]); + assert_eq!(s.doc().unwrap().isolation, None); + } + assert_eq!(s.doc().unwrap().history.undo.len(), undo); + s.execute("shaper.select", &json!({"point": [104, 50], "tolerance": 5})).unwrap(); + assert_eq!(s.doc().unwrap().selection.objects, vec![a]); + s.execute("object.exitIsolation", &json!({})).unwrap(); + // A wide tolerance (a zoomed-out view) reaches an outline from well outside the group's bounds. + s.execute("shaper.select", &json!({"point": [165, 50], "tolerance": 20})).unwrap(); + assert_eq!(s.doc().unwrap().selection.objects, vec![b]); + assert_eq!(s.doc().unwrap().isolation, Some(sources)); + // A locked or hidden original shape is not picked by its outline. + for hide in ["object.lock", "object.hide"] { + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + s.execute(hide, &json!({})).unwrap(); + s.execute("object.exitIsolation", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + s.execute("shaper.select", &json!({"point": [149, 50]})).unwrap(); + assert_ne!(s.doc().unwrap().selection.objects, vec![b], "{hide}"); + assert_eq!(s.doc().unwrap().isolation, None, "{hide}"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + } +} + +/// A click on a selected Shaper Group's original outline where another Shaper Group lies above it +/// selects the group above, as a click there did before. +#[test] +fn shaper_outline_click_under_another_group_selects_the_group_above() { + let mut s = session(); + rectangle(&mut s, 0.0, "#ff0000"); + rectangle(&mut s, 50.0, "#0000ff"); + let lower = scribble(&mut s, &[[25.0, 20.0], [75.0, 35.0], [30.0, 50.0], [125.0, 65.0]]); + let c = rectangle(&mut s, 20.0, "#00ff00"); + let d = rectangle(&mut s, 70.0, "#ffff00"); + let upper = NodeId( + s.execute("shaper.scribble", &json!({"points": [[45, 20], [95, 35], [50, 50], [145, 65]], "ids": [c.0, d.0]})).unwrap()["id"] + .as_u64() + .unwrap(), + ); + s.execute("select.set", &json!({"ids": [lower.0]})).unwrap(); + s.execute("shaper.select", &json!({"point": [100, 50]})).unwrap(); + assert_eq!(s.doc().unwrap().selection.objects, vec![upper]); + assert_eq!(s.doc().unwrap().isolation, None); +} + /// The arrow widget beside a selected Shaper Group switches it to Construction mode and back, with /// the Shaper tool and with the Selection tool. In Construction mode a Shaper tap selects a source /// shape, and the mode lasts through undo and redo of an edit made in it. diff --git a/crates/engine/src/tests/shortcutset.rs b/crates/engine/src/tests/shortcutset.rs index 8f216b8c00..fb5292e243 100644 --- a/crates/engine/src/tests/shortcutset.rs +++ b/crates/engine/src/tests/shortcutset.rs @@ -51,7 +51,7 @@ fn entries_keep_their_sections_and_the_command_counts_codes() { assert_eq!(r["codes"]["modifiers"], json!([{"value": 64, "count": 2}, {"value": 80, "count": 1}])); assert_eq!((r["unread"].as_array().unwrap().len(), r["truncated"].as_bool()), (0, Some(false)), "{r}"); // The same from a file, and from its bytes. - let dir = vectorcraft_testkit::temp_dir("shortcutset-read"); + let dir = vectorcraft_testkit::TempDir::new("shortcutset-read"); let path = dir.join("Studio Keys.kys"); std::fs::write(&path, text).unwrap(); let mut s = Session::new(); @@ -59,7 +59,6 @@ fn entries_keep_their_sections_and_the_command_counts_codes() { assert_eq!((r["set"].as_str(), r["entries"].as_array().unwrap().len()), (Some("Studio Keys"), 3)); let b64 = vectorcraft_format::base64_encode(text.as_bytes()); assert_eq!(s.execute("shortcutSet.read", &json!({ "dataBase64": b64 })).unwrap()["entries"].as_array().unwrap().len(), 3); - let _ = std::fs::remove_dir_all(dir); } #[test] @@ -124,7 +123,7 @@ fn caps_nesting_entries_and_names() { #[test] fn big_files_are_read_up_to_the_cap() { let text = format!("/Menus {{ /E {{ /Key 1 }} {} }}", " ".repeat(5 << 20)); - let dir = vectorcraft_testkit::temp_dir("shortcutset-big"); + let dir = vectorcraft_testkit::TempDir::new("shortcutset-big"); let path = dir.join("Big.kys"); std::fs::write(&path, &text).unwrap(); let b64 = vectorcraft_format::base64_encode(text.as_bytes()); @@ -145,7 +144,6 @@ fn big_files_are_read_up_to_the_cap() { assert_eq!(fits.len(), (4 << 20) + 3); std::fs::write(&path, &fits).unwrap(); assert_eq!(s.execute("shortcutSet.read", &json!({ "path": path.to_string_lossy() })).unwrap()["truncated"], false); - let _ = std::fs::remove_dir_all(dir); } fn matched(s: &mut Session, p: Value) -> Vec { diff --git a/crates/engine/src/tests/spelling.rs b/crates/engine/src/tests/spelling.rs index 16d7f01993..dd10df1597 100644 --- a/crates/engine/src/tests/spelling.rs +++ b/crates/engine/src/tests/spelling.rs @@ -161,7 +161,7 @@ fn a_changed_word_replaces_the_old_one() { #[test] fn the_custom_dictionary_file_is_read_and_kept_up_to_date() { let _one_at_a_time = dictionary_lock(); - let dir = vectorcraft_testkit::temp_dir("spelling-dictionary"); + let dir = vectorcraft_testkit::TempDir::new("spelling-dictionary"); let file = dir.join("Custom Dictionary.txt"); std::fs::write(&file, "kqzvwx\nnot one word\n\n").unwrap(); let mut s = session(); @@ -224,7 +224,7 @@ fn in_dictionary(s: &mut Session, word: &str) -> bool { #[test] fn a_dictionary_file_that_cant_be_read_whole_is_never_written_over() { let _one_at_a_time = dictionary_lock(); - let dir = vectorcraft_testkit::temp_dir("spelling-unreadable"); + let dir = vectorcraft_testkit::TempDir::new("spelling-unreadable"); // A folder where the file should be can't be read as one; a file past what craft-proof reads // would lose its other words if written back. let folder = dir.join("Custom Dictionary.txt"); @@ -248,7 +248,7 @@ fn a_change_that_cant_be_saved_is_taken_back() { let _one_at_a_time = dictionary_lock(); let mut s = session(); run(&mut s, "text.spelling.addWord", json!({"word": "wkqzvx"})); - let dir = vectorcraft_testkit::temp_dir("spelling-rollback"); + let dir = vectorcraft_testkit::TempDir::new("spelling-rollback"); let folder = dir.join("Custom Dictionary.txt"); std::fs::create_dir_all(&folder).unwrap(); let mut failing = session(); @@ -266,7 +266,7 @@ fn a_change_that_cant_be_saved_is_taken_back() { fn a_dictionary_edit_is_saved_whole_or_not_at_all() { let _one_at_a_time = dictionary_lock(); const EDIT: &str = "text.spelling.editDictionary"; - let dir = vectorcraft_testkit::temp_dir("spelling-edit"); + let dir = vectorcraft_testkit::TempDir::new("spelling-edit"); let file = dir.join("Custom Dictionary.txt"); std::fs::write(&file, "pqzvka\npqzvkb\n").unwrap(); let mut s = session(); @@ -302,7 +302,7 @@ fn a_dictionary_edit_is_saved_whole_or_not_at_all() { fn a_word_another_window_saved_stays_when_this_save_fails() { let _one_at_a_time = dictionary_lock(); use std::os::unix::fs::PermissionsExt; - let dir = vectorcraft_testkit::temp_dir("spelling-readonly"); + let dir = vectorcraft_testkit::TempDir::new("spelling-readonly"); let file = dir.join("Custom Dictionary.txt"); std::fs::write(&file, "").unwrap(); let mut s = session(); diff --git a/crates/engine/src/tests/store.rs b/crates/engine/src/tests/store.rs index b6ac7b0201..21967473bb 100644 --- a/crates/engine/src/tests/store.rs +++ b/crates/engine/src/tests/store.rs @@ -7,10 +7,8 @@ use vectorcraft_color::cms; use crate::Session; use crate::store::{MAX_PRESET_FILE, file_stem, holds}; -fn fresh_dir(tag: &str) -> std::path::PathBuf { - let dir = vectorcraft_testkit::temp_dir(&format!("store-{tag}")); - let _ = std::fs::remove_dir_all(&dir); - dir +fn fresh_dir(tag: &str) -> vectorcraft_testkit::TempDir { + vectorcraft_testkit::TempDir::new(&format!("store-{tag}")) } fn saved_names(s: &mut Session) -> Vec { @@ -20,7 +18,8 @@ fn saved_names(s: &mut Session) -> Vec { #[test] fn saved_presets_come_back_in_the_next_session_and_renames_and_deletes_follow() { - let dir = fresh_dir("presets").join("PDF Presets"); + let root = fresh_dir("presets"); + let dir = root.join("PDF Presets"); let mut a = Session::new(); a.attach_pdf_preset_store(dir.clone()); a.execute("pdf.preset.save", &json!({"name": "Press", "description": "for the printer", "preset": "Press Quality"})).unwrap(); @@ -42,7 +41,8 @@ fn saved_presets_come_back_in_the_next_session_and_renames_and_deletes_follow() #[test] fn a_rename_that_cannot_be_written_keeps_the_preset_under_its_old_name() { - let dir = fresh_dir("rename-fails").join("PDF Presets"); + let root = fresh_dir("rename-fails"); + let dir = root.join("PDF Presets"); let mut a = Session::new(); a.attach_pdf_preset_store(dir.clone()); a.execute("pdf.preset.save", &json!({"name": "Web", "description": "for screens"})).unwrap(); @@ -59,7 +59,8 @@ fn a_rename_that_cannot_be_written_keeps_the_preset_under_its_old_name() { #[test] fn a_rename_that_only_changes_case_keeps_one_file() { - let dir = fresh_dir("rename-case").join("PDF Presets"); + let root = fresh_dir("rename-case"); + let dir = root.join("PDF Presets"); let mut a = Session::new(); a.attach_pdf_preset_store(dir.clone()); a.execute("pdf.preset.save", &json!({"name": "Web"})).unwrap(); @@ -80,7 +81,8 @@ fn file_names(dir: &std::path::Path) -> Vec { #[cfg(windows)] #[test] fn a_rename_that_only_changes_case_and_cannot_be_written_keeps_the_old_file() { - let dir = fresh_dir("rename-case-fails").join("PDF Presets"); + let root = fresh_dir("rename-case-fails"); + let dir = root.join("PDF Presets"); let mut a = Session::new(); a.attach_pdf_preset_store(dir.clone()); a.execute("pdf.preset.save", &json!({"name": "Web", "description": "for screens"})).unwrap(); @@ -103,7 +105,8 @@ fn a_rename_that_only_changes_case_and_cannot_be_written_keeps_the_old_file() { #[cfg(not(any(windows, target_vendor = "apple")))] #[test] fn a_rename_that_only_changes_case_and_cannot_be_moved_keeps_the_old_preset() { - let dir = fresh_dir("rename-case-blocked").join("PDF Presets"); + let root = fresh_dir("rename-case-blocked"); + let dir = root.join("PDF Presets"); let mut a = Session::new(); a.attach_pdf_preset_store(dir.clone()); a.execute("pdf.preset.save", &json!({"name": "Web", "description": "for screens"})).unwrap(); @@ -118,7 +121,8 @@ fn a_rename_that_only_changes_case_and_cannot_be_moved_keeps_the_old_preset() { #[test] fn a_folder_that_does_not_exist_yet_takes_the_presets_the_preferences_held() { - let dir = fresh_dir("seed").join("PDF Presets"); + let root = fresh_dir("seed"); + let dir = root.join("PDF Presets"); let mut a = Session::new(); a.execute("pdf.preset.save", &json!({"name": "From Preferences"})).unwrap(); a.attach_pdf_preset_store(dir.clone()); @@ -155,7 +159,8 @@ fn a_write_reads_the_file_it_replaces_only_one_byte_past_the_new_length() { #[test] fn a_saved_preset_replaces_an_oversized_file_in_its_place() { - let dir = fresh_dir("oversized-put").join("PDF Presets"); + let root = fresh_dir("oversized-put"); + let dir = root.join("PDF Presets"); let mut a = Session::new(); a.attach_pdf_preset_store(dir.clone()); a.execute("pdf.preset.save", &json!({"name": "Web"})).unwrap(); @@ -171,7 +176,8 @@ fn a_saved_preset_replaces_an_oversized_file_in_its_place() { #[test] fn damaged_unsafe_and_oversized_preset_files_are_skipped() { - let dir = fresh_dir("damaged").join("PDF Presets"); + let root = fresh_dir("damaged"); + let dir = root.join("PDF Presets"); let mut a = Session::new(); a.attach_pdf_preset_store(dir.clone()); a.execute("pdf.preset.save", &json!({"name": "Good"})).unwrap(); @@ -214,7 +220,8 @@ fn icc_named(name: &str) -> Vec { #[test] fn stored_profiles_register_again_and_removing_one_removes_its_copy() { - let dir = fresh_dir("profiles").join("Color Profiles"); + let root = fresh_dir("profiles"); + let dir = root.join("Color Profiles"); std::fs::create_dir_all(&dir).unwrap(); let name = "StoreRGB-1"; let file = format!("{}.icc", file_stem(name)); @@ -229,7 +236,8 @@ fn stored_profiles_register_again_and_removing_one_removes_its_copy() { // A profile loaded from elsewhere is copied in, whatever the file is called. let other = "StoreRGB-2"; - let loose = vectorcraft_testkit::temp_dir("store-loose").join("whatever.icm"); + let loose_dir = vectorcraft_testkit::TempDir::new("store-loose"); + let loose = loose_dir.join("whatever.icm"); std::fs::write(&loose, icc_named(other)).unwrap(); let r = s.execute("color.loadProfile", &json!({"path": loose.to_str().unwrap()})).unwrap(); assert_eq!((r["name"].as_str(), r["remembered"].as_bool()), (Some(other), Some(true))); diff --git a/crates/engine/src/tests/stored_path.rs b/crates/engine/src/tests/stored_path.rs new file mode 100644 index 0000000000..3e3bd4ef95 --- /dev/null +++ b/crates/engine/src/tests/stored_path.rs @@ -0,0 +1,202 @@ +//! `select.storedPath`, the Actions panel's Select Path step: the step stores a path's id and a +//! fingerprint of it, and playback selects that path only while it is still there unchanged and +//! can be selected. + +use std::io::Write; + +use serde_json::{Value, json}; + +use crate::*; + +/// A document with two rectangles and an ellipse, nothing selected → the session and their ids. +fn doc() -> (Session, [u64; 3]) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let mut add = |shape: &str, x: u32| s.execute(shape, &json!({"x": x, "y": 10, "width": 40, "height": 30})).unwrap()["id"].as_u64().unwrap(); + let ids = [add("shape.rectangle", 10), add("shape.rectangle", 80), add("shape.ellipse", 150)]; + s.execute("select.none", &json!({})).unwrap(); + (s, ids) +} + +fn select(s: &mut Session, ids: &[u64]) { + s.execute("select.set", &json!({"ids": ids})).unwrap(); +} + +fn selected(s: &Session) -> Vec { + s.doc().unwrap().selection.objects.iter().map(|id| id.0).collect() +} + +/// The Select Path step's params for `id`, selected alone. +fn step_for(s: &mut Session, id: u64) -> Value { + select(s, &[id]); + stored_path_step(s.doc().unwrap()).unwrap() +} + +#[test] +fn the_hash_is_fnv_1a_64() { + // The published FNV-1a 64-bit test values for "", "a" and "foobar". + for (bytes, want) in [(&b""[..], 0xcbf2_9ce4_8422_2325_u64), (b"a", 0xaf63_dc4c_8601_ec8c), (b"foobar", 0x8594_4171_f739_67e8)] { + let mut h = crate::cmd::select::Fnv::default(); + h.write_all(bytes).unwrap(); + assert_eq!(h.0, want, "{bytes:?}"); + } +} + +#[test] +fn the_step_stores_the_id_and_a_fingerprint_and_plays_by_selecting_the_path() { + let (mut s, [a, b, _]) = doc(); + let p = step_for(&mut s, a); + assert_eq!(p["id"], json!(a)); + let fingerprint = p["fingerprint"].as_str().unwrap(); + assert!(fingerprint.starts_with("v1:") && fingerprint.len() == 19, "{fingerprint}"); + assert_eq!(step_for(&mut s, a), p, "the same path gives the same step"); + assert_ne!(step_for(&mut s, b)["fingerprint"], p["fingerprint"], "another path gives another fingerprint"); + select(&mut s, &[b]); + let r = s.execute("select.storedPath", &p).unwrap(); + assert_eq!(r, json!({"count": 1, "ids": [a]})); + assert_eq!(selected(&s), [a], "only the stored path is selected"); +} + +#[test] +fn a_compound_path_is_one_step_and_a_path_in_a_group_is_one_too() { + let (mut s, [a, b, c]) = doc(); + select(&mut s, &[a, b]); + let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + let p = step_for(&mut s, compound); + let member = s.doc().unwrap().doc.children(Some(vectorcraft_doc::NodeId(compound))).unwrap()[0].id.0; + select(&mut s, &[member]); + assert_eq!(stored_path_step(s.doc().unwrap()).unwrap_err(), "select one whole path or compound path", "a member alone is not stored"); + s.execute("select.none", &json!({})).unwrap(); + s.execute("select.storedPath", &p).unwrap(); + assert_eq!(selected(&s), [compound]); + + select(&mut s, &[c, compound]); + let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + assert_eq!(stored_path_step(s.doc().unwrap()).unwrap_err(), "select one whole path or compound path", "a group is not stored"); + let inner = step_for(&mut s, c); + select(&mut s, &[group]); + s.execute("select.storedPath", &inner).unwrap(); + assert_eq!(selected(&s), [c], "the path inside the group is selected alone"); +} + +#[test] +fn only_one_whole_path_that_can_be_selected_is_stored() { + let (mut s, [a, b, _]) = doc(); + let whole = "select one whole path or compound path"; + assert_eq!(stored_path_step(s.doc().unwrap()).unwrap_err(), "select a path"); + select(&mut s, &[a, b]); + assert_eq!(stored_path_step(s.doc().unwrap()).unwrap_err(), "select only one path"); + s.execute("guide.add", &json!({"vertical": true, "pos": 200})).unwrap(); + select(&mut s, &[a]); + s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap(); + assert_eq!(s.doc().unwrap().selection.guides.len(), 1, "the guide is selected with the path"); + assert_eq!(stored_path_step(s.doc().unwrap()).unwrap_err(), "select only one path", "a path with a guide"); + s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap(); + assert_eq!(stored_path_step(s.doc().unwrap()).unwrap(), step_for(&mut s, a), "the path alone again"); + s.execute("select.anchors", &json!({"id": a, "anchors": [[0, 0]], "mode": "set"})).unwrap(); + assert_eq!(stored_path_step(s.doc().unwrap()).unwrap_err(), whole, "an anchor alone"); + let t = s.execute("text.create", &json!({"x": 10, "y": 200, "text": "Type"})).unwrap()["id"].as_u64().unwrap(); + select(&mut s, &[t]); + assert_eq!(stored_path_step(s.doc().unwrap()).unwrap_err(), whole, "type"); + select(&mut s, &[a]); + s.execute("object.lock", &json!({})).unwrap(); + let mut st = s.doc().unwrap().clone(); + st.selection.objects = vec![vectorcraft_doc::NodeId(a)]; + assert_eq!(stored_path_step(&st).unwrap_err(), "the path is hidden or locked, or cannot be selected here"); + let guide = { + let mut d = (*st.doc).clone(); + if let Some(vectorcraft_doc::NodeKind::Path { guide, .. }) = d.node_mut(vectorcraft_doc::NodeId(a)).map(|n| &mut n.kind) { + *guide = true; + } + d + }; + assert!(path_fingerprint(guide.node(vectorcraft_doc::NodeId(a)).unwrap()).is_none(), "a guide is not stored"); +} + +#[test] +fn a_changed_missing_hidden_or_other_path_is_an_error_and_keeps_the_selection() { + let (mut s, [a, b, c]) = doc(); + let p = step_for(&mut s, a); + let fails = |s: &mut Session, p: &Value, want: &str| { + select(s, &[c]); + let e = s.execute("select.storedPath", p).unwrap_err().to_string(); + assert!(e.contains(want), "{e}"); + assert_eq!(selected(s), [c], "the selection stays as it was"); + }; + select(&mut s, &[a]); + s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap(); + fails(&mut s, &p, "is not the stored path"); + let moved = step_for(&mut s, a); + s.execute("object.hide", &json!({})).unwrap(); + fails(&mut s, &moved, "hidden or locked"); + s.execute("object.showAll", &json!({})).unwrap(); + let shown = step_for(&mut s, b); + s.execute("edit.clear", &json!({})).unwrap(); + fails(&mut s, &shown, "no such object id"); + // Another document: the id names another path there, or nothing. + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 1, "y": 1, "width": 7, "height": 9})).unwrap(); + let c2 = s.execute("shape.ellipse", &json!({"x": 20, "y": 20, "width": 9, "height": 7})).unwrap()["id"].as_u64().unwrap(); + select(&mut s, &[c2]); + assert!(s.execute("select.storedPath", &moved).is_err()); + assert_eq!(selected(&s), [c2]); +} + +#[test] +fn a_path_on_a_locked_artboard_is_refused_in_isolation_mode_too() { + let (mut s, [a, b, _]) = doc(); + select(&mut s, &[a, b]); + let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + let p = step_for(&mut s, a); + s.execute("select.none", &json!({})).unwrap(); + s.execute("object.isolate", &json!({"id": group})).unwrap(); + s.execute("artboard.new", &json!({"x": 0, "y": 0, "width": 300, "height": 200})).unwrap(); + s.execute("artboard.setProps", &json!({"index": 1, "locked": true})).unwrap(); + assert!(s.doc().unwrap().isolation.is_some(), "the group stays isolated"); + assert!(s.doc().unwrap().doc.on_locked_artboard(vectorcraft_doc::NodeId(a)), "the path is on the locked artboard"); + let mut st = s.doc().unwrap().clone(); + st.selection.objects = vec![vectorcraft_doc::NodeId(a)]; + assert_eq!(stored_path_step(&st).unwrap_err(), "the path is hidden or locked, or cannot be selected here", "capture"); + let before = selected(&s); + let e = s.execute("select.storedPath", &p).unwrap_err().to_string(); + assert!(e.contains("hidden or locked"), "{e}"); + assert_eq!(selected(&s), before, "the selection stays as it was"); +} + +#[test] +fn a_failing_step_in_a_batch_undoes_the_steps_before_it() { + let (mut s, [a, _, c]) = doc(); + let p = step_for(&mut s, a); + select(&mut s, &[a]); + s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap(); + select(&mut s, &[c]); + let before = s.doc().unwrap().doc.clone(); + let steps = [json!({"command": "object.move", "params": {"dx": 1, "dy": 0}}), json!({"command": "select.storedPath", "params": p})]; + assert!(s.execute("command.batch", &json!({"commands": steps})).is_err()); + assert!(s.doc().unwrap().doc == before, "the move before the step is undone"); +} + +#[test] +fn params_are_an_id_and_a_v1_fingerprint() { + let (mut s, [a, ..]) = doc(); + let p = step_for(&mut s, a); + let f = p["fingerprint"].clone(); + for bad in [ + json!({"fingerprint": f}), + json!({"id": -1, "fingerprint": f}), + json!({"id": "1", "fingerprint": f}), + json!({"id": a}), + json!({"id": a, "fingerprint": 5}), + json!({"id": a, "fingerprint": "v2:0123456789abcdef"}), + json!({"id": a, "fingerprint": "v1:0123456789ABCDEF"}), + json!({"id": a, "fingerprint": "v1:0123456789abcde"}), + json!({"id": a, "fingerprint": f, "extra": 1}), + json!([a]), + ] { + assert!(stored_path_params(&bad).is_err(), "{bad}"); + s.execute("select.none", &json!({})).unwrap(); + assert!(s.execute("select.storedPath", &bad).is_err(), "{bad}"); + assert!(selected(&s).is_empty(), "{bad}"); + } + assert!(stored_path_params(&p).is_ok()); +} diff --git a/crates/engine/src/tests/strokegeom.rs b/crates/engine/src/tests/strokegeom.rs index f7500af358..524dabef3e 100644 --- a/crates/engine/src/tests/strokegeom.rs +++ b/crates/engine/src/tests/strokegeom.rs @@ -51,7 +51,7 @@ fn profiles_come_from_the_preset_catalogue() { assert!(spec.params.contains("arrowAlign")); // …and every arrowhead name `startArrow`/`endArrow` accept. for a in vectorcraft_doc::Arrowhead::ALL { - let name = serde_json::to_value(a).unwrap(); + let name = serde_json::to_value(&a).unwrap(); assert!(spec.params.contains(name.as_str().unwrap()), "{name}"); s.execute("stroke.set", &json!({"endArrow": name})).unwrap(); assert_eq!(stroke(&s, id).end_arrow, Some(a)); diff --git a/crates/engine/src/tests/stylelib.rs b/crates/engine/src/tests/stylelib.rs index 5124fb4502..fd8f2c7e24 100644 --- a/crates/engine/src/tests/stylelib.rs +++ b/crates/engine/src/tests/stylelib.rs @@ -44,6 +44,7 @@ fn builtin_libraries_are_listed_with_original_styles_using_catalogued_effects() assert!(libs.len() >= 8 && libs.iter().all(|l| l["category"] == "builtIn"), "{libs:?}"); assert!(libs.iter().any(|l| l["id"] == "game-hud" && l["name"] == "Game HUD"), "{libs:?}"); assert!(libs.iter().any(|l| l["id"] == "status-effects" && l["name"] == "Status Effects"), "{libs:?}"); + assert!(libs.iter().any(|l| l["id"] == "textures" && l["name"] == "Textures" && l["count"] == 8), "{libs:?}"); for l in libs { let id = l["id"].as_str().unwrap(); let g = run(&mut s, "graphicStyle.library", json!({"library": id})); @@ -64,6 +65,10 @@ fn builtin_libraries_are_listed_with_original_styles_using_catalogued_effects() let status = run(&mut s, "graphicStyle.library", json!({"library": "status-effects"})); let status_names: Vec<&str> = status["styles"].as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap()).collect(); assert_eq!(status_names, ["Poison Tint", "Freeze Edge", "Burn Aura", "Stun Pulse", "Stealth Fade", "Shield Buff"]); + let textures = run(&mut s, "graphicStyle.library", json!({"library": "textures"})); + let texture_names: Vec<&str> = textures["styles"].as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap()).collect(); + let expected = ["Fine Grain", "Canvas Weave", "Burlap Sack", "Cracked Glaze", "Mosaic Floor", "Quilted Squares", "Leaded Glass", "Damp Paper"]; + assert_eq!(texture_names, expected); let id = rect(&mut s, 10.0, 20.0, 40.0, 30.0); let r = run(&mut s, "graphicStyle.addFromLibrary", json!({"library": "game-hud", "name": "Mana Glow", "apply": true, "ids": [id.0]})); assert_eq!((names(&r["added"]), r["applied"].as_str()), (vec!["Mana Glow"], Some("Mana Glow"))); @@ -82,6 +87,87 @@ fn builtin_libraries_are_listed_with_original_styles_using_catalogued_effects() assert!(s.execute("graphicStyle.library", &json!({"library": "nope"})).is_err()); } +#[test] +fn painted_and_sketched_styles_set_every_effect_setting_and_reopen_applied() { + let mut s = session(); + let list = run(&mut s, "graphicStyle.libraries", json!({})); + let libs = list["libraries"].as_array().unwrap(); + let at = libs.iter().position(|l| l["id"] == "painted-sketched").expect("listed"); + assert_eq!((libs[at]["name"].as_str(), libs[at]["count"].as_u64()), (Some("Painted and Sketched"), Some(7))); + assert_eq!(libs[at - 1]["id"], "textures"); + let g = run(&mut s, "graphicStyle.library", json!({"library": "Painted and Sketched"})); + let listed: Vec<(&str, &str, Vec<&str>)> = + g["styles"].as_array().unwrap().iter().map(|x| (x["name"].as_str().unwrap(), x["fill"].as_str().unwrap(), names(&x["effects"]))).collect(); + let want = [ + ("Washed Blue", "#8ab9c9", "artistic.watercolor"), + ("Bristle Ochre", "#c4975a", "artistic.dryBrush"), + ("Pastel Heather", "#a78ca5", "artistic.roughPastels"), + ("Charcoal Shade", "#666666", "sketch.charcoal"), + ("Ink Contour", "#d9e2df", "brushStrokes.inkOutlines"), + ("Wet Ink", "#637b85", "brushStrokes.sumiE"), + ("Fine Pen", "#d8d4c6", "sketch.graphicPen"), + ]; + assert_eq!(listed, want.iter().map(|&(n, f, e)| (n, f, vec![e])).collect::>()); + // Every setting of each effect is given, with the catalog's key and kind of value. + let (_, lib) = cmd::stylelib::library(&s, "painted-sketched").unwrap(); + for st in &lib.styles { + let e = &st.appearance.effects[0]; + let defaults = vectorcraft_render::effects::effect_info(&e.id).unwrap().defaults; + let (set, all) = (e.params.as_object().unwrap(), defaults.as_object().unwrap()); + let keys = |m: &serde_json::Map| m.keys().cloned().collect::>(); + assert_eq!(keys(set), keys(all), "{}", st.name); + for (k, v) in set { + let kind = |v: &Value| (v.is_number(), v.is_string(), v.is_boolean()); + assert_eq!(kind(v), kind(&all[k]), "{} / {k}", st.name); + } + } + let strokes: Vec<(&str, f64)> = + lib.styles.iter().filter(|g| g.appearance.stroke_paint() != Paint::None).map(|g| (g.name.as_str(), g.appearance.stroke_width())).collect(); + assert_eq!(strokes, [("Bristle Ochre", 1.0), ("Ink Contour", 1.0)]); + + // Each one adds and applies to a rectangle in one undo step. + let mut ids = vec![]; + for (i, (name, fill, effect)) in want.iter().enumerate() { + let id = rect(&mut s, 10.0 + 25.0 * i as f64, 20.0, 20.0, 30.0); + let before = undo_len(&s); + let r = run(&mut s, "graphicStyle.addFromLibrary", json!({"library": "painted-sketched", "name": name, "apply": true, "ids": [id.0]})); + assert_eq!((names(&r["added"]), r["applied"].as_str()), (vec![*name], Some(*name))); + assert_eq!(undo_len(&s), before + 1, "{name}"); + let node = doc(&s).node(id).unwrap(); + assert_eq!(node.appearance.fill_paint(), Paint::solid(vectorcraft_color::Color::from_hex(fill).unwrap()), "{name}"); + assert_eq!(node.appearance.effects.iter().map(|e| e.id.as_str()).collect::>(), [*effect]); + assert_eq!(node.appearance.effects[0].params, lib.style(name).unwrap().appearance.effects[0].params, "{name}"); + ids.push((id, *name)); + } + // Adding one again reuses it: no new style, no undo step. + let before = (undo_len(&s), doc(&s).graphic_styles.len()); + let r = run(&mut s, "graphicStyle.addFromLibrary", json!({"library": "painted-sketched", "name": "Wet Ink"})); + assert_eq!((names(&r["added"]), names(&r["existing"])), (vec![], vec!["Wet Ink"])); + assert_eq!((undo_len(&s), doc(&s).graphic_styles.len()), before); + // An unknown style or library changes nothing. + assert!(s.execute("graphicStyle.addFromLibrary", &json!({"library": "painted-sketched", "names": ["Wet Ink", "Nope"]})).is_err()); + assert!(s.execute("graphicStyle.addFromLibrary", &json!({"library": "painted-and-sketched", "name": "Wet Ink"})).is_err()); + assert_eq!((undo_len(&s), doc(&s).graphic_styles.len()), before); + + // Saved and opened again, the styles keep their effects and the rectangles stay linked to them. + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + run(&mut s, "document.open", json!({"name": "painted.vectorcraft", "dataBase64": b64})); + for (id, name) in &ids { + let d = doc(&s); + let style = d.graphic_style(name).unwrap(); + assert!(style.same_look(lib.style(name).unwrap()), "{name}"); + let node = d.node(*id).unwrap(); + assert_eq!((node.extras().graphic_style, &node.appearance.effects), (Some(style.id), &style.appearance.effects), "{name}"); + } + + // With nothing selected, `apply` only adds; empty `names` adds the whole library in order. + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let r = run(&mut s, "graphicStyle.addFromLibrary", json!({"library": "painted-sketched", "name": "Fine Pen", "apply": true})); + assert!(r.get("applied").is_none() && doc(&s).graphic_style("Fine Pen").is_some()); + let r = run(&mut s, "graphicStyle.addFromLibrary", json!({"library": "painted-sketched", "names": []})); + assert_eq!((names(&r["added"]), names(&r["existing"])), (want[..6].iter().map(|w| w.0).collect::>(), vec!["Fine Pen"])); +} + #[test] fn add_dedupes_names_as_one_undo_step() { let mut s = session(); @@ -167,6 +253,53 @@ fn add_with_null_ids_applies_to_selection() { assert_eq!(doc(&s).node(id).unwrap().extras().graphic_style, Some(style.id)); } +#[test] +fn textures_styles_apply_their_texture_effects_and_keep_their_params_through_save_and_open() { + let mut s = session(); + let (_, lib) = cmd::stylelib::library(&s, "textures").unwrap(); + let mut ids = vec![]; + for (i, g) in lib.styles.iter().enumerate() { + let id = rect(&mut s, (i % 4) as f64 * 50.0, (i / 4) as f64 * 50.0, 40.0, 40.0); + let before = undo_len(&s); + let r = run(&mut s, "graphicStyle.addFromLibrary", json!({"library": "textures", "name": g.name, "apply": true, "ids": [id.0]})); + assert_eq!((names(&r["added"]), r["applied"].as_str()), (vec![g.name.as_str()], Some(g.name.as_str()))); + assert_eq!(undo_len(&s), before + 1, "{}: added and applied as one step", g.name); + ids.push(id); + } + let effects = |s: &Session| -> Vec> { + ids.iter().map(|id| doc(s).node(*id).unwrap().appearance.effects.iter().map(|e| (e.id.clone(), e.params.clone())).collect()).collect() + }; + let applied = effects(&s); + let effect_ids: Vec> = applied.iter().map(|fx| fx.iter().map(|(id, _)| id.as_str()).collect()).collect(); + assert_eq!( + effect_ids, + [ + ["texture.grain"], + ["texture.texturizer"], + ["texture.texturizer"], + ["texture.craquelure"], + ["texture.mosaicTiles"], + ["texture.patchwork"], + ["texture.stainedGlass"], + ["sketch.waterPaper"], + ] + ); + assert_eq!(applied[1][0].1["texture"], "canvas"); + assert_eq!(applied[3][0].1["crackSpacing"], 12.0); + for (fx, g) in applied.iter().zip(&lib.styles) { + let want: Vec<(String, Value)> = g.appearance.effects.iter().map(|e| (e.id.clone(), e.params.clone())).collect(); + assert_eq!(fx, &want, "{} applies the library's params", g.name); + } + let b64 = run(&mut s, "document.serialize", json!({"format": "vectorcraft"}))["dataBase64"].as_str().unwrap().to_string(); + run(&mut s, "document.open", json!({"name": "textures.vectorcraft", "dataBase64": b64})); + assert_eq!(effects(&s), applied, "the params survive a save and open"); + for g in &lib.styles { + let saved = doc(&s).graphic_style(&g.name).unwrap(); + assert!(saved.same_look(g), "{} keeps its look", g.name); + assert!(ids.iter().any(|id| doc(&s).node(*id).unwrap().extras().graphic_style == Some(saved.id)), "{} stays linked", g.name); + } +} + /// A document with pattern `name` (a dot) and its swatch. fn add_pattern(s: &mut Session, name: &str, radius: f64) { s.edit("Pattern", |d, _| { diff --git a/crates/engine/src/tests/styles.rs b/crates/engine/src/tests/styles.rs index 3ffb2ed615..6f77b58971 100644 --- a/crates/engine/src/tests/styles.rs +++ b/crates/engine/src/tests/styles.rs @@ -3,7 +3,7 @@ use serde_json::{Value, json}; use vectorcraft_color::{BlendMode, Color, Paint}; -use vectorcraft_doc::{GraphicStyle, Knockout, Node}; +use vectorcraft_doc::{GraphicStyle, Knockout, Node, Shared}; use crate::*; @@ -202,6 +202,77 @@ fn redefine_leaves_unlinked_and_edited_objects_alone() { assert!(s.execute("graphicStyle.redefine", &json!({"id": c.0})).is_err()); } +/// Applying a style to several objects gives them one shared copy of its appearance; editing one +/// object gives that one its own, and the saved file is the same as with a copy for each. +#[test] +fn applying_a_style_shares_one_appearance() { + let mut s = session(); + let a = rect(&mut s, 10.0); + run(&mut s, "appearance.clear", json!({})); + run(&mut s, "paint.setFill", json!({"color": "#00ff00"})); + run(&mut s, "paint.setStroke", json!({"color": "#0000ff"})); + run(&mut s, "effect.apply", json!({"effect": "distort.roughen"})); + run(&mut s, "graphicStyle.new", json!({"name": "Rough"})); + let rough = style(&s, "Rough"); + let ids = [rect(&mut s, 100.0), rect(&mut s, 200.0), rect(&mut s, 300.0)]; + let [b, c, d] = ids; + run(&mut s, "graphicStyle.apply", json!({"name": "Rough", "ids": [b.0, c.0, d.0]})); + let shared = |s: &Session, x: NodeId, y: NodeId| Shared::ptr_eq(&node(s, x).appearance, &node(s, y).appearance); + assert!(shared(&s, b, c) && shared(&s, c, d), "one appearance for every object"); + for id in ids { + assert_eq!(node(&s, id).appearance, rough.appearance); + assert_eq!(node(&s, id).extras().graphic_style, Some(rough.id)); + } + // The saved file is the same as one where each object has its own copy. + let doc = s.doc().unwrap().doc.clone(); + let mut copies = (*doc).clone(); + for id in ids { + let n = copies.node_mut(id).unwrap(); + n.appearance = Shared::new((*n.appearance).clone()); + } + assert!(!Shared::ptr_eq(&copies.node(b).unwrap().appearance, &copies.node(c).unwrap().appearance)); + for pretty in [false, true] { + assert_eq!(vectorcraft_format::save(&doc, pretty), vectorcraft_format::save(&copies, pretty)); + } + + // Editing one object leaves the others and the style as they were. + set_fill(&mut s, b, "#ff0000"); + assert!(!shared(&s, b, c) && shared(&s, c, d)); + assert_eq!(fill(&s, b), Paint::solid(Color::from_hex("#ff0000").unwrap())); + assert_eq!(node(&s, c).appearance, rough.appearance); + assert_eq!(style(&s, "Rough"), rough); + assert_eq!(linked(&mut s, "Rough"), vec![a.0, c.0, d.0]); + + // Undo and redo restore the values, still shared. + run(&mut s, "edit.undo", json!({})); + assert!(shared(&s, b, c) && node(&s, b).appearance == rough.appearance); + run(&mut s, "edit.undo", json!({})); + for id in ids { + assert_ne!(node(&s, id).appearance, rough.appearance); + assert_eq!(node(&s, id).extras().graphic_style, None); + } + run(&mut s, "edit.redo", json!({})); + assert!(shared(&s, b, c) && shared(&s, c, d) && node(&s, d).appearance == rough.appearance); +} + +/// Redefine Graphic Style gives the objects still linked one shared copy of the new appearance. +#[test] +fn redefine_shares_one_appearance() { + let mut s = session(); + let (a, b, c) = linked_three(&mut s); + let d = rect(&mut s, 300.0); + run(&mut s, "graphicStyle.apply", json!({"name": "S"})); + set_fill(&mut s, d, "#00ff00"); + set_fill(&mut s, a, "#0000ff"); + run(&mut s, "graphicStyle.redefine", json!({"name": "S", "id": a.0})); + let (nb, nc) = (node(&s, b), node(&s, c)); + assert!(Shared::ptr_eq(&nb.appearance, &nc.appearance)); + assert_eq!(nb.appearance, style(&s, "S").appearance); + // The edited object keeps its own look. + assert_eq!(fill(&s, d), Paint::solid(Color::from_hex("#00ff00").unwrap())); + assert!(!Shared::ptr_eq(&node(&s, d).appearance, &nb.appearance)); +} + #[test] fn deleting_a_style_unlinks_and_renaming_keeps_links() { let mut s = session(); diff --git a/crates/engine/src/tests/swatchcmds.rs b/crates/engine/src/tests/swatchcmds.rs index cbf595d6d8..af059e5e33 100644 --- a/crates/engine/src/tests/swatchcmds.rs +++ b/crates/engine/src/tests/swatchcmds.rs @@ -355,6 +355,35 @@ fn new_color_group_from_artwork_lists_each_color_once_with_free_names() { assert_eq!(*doc(&s), before); } +/// New Color Group takes the named solid swatches in the order given. A name listed twice takes +/// the next swatch of that name, found ungrouped first and then in each colour group, and the +/// lists the swatches leave keep their order. Gradients and names no swatch has take nothing. +#[test] +fn new_color_group_takes_named_swatches_in_order_from_every_list() { + let mut s = session(); + let twin = vectorcraft_color::Swatch { name: "Red".into(), paint: Paint::solid(Color::rgb(0.5, 0.0, 0.0)), global: false, spot: false }; + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc) + .swatch_groups + .iter_mut() + .find(|g| g.name == "Brights") + .unwrap() + .swatches + .push(twin.clone()); + let red = doc(&s).swatch("Red").cloned().unwrap(); + let mut ungrouped = names(&s, None); + let mut brights = names(&s, Some("Brights")); + let r = run(&mut s, "swatch.newGroup", json!({"name": "Mine", "swatches": ["Red", "Orange", "Sunset", "Red", "Missing", "Bright Red"]})); + assert_eq!(r["swatches"], json!(["Red", "Orange", "Red", "Bright Red"])); + let group = &doc(&s).swatch_groups.iter().find(|g| g.name == "Mine").unwrap().swatches; + assert_eq!(group[0], red); + assert_eq!(group[2], twin); + ungrouped.retain(|n| n != "Red" && n != "Orange"); + brights.retain(|n| n != "Red" && n != "Bright Red"); + assert_eq!(names(&s, None), ungrouped); + assert_eq!(names(&s, Some("Brights")), brights); + assert!(doc(&s).swatch("Sunset").is_some()); +} + #[test] fn edit_color_group_numbers_extra_colors_after_the_names_it_keeps() { let mut s = session(); diff --git a/crates/engine/src/tests/swatchlib.rs b/crates/engine/src/tests/swatchlib.rs index 3ecb5e68e1..445ce38ea7 100644 --- a/crates/engine/src/tests/swatchlib.rs +++ b/crates/engine/src/tests/swatchlib.rs @@ -130,11 +130,9 @@ fn reset_defaults_restores_missing_swatches_or_replaces_them() { assert_eq!(s.paint.fill, Paint::solid(Color::from_hex("#abcdef").unwrap()), "the default fill is unlinked too"); } -/// A fresh scratch folder for one test. -fn temp_dir(name: &str) -> std::path::PathBuf { - let d = std::env::temp_dir().join(format!("vc-swatchlib-{name}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&d); - d +/// A fresh scratch folder for one test, removed when the returned value is dropped. +fn temp_dir(name: &str) -> vectorcraft_testkit::TempDir { + vectorcraft_testkit::TempDir::new(&format!("swatchlib-{name}")) } #[test] @@ -638,6 +636,77 @@ fn gradient_libraries_are_listed_and_gradient_swatches_rename_and_take_new_gradi assert_eq!(doc(&s).swatch("Red").unwrap().paint.color().map(|c| c.to_hex()), Some("#00ff00".into())); } +#[test] +fn organic_fades_add_with_their_method_midpoints_and_opacities_in_rgb_and_cmyk() { + let lib = vectorcraft_color::libraries::builtin_library("organic-fades").unwrap(); + for mode in ["rgb", "cmyk"] { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 100, "height": 100, "colorMode": mode})); + let list = run(&mut s, "swatch.library.list", json!({})); + let row = list["libraries"].as_array().unwrap().iter().find(|l| l["id"] == "organic-fades").unwrap().clone(); + assert_eq!( + (row["name"].as_str(), row["category"].as_str(), row["count"].as_u64()), + (Some("Organic Fades"), Some("gradients"), Some(lib.len() as u64)) + ); + let id = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}))["id"].clone(); + let r = run(&mut s, "swatch.library.add", json!({"library": "organic-fades", "names": ["Petal", "Dew"], "apply": "fill"})); + assert_eq!((r["added"].clone(), r["applied"].clone()), (json!(["Petal", "Dew"]), json!("Petal")), "{mode}"); + for name in ["Petal", "Dew"] { + // The swatch comes as the library has it: stops (colors as given, opacities, midpoints) and method. + let Paint::Gradient(added) = &doc(&s).swatch(name).unwrap().paint else { panic!("{name} is a gradient") }; + let Paint::Gradient(want) = &lib.swatch(name).unwrap().paint else { panic!("{name} is a gradient") }; + assert_eq!(added.gradient, want.gradient, "{mode} {name}"); + assert_eq!(added.gradient.method, vectorcraft_color::GradientMethod::Perceptual); + assert!(added.gradient.stops.iter().all(|st| matches!(st.color, Color::Rgb { .. })), "{mode} {name}: the stops stay RGB"); + assert!(added.gradient.stops.iter().any(|st| st.opacity < 1.0 && (st.midpoint - 0.5).abs() > 0.02), "{mode} {name}"); + } + // The fill takes the fade's method, opacities and midpoints. + let fill = doc(&s).node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).unwrap().appearance.fill_paint(); + let (Paint::Gradient(fill), Paint::Gradient(want)) = (fill, &lib.swatch("Petal").unwrap().paint) else { panic!("a gradient fill") }; + assert_eq!(fill.gradient.method, want.gradient.method, "{mode}"); + let shape = |g: &vectorcraft_color::Gradient| g.stops.iter().map(|st| (st.offset, st.opacity, st.midpoint)).collect::>(); + assert_eq!(shape(&fill.gradient), shape(&want.gradient), "{mode}"); + } +} + +#[test] +fn holographic_glows_add_whole_in_rgb_and_cmyk_as_one_undo_step() { + let lib = vectorcraft_color::libraries::builtin_library("holographic").unwrap(); + let Paint::Gradient(want) = &lib.swatch("Mint Halo").unwrap().paint else { panic!("Mint Halo is a gradient") }; + for mode in ["rgb", "cmyk"] { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 100, "height": 100, "colorMode": mode})); + let list = run(&mut s, "swatch.library.list", json!({})); + let row = list["libraries"].as_array().unwrap().iter().find(|l| l["id"] == "holographic").unwrap().clone(); + assert_eq!((row["name"].as_str(), row["category"].as_str(), row["count"].as_u64()), (Some("Holographic"), Some("gradients"), Some(14))); + let got = run(&mut s, "swatch.library.get", json!({"library": "holographic"})); + assert!(got.to_string().contains("Mint Halo"), "{mode}: get lists Mint Halo"); + let id = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}))["id"].clone(); + let node = vectorcraft_doc::NodeId(id.as_u64().unwrap()); + let before = undo_len(&s); + let r = run(&mut s, "swatch.library.add", json!({"library": "holographic", "names": ["Mint Halo"], "apply": "fill"})); + assert_eq!((r["added"].clone(), r["applied"].clone()), (json!(["Mint Halo"]), json!("Mint Halo")), "{mode}"); + assert_eq!(undo_len(&s), before + 1, "{mode}: added and applied as one step"); + // The swatch comes as the library has it: kind, stops (RGB colors, opacities, midpoints) and method. + let Paint::Gradient(added) = &doc(&s).swatch("Mint Halo").unwrap().paint else { panic!("{mode}: a gradient swatch") }; + assert_eq!(added.gradient, want.gradient, "{mode}"); + assert!(added.gradient.stops.iter().all(|st| matches!(st.color, Color::Rgb { .. })), "{mode}: the stops stay RGB"); + assert_eq!(added.gradient.stops.last().map(|st| st.opacity), Some(0.0), "{mode}: clear at the edge"); + let Paint::Gradient(fill) = doc(&s).node(node).unwrap().appearance.fill_paint() else { panic!("{mode}: a gradient fill") }; + assert_eq!((fill.gradient.kind, fill.gradient.method), (want.gradient.kind, want.gradient.method), "{mode}"); + assert_eq!(fill.gradient.stops, want.gradient.stops, "{mode}"); + run(&mut s, "edit.undo", json!({})); + assert!(doc(&s).swatch("Mint Halo").is_none(), "{mode}: undo removes the add"); + assert!(!matches!(doc(&s).node(node).unwrap().appearance.fill_paint(), Paint::Gradient(_)), "{mode}: and the fill"); + // A document swatch already named Mint Halo stays; the glow comes in under a number. + run(&mut s, "swatch.new", json!({"name": "Mint Halo", "color": "#123456"})); + let r = run(&mut s, "swatch.library.add", json!({"library": "holographic", "names": ["Mint Halo"]})); + assert_eq!(r["added"], json!(["Mint Halo 2"]), "{mode}"); + assert!(doc(&s).swatch("Mint Halo").unwrap().paint.color().is_some(), "{mode}: the document's swatch is kept"); + assert!(matches!(&doc(&s).swatch("Mint Halo 2").unwrap().paint, Paint::Gradient(g) if g.gradient == want.gradient)); + } +} + #[test] fn pattern_libraries_bring_their_patterns_and_add_each_once() { let mut s = session(); @@ -765,6 +834,82 @@ fn a_pattern_library_adds_only_the_picked_pattern_and_it_undoes_and_saves() { assert_eq!(back.swatch("Checkerboard").map(|w| &w.paint), doc(&s).swatch("Checkerboard").map(|w| &w.paint)); } +/// Grit Textures is listed after Geometric Patterns. One of its patterns comes in with its swatch +/// once, as one undo step that also takes both away, and both stay after a save and reopen. +#[test] +fn a_grit_texture_adds_once_undoes_and_saves() { + let mut s = session(); + let list = run(&mut s, "swatch.library.list", json!({})); + let ids: Vec<&str> = + list["libraries"].as_array().unwrap().iter().filter(|l| l["category"] == "patterns").map(|l| l["id"].as_str().unwrap()).collect(); + assert_eq!(ids, ["geometric-patterns", "grit-textures", "optical-effects"]); + let got = run(&mut s, "swatch.library.get", json!({"library": "Grit Textures"})); + let names: Vec<&str> = got["swatches"].as_array().unwrap().iter().map(|w| w["name"].as_str().unwrap()).collect(); + assert_eq!(names, ["Fine Grain", "Coarse Grit", "Sand", "Speckle", "Stipple", "Scratches", "Sparse Flecks", "Dense Flecks"]); + let counts = |d: &vectorcraft_doc::Document| (d.patterns.len(), d.swatches_iter().count()); + let empty = counts(doc(&s)); + let undo = undo_len(&s); + let r = run(&mut s, "swatch.library.add", json!({"library": "grit-textures", "names": ["Stipple"]})); + assert_eq!(r["added"], json!(["Stipple"])); + assert_eq!((counts(doc(&s)), undo_len(&s)), ((empty.0 + 1, empty.1 + 1), undo + 1)); + let def = doc(&s).pattern("Stipple").expect("the pattern comes with its swatch").clone(); + assert!(def.art.len() >= 144, "{} marks", def.art.len()); + assert!(matches!(doc(&s).swatch("Stipple").map(|w| &w.paint), Some(Paint::Pattern { pattern, .. }) if pattern == "Stipple")); + let r = run(&mut s, "swatch.library.add", json!({"library": "grit-textures", "names": ["Stipple"]})); + assert_eq!((r["added"].clone(), r["existing"].clone()), (json!([]), json!(["Stipple"]))); + assert_eq!((counts(doc(&s)), undo_len(&s)), ((empty.0 + 1, empty.1 + 1), undo + 1), "added once"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(counts(doc(&s)), empty); + assert!(doc(&s).pattern("Stipple").is_none() && doc(&s).swatch("Stipple").is_none()); + run(&mut s, "edit.redo", json!({})); + let back = vectorcraft_format::load(&vectorcraft_format::save(doc(&s), false)).unwrap(); + assert_eq!(back.pattern("Stipple"), Some(&def)); + assert_eq!(back.swatch("Stipple").map(|w| &w.paint), doc(&s).swatch("Stipple").map(|w| &w.paint)); +} + +/// Optical Effects is listed after Grit Textures, and reading it adds nothing. Clicking one of +/// its patterns brings it with its swatch and fills the selection with it, once, as one undo step +/// that also takes both away, and both stay after a save and reopen. +#[test] +fn an_optical_effect_adds_once_fills_undoes_and_saves() { + let mut s = session(); + let counts = |d: &vectorcraft_doc::Document| (d.patterns.len(), d.swatches_iter().count()); + let empty = counts(doc(&s)); + let list = run(&mut s, "swatch.library.list", json!({})); + let ids: Vec<&str> = + list["libraries"].as_array().unwrap().iter().filter(|l| l["category"] == "patterns").map(|l| l["id"].as_str().unwrap()).collect(); + assert_eq!(ids, ["geometric-patterns", "grit-textures", "optical-effects"]); + let got = run(&mut s, "swatch.library.get", json!({"library": "Optical Effects"})); + let names: Vec<&str> = got["swatches"].as_array().unwrap().iter().map(|w| w["name"].as_str().unwrap()).collect(); + assert_eq!( + names, + ["Sine Bands", "Ripple Lines", "Interference Rings", "Offset Rings", "Warped Checks", "Pinched Stripes", "Chevron Pulse", "Radiating Lenses"] + ); + assert_eq!(counts(doc(&s)), empty, "reading a library adds no pattern or swatch"); + let id = vectorcraft_doc::NodeId(run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}))["id"].as_u64().unwrap()); + let undo = undo_len(&s); + let r = run(&mut s, "swatch.library.add", json!({"library": "optical-effects", "names": ["Warped Checks"], "apply": "fill"})); + assert_eq!((r["added"].clone(), r["applied"].clone()), (json!(["Warped Checks"]), json!("Warped Checks"))); + assert_eq!((counts(doc(&s)), undo_len(&s)), ((empty.0 + 1, empty.1 + 1), undo + 1)); + let def = doc(&s).pattern("Warped Checks").expect("the pattern comes with its swatch").clone(); + assert_eq!(def.art.len(), 32, "the black cells of an 8 × 8 checkerboard"); + assert!(matches!(doc(&s).swatch("Warped Checks").map(|w| &w.paint), Some(Paint::Pattern { pattern, .. }) if pattern == "Warped Checks")); + let filled = |d: &vectorcraft_doc::Document| matches!(d.node(id).unwrap().appearance.fill_paint(), Paint::Pattern { pattern, .. } if pattern == "Warped Checks"); + assert!(filled(doc(&s))); + let r = run(&mut s, "swatch.library.add", json!({"library": "optical-effects", "names": ["Warped Checks"]})); + assert_eq!((r["added"].clone(), r["existing"].clone()), (json!([]), json!(["Warped Checks"]))); + assert_eq!((counts(doc(&s)), undo_len(&s)), ((empty.0 + 1, empty.1 + 1), undo + 1), "added once"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(counts(doc(&s)), empty); + assert!(doc(&s).pattern("Warped Checks").is_none() && doc(&s).swatch("Warped Checks").is_none() && !filled(doc(&s))); + run(&mut s, "edit.redo", json!({})); + assert!(filled(doc(&s))); + let back = vectorcraft_format::load(&vectorcraft_format::save(doc(&s), false)).unwrap(); + assert_eq!(back.pattern("Warped Checks"), Some(&def)); + assert_eq!(back.swatch("Warped Checks").map(|w| &w.paint), doc(&s).swatch("Warped Checks").map(|w| &w.paint)); + assert!(filled(&back)); +} + /// A device name is saved with a `-` after it, which can be another library's own name: neither /// library replaces the other, and saving either again replaces only itself. #[test] diff --git a/crates/engine/src/tests/symbol_nine_slice.rs b/crates/engine/src/tests/symbol_nine_slice.rs index fba17f11ee..b0689d1587 100644 --- a/crates/engine/src/tests/symbol_nine_slice.rs +++ b/crates/engine/src/tests/symbol_nine_slice.rs @@ -250,3 +250,103 @@ fn a_guide_dragged_on_the_canvas_changes_how_a_scaled_instance_draws() { let left = s.doc().unwrap().doc.symbol_nine_slice("Panel").unwrap().left; assert!((left - 0.05).abs() < 1e-9, "{left}"); } + +/// The 200 × 150 [`panel`] instance with its left guide 25 % outside the art: the left column +/// holds no art, so the corner square is in the center column, which runs 0..75 in the art and +/// 0..175 in the instance, and the center square moves with it. The rows are as before. +fn assert_left_outside(boxes: &[Rect]) { + let k = 175.0 / 75.0; + let want = [ + Rect::new(50.0, 50.0, 250.0, 200.0), + Rect::new(50.0, 50.0, 50.0 + 10.0 * k, 60.0), + Rect::new(50.0 + 45.0 * k, 115.0, 50.0 + 55.0 * k, 135.0), + ]; + assert_eq!(boxes.len(), want.len(), "{boxes:?}"); + for (b, w) in boxes.iter().zip(want) { + assert!(close(*b, w), "{b:?} vs {w:?} in {boxes:?}"); + } +} + +/// `symbol.options` takes guides outside the art, within -16..16 and in order on each axis, as +/// one undo step; a scaled instance then draws by the cells its art falls in, and Break Link to +/// Symbol gives that art. Values out of range or out of order are refused without an edit. +#[test] +fn guides_outside_the_art_are_set_by_command_and_scale_by_the_cells_that_hold_art() { + let (mut s, id) = panel(); + s.execute("symbol.options", &json!({"name": "Panel", "nineSliceGuides": [-0.25, 0.25, 0.25, 0.25]})).unwrap(); + assert_left_outside(&placed_boxes(&s, id)); + let list = s.execute("symbol.list", &json!({})).unwrap(); + assert_eq!(list["symbols"][0]["nineSlice"], json!([-0.25, 0.25, 0.25, 0.25])); + for bad in [json!([-16.5, 0.25, 0.25, 0.25]), json!([0.25, 0.25, 0.25, 17]), json!([1.2, 0.25, -0.2, 0.25]), json!([0.25, 0.6, 0.25, 0.6])] { + let e = s.execute("symbol.options", &json!({"name": "Panel", "nineSliceGuides": bad})).unwrap_err().to_string(); + assert!(e.contains("each -16..16"), "{e}"); + } + assert_eq!(s.doc().unwrap().doc.symbol_nine_slice("Panel").unwrap().left, -0.25, "no edit"); + s.execute("symbol.options", &json!({"name": "Panel", "nineSliceGuides": [1.25, 0.25, -0.5, 0.25]})).unwrap(); + // Both vertical guides past the art's right edge: the art keeps its width from the left. + let boxes = placed_boxes(&s, id); + assert!(close(boxes[0], Rect::new(50.0, 50.0, 150.0, 200.0)) && close(boxes[1], Rect::new(50.0, 50.0, 60.0, 60.0)), "{boxes:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_left_outside(&placed_boxes(&s, id)); + let r = s.execute("symbol.breakLink", &json!({})).unwrap(); + let art = NodeId(r["ids"][0].as_u64().unwrap()); + assert_left_outside(&path_boxes(s.doc().unwrap().doc.node(art).unwrap())); +} + +/// Dragging the left guide past the art's left edge on the canvas puts it outside the art, as one +/// undo step, and the scaled instance draws by the cells that hold art. +#[test] +fn a_guide_dragged_past_the_arts_edge_lies_outside_it() { + let (mut s, id) = panel(); + s.execute("symbol.edit", &json!({"name": "Panel"})).unwrap(); + let v = ViewInfo::default(); + s.select_tool("selection", v).unwrap(); + let e = s.doc().unwrap().doc.edited_nine_slice().unwrap(); + let ((a, b), (l, r)) = (e.line(NineSliceGuide::Left), (e.line(NineSliceGuide::Left).0.x, e.line(NineSliceGuide::Right).0.x)); + let y = (a.y + b.y) / 2.0; + // The guides lie a quarter in from each edge, so the art's left edge lies half the guides' + // distance to the left of the left guide, and 25 % outside it lies as far again. + let to = l - (r - l); + s.pointer(&PointerEvent::new(PointerKind::Down, l + 1.0, y), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, to, y), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, to, y), v).unwrap(); + let g = s.doc().unwrap().doc.symbol_nine_slice("Panel").unwrap(); + assert!((g.left + 0.25).abs() < 1e-9, "{g:?}"); + let e = s.doc().unwrap().doc.edited_nine_slice().unwrap(); + assert!((e.line(NineSliceGuide::Left).0.x - to).abs() < 1e-9, "the guide is drawn where it was dropped"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.symbol_nine_slice("Panel").unwrap().left, 0.25, "one undo step"); + s.execute("edit.redo", &json!({})).unwrap(); + s.execute("symbol.exitEditing", &json!({})).unwrap(); + assert_left_outside(&placed_boxes(&s, id)); +} + +/// A native file keeps guides outside the art exactly, and an instance opened from it draws as +/// before saving; a file whose saved guides are out of range or out of order opens with 9-slice +/// off for that symbol. +#[test] +fn guides_outside_the_art_survive_saving_and_reopening_a_native_file() { + let (mut s, id) = panel(); + let guides = [-0.123456789, 1.5, 0.3, -2.75]; + s.execute("symbol.options", &json!({"name": "Panel", "nineSliceGuides": guides})).unwrap(); + s.execute("symbol.options", &json!({"name": "Panel", "nineSliceGuides": [-0.25, 0.25, 0.25, 0.25]})).unwrap(); + s.execute("symbol.options", &json!({"name": "Panel", "nineSliceGuides": guides})).unwrap(); + let doc = s.doc().unwrap().doc.clone(); + let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap(); + let g = back.symbol_nine_slice("Panel").unwrap(); + assert_eq!([g.left, g.top, g.right, g.bottom], guides); + let placed = |d: &vectorcraft_doc::Document| { + let NodeKind::SymbolInstance { symbol, xf } = &d.node(id).unwrap().kind else { panic!("an instance") }; + let art = d.symbols.iter().find(|s| &s.name == symbol).unwrap().art.clone(); + path_boxes(&d.place_symbol_art(symbol, &art, *xf).unwrap()) + }; + assert_eq!(placed(&back), placed(&doc)); + for bad in [json!([-20.0, 0.25, 0.25, 0.25]), json!([0.8, 0.25, 0.5, 0.25]), json!([0.25, 0.25, 0.25]), json!("x")] { + let mut d = (*doc).clone(); + d.unknown.insert(vectorcraft_doc::SYMBOL_NINE_SLICE.into(), json!({ "Panel": bad })); + let back = vectorcraft_format::load(&vectorcraft_format::save(&d, false)).unwrap(); + assert!(back.symbol_nine_slice("Panel").is_none(), "{bad}"); + let NodeKind::SymbolInstance { symbol, xf } = &back.node(id).unwrap().kind else { panic!("an instance") }; + assert!(back.symbol_slice_map(symbol, *xf).is_none(), "{bad}: scaled as a whole"); + } +} diff --git a/crates/engine/src/tests/textedit.rs b/crates/engine/src/tests/textedit.rs index 9eea9cf456..adcc35d352 100644 --- a/crates/engine/src/tests/textedit.rs +++ b/crates/engine/src/tests/textedit.rs @@ -87,6 +87,50 @@ fn set_range_style_splits_runs() { assert!(s.execute("text.setRangeStyle", &json!({"id": id.0, "size": -1})).is_err()); } +/// `text.create`, `text.createInPath`, `text.setStyle` and `text.setRangeStyle` refuse a size +/// outside 0.1 to 1296 pt with an error naming the range, and change nothing; both ends are taken. +#[test] +fn a_type_size_outside_its_range_is_refused() { + let mut s = session(); + let message = "`size` must be from 0.1 to 1296"; + let state = |s: &Session| (s.doc().unwrap().doc.node_count(), s.doc().unwrap().history.undo.len()); + let before = state(&s); + for size in [2835.0, 1296.5, 0.05, 0.0, -1.0] { + let e = s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Big", "size": size})).unwrap_err().to_string(); + assert!(e.contains(message), "{size}: {e}"); + } + assert_eq!(state(&s), before, "no type is made"); + let big = s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Big", "size": 1296})).unwrap(); + let big = NodeId(big["id"].as_u64().unwrap()); + assert_eq!(obj(&s, big).runs[0].style.size, 1296.0); + let small = s.execute("text.create", &json!({"x": 10, "y": 20, "text": "small", "size": 0.1})).unwrap(); + assert_eq!(obj(&s, NodeId(small["id"].as_u64().unwrap())).runs[0].style.size, 0.1); + let path = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 200, "height": 100})).unwrap()["id"].clone(); + let before = state(&s); + let e = s.execute("text.createInPath", &json!({"path": path, "text": "In", "size": 2835})).unwrap_err().to_string(); + assert!(e.contains(message), "{e}"); + assert_eq!(state(&s), before); + s.execute("text.createInPath", &json!({"path": path, "text": "In", "size": 1296})).unwrap(); + let id = text(&mut s, "Hello"); + let before = state(&s); + for (cmd, params) in [ + ("text.setStyle", json!({"ids": [id.0], "size": 2835})), + ("text.setStyle", json!({"ids": [id.0], "size": "1300 pt"})), + ("text.setStyle", json!({"ids": [id.0], "size": 0.05})), + ("text.setRangeStyle", json!({"id": id.0, "start": 0, "end": 2, "size": 2835})), + ("text.setRangeStyle", json!({"id": id.0, "size": 0})), + ] { + let e = s.execute(cmd, ¶ms).unwrap_err().to_string(); + assert!(e.contains(message), "{cmd} {params}: {e}"); + } + assert_eq!(state(&s), before, "nothing changes"); + assert_eq!(obj(&s, id).runs[0].style.size, 20.0); + s.execute("text.setStyle", &json!({"ids": [id.0], "size": 1296})).unwrap(); + assert_eq!(obj(&s, id).runs[0].style.size, 1296.0); + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 0, "end": 1, "size": 0.1})).unwrap(); + assert_eq!(obj(&s, id).runs[0].style.size, 0.1); +} + /// `featureChanges` turns features on and off on top of each run's own and keeps the rest, in /// `text.setStyle` and `text.setRangeStyle`, in one undo step; an unknown tag is an error. #[test] @@ -139,6 +183,54 @@ fn feature_changes_keep_each_runs_other_features() { assert_eq!(features(&s), [vec!["smcp", "numr", "liga", "dnom"], vec!["swsh", "numr", "liga", "dnom"], vec!["-onum", "swsh", "dnom"]]); } +/// A feature with a value (`salt=2`): `features` and `featureChanges` take it, the next value +/// replaces it, `salt=1` is a plain `salt` and `salt=0` and `-salt` are off, a value this build +/// does not know is an error, one undo step each, and the native format keeps the plain string. +#[test] +fn feature_values_are_set_replaced_and_saved() { + let mut s = session(); + let id = text(&mut s, "abcd"); + let features = |s: &Session| obj(s, id).runs.iter().map(|r| (r.text.clone(), r.style.features.clone())).collect::>(); + let range = |s: &mut Session, p: Value| { + let mut p = p; + p["id"] = json!(id.0); + p["start"] = json!(1); + p["end"] = json!(2); + s.execute("text.setRangeStyle", &p).map(|_| ()) + }; + let undo = s.doc().unwrap().history.undo.len(); + range(&mut s, json!({"features": ["salt=2"]})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + assert_eq!(features(&s), [("a".into(), vec![]), ("b".into(), vec!["salt=2".to_string()]), ("cd".into(), vec![])]); + range(&mut s, json!({"features": ["salt=3"]})).unwrap(); + assert_eq!(features(&s)[1].1, ["salt=3"], "the next value replaces it"); + range(&mut s, json!({"featureChanges": ["salt=2", "ss01"]})).unwrap(); + assert_eq!(features(&s)[1].1, ["ss01", "salt=2"], "written in the canonical order"); + range(&mut s, json!({"featureChanges": ["salt=1"]})).unwrap(); + assert_eq!(features(&s)[1].1, ["ss01", "salt"], "salt=1 is a plain salt"); + range(&mut s, json!({"featureChanges": ["salt=2"]})).unwrap(); + let saved = vectorcraft_format::save(&s.doc().unwrap().doc, false); + let back = vectorcraft_format::load(&saved).unwrap(); + let Some(NodeKind::Text(t)) = back.node(id).map(|n| &n.kind) else { panic!("the text survives") }; + assert_eq!(t.runs[1].style.features, ["ss01", "salt=2"], "the native format keeps the string"); + assert!(String::from_utf8_lossy(&saved).contains("\"salt=2\"")); + range(&mut s, json!({"featureChanges": ["-salt"]})).unwrap(); + assert_eq!(features(&s)[1].1, ["ss01"], "-salt turns it off"); + range(&mut s, json!({"featureChanges": ["salt=2"], "features": null})).unwrap(); + range(&mut s, json!({"featureChanges": ["salt=0"]})).unwrap(); + assert_eq!(features(&s)[1].1, ["ss01"], "salt=0 turns it off"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(features(&s)[1].1, ["ss01", "salt=2"], "undo takes it back"); + let before = features(&s); + for tag in ["salt=", "salt=x", "salt=65536", "-salt=2", "liga=2", "salt=2=3", "zzzz=2"] { + for key in ["features", "featureChanges"] { + let e = range(&mut s, json!({ key: [tag] })).unwrap_err().to_string(); + assert!(e.contains(&format!("`{tag}`")), "{key} {tag}: {e}"); + } + } + assert_eq!(features(&s), before, "the refused commands change nothing"); +} + /// `text.setStyle {stroke, strokeWidth}` sets the character stroke of all the text or of a range, as /// `text.setRangeStyle` does, and a call with `fill` and `stroke` sets both in one undo step. #[test] @@ -475,6 +567,8 @@ fn type_commands_refuse_a_number_or_boolean_given_as_text() { ("text.setFormat", json!({"ids": [id.0], "hyphenate": "false"}), "hyphenate"), ("text.setFormat", json!({"ids": [id.0], "hyphenateCapitalized": 0}), "hyphenateCapitalized"), ("text.setFormat", json!({"ids": [id.0], "romanHangingPunctuation": "true"}), "romanHangingPunctuation"), + ("text.setFormat", json!({"ids": [id.0], "koreanLineBreakAnywhere": 1}), "koreanLineBreakAnywhere"), + ("text.setFormat", json!({"ids": [id.0], "bunriKinshi": "on"}), "bunriKinshi"), ("text.getRange", json!({"id": id.0, "effective": "true"}), "effective"), ("type.opticalMarginAlignment", json!({"on": "true"}), "on"), ("type.systemLayout", json!({"on": "true"}), "on"), @@ -2523,6 +2617,68 @@ fn converting_tracked_type_between_point_and_area_keeps_it_in_place() { } } +/// Horizontal and vertical type keep every line where it is when converted from point to area +/// type and back, and from area to point type and back, however the lines are aligned. Vertical +/// lines run down their columns, and each next column sits to the left of the one before it. +#[test] +fn converting_vertical_type_between_point_and_area_keeps_it_in_place() { + for vertical in [false, true] { + for j in ["left", "center", "right"] { + for text in ["Wave", "Wave\nWaves"] { + let mut s = session(); + let r = s.execute("text.create", &json!({"x": 300, "y": 40, "text": text, "size": 12, "vertical": vertical})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + s.execute("text.setStyle", &json!({"ids": [id.0], "justify": j})).unwrap(); + let before = line_starts_doc(&obj(&s, id)); + assert_eq!(before.len(), text.lines().count()); + if vertical && before.len() > 1 { + assert!(before[1].x < before[0].x, "{j}: the second column is to the left: {before:?}"); + } + for round in 0..2 { + s.execute("type.convertToAreaType", &json!({"ids": [id.0]})).unwrap(); + let t = obj(&s, id); + assert!(matches!(t.kind, TextKind::Area { .. })); + let area = line_starts_doc(&t); + assert_eq!(area.len(), before.len(), "vertical {vertical}, {j}, {text:?}: no rewrap"); + for (a, b) in area.iter().zip(&before) { + assert!((*a - *b).hypot() < 0.01, "vertical {vertical}, {j}, {text:?}, round {round}, area: {before:?} → {area:?}"); + } + s.execute("type.convertToPointType", &json!({"ids": [id.0]})).unwrap(); + let t = obj(&s, id); + assert!(matches!(t.kind, TextKind::Point)); + let point = line_starts_doc(&t); + for (a, b) in point.iter().zip(&before) { + assert!((*a - *b).hypot() < 0.01, "vertical {vertical}, {j}, {text:?}, round {round}, point: {before:?} → {point:?}"); + } + } + } + // Area type to point type and back. + let mut s = session(); + let r = s + .execute( + "text.create", + &json!({"x": 300, "y": 40, "text": "Wave\nWaves", "size": 12, "vertical": vertical, "area": {"width": 120, "height": 120}}), + ) + .unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + s.execute("text.setStyle", &json!({"ids": [id.0], "justify": j})).unwrap(); + let before = line_starts_doc(&obj(&s, id)); + assert_eq!(before.len(), 2); + s.execute("type.convertToPointType", &json!({"ids": [id.0]})).unwrap(); + let point = line_starts_doc(&obj(&s, id)); + for (a, b) in point.iter().zip(&before) { + assert!((*a - *b).hypot() < 0.01, "vertical {vertical}, {j}, from area, point: {before:?} → {point:?}"); + } + s.execute("type.convertToAreaType", &json!({"ids": [id.0]})).unwrap(); + let area = line_starts_doc(&obj(&s, id)); + assert_eq!(area.len(), 2); + for (a, b) in area.iter().zip(&before) { + assert!((*a - *b).hypot() < 0.01, "vertical {vertical}, {j}, from area, area again: {before:?} → {area:?}"); + } + } + } +} + #[test] fn convert_area_to_point_keeps_a_deeper_list_item_in_place() { let mut s = session(); @@ -3103,6 +3259,41 @@ fn a_glyph_alternate_replaces_one_character_through_undo_and_reopen() { assert!(s.execute("text.glyphAlternates", &json!({"id": id.0, "start": 2})).unwrap_err().to_string().contains("is not available")); } +/// `glyphAlternate: null` in `text.setRangeStyle` takes a glyph choice away in the same undo step +/// as the other style it sets (a feature: what the Glyphs panel does for a variant a feature +/// draws); anything but null is refused. +#[test] +fn set_range_style_takes_a_glyph_choice_away_with_a_feature() { + use vectorcraft_text::test_fonts::{alternates_family, alternates_font, unencoded_glyphs}; + let _fonts = crate::adding_fonts(); + let db = vectorcraft_text::FontDb::global(); + db.add_font(alternates_font(true).expect("the test font builds")); + let [u1, ..] = unencoded_glyphs().expect("unencoded glyphs"); + let face = db.face(alternates_family(true), "Regular").expect("the test face"); + let mut s = session(); + let r = s.execute("text.create", &json!({"x": 100, "y": 100, "text": "xay", "size": 20, "font": alternates_family(true)})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + s.execute("text.setGlyphAlternate", &json!({"id": id.0, "start": 1, "gid": u1})).unwrap(); + let gids = |s: &Session| vectorcraft_text::layout(db, &obj(s, id)).glyphs.iter().map(|g| g.gid).collect::>(); + assert_eq!(gids(&s)[1], u1); + let undo = s.doc().unwrap().history.undo.len(); + let e = s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 1, "end": 2, "glyphAlternate": 5})).unwrap_err().to_string(); + assert!(e.contains("takes only null"), "{e}"); + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 1, "end": 2, "glyphAlternate": null, "featureChanges": ["ss01"]})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + assert!(obj(&s, id).runs.iter().all(|r| r.style.glyph_alternate.is_none()), "the choice is gone"); + assert_eq!( + gids(&s)[1], + face.substitutions(face.glyph_for('a')).iter().find(|x| &x.feature == b"ss01").map(|x| x.glyphs[0]).unwrap(), + "ss01 draws its glyph" + ); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(gids(&s)[1], u1, "undone: the choice again"); + // With nothing else to set it is still a change. + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 1, "end": 2, "glyphAlternate": null})).unwrap(); + assert_eq!(gids(&s)[1], face.glyph_for('a')); +} + /// The glyph already drawn, chosen again, and null for a character drawn with its default glyph /// leave the document and its undo history as they are. An empty run before the character does /// not stand in for the character's own choice. @@ -3495,6 +3686,89 @@ fn an_overflowing_grapheme_keeps_the_styles_of_its_characters() { assert_eq!(r["gid"], json!(g('b')), "the overflowing Ka is shaped apart from the nukta of another size"); } +/// A contextual alternate with no feature must name the fallback face that supplies the glyph, +/// including when the character is outside its frame. Neither another face's glyph nor an +/// out-of-range id becomes a choice. +#[test] +fn a_contextual_fallback_glyph_choice_draws_through_undo_and_reopen() { + use vectorcraft_text::test_fonts::{ + CONTEXTUAL_FALLBACK_CHAR as CH, CONTEXTUAL_FALLBACK_FAMILY, alternates_family, alternates_font, contextual_fallback_font, source_sans_gid, + }; + let _fonts = crate::adding_fonts(); + let db = vectorcraft_text::FontDb::global(); + db.add_font(alternates_font(true).expect("the primary test font builds")); + db.add_font(contextual_fallback_font().expect("the fallback test font builds")); + let primary = db.face(alternates_family(true), "Regular").expect("the primary face"); + let fallback = db.face(CONTEXTUAL_FALLBACK_FAMILY, "Regular").expect("the supplying face"); + let g = |c| u32::from(source_sans_gid(c).expect("a Source Sans glyph")); + let (default, alternate) = (g('m'), g('d')); + assert_eq!(primary.glyph_for(CH), 0); + assert_eq!(db.face_covering(CH).unwrap().id(), fallback.id(), "only the fixture supplies the private-use character"); + assert!(!fallback.alternates(CH).iter().any(|a| a.gid == alternate), "the alternate belongs to its shaped, not nominal, glyph"); + assert!(!fallback.is_unlisted_alternate(CH, alternate), "the contextual validation path is required"); + let text = format!("a{CH}a"); + let start = 1; + let end = start + CH.len_utf8(); + let drawn = |t: &TextObject| { + let mut open = t.clone(); + open.kind = TextKind::Point; + vectorcraft_text::layout(db, &open).glyphs.into_iter().find(|g| g.byte == start).map(|g| (g.font_id, g.gid)) + }; + let state = |s: &Session| (s.doc().unwrap().history.undo.len(), s.doc().unwrap().revision); + + for overflow in [false, true] { + let mut s = session(); + let mut spec = json!({"x": 0, "y": 0, "text": text, "size": 20, "font": alternates_family(true)}); + if overflow { + spec["area"] = json!({"width": 200, "height": 2}); + } + let id = NodeId(s.execute("text.create", &spec).unwrap()["id"].as_u64().unwrap()); + let before = obj(&s, id); + assert_eq!(drawn(&before), Some((fallback.id(), default))); + if overflow { + assert!(vectorcraft_text::layout(db, &before).glyphs.is_empty(), "the original frame overflows"); + } + let contextual = vectorcraft_text::alternates_in_context(db, &before, start).expect("the panel's contextual alternates"); + assert_eq!((contextual.font_id, contextual.default), (fallback.id(), default)); + assert!(contextual.alternates.iter().any(|a| a.gid == alternate && a.apply.is_none())); + + let unchanged = state(&s); + for gid in [primary.glyph_for('a'), fallback.glyph_count()] { + let err = s.execute("text.setGlyphAlternate", &json!({"id": id.0, "start": start, "gid": gid})).unwrap_err(); + assert!(err.to_string().contains("is not an alternate"), "{err}"); + assert_eq!(state(&s), unchanged, "a refused choice makes no edit"); + assert_eq!(obj(&s, id).runs, before.runs); + } + let result = s.execute("text.setGlyphAlternate", &json!({"id": id.0, "start": start, "gid": alternate})).unwrap(); + assert_eq!(result, json!({"id": id.0, "start": start, "end": end, "gid": alternate})); + assert_eq!(state(&s).0, unchanged.0 + 1, "one undo step"); + let chosen = obj(&s, id); + assert_eq!(chosen.plain_text(), text); + assert_eq!(drawn(&chosen), Some((fallback.id(), alternate))); + let choice = chosen.runs.iter().find_map(|r| r.style.glyph_alternate.as_ref()).expect("the stored choice"); + assert_eq!(choice, &fallback.choice(CH, alternate), "the choice keeps the supplying face's identity"); + + let mut wrong_face = chosen.clone(); + wrong_face.runs.iter_mut().find(|r| r.style.glyph_alternate.is_some()).unwrap().style.glyph_alternate = Some(primary.choice(CH, alternate)); + assert_eq!(drawn(&wrong_face), Some((fallback.id(), default)), "another face's choice is not drawn"); + + let bytes = vectorcraft_format::save_file(&s.doc().unwrap().doc); + let reopened = vectorcraft_format::load(&bytes).unwrap(); + let NodeKind::Text(reopened) = &reopened.node(id).unwrap().kind else { panic!("text missing") }; + assert_eq!(drawn(reopened), Some((fallback.id(), alternate)), "native restore retains the face and glyph"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(obj(&s, id).runs, before.runs, "Undo restores the original runs"); + assert_eq!(drawn(&obj(&s, id)), Some((fallback.id(), default))); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(drawn(&obj(&s, id)), Some((fallback.id(), alternate)), "Redo restores the choice"); + + let result = s.execute("text.setGlyphAlternate", &json!({"id": id.0, "start": start, "gid": null})).unwrap(); + assert_eq!(result["gid"], json!(default), "clearing reports the fallback's shaped glyph"); + assert_eq!(drawn(&obj(&s, id)), Some((fallback.id(), default))); + assert!(obj(&s, id).runs.iter().all(|r| r.style.glyph_alternate.is_none())); + } +} + #[test] fn glyph_alternates_query_reports_the_fallback_glyph_that_is_drawn() { use vectorcraft_text::test_fonts::{alternates_family, alternates_font}; diff --git a/crates/engine/src/tests/turn_direction.rs b/crates/engine/src/tests/turn_direction.rs index f12f0d1962..a8961f3c46 100644 --- a/crates/engine/src/tests/turn_direction.rs +++ b/crates/engine/src/tests/turn_direction.rs @@ -114,3 +114,12 @@ fn keys_named(doc: &str) -> Vec { } found.into_iter().map(|(k, _)| k).collect() } + +/// Turn notes the key walk above doesn't reach: a numeric reflection axis and the Scatter brush's +/// `rotation [a, b]` range, whose head isn't a plain key. +#[test] +fn turns_outside_plain_keys_say_which_way() { + let doc = |id: &str| command_specs().iter().find(|c| c.id == id).map(|c| c.params).unwrap_or_default(); + assert!(doc("object.reflect").contains("|deg (the mirror line, counter-clockwise from horizontal"), "object.reflect's numeric axis"); + assert!(doc("brush.options").contains("rotation [a, b] −180..180° (counter-clockwise)"), "the Scatter brush's rotation"); +} diff --git a/crates/engine/src/tests/variables.rs b/crates/engine/src/tests/variables.rs index 4b773c889c..08ba426ef1 100644 --- a/crates/engine/src/tests/variables.rs +++ b/crates/engine/src/tests/variables.rs @@ -2916,3 +2916,191 @@ fn applying_a_graph_row_again_records_no_undo_step() { s.execute("dataset.select", &json!({"name": "B"})).unwrap(); assert_eq!(super::history(&s), (before.0 + 1, 0, true)); } + +/// The document's SVG with the options `svg` → (its text, the export's warnings). +fn svg_export(s: &mut Session, svg: Value) -> (String, Vec) { + let r = s.execute("document.export", &json!({"format": "svg", "svg": svg})).unwrap(); + let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap(); + (String::from_utf8(bytes).unwrap(), r["warnings"].as_array().cloned().unwrap_or_default()) +} + +/// A new session with `svg` opened as `name` → (the session, the open's warnings). +fn svg_opened(svg: &str, name: &str) -> (Session, Vec) { + let mut o = Session::new(); + let r = o.execute("document.open", &json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(svg.as_bytes())})).unwrap(); + let warnings = r["warnings"].as_array().cloned().unwrap_or_default(); + (o, warnings) +} + +/// Include Variable Data writes the text variables, the data sets' text values and each text +/// variable's bound type object into the SVG, and opening the SVG reads them back: the type +/// objects are bound again, so a data set changes them. Variables of other kinds are left out with +/// a warning. Unnamed objects get ids with Minimal ids, minified files, unique ids and style +/// entities alike, and Load Variable Library reads the same file. +#[test] +fn an_svg_with_variable_data_opens_with_its_variables_data_sets_and_bindings() { + let mut s = session(); + let t = text(&mut s, "Alice"); + let u = text(&mut s, "9.99"); + // A fill of its appearance writes the type in a group with the fill's path. + s.execute("appearance.addFill", &json!({"ids": [u.0]})).unwrap(); + let r = rect(&mut s); + for (name, kind) in [("Name", "text"), ("Shown", "visibility"), ("Price", "text")] { + s.execute("variable.define", &json!({"name": name, "kind": kind})).unwrap(); + } + s.execute("variable.bind", &json!({"variable": "Name", "ids": [t.0]})).unwrap(); + s.execute("variable.bind", &json!({"variable": "Price", "ids": [u.0]})).unwrap(); + s.execute("variable.bind", &json!({"variable": "Shown", "ids": [r.0]})).unwrap(); + s.execute("dataset.new", &json!({"name": "A & ", "values": {"Name": "Bob", "Price": "1.00\nper pound & tax\r", "Shown": false}})).unwrap(); + s.execute("dataset.new", &json!({"name": "Second", "values": {"Name": ""}})).unwrap(); + let before = s.doc().unwrap().doc.variables.clone(); + let text_only: Vec = before + .datasets + .iter() + .map(|d| { + let mut d = d.clone(); + d.values.retain(|k, _| k != "Shown"); + d + }) + .collect(); + + for opts in [ + json!({"variableData": true}), + json!({"variableData": true, "objectIds": "minimal", "minify": true}), + json!({"variableData": true, "objectIds": "unique"}), + json!({"variableData": true, "styling": "entities", "encoding": "latin1"}), + ] { + let (svg, warnings) = svg_export(&mut s, opts.clone()); + assert!(warnings.contains(&json!("Variables that aren't text variables were left out of the SVG's variable data")), "{opts}: {warnings:?}"); + assert_eq!(svg.matches("docRef=\"id('").count(), 2, "{opts}: {svg}"); + assert_eq!(s.doc().unwrap().doc.variables, before, "{opts}: exporting changes nothing"); + + let (mut o, warnings) = svg_opened(&svg, "vars.svg"); + assert!(warnings.is_empty(), "{opts}: {warnings:?}"); + let vars = o.doc().unwrap().doc.variables.clone(); + assert_eq!(vars.variables.iter().map(|v| (v.name.as_str(), v.kind.label())).collect::>(), [("Name", "text"), ("Price", "text")]); + assert_eq!(vars.datasets, text_only, "{opts}"); + assert_eq!(vars.active_dataset, None); + let bound = |name: &str| { + let ids = vars.objects_of(name); + assert_eq!(ids.len(), 1, "{opts}: {name}"); + ids[0] + }; + let (name, price) = (bound("Name"), bound("Price")); + assert_eq!((plain(&o, name), plain(&o, price)), ("Alice".into(), "9.99".into()), "{opts}: the art stays as the file draws it"); + let v = o.execute("dataset.select", &json!({"name": "A & "})).unwrap(); + assert_eq!(v["applied"], json!(2), "{opts}: {v}"); + assert_eq!(plain(&o, name), "Bob"); + + let mut lib = session(); + lib.execute("variable.loadLibrary", &json!({"xml": svg})).unwrap(); + assert_eq!(lib.doc().unwrap().doc.variables.datasets, text_only, "{opts}"); + } +} + +/// Without Include Variable Data the SVG holds no variable data, and a document without variables +/// writes none with it on. Outlined type is written unbound, characters XML can't hold are left +/// out of the values, and variable data past the 8 MiB or 2,000,000-node cap is left out, each +/// with a warning; past 256 text variables or 1,000 data sets the rest are left out with a +/// warning. Look-alike text in comments and other markup is skipped when the file opens. A file +/// whose variable data can't be read opens its art with a warning, and so does one whose +/// namespace entities would grow the library past its cap. +#[test] +fn an_svg_without_readable_variable_data_opens_its_art() { + let mut s = session(); + let t = text(&mut s, "Alice"); + let (plain_svg, _) = svg_export(&mut s, json!({})); + assert!(!plain_svg.contains("variableSets")); + let (none, _) = svg_export(&mut s, json!({"variableData": true})); + assert!(!none.contains("variableSets"), "no variables, no variable data"); + s.execute("variable.define", &json!({"name": "Name", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "Name", "ids": [t.0]})).unwrap(); + let (off, _) = svg_export(&mut s, json!({})); + assert!(!off.contains("variableSets"), "off by default"); + // Outlined type opens as art: the variable is written unbound, and the values lose the + // characters XML can't hold, each with a warning. + s.execute("dataset.new", &json!({"name": "Row", "values": {"Name": "a\u{b}b\u{1}c"}})).unwrap(); + let (outlined, warnings) = svg_export(&mut s, json!({"variableData": true, "outlineText": true})); + assert!(outlined.contains(""; + let art = ""; + let untraited = format!("{head}{art}"); + let refs = "&ns_big;".repeat(40_000); + let big = "x".repeat(250); + let growing = format!( + "]>{head}{art}" + ); + // Variable data under 8 MiB with more XML nodes than Load Variable Library reads (a million + // one-character paragraphs, minified) is left out with a warning. + let mut lines = session(); + lines.execute("variable.define", &json!({"name": "Name", "kind": "text"})).unwrap(); + lines.execute("dataset.new", &json!({"name": "Row", "values": {"Name": "a\n".repeat(1_000_000)}})).unwrap(); + let (dense, warnings) = svg_export(&mut lines, json!({"variableData": true, "minify": true})); + assert!(!dense.contains("variableSets")); + assert!( + warnings.contains(&json!( + "The variable data holds more than 2,000,000 XML nodes, which Load Variable Library reads, and was left out of the SVG" + )), + "{warnings:?}" + ); + + // More text variables and data sets than Load Variable Library reads: the first 256 and the + // first 1,000 are written, each with a warning, and the file opens with them. + let mut many = session(); + { + let vars = &mut std::sync::Arc::make_mut(&mut many.doc_mut().unwrap().doc).variables; + vars.variables = (0..300).map(|i| vectorcraft_doc::Variable { name: format!("V{i}"), kind: vectorcraft_doc::VariableKind::Text }).collect(); + vars.datasets = (0..1_100) + .map(|i| vectorcraft_doc::DataSet { + name: format!("D{i}"), + values: [("V0".to_string(), vectorcraft_doc::DataValue::Text(format!("{i}")))].into_iter().collect(), + }) + .collect(); + } + let (capped, warnings) = svg_export(&mut many, json!({"variableData": true})); + for w in [ + "Text variables past the first 256, which Load Variable Library reads, were left out of the SVG's variable data", + "Data sets past the first 1,000, which Load Variable Library reads, were left out of the SVG's variable data", + ] { + assert!(warnings.contains(&json!(w)), "{warnings:?}"); + } + let (o, warnings) = svg_opened(&capped, "many.svg"); + assert!(warnings.is_empty(), "{warnings:?}"); + let vars = &o.doc().unwrap().doc.variables; + assert_eq!((vars.variables.len(), vars.datasets.len()), (256, 1_000)); + assert_eq!(vars.datasets[999].values["V0"], vectorcraft_doc::DataValue::Text("999".into())); + + // Text that only looks like variable data, in a comment, a CDATA section, a processing + // instruction or the document type declaration, is skipped for the element itself. + let library = ""; + let decoys = format!( + " -->]>{head} ]]> ?>{library}{art}" + ); + let (o, warnings) = svg_opened(&decoys, "decoys.svg"); + assert!(warnings.is_empty(), "{warnings:?}"); + assert_eq!(o.doc().unwrap().doc.variables.variables.len(), 1); + + for (svg, why) in [(untraited, "variable `A` has no `trait`"), (growing, "entities expand to more than")] { + let (o, warnings) = svg_opened(&svg, "broken.svg"); + assert!(warnings.iter().any(|w| w.as_str().is_some_and(|w| w.contains("variable data wasn't read") && w.contains(why))), "{warnings:?}"); + let d = &o.doc().unwrap().doc; + assert!(d.variables.variables.is_empty()); + assert_eq!(vectorcraft_testkit::svg_shapes(&vectorcraft_svg::export(d, &Default::default())), 1, "the art opens"); + } +} diff --git a/crates/engine/src/tests/warp_images.rs b/crates/engine/src/tests/warp_images.rs new file mode 100644 index 0000000000..47175fc866 --- /dev/null +++ b/crates/engine/src/tests/warp_images.rs @@ -0,0 +1,293 @@ +//! Effect › Warp on placed images: the pixels bend with the frame, in the canvas and in exports. + +use serde_json::{Value, json}; +use vectorcraft_doc::live::{WarpNet, WarpStyle, uses_net, warp_version}; +use vectorcraft_doc::{Node, NodeKind}; +use vectorcraft_geom::{Affine, Point, Rect}; + +use crate::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + s +} + +/// The box of the image [`quarters`] places. +const FRAME: Rect = Rect::new(100.0, 100.0, 180.0, 180.0); + +/// The color of the quarter of the image [`quarters`] places that holds (u, v) of its box: red top +/// left, green top right, blue bottom left, yellow bottom right. +fn quarter(u: f64, v: f64) -> [u8; 3] { + match (u < 0.5, v < 0.5) { + (true, true) => [255, 0, 0], + (false, true) => [0, 255, 0], + (true, false) => [0, 0, 255], + (false, false) => [255, 255, 0], + } +} + +/// A selected embedded 40×40 px image filling [`FRAME`], each quarter one color ([`quarter`]). +fn quarters(s: &mut Session) -> NodeId { + let img = image::RgbaImage::from_fn(40, 40, |x, y| { + let [r, g, b] = quarter(x as f64 / 40.0, y as f64 / 40.0); + image::Rgba([r, g, b, 255]) + }); + let mut png = vec![]; + img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + s.edit("Place", |d, sel| { + d.images.insert("quarters".into(), vectorcraft_doc::ImageBlob::png(png)); + let id = d.alloc_id(); + let xf = Affine::translate((FRAME.x0, FRAME.y0)) * Affine::scale(2.0); + let im = vectorcraft_doc::ImageObject { + key: "quarters".into(), + width: 40, + height: 40, + xf, + link: None, + placement: Default::default(), + pixels: None, + }; + d.insert(d.default_layer(), 0, Node::new(id, NodeKind::Image(Box::new(im))))?; + sel.set([id]); + Ok(id) + }) + .unwrap() +} + +/// Where an Arc warp bending `bend` % takes the point at (u, v) of [`FRAME`]. +fn arced(bend: f64, u: f64, v: f64) -> Point { + let net = WarpNet::new(WarpStyle::Arc, bend / 100.0, 0.0, 0.0, FRAME.width(), FRAME.height(), false); + FRAME.origin() + net.at(u, v).to_vec2() +} + +/// Points of the image's box: near each quarter's middle and on both sides of the line between +/// the top and bottom quarters, where a warp that moves the pixels up or down changes the color. +const SAMPLES: [(f64, f64); 10] = + [(0.2, 0.2), (0.8, 0.2), (0.2, 0.8), (0.8, 0.8), (0.4, 0.4), (0.6, 0.4), (0.4, 0.6), (0.6, 0.6), (0.3, 0.62), (0.7, 0.62)]; + +/// The document drawn over (0, 0)–(400, 400) at one pixel a point, on white. +fn drawn(s: &Session) -> vectorcraft_render::Rendered { + vectorcraft_render::Renderer::new().render_region(&s.doc().unwrap().doc, Rect::new(0.0, 0.0, 400.0, 400.0), 1.0, true) +} + +/// The sample points whose color in `img` at `at(u, v)` is not the image's color at (u, v). +fn wrong(img: &vectorcraft_render::Rendered, at: &dyn Fn(f64, f64) -> Point) -> Vec<(f64, f64, [u8; 4])> { + SAMPLES + .iter() + .filter_map(|&(u, v)| { + let p = at(u, v); + let px = img.pixel(p.x.floor() as u32, p.y.floor() as u32); + let want = quarter(u, v); + let near = (0..3).all(|i| (px[i] as i32 - want[i] as i32).abs() <= 40); + (!near).then_some((u, v, px)) + }) + .collect() +} + +/// `quarters` with Effect › Warp › Arc at 50 %: the warp the effect holds, checked to be the +/// Bézier patch [`arced`] follows. +fn arc_image(s: &mut Session) -> NodeId { + let id = quarters(s); + s.execute("effect.apply", &json!({"effect": "warp.arc", "params": {"bend": 50}})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let e = &n.appearance.effects[0]; + assert!(warp_version(&e.params["version"]).is_some_and(uses_net), "{}", e.params); + id +} + +fn decoded(v: &Value) -> Vec { + vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap() +} + +#[test] +fn an_images_pixels_bend_with_effect_warp() { + let mut s = session(); + let id = arc_image(&mut s); + // The arc lifts the middle of the image: the line between the quarters rises there. + assert!(arced(50.0, 0.5, 0.6).y < FRAME.y0 + 0.5 * FRAME.height(), "{:?}", arced(50.0, 0.5, 0.6)); + let bent = drawn(&s); + assert_eq!(wrong(&bent, &|u, v| arced(50.0, u, v)), vec![], "each pixel is drawn where the warp takes it"); + // Drawn as pieces of the one image, each placed by the warp. + let d = &s.doc().unwrap().doc; + let art = vectorcraft_render::effects::reshape(Some(d), d.node(id).unwrap(), None).unwrap(); + let mut pieces = 0; + art.walk(&mut |c| pieces += matches!(c.kind, NodeKind::Image(_)) as usize); + assert!(pieces >= 100, "{pieces} pieces"); + // Removing the warp draws the image as it was, in one undo step. + let steps = s.doc().unwrap().history.undo.len(); + s.execute("effect.remove", &json!({"index": 0})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); + let plain = |u: f64, v: f64| Point::new(FRAME.x0 + u * FRAME.width(), FRAME.y0 + v * FRAME.height()); + assert_eq!(wrong(&drawn(&s), &plain), vec![]); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(wrong(&drawn(&s), &|u, v| arced(50.0, u, v)), vec![], "undo brings the bend back"); +} + +/// `out`, an export of [`arc_image`]'s document named `name`, opened again: it draws the image +/// bent. +fn opens_bent(name: &str, out: &Value) { + let mut back = session(); + back.execute("document.open", &json!({"name": name, "dataBase64": out["dataBase64"]})).unwrap(); + assert_eq!(wrong(&drawn(&back), &|u, v| arced(50.0, u, v)), vec![], "{name}"); +} + +#[test] +fn a_warped_image_keeps_its_bend_in_svg() { + let mut s = session(); + arc_image(&mut s); + let svg = s.execute("document.export", &json!({"format": "svg"})).unwrap(); + let text = String::from_utf8(decoded(&svg)).unwrap(); + assert_eq!(text.matches("= 100, "{images} pieces"); + assert_eq!(wrong(&drawn(&s), &|u, v| arced(50.0, u, v)), vec![]); + s.execute("edit.undo", &json!({})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap(); + assert!(matches!(n.kind, NodeKind::Image(_)) && n.appearance.effects.len() == 1); + assert_eq!(wrong(&drawn(&s), &|u, v| arced(50.0, u, v)), vec![]); +} + +/// A selected embedded grayscale 40×40 px image filling [`FRAME`], black above white, colorized +/// red by its fill color: red above, nothing below. +fn red_on_clear(s: &mut Session) -> NodeId { + let img = image::GrayImage::from_fn(40, 40, |_, y| image::Luma([if y < 20 { 0 } else { 255 }])); + let mut png = vec![]; + image::DynamicImage::ImageLuma8(img).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let id = s + .edit("Place", |d, sel| { + d.images.insert("gray".into(), vectorcraft_doc::ImageBlob::png(png)); + let id = d.alloc_id(); + let xf = Affine::translate((FRAME.x0, FRAME.y0)) * Affine::scale(2.0); + let im = vectorcraft_doc::ImageObject { + key: "gray".into(), + width: 40, + height: 40, + xf, + link: None, + placement: Default::default(), + pixels: None, + }; + d.insert(d.default_layer(), 0, Node::new(id, NodeKind::Image(Box::new(im))))?; + sel.set([id]); + Ok(id) + }) + .unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000", "ids": [id.0]})).unwrap(); + id +} + +#[test] +fn a_colorized_image_keeps_its_color_when_warped() { + let mut s = session(); + red_on_clear(&mut s); + s.execute("effect.apply", &json!({"effect": "warp.arc", "params": {"bend": 50}})).unwrap(); + let img = drawn(&s); + let (red, white) = ([255u8, 0, 0], [255u8, 255, 255]); + for (u, v, want) in [(0.5, 0.35, red), (0.2, 0.2, red), (0.5, 0.65, white), (0.8, 0.8, white)] { + let p = arced(50.0, u, v); + let px = img.pixel(p.x.floor() as u32, p.y.floor() as u32); + assert!((0..3).all(|i| (px[i] as i32 - want[i] as i32).abs() <= 40), "({u}, {v}) at {p:?}: {px:?}"); + } +} + +#[test] +fn a_warp_on_a_group_bends_the_image_in_it() { + let mut s = session(); + let im = quarters(&mut s); + // A group of the image and a line below it as wide as the image: the group's box is the image's. + let line = s.execute("shape.line", &json!({"x1": FRAME.x0, "y1": FRAME.y1, "x2": FRAME.x1, "y2": FRAME.y1})).unwrap(); + let line = NodeId(line["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [im.0, line.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("effect.apply", &json!({"effect": "warp.arc", "params": {"bend": 50}})).unwrap(); + assert_eq!(wrong(&drawn(&s), &|u, v| arced(50.0, u, v)), vec![]); +} diff --git a/crates/engine/src/tests/webexport.rs b/crates/engine/src/tests/webexport.rs index bdd474612f..cf427f8174 100644 --- a/crates/engine/src/tests/webexport.rs +++ b/crates/engine/src/tests/webexport.rs @@ -294,7 +294,7 @@ fn files_named_after_the_title_follow_windows_naming_rules() { #[test] fn files_are_written_beside_the_path() { - let dir = vectorcraft_testkit::temp_dir("webexport"); + let dir = vectorcraft_testkit::TempDir::new("webexport"); let mut s = two_colours(); let path = dir.join("art.gif").to_string_lossy().to_string(); let r = run(&mut s, "document.exportForWeb", json!({"path": path})); @@ -324,7 +324,7 @@ fn an_export_says_when_an_image_could_not_be_decoded() { let r = run(&mut s, "document.exportForWeb.preview", json!({"format": format})); assert!(undecoded(&r), "{format} preview: {}", r["warnings"]); } - let dir = vectorcraft_testkit::temp_dir("webexport-undecoded"); + let dir = vectorcraft_testkit::TempDir::new("webexport-undecoded"); let page = dir.join("page.html").to_string_lossy().to_string(); let r = run(&mut s, "document.exportForWeb", json!({"path": page, "output": "html"})); assert!(undecoded(&r), "{r}"); diff --git a/crates/engine/src/tests/widthpoints.rs b/crates/engine/src/tests/widthpoints.rs index 4c837c300f..6aa324aa90 100644 --- a/crates/engine/src/tests/widthpoints.rs +++ b/crates/engine/src/tests/widthpoints.rs @@ -221,9 +221,9 @@ fn new_width_point_adjust_adjoining_uses_sampled_widths() { let (mut s, id) = line_session(); let original = vec![(0.0, 9.0, 9.0), (0.25, 1.0, 0.0), (0.75, 3.0, 0.0), (1.0, 7.0, 7.0)]; s.execute("stroke.widthProfile.set", &json!({"ids": [id.0], "points": original})).unwrap(); - // At t=0.5 the old left side is where the profile's curve is there (#5714) and the right - // side is 0pt. Indexed editing of that sampled point is the existing convention: scale the - // nonzero side, add from zero. + // At t=0.5 the old left side is where the profile's curve is there and the right side is + // 0pt. Indexed editing of that sampled point is the existing convention: scale the nonzero + // side, add from zero. let sampled = vectorcraft_doc::WidthProfile { points: original }.at(0.5).0; let index = if indexed { Some(set(&mut s, json!({"id": id.0, "t": 0.5, "left": sampled * 5.0, "right": 0}))) } else { None }; set(&mut s, json!({"id": id.0, "index": index, "t": 0.5, "left": 20, "right": 5, "adjustAdjoining": true})); diff --git a/crates/engine/src/tests/xform.rs b/crates/engine/src/tests/xform.rs index e9aa3c5329..7de9793525 100644 --- a/crates/engine/src/tests/xform.rs +++ b/crates/engine/src/tests/xform.rs @@ -526,6 +526,51 @@ fn distort_command_maps_corners() { assert!(close(bounds(&s, a), Rect::new(0.0, 0.0, 100.0, 100.0))); } +/// Free Distort warps the art of a linked opacity mask with the object it masks, and one undo puts +/// both back; an unlinked mask stays where it is. +#[test] +fn distort_command_warps_a_linked_opacity_mask_with_its_object() { + for linked in [true, false] { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let b = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("transparency.makeOpacityMask", &json!({})).unwrap(); + if !linked { + s.execute("transparency.unlinkOpacityMask", &json!({})).unwrap(); + } + let mask_path = |s: &Session| s.doc().unwrap().doc.node(a).unwrap().extras().mask.as_ref().unwrap().art.path_data().cloned(); + let path = |s: &Session| s.doc().unwrap().doc.node(a).unwrap().path_data().cloned(); + let before = (path(&s), mask_path(&s)); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.distort", &json!({"corners": [[10, 0], [90, 0], [100, 100], [0, 100]]})).unwrap(); + assert!(path(&s) != before.0); + let want = if linked { path(&s) } else { before.1.clone() }; + assert_eq!(mask_path(&s), want, "linked: {linked}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((path(&s), mask_path(&s)), before); + } +} + +/// Free Distort of a group warps the linked opacity mask of a path inside it with the path. +#[test] +fn distort_command_warps_the_linked_mask_of_a_path_in_a_group() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let b = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("transparency.makeOpacityMask", &json!({})).unwrap(); + let c = rect(&mut s, 150.0, 0.0, 50.0, 50.0); + s.execute("select.set", &json!({"ids": [a.0, c.0]})).unwrap(); + let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + let before = s.doc().unwrap().doc.node(a).unwrap().path_data().cloned(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + s.execute("object.distort", &json!({"corners": [[10, 0], [190, 0], [200, 100], [0, 100]]})).unwrap(); + let a = s.doc().unwrap().doc.node(a).unwrap(); + assert!(a.path_data().cloned() != before, "the path is warped"); + assert_eq!(a.extras().mask.as_ref().unwrap().art.path_data(), a.path_data(), "and so is its mask"); +} + #[test] fn distort_perspective_midpoint_is_projective() { // Distort a tiny probe at the centre of a 100×100 source box into a trapezoid: with a real @@ -555,6 +600,35 @@ fn free_transform_distort_mode_via_pointer() { assert_eq!(s.journal.last().map(|j| j.0.as_str()), Some("object.distort")); } +/// With Constrain on, a Free Distort corner keeps to the diagonal through the opposite corner, in +/// one undo step that undoes and redoes whole. +#[test] +fn free_transform_constrained_distort_keeps_the_corner_on_its_diagonal() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 200.0, 100.0); + let v = ViewInfo::default(); + s.select_tool("freeTransform", v).unwrap(); + s.set_tool_option("mode", &json!("distort")); + s.set_tool_option("constrain", &json!(true)); + let before = undo_len(&s); + s.pointer(&PointerEvent::new(PointerKind::Down, 300.0, 200.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 320.0, 230.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 340.0, 260.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 340.0, 260.0), v).unwrap(); + let pts = |s: &Session| -> Vec { s.doc().unwrap().doc.node(a).unwrap().path_data().unwrap().anchors().map(|(_, _, an)| an.p).collect() }; + let has_all = |pts: &[Point], want: [(f64, f64); 4]| want.iter().all(|&(x, y)| pts.iter().any(|q| q.distance(Point::new(x, y)) < 1e-6)); + // (40, 60) along the diagonal (200, 100) is 0.28 of it, (56, 28). + let distorted = [(100.0, 100.0), (300.0, 100.0), (356.0, 228.0), (100.0, 200.0)]; + let original = [(100.0, 100.0), (300.0, 100.0), (300.0, 200.0), (100.0, 200.0)]; + assert!(has_all(&pts(&s), distorted), "{:?}", pts(&s)); + assert_eq!(undo_len(&s), before + 1); + assert_eq!(s.journal.last().map(|j| j.0.as_str()), Some("object.distort")); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(has_all(&pts(&s), original), "{:?}", pts(&s)); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(has_all(&pts(&s), distorted), "{:?}", pts(&s)); +} + #[test] fn free_transform_cmd_held_once_a_corner_drag_started_distorts_in_one_step() { let mut s = session(); @@ -1145,6 +1219,32 @@ fn distort_rejects_malformed_coordinates_and_ids_without_editing_art() { assert_eq!(undo_len(&s), history + 1); } +/// `object.distort` with `angle` reads `from` as a box in the frame turned by it, as the Free +/// Transform tool sends a turned bounding box: corners where that box already stands leave the art. +#[test] +fn distort_reads_from_in_a_turned_frame_and_rejects_a_bad_angle() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let original = bounds(&s, a); + let bx = vectorcraft_doc::OrientedBox { angle: 90.0, rect: Rect::new(-100.0, 0.0, 0.0, 100.0) }; + let corners: Vec = bx.corners().iter().map(|c| json!([c.x, c.y])).collect(); + let history = undo_len(&s); + for p in [ + json!({"corners": corners, "from": [-100, 0, 0, 100], "angle": "90", "ids": [a.0]}), + json!({"corners": corners, "from": [-100, 0, 0, 100], "angle": [90], "ids": [a.0]}), + ] { + assert!(s.execute("object.distort", &p).is_err(), "invalid input: {p}"); + assert!(close(bounds(&s, a), original)); + assert_eq!(undo_len(&s), history); + } + s.execute("object.distort", &json!({"corners": corners, "from": [-100, 0, 0, 100], "angle": 90, "ids": [a.0]})).unwrap(); + assert!(close(bounds(&s, a), original), "{:?}", bounds(&s, a)); + assert_eq!(undo_len(&s), history + 1); + // Without `from`, the box is the objects' bounds in the turned frame: the same box here. + s.execute("object.distort", &json!({"corners": corners, "angle": 90, "ids": [a.0]})).unwrap(); + assert!(close(bounds(&s, a), original), "{:?}", bounds(&s, a)); +} + /// `artboard.move` and `artboard.delete` take several artboards at once (#1139): one undo step /// each, the art on each moving with it, and one artboard always left. #[test] diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index b222f32107..ae0c55ac76 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -25,7 +25,8 @@ pub struct ViewInfo { /// View → Pixel Preview: while it is on, the tools use no Smart Guides. pub pixel_preview: bool, pub show_bbox: bool, - /// View → Snap to Pixel: drawing and moving land on whole pixels (points at 72 ppi). + /// View → Snap to Pixel: drawing, moving and scaling land on whole pixels (points at 72 ppi), + /// each while its Pixel Snapping option (`view.snapToPixel.options`) is on. pub snap_to_pixel: bool, /// View → Snap to Point: picked points (a transform's reference point) land on anchors. pub snap_to_point: bool, @@ -75,6 +76,15 @@ fn nine_slice_guide_preview(cmd: &str, p: &Value) -> bool { && p.as_object().is_some_and(|m| m.contains_key("nineSliceGuides") && m.keys().all(|k| k == "name" || k == "nineSliceGuides")) } +/// `ui` with a status message first for each of `warnings` (which came before its requests) that it +/// doesn't already show. +fn with_status(mut ui: Vec, warnings: Vec) -> Vec { + let new: Vec = + warnings.into_iter().filter(|w| !ui.iter().any(|r| matches!(r, UiRequest::Status(s) if s == w))).map(UiRequest::Status).collect(); + ui.splice(0..0, new); + ui +} + /// Requests from tools that only the frontend can fulfil. #[derive(Clone, Debug, PartialEq)] pub enum UiRequest { @@ -227,24 +237,28 @@ impl Session { /// A press with Cmd held (Ctrl elsewhere) and any other tool than a selection tool: the /// selection tool [`Self::lent_tool`] takes the gesture, pressing without Cmd (a plain click, - /// not Select Behind). The tool lent to stays as it was, unaware, until the release. - fn lend_selection_tool(&mut self, ev: &PointerEvent) -> PointerEvent { + /// not Select Behind). The tool lent to stays as it was, unaware, until the release. → the event + /// for the tool, and the warnings of a preview that keeping the typing applied. + fn lend_selection_tool(&mut self, ev: &PointerEvent) -> Result<(PointerEvent, Vec)> { if ev.kind != PointerKind::Down || !ev.mods.cmd || self.lender.is_some() { - return *ev; + return Ok((*ev, vec![])); } - let Some(id) = self.lent_tool(self.tool.id(), &ev.mods) else { return *ev }; + let Some(id) = self.lent_tool(self.tool.id(), &ev.mods) else { return Ok((*ev, vec![])) }; // Typing in progress is kept as its own step first: the lent tool's drag previews from the - // document its interaction started from, which would drop the typing (#1881). + // document its interaction started from, which would drop the typing (#1881). When it + // can't be kept, the press is not lent. + let mut settled = vec![]; if crate::cmd::typing_in_progress(self) { - // Fails only without a document, and then there is no typing to keep. - let _ = crate::cmd::settle_interaction(self); + let (r, warnings) = self.collect_settled_warnings(crate::cmd::settle_interaction); + r?; + settled = warnings; } // The Selection and Group Selection tools act on the instance whole. self.select_whole_instance(id); let lent = self.make_tool(id); self.selection_at_lend = self.active().map(|d| (d.uid, d.selection.clone())); self.lender = Some(std::mem::replace(&mut self.tool, lent)); - PointerEvent { mods: Mods { cmd: false, ..ev.mods }, ..*ev } + Ok((PointerEvent { mods: Mods { cmd: false, ..ev.mods }, ..*ev }, settled)) } /// The lent selection tool's gesture is over: the tool it was lent to is back as it was (the @@ -355,6 +369,7 @@ impl Session { // Snap to Grid and Snap to Pixel are exclusive, as in Illustrator; left both on, the grid // wins instead of pixels quietly rounding every drag to whole points (#1816). snap_to_pixel: view.snap_to_pixel && !view.snap_to_grid, + pixel_snap: self.prefs.pixel_snap, snap_to_point: view.snap_to_point, snap_tangent: self.prefs.snap_tangent, snap_perpendicular: self.prefs.snap_perpendicular, @@ -659,7 +674,8 @@ impl Session { } self.leave_draw_inside(ev, view)?; self.tell_tool_history_moved(); - let ev = &self.lend_selection_tool(ev); + let (ev, settled) = self.lend_selection_tool(ev)?; + let ev = &ev; let lent = self.lender.is_some(); let mut acts = self.with_tool_cx(view, |t, cx| t.pointer(cx, ev)); if !keep { @@ -670,7 +686,7 @@ impl Session { if keep && ev.kind == PointerKind::Up { self.keep_tool_settings(); } - self.apply_actions(acts) + self.apply_actions(acts).map(|ui| with_status(ui, settled)) }); // The tool's own edits do not move the history for it. A selection tool that Cmd lends // edits for the lender, which hears of the edit at its next event. @@ -751,6 +767,27 @@ impl Session { self.apply_actions(acts).map(drop) } + /// The rulers' origin dragged out of their corner, whatever the tool, with the pointer at `p` in + /// document space (none off the canvas): where it goes, snapped as a drawn point is + /// ([`vectorcraft_tools::rulerguide::OriginDrag`]), the targets gathered on the drag's first + /// call. It changes nothing: the caller sets the origin where the button is released + /// (`document.setRulerOrigin`) and ends the drag ([`Session::end_ruler_origin_drag`]). + pub fn ruler_origin_drag(&mut self, p: Option, view: ViewInfo) -> Option { + let drag = match self.ruler_origin.take() { + Some(d) => Some(d), + None => self.with_tool_cx(view, |_, cx| Some(vectorcraft_tools::rulerguide::OriginDrag::new(cx))), + }; + let Some(mut drag) = drag else { return p }; + let at = self.with_tool_cx(view, |_, cx| drag.pointer(cx, p)); + self.ruler_origin = Some(drag); + at + } + + /// The drag of the rulers' origin ended, released or cancelled: its guides go. + pub fn end_ruler_origin_drag(&mut self) { + self.ruler_origin = None; + } + /// Time passed while the pointer button is held (`dt` seconds; see [`Tool::tick`]): the /// desktop app ticks every frame of a press, agents with `holdMs` on a pointer event. pub fn tool_tick(&mut self, dt: f64, view: ViewInfo) -> Result> { @@ -767,6 +804,12 @@ impl Session { self.tool.wants_ticks() } + /// Did the active tool leave part of its overlays for the next frame + /// ([`vectorcraft_tools::Tool::overlays_pending`])? + pub fn tool_overlays_pending(&self) -> bool { + self.tool.overlays_pending() + } + /// Does the active tool build a stroke from every position the pointer passed /// ([`vectorcraft_tools::Tool::wants_samples`])? pub fn tool_wants_samples(&self) -> bool { @@ -1069,22 +1112,51 @@ impl Session { self.tool.resizing() } - /// With Real-time Drawing off, how far a Selection-tool move drag has carried the selection - /// so far: the document moves on release, and the bounding box shows at this offset meanwhile. - pub fn deferred_move(&self) -> Option { - if self.tool.id() != "selection" || !self.tool.transforming() { + /// Does the canvas draw the bounding box around a shape being drawn: the active tool is drawing + /// a new shape whose box it shows once drawn (see `Tool::drawing_boxed`), and General › Show + /// Bounding Box While Moving and Drawing is on? + pub fn draws_new_shape_box(&self) -> bool { + self.prefs.bounding_box_while_moving_and_drawing && self.tool.drawing_boxed() + } + + /// Has the interaction no preview applied to the document: none has run yet, the last one failed, + /// or Real-time Drawing is off and the document is still the interaction's snapshot? + pub fn interaction_unapplied(&self) -> bool { + self.active().is_some_and(|d| d.interaction.as_ref().is_some_and(|it| it.preview.is_none() || std::sync::Arc::ptr_eq(&it.doc, &d.doc))) + } + + /// The bounding box of the selection a move drag is carrying (an Alt-drag copy included), where + /// the drag has carried it: the box of the selection at the drag's start, measured once per + /// drag, offset by the move of the latest preview. With General › Show Bounding Box While + /// Moving and Drawing on, for every tool that moves the selection; off, only for the Selection + /// tool with Real-time Drawing off, where the document moves on release. `None` for any other + /// drag, and before a preview has moved the selection. + pub fn move_drag_box(&self) -> Option { + if !self.tool.moving() { + return None; + } + let st = self.active()?; + let it = st.interaction.as_ref()?; + let deferred = std::sync::Arc::ptr_eq(&it.doc, &st.doc); + if !self.prefs.bounding_box_while_moving_and_drawing && !(self.tool.id() == "selection" && deferred) { return None; } - let it = self.active()?.interaction.as_ref()?; if !matches!(it.label.as_str(), "Move" | "Copy") { return None; } - let (cmd, p) = self.unapplied_interaction_preview()?; + let (cmd, p) = it.preview.as_ref()?; if cmd != "object.transform" || p.get("objects").and_then(Value::as_bool) == Some(false) { return None; } - let [a, b, c, d, e, f] = crate::cmd::matrix_param(&p, "matrix")?.as_coeffs(); - (a == 1.0 && b == 0.0 && c == 0.0 && d == 1.0).then(|| vectorcraft_geom::Vec2::new(e, f)) + let [a, b, c, d, e, f] = crate::cmd::matrix_param(p, "matrix")?.as_coeffs(); + if !(a == 1.0 && b == 0.0 && c == 0.0 && d == 1.0) { + return None; + } + let measure = self.bounds_measure(); + let start = + (*it.move_box.get_or_init(|| vectorcraft_render::effects::preview::oriented_bounds_with(&it.doc, &it.selection.objects, measure)))?; + let moved = start.to_local(Point::new(e, f)).to_vec2(); + Some(vectorcraft_doc::OrientedBox { rect: start.rect + moved, ..start }) } /// Does the active tool take `key` ahead of the shortcuts bound to it (see `Tool::claims_key`)? @@ -1112,14 +1184,20 @@ impl Session { v.extend(self.with_tool_cx(view, |_, cx| g.overlays(cx))); self.ruler_guide = Some(g); } + if let Some(d) = &self.ruler_origin { + v.extend(d.overlays()); + } let deferred_preview = self.unapplied_interaction_preview(); if let Some(d) = self.active() { let w = self.prefs.perspective_widget; let place = w.show.then_some(WidgetPlace { screen: view.screen.as_ref(), corner: w.position }); v.splice(0..0, vectorcraft_tools::distort::perspective::grid_overlays_in(&d.doc, 1.0 / view.zoom.max(1e-9), place)); } - // Global Edit: the objects edited with the selected one are highlighted. - for (path, color) in crate::cmd::globaledit::highlights(self) { + // Global Edit: the objects edited with the selected one are highlighted; before it starts, + // with the Selection tool, the objects it would take. + let ge_on = self.active().is_some_and(|d| d.global_edit.is_some()); + let shown = if ge_on || self.tool.id() == "selection" { crate::cmd::globaledit::highlights(self) } else { vec![] }; + for (path, color) in shown { v.push(Overlay::Path { path, color, width: 1.0, dashed: false }); } if let Some((cmd, p)) = deferred_preview { @@ -1319,7 +1397,14 @@ impl Session { /// Apply tool actions. Errors from previews are reported but keep the interaction alive. pub fn apply_actions(&mut self, acts: Vec) -> Result> { let outer = std::mem::replace(&mut self.in_tool_actions, true); - let r = self.apply_tool_actions(acts); + // A preview that settling applied (typing kept as its own step before a drag begins) shows + // its warning in the status bar, as the tool's own commit shows its preview's. + let r = if !outer && self.depth == 0 { + let (r, settled) = self.collect_settled_warnings(|s| s.apply_tool_actions(acts)); + r.map(|ui| with_status(ui, settled)) + } else { + self.apply_tool_actions(acts) + }; self.in_tool_actions = outer; if !outer && self.depth == 0 { self.trim_histories(); @@ -1411,23 +1496,30 @@ impl Session { } /// With Real-time Drawing off, the selection's transform box ([`Session::transform_box`]) as the - /// pending preview of a handle resize leaves it, measured once per preview step; `None` when no - /// such preview is pending, or when the preview fails. - pub fn deferred_transform_box(&mut self) -> Option { - if !self.tool.resizing() { + /// pending preview of a handle resize or of a shape being drawn leaves it, measured once per + /// preview step, with the layer color of the first object it measures; `None` when no such + /// preview is pending, or when the preview fails. + pub fn deferred_transform_box(&mut self) -> Option<(vectorcraft_doc::OrientedBox, [u8; 3])> { + if !self.measures_deferred_box() { return None; } let (cmd, p) = self.unapplied_interaction_preview()?; self.deferred_feedback(&cmd, &p)?.transform_box } + /// Does the canvas draw the bounding box of what the pending preview leaves: during a handle + /// resize, or while a shape is drawn by a tool that shows its box ([`Session::draws_new_shape_box`])? + fn measures_deferred_box(&self) -> bool { + self.tool.resizing() || self.draws_new_shape_box() + } + fn deferred_preview_overlays_from_command(&mut self, cmd: &str, p: &Value) -> Vec { self.deferred_feedback(cmd, p).map(|f| f.overlays.clone()).unwrap_or_default() } /// Canvas feedback while Real-time Drawing is off: run the pending preview command once, take - /// outlines from the objects it touched (and, during a handle resize, their transform box), then - /// put the document back at the interaction snapshot. + /// outlines from the objects it touched (and, during a handle resize or while a shape is drawn, + /// their transform box), then put the document back at the interaction snapshot. fn deferred_feedback(&mut self, cmd: &str, p: &Value) -> Option<&DeferredFeedback> { if !self.deferred_overlay_cache.as_ref().is_some_and(|f| f.cmd == cmd && f.params == *p) { let feedback = self.measure_deferred_preview(cmd, p)?; @@ -1448,8 +1540,12 @@ impl Session { }; let (overlays, transform_box) = if self.preview(cmd, p).is_ok() { let overlays = self.active().map(|st| outlines_for_selection(&st.doc, &st.selection)).unwrap_or_default(); - let objects = self.active().map(|st| st.selection.objects.clone()).unwrap_or_default(); - (overlays, if self.tool.resizing() { self.transform_box(&objects) } else { None }) + let (objects, color) = self + .active() + .map(|st| (st.selection.objects.clone(), st.selection.objects.first().map(|id| st.doc.layer_color(*id)))) + .unwrap_or_default(); + let transform_box = if self.measures_deferred_box() { self.transform_box(&objects).zip(color) } else { None }; + (overlays, transform_box) } else { (vec![], None) }; @@ -1473,7 +1569,7 @@ pub(crate) struct DeferredFeedback { cmd: String, params: Value, overlays: Vec, - transform_box: Option, + transform_box: Option<(vectorcraft_doc::OrientedBox, [u8; 3])>, } /// The most points the outlines of [`outlines_for_selection`] are drawn for, the same number as the diff --git a/crates/engine/tests/color_settings.rs b/crates/engine/tests/color_settings.rs index 0cc0edc4d4..e8b3ab0906 100644 --- a/crates/engine/tests/color_settings.rs +++ b/crates/engine/tests/color_settings.rs @@ -57,6 +57,258 @@ fn legacy_profile_name_resolves_in_commands_and_files() { cms::set_active(&before).unwrap(); } +/// Assigning a profile other than the working space replaces the active color settings and raises +/// the other open documents' revisions. +#[test] +fn assigning_another_profile_replaces_the_active_color_settings() { + let _g = settings(); + let mut s = session(); + exec(&mut s, "file.new", json!({"width": 100, "height": 100})); + let before = cms::active_settings(); + assert_ne!(before.cmyk, cms::DEVICE_CMYK); + let active = cms::active(); + let other = s.documents()[0].revision; + exec(&mut s, "edit.assignProfile", json!({"cmyk": cms::DEVICE_CMYK})); + assert_eq!(cms::active_settings().cmyk, cms::DEVICE_CMYK); + assert!(!std::sync::Arc::ptr_eq(&active, &cms::active()), "the active color settings were not replaced"); + assert!(s.documents()[0].revision > other, "the other document's revision did not change"); + cms::set_active(&before).unwrap(); +} + +/// Assign Profile tags the document and leaves the working spaces: Color Settings shows the +/// working spaces, a later change to it saves them and not the assigned profile, and taking the +/// profile off the document brings the working spaces back. +#[test] +fn assign_profile_leaves_the_working_spaces() { + let _g = settings(); + let dir = fresh_dir("assign-profile"); + let _reset = ColorSettingsReset { profile: None, paths: vec![dir.clone()] }; + let file = dir.join("Color Settings.json"); + let mut s = session(); + s.attach_color_settings(file.clone()); + let working = cms::working_settings(); + assert_ne!(working.cmyk, cms::DEVICE_CMYK); + exec(&mut s, "edit.assignProfile", json!({"cmyk": cms::DEVICE_CMYK})); + assert_eq!(cms::active_settings().cmyk, cms::DEVICE_CMYK, "the document draws through its profile"); + assert_eq!(cms::working_settings(), working); + assert!(!file.exists(), "Assign Profile saves no Color Settings"); + let r = exec(&mut s, "edit.colorSettings", json!({})); + assert_eq!(r["cmyk"], working.cmyk.as_str(), "Color Settings shows the working CMYK space"); + exec(&mut s, "edit.colorSettings", json!({"intent": "perceptual"})); + let saved: cms::ColorSettings = serde_json::from_slice(&std::fs::read(&file).unwrap()).unwrap(); + assert_eq!((saved.cmyk.as_str(), saved.intent), (working.cmyk.as_str(), cms::Intent::Perceptual)); + assert_eq!(cms::active_settings().cmyk, cms::DEVICE_CMYK, "the document still draws through its profile"); + exec(&mut s, "edit.assignProfile", json!({"cmyk": null})); + assert_eq!(cms::active_settings(), cms::working_settings(), "no profile: the working spaces"); +} + +/// A loaded profile that is assigned but is not a working space can be removed: the working space +/// takes its place in the active settings, and the working spaces stay as they are. +#[test] +fn removing_an_assigned_profile_puts_the_working_space_back() { + const NAME: &str = "Assigned CMYK"; + let _g = settings(); + let _reset = ColorSettingsReset { profile: Some(NAME), paths: vec![] }; + cms::register_icc(&cms::icc_bytes(cms::GENERIC_CMYK).unwrap(), Some(NAME.into())).unwrap(); + let mut s = session(); + let working = cms::working_settings(); + exec(&mut s, "edit.assignProfile", json!({"cmyk": NAME})); + assert_eq!(cms::active_settings().cmyk, NAME); + let revision = s.doc().unwrap().revision; + let r = exec(&mut s, "color.removeProfile", json!({"name": NAME})); + assert_eq!(r["removed"], NAME); + assert_eq!(cms::active_settings(), working, "the working CMYK space is in use again"); + assert_eq!(cms::working_settings(), working); + assert!(s.doc().unwrap().revision > revision, "the canvas redraws"); +} + +/// Loading the file of an assigned profile in use again keeps it in use, loading it after it was +/// removed puts it back in use, and the working spaces stay as they are. +#[test] +fn loading_an_assigned_profile_again_keeps_it_in_use() { + const NAME: &str = "Assigned P"; + let _g = settings(); + let dir = fresh_dir("reload-assigned"); + let _reset = ColorSettingsReset { profile: Some(NAME), paths: vec![dir.clone()] }; + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("assigned.icc"); + std::fs::write(&path, icc_named(NAME)).unwrap(); + let mut s = session(); + let working = cms::working_settings(); + let load = |s: &mut Session| assert_eq!(exec(s, "color.loadProfile", json!({"path": path.to_str().unwrap()}))["name"], NAME); + load(&mut s); + exec(&mut s, "edit.assignProfile", json!({"rgb": NAME})); + let before = cms::active(); + load(&mut s); + assert_eq!(cms::active_settings().rgb, NAME, "the assigned profile stays in use"); + assert!(!std::sync::Arc::ptr_eq(&before, &cms::active()), "the new file is in use"); + exec(&mut s, "color.removeProfile", json!({"name": NAME})); + assert_eq!(cms::active_settings(), working); + load(&mut s); + assert_eq!(cms::active_settings().rgb, NAME, "loaded again, the assigned profile is in use"); + assert_eq!(cms::working_settings(), working); +} + +/// A batch that assigns a profile and then changes the color mode, as Document Setup's OK does, +/// converts the colors through the profile it assigns. +#[test] +fn a_batch_converts_through_the_profile_it_assigns() { + let _g = settings(); + let _reset = ColorSettingsReset { profile: None, paths: vec![] }; + let blue = |s: &mut Session| { + let id = rect(s, 10.0, 10.0, 50.0, 50.0); + exec(s, "paint.setFill", json!({"ids": [id.0], "color": "#3366cc"})); + id + }; + let fill = |s: &Session, id| s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint().color(); + let mut working = session(); + let w = blue(&mut working); + exec(&mut working, "file.documentColorMode", json!({"mode": "cmyk"})); + let mut tagged = session(); + let a = blue(&mut tagged); + let steps = json!([ + {"command": "edit.assignProfile", "params": {"cmyk": cms::DEVICE_CMYK}}, + {"command": "file.documentColorMode", "params": {"mode": "cmyk"}}, + ]); + exec(&mut tagged, "command.batch", json!({"commands": steps})); + let converted = fill(&tagged, a); + assert_ne!(converted, fill(&working, w), "converted through the working CMYK space"); + let mut device = session(); + let b = blue(&mut device); + exec(&mut device, "edit.colorSettings", json!({"cmyk": cms::DEVICE_CMYK})); + exec(&mut device, "file.documentColorMode", json!({"mode": "cmyk"})); + assert_eq!(converted, fill(&device, b)); +} + +/// The profiles a document is assigned are in use while it is in front: a new or opened document +/// assigned none draws through the working spaces, switching back to the assigned document puts its +/// profile in use again, and closing a document puts the profiles of the document left in front, or +/// with none open the working spaces, in use. +#[test] +fn assigned_profiles_follow_the_front_document() { + let _g = settings(); + let dir = fresh_dir("front-profiles"); + let _reset = ColorSettingsReset { profile: None, paths: vec![dir.clone()] }; + std::fs::create_dir_all(&dir).unwrap(); + let tagged = dir.join("tagged.vectorcraft"); + let mut s = session(); + let working = cms::working_settings(); + assert_ne!(working.cmyk, cms::DEVICE_CMYK); + exec(&mut s, "edit.assignProfile", json!({"cmyk": cms::DEVICE_CMYK})); + exec(&mut s, "file.saveAs", json!({"path": tagged.to_str().unwrap()})); + exec(&mut s, "file.new", json!({"width": 100, "height": 100})); + assert_eq!(cms::active_settings(), working, "a new document draws through the working spaces"); + exec(&mut s, "document.activate", json!({"index": 0})); + assert_eq!(cms::active_settings().cmyk, cms::DEVICE_CMYK, "back in front, the document draws through its profile"); + assert!(s.set_active(1)); + assert_eq!(cms::active_settings(), working, "a tab switch to the untagged document"); + exec(&mut s, "file.close", json!({})); + assert_eq!(cms::active_settings().cmyk, cms::DEVICE_CMYK, "the document left in front draws through its profile"); + exec(&mut s, "file.close", json!({})); + assert_eq!(cms::active_settings(), working, "no document open: the working spaces"); + exec(&mut s, "document.open", json!({"path": tagged.to_str().unwrap()})); + assert_eq!(cms::active_settings().cmyk, cms::DEVICE_CMYK, "an opened document draws through its saved profile"); +} + +/// Undo and Redo of Assign Profile, and File › Revert to a file assigned no profile, put the +/// profiles the document has then in use. +#[test] +fn undo_redo_and_revert_put_the_document_profiles_in_use() { + let _g = settings(); + let dir = fresh_dir("undo-profiles"); + let _reset = ColorSettingsReset { profile: None, paths: vec![dir.clone()] }; + std::fs::create_dir_all(&dir).unwrap(); + let untagged = dir.join("untagged.vectorcraft"); + let mut s = session(); + let working = cms::working_settings(); + exec(&mut s, "file.saveAs", json!({"path": untagged.to_str().unwrap()})); + exec(&mut s, "edit.assignProfile", json!({"cmyk": cms::DEVICE_CMYK})); + assert_eq!(cms::active_settings().cmyk, cms::DEVICE_CMYK); + exec(&mut s, "edit.undo", json!({})); + assert_eq!(doc_profiles(&s.doc().unwrap().doc), (None, None)); + assert_eq!(cms::active_settings(), working, "undone: the working spaces"); + exec(&mut s, "edit.redo", json!({})); + assert_eq!(doc_profiles(&s.doc().unwrap().doc), (None, Some(cms::DEVICE_CMYK.to_string()))); + assert_eq!(cms::active_settings().cmyk, cms::DEVICE_CMYK, "redone: the assigned profile"); + exec(&mut s, "file.revert", json!({})); + assert_eq!(doc_profiles(&s.doc().unwrap().doc), (None, None)); + assert_eq!(cms::active_settings(), working, "reverted: the working spaces"); +} + +/// A batch that assigns a profile and then fails puts the document back without it, and the +/// working spaces back in use. +#[test] +fn a_failed_batch_puts_the_profiles_in_use_back() { + let _g = settings(); + let _reset = ColorSettingsReset { profile: None, paths: vec![] }; + let mut s = session(); + let working = cms::working_settings(); + let steps = json!([ + {"command": "edit.assignProfile", "params": {"cmyk": cms::DEVICE_CMYK}}, + {"command": "document.activate", "params": {"index": 99}}, + ]); + assert!(s.execute("command.batch", &json!({"commands": steps})).is_err()); + assert_eq!(doc_profiles(&s.doc().unwrap().doc), (None, None)); + assert_eq!(cms::active_settings(), working); +} + +/// A batch step that switches documents makes the next step convert through the profiles of the +/// document it switched to, not those of the document the batch began in. +#[test] +fn a_batch_converts_the_document_it_switches_to_through_its_profiles() { + let _g = settings(); + let _reset = ColorSettingsReset { profile: None, paths: vec![] }; + let blue = |s: &mut Session| { + let id = rect(s, 10.0, 10.0, 50.0, 50.0); + exec(s, "paint.setFill", json!({"ids": [id.0], "color": "#3366cc"})); + id + }; + let fill = |s: &Session, id| s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint().color(); + let mut working = session(); + let w = blue(&mut working); + exec(&mut working, "file.documentColorMode", json!({"mode": "cmyk"})); + let mut s = session(); + let b = blue(&mut s); + exec(&mut s, "file.new", json!({"width": 100, "height": 100})); + exec(&mut s, "edit.assignProfile", json!({"cmyk": cms::DEVICE_CMYK})); + let steps = json!([ + {"command": "document.activate", "params": {"index": 0}}, + {"command": "file.documentColorMode", "params": {"mode": "cmyk"}}, + ]); + exec(&mut s, "command.batch", json!({"commands": steps})); + assert_eq!(s.active_index(), Some(0)); + assert_eq!(fill(&s, b), fill(&working, w), "converted through the working CMYK space"); +} + +/// View › Proof Setup › Working CMYK simulates the working CMYK space of Color Settings in a +/// document assigned another CMYK profile, in Proof Colors and in Separations Preview, and a change +/// of the working CMYK space shows in the next proof while the document keeps its profile. +#[test] +fn working_cmyk_proofs_a_tagged_document_through_the_working_space() { + const NAME: &str = "Tagged CMYK"; + let _g = settings(); + let _reset = ColorSettingsReset { profile: Some(NAME), paths: vec![] }; + cms::register_icc(&cms::icc_bytes(cms::GENERIC_CMYK).unwrap(), Some(NAME.into())).unwrap(); + let proof = cms::ProofSetup::default(); + assert_eq!(proof.target, cms::ProofTarget::WorkingCmyk); + let (blue, inks) = ([0.2, 0.4, 0.8], [0.6, 0.3, 0.0, 0.1]); + let mut s = session(); + exec(&mut s, "edit.assignProfile", json!({"cmyk": NAME})); + let (active, working) = (cms::active(), cms::working()); + assert_eq!(active.settings().cmyk, NAME); + assert_eq!(active.proof_srgb(blue, &proof), working.proof_srgb(blue, &proof), "Proof Colors"); + assert_eq!(active.proof_cmyk_to_srgb(inks, &proof), working.proof_cmyk_to_srgb(inks, &proof), "Separations Preview"); + let _ = active.proof_lut(&proof); + exec(&mut s, "edit.colorSettings", json!({"cmyk": cms::DEVICE_CMYK})); + let (active, working) = (cms::active(), cms::working()); + assert_eq!(active.settings().cmyk, NAME, "the document keeps its profile"); + let lut = active.proof_lut(&proof); + let fresh = cms::ProofLut::build(|rgb| working.proof_srgb(rgb, &proof)); + for px in [[51, 102, 204], [230, 30, 30], [20, 160, 40], [128, 128, 128]] { + assert_eq!(lut.apply8(px), fresh.apply8(px), "the proof of {px:?} through the new working CMYK space"); + } +} + /// Separations Preview follows the Color Settings and the profiles loaded: a renderer draws a gray /// square on the Black plate through the new working CMYK profile, and the four process plates /// through a proof profile loaded again under the same name, as a new renderer draws them. @@ -401,7 +653,7 @@ fn loading_the_working_rgb_profile_again_takes_effect_at_once() { bytes }; let name = "Reload RGB"; - let dir = vectorcraft_testkit::temp_dir("reload-working-rgb"); + let dir = vectorcraft_testkit::TempDir::new("reload-working-rgb"); let load = |s: &mut Session, builtin: &str| { let path = dir.join(format!("{}.icc", builtin.len())); std::fs::write(&path, renamed(builtin, name)).unwrap(); @@ -428,11 +680,63 @@ fn loading_the_working_rgb_profile_again_takes_effect_at_once() { assert!(redrawn, "the canvas redraws"); } -/// A folder of its own for the test `tag`, empty. -fn fresh_dir(tag: &str) -> std::path::PathBuf { - let dir = vectorcraft_testkit::temp_dir(&format!("color-settings-{tag}")); - let _ = std::fs::remove_dir_all(&dir); - dir +/// Loading a new file of the CMYK profile View → Proof Setup targets, or removing that profile, +/// gives the documents new revisions, as a working space's new file does; loading or removing +/// another profile does not. +#[test] +fn loading_or_removing_the_proof_profile_redraws() { + let _g = settings(); + // A built-in CMYK profile's file renamed `name`: padded with spaces, which names drop. + let renamed = |builtin: &str, name: &str| { + let utf16 = |s: &str| s.encode_utf16().flat_map(u16::to_be_bytes).collect::>(); + let mut bytes = cms::icc_bytes(builtin).unwrap().to_vec(); + let (from, to) = (utf16(builtin), utf16(&format!("{name: revision, "the proof profile's file"); + exec(&mut s, "color.removeProfile", json!({"name": other})); + assert_eq!(s.doc().unwrap().revision, reloaded, "another profile removed"); + exec(&mut s, "color.removeProfile", json!({"name": proofed})); + assert!(s.doc().unwrap().revision > reloaded, "the proof profile removed"); +} + +/// Sets the default proof view and unregisters the profiles when dropped, also after a failed +/// assertion. +struct ProofReset([&'static str; 2]); + +impl Drop for ProofReset { + fn drop(&mut self) { + vectorcraft_render::proof::set_view(Default::default()); + for name in self.0 { + cms::unregister_icc(name); + } + } +} + +/// A folder of its own for the test `tag`, empty, removed when dropped. +fn fresh_dir(tag: &str) -> vectorcraft_testkit::TempDir { + vectorcraft_testkit::TempDir::new(&format!("color-settings-{tag}")) } /// An ICC file of an RGB profile named `name` (a built-in one with its description replaced by a @@ -479,7 +783,8 @@ fn color_settings_come_back_in_the_next_session() { let root = fresh_dir("color-settings"); let (profiles, file) = (root.join("Color Profiles"), root.join("Color Settings.json")); let loaded = "StoreRGB-6"; - let icc = vectorcraft_testkit::temp_dir("store-color-settings").join("loaded.icc"); + let icc_dir = vectorcraft_testkit::TempDir::new("store-color-settings"); + let icc = icc_dir.join("loaded.icc"); let _reset = ColorSettingsReset { profile: Some(loaded), paths: vec![root.clone(), icc.clone()] }; std::fs::write(&icc, icc_named(loaded)).unwrap(); diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 947cf559d0..d88d99665f 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -9,13 +9,13 @@ use vectorcraft_engine::{Session, command_specs}; use vectorcraft_testkit::catch_quiet; use vectorcraft_testkit::fixtures::Fixture; use vectorcraft_testkit::invariants::{check_all, check_session, doc_json}; -use vectorcraft_testkit::strategies::{junk_params, junk_values, param_keys, safe_value}; +use vectorcraft_testkit::strategies::{command_param_keys, junk_params_for_command, junk_values, param_keys, safe_value_for_command}; -/// Commands that replace/close the active document or touch the filesystem are fine to call, but a -/// few need their file and folder params redirected into a temp dir (`safe_value`, which -/// `junk_params` applies). -fn safe_path() -> String { - vectorcraft_testkit::temp_dir("sweep").join("out.bin").to_string_lossy().to_string() +/// Commands that replace/close the active document or touch the filesystem are fine to call, but +/// their file and folder params are redirected into the test's temp dir `dir` (`safe_value_for_command`, +/// which `junk_params_for_command` applies, by the keys the command catalog names as files and folders). +fn safe_path(dir: &std::path::Path) -> String { + dir.join("out.bin").to_string_lossy().to_string() } /// `r`, after failing the case if the command panicked. The engine's guard reports a panic as @@ -190,17 +190,42 @@ fn heavy(id: &str) -> bool { id.starts_with("document.serialize") || id.starts_with("document.export") || id == "document.open" } +/// Is `p` a params object with `k` as its only key? +fn sends_alone(p: &Value, k: &str) -> bool { + p.as_object().is_some_and(|o| o.len() == 1 && o.contains_key(k)) +} + +/// The junk params the sweeps send `c`: all of them, or for a [`heavy`] command the first 12 and, +/// for each key the command catalog names as a file or folder that no case among those sends alone +/// ([`sends_alone`]), the first case that sends a string under it alone (or any value when none +/// does). +fn junk_cases(c: &vectorcraft_engine::CommandSpec, path: &str) -> Vec { + let mut cases = junk_params_for_command(c, path); + if heavy(c.id) { + let rest = cases.split_off(cases.len().min(12)); + for (k, _) in vectorcraft_engine::cmd::location_keys(c) { + if cases.iter().any(|p| sends_alone(p, k)) { + continue; + } + let alone = || rest.iter().filter(|p| sends_alone(p, k)); + let found = alone().find(|p| p.get(k).is_some_and(Value::is_string)).or_else(|| alone().next()); + if let Some(p) = found { + cases.push(p.clone()); + } + } + } + cases +} + #[test] fn every_command_with_junk_params() { - let path = safe_path(); + let dir = vectorcraft_testkit::TempDir::new("sweep"); + let path = safe_path(&dir); let mut failures = vec![]; let mut calls = 0usize; for fx in Fixture::ALL { for c in command_specs() { - let mut cases = junk_params(c.params, &path); - if heavy(c.id) { - cases.truncate(12); - } + let cases = junk_cases(c, &path); for p in &cases { calls += 1; if let Some(f) = probe(fx, c.id, p) { @@ -234,13 +259,10 @@ fn tool_edit_state(s: &Session) -> ToolEditState { /// The params the tool-edit sweep sends `c`: junk params, then each documented key turned on and /// off, with a string under a file or folder key replaced by a location inside `path`'s folder. fn tool_edit_cases(c: &vectorcraft_engine::CommandSpec, path: &str) -> Vec { - let mut cases = junk_params(c.params, path); - if heavy(c.id) { - cases.truncate(12); - } - for k in param_keys(c.params) { + let mut cases = junk_cases(c, path); + for k in command_param_keys(c) { for v in [json!(true), json!(false), json!(1), json!("on")] { - cases.push(json!({ k.as_str(): safe_value(&k, &v, path) })); + cases.push(json!({ k.as_str(): safe_value_for_command(c, &k, &v, path) })); } } // Find Objects selects only with a filter, which one key at a time does not give it. @@ -250,35 +272,109 @@ fn tool_edit_cases(c: &vectorcraft_engine::CommandSpec, path: &str) -> Vec) { + match v { + Value::String(s) if named && !std::path::Path::new(s).starts_with(dir) => { + out.insert(format!("{id} {at}: {v}")); + } + Value::Array(a) => { + for (i, x) in a.iter().enumerate() { + outside_locations(id, &format!("{at}[{i}]"), x, named, dir, out); + } + } + Value::Object(o) => { + for (k, x) in o { + outside_locations(id, &format!("{at}.{k}"), x, names_location(None, k), dir, out); + } + } + _ => {} + } +} + +/// Does `key` name a file or folder, in command `spec` when given: a key in +/// `vectorcraft_engine::cmd::key_location`'s list that `vectorcraft_engine::cmd::location_in` keeps +/// for `spec`. +fn names_location(spec: Option<&vectorcraft_engine::CommandSpec>, key: &str) -> bool { + match spec { + Some(spec) => vectorcraft_engine::cmd::location_in(spec, key).is_some(), + None => vectorcraft_engine::cmd::key_location(key).is_some(), + } +} + +/// Every string the sweeps send under a key that names a file or folder, in the command catalog +/// (`vectorcraft_engine::cmd::location_keys`, so a command added later is checked too) or inside +/// an object or an array at any depth, is inside the sweep's temp folder, so no run reads or +/// writes in the working directory. `every_command_with_junk_params` sends every such key of every +/// command alone in at least one case ([`junk_cases`]). #[test] fn sweep_cases_name_files_only_inside_the_temp_folder() { - let path = safe_path(); - let dir = vectorcraft_testkit::temp_dir("sweep"); - let keys = ["path", "diffPath", "folder", "destinationFolder"]; - let mut seen = std::collections::BTreeSet::new(); + let dir = vectorcraft_testkit::TempDir::new("sweep"); + let path = safe_path(&dir); + let mut unsent = vec![]; let mut outside = std::collections::BTreeSet::new(); for c in command_specs() { - let mut cases = junk_params(c.params, &path); + let keys = vectorcraft_engine::cmd::location_keys(c); + let run = junk_cases(c, &path); + for (k, _) in &keys { + if !run.iter().any(|p| sends_alone(p, k)) { + unsent.push(format!("{} {k}", c.id)); + } + } + let mut cases = junk_params_for_command(c, &path); cases.extend(tool_edit_cases(c, &path)); + cases.extend(serializable_cases(c, &path)); for p in &cases { let Some(o) = p.as_object() else { continue }; - for (k, v) in o.iter().filter(|(k, _)| keys.contains(&k.as_str())) { - seen.insert(k.clone()); - if let Some(s) = v.as_str() - && !std::path::Path::new(s).starts_with(&dir) - { - outside.insert(format!("{} {{\"{k}\": {v}}}", c.id)); - } + for (k, v) in o { + outside_locations(c.id, k, v, names_location(Some(c), k), &dir, &mut outside); } } } - assert_eq!(seen.len(), keys.len(), "the sweeps send only {seen:?}"); + assert!(unsent.is_empty(), "every_command_with_junk_params sends no case for {unsent:?}"); let outside: Vec = outside.into_iter().collect(); assert!(outside.is_empty(), "{} cases name a location outside {}:\n{}", outside.len(), dir.display(), outside.join("\n")); } +/// The cases sweep keys the command catalog names as files and folders: `document.open`'s +/// `{path | name …}`, `addon.document.saveTimestampedCopy`'s `{folder? (…)}`, `document.compare`'s +/// `diffPath`, `file.saveAs`'s `path` after `{…as document.save}` and `links.relink`'s +/// `paths: [{ids, path}]`, each with a string in the temp folder, and a folder key a folder there. +#[test] +fn sweep_cases_send_the_file_keys_of_the_command_catalog() { + let dir = vectorcraft_testkit::TempDir::new("sweep"); + let path = safe_path(&dir); + let spec = |id: &str| command_specs().iter().find(|c| c.id == id).unwrap(); + let inside = |v: &Value| v.as_str().is_some_and(|s| std::path::Path::new(s).starts_with(&dir)); + for (id, key) in [ + ("document.open", "path"), + ("addon.document.saveTimestampedCopy", "folder"), + ("document.compare", "diffPath"), + ("text.addFontFiles", "files"), + ("file.saveAs", "path"), + ] { + let cases = junk_params_for_command(spec(id), &path); + let sent: Vec<&Value> = cases.iter().filter_map(|p| p.get(key)).collect(); + assert!(sent.iter().any(|v| inside(v) || v.as_array().is_some_and(|a| a.iter().any(inside))), "{id} sends no `{key}` in the temp folder"); + } + for (id, key) in + [("document.open", "path"), ("document.open", "name"), ("addon.document.saveTimestampedCopy", "folder"), ("links.relink", "folder")] + { + assert!(param_keys(spec(id).params).iter().any(|k| k == key), "{id} has no `{key}` key"); + } + let folder = junk_params_for_command(spec("addon.document.saveTimestampedCopy"), &path); + assert!(folder.iter().filter_map(|p| p.get("folder")?.as_str()).all(|s| s != path && std::path::Path::new(s).starts_with(&dir))); + let relink = junk_params_for_command(spec("links.relink"), &path); + let nested = relink.iter().filter_map(|p| p.get("paths")?.as_array()).flatten().filter_map(|e| e.get("path")).filter(|v| v.is_string()); + assert!(nested.clone().count() > 0 && nested.clone().all(inside), "links.relink sends no `paths[].path` in the temp folder"); + // A key that names part of the document in a command keeps its junk there. + let on_path = junk_params_for_command(spec("text.createInPath"), &path); + assert!(on_path.iter().any(|p| p.get("path") == Some(&json!("junk")))); +} + /// Every command that runs at once while the active tool computes an edit on another thread (a /// Shape Builder merge), rather than applying the edit first (`waits_for_tool_edit`), leaves the /// documents' revisions and selections, the active document and the current paint as they were, @@ -286,7 +382,8 @@ fn sweep_cases_name_files_only_inside_the_temp_folder() { /// document as it was, still applies after it. #[test] fn commands_that_do_not_wait_for_a_tool_edit_change_no_document() { - let path = safe_path(); + let dir = vectorcraft_testkit::TempDir::new("sweep"); + let path = safe_path(&dir); let mut failures = vec![]; for fx in [Fixture::Single, Fixture::Multi] { for c in command_specs().iter().filter(|c| !vectorcraft_engine::waits_for_tool_edit(c.id)) { @@ -674,6 +771,8 @@ fn structured_junk() { ("object.blend.options", json!({"spacing": "distance", "value": -1e308, "orientation": 5})), ("object.blend.options", json!({"ramp": 1e308, "colorShift": -1e308, "easingType": [1]})), ("object.blend.make", json!({"ids": [1, 2], "ramp": f64::NAN, "colorShift": [1]})), + ("object.blend.make", json!({"ids": [1, 2], "createSpine": ["never"], "easingType": "easeIn"})), + ("object.blend.createSpine", json!({"mode": 1e308})), ("object.blend.spine.moveAnchor", json!({"id": 2, "anchor": u64::MAX, "x": 1e308, "y": -1e308, "handle": "sideways"})), ("object.blend.spine.addAnchor", json!({"id": u64::MAX, "x": 0, "y": 0})), ("object.blend.spine.reshapeSegment", json!({"id": 2, "segment": u64::MAX, "t": f64::NAN, "dx": 1e308, "dy": -1e308})), @@ -796,6 +895,12 @@ fn structured_junk() { ("addon.pen.reshape", json!({"id": 2, "segment": 0, "t": "x", "dx": 1, "dy": 1, "mode": "symmetric"})), ("addon.pen.nextSegment", json!({"curved": "yes"})), ("addon.pen.closeJoin", json!({"ids": [u64::MAX]})), + // Cutting Tools add-on. + ("addon.cutting.weed", json!({"margin": 1e5, "count": 1000, "gap": 1e5, "direction": "both"})), + ("addon.cutting.weed", json!({"margin": -1, "count": 1.5, "spacing": 0, "gap": f64::MAX, "weight": 1e308})), + ("addon.cutting.weed", json!({"spacing": 1e-300, "box": "no", "direction": ["both"], "swatch": 5})), + ("addon.cutting.weed", json!({"spacing": "1 mm", "box": false, "direction": "vertical", "swatch": "no such swatch"})), + ("addon.cutting.weed", json!({"count": u64::MAX, "margin": "x", "gap": null, "weight": 0})), // Type Tools add-on. ("addon.type.textTweaker", json!({"attribute": "size", "from": 1296, "to": 0.1, "shape": "random", "seed": u64::MAX})), ("addon.type.textTweaker", json!({"attribute": "tracking", "from": f64::MAX, "to": -1e308, "shape": "spike"})), @@ -807,6 +912,12 @@ fn structured_junk() { ("addon.type.releasePath", json!({"mode": "text", "keepOriginal": false, "id": 2})), ("addon.type.releasePath", json!({"mode": ["both"], "keepOriginal": "no", "ids": "all", "id": -1})), ("addon.type.releasePath", json!({"mode": "nope", "keepOriginal": 1e308, "ids": [1.5, null, "x"]})), + // Cutting Tools add-on: Stencil Bridges. + ("addon.cutting.bridges", json!({"width": 0.01, "count": 16, "direction": "shortest", "keepOriginal": true})), + ("addon.cutting.bridges", json!({"width": 1000, "count": 1, "direction": "horizontal", "keepOriginal": false})), + ("addon.cutting.bridges", json!({"width": "3 mm", "direction": "vertical"})), + ("addon.cutting.bridges", json!({"width": f64::MAX, "count": 1e308, "direction": ["vertical"], "keepOriginal": "no"})), + ("addon.cutting.bridges", json!({"width": -1, "count": -3, "direction": "diagonal", "keepOriginal": 1e308})), ("addon.cleanup.breakText", json!({"by": "glyphs", "ids": [0, 1, 2, 3, 4, 5, 6, 7, 8, u64::MAX]})), ("addon.cleanup.breakText", json!({"by": ["lines"]})), ("addon.cleanup.breakText", json!({"by": "paragraphs"})), @@ -999,28 +1110,37 @@ fn polygon_properties_junk() { assert!(failures.is_empty(), "{} failures:\n{}", failures.len(), failures.join("\n")); } +/// The params `fuzzed_calls_keep_documents_serializable` sends `c`: each key with each of the +/// first junk values, a string under a file or folder key replaced by a location inside `path`'s +/// folder. +fn serializable_cases(c: &vectorcraft_engine::CommandSpec, path: &str) -> Vec { + if heavy(c.id) || c.id.starts_with("file.") { + return vec![]; + } + let mut cases = vec![]; + for v in junk_values().iter().take(8) { + for k in command_param_keys(c) { + cases.push(json!({ k.as_str(): safe_value_for_command(c, &k, v, path) })); + } + } + cases +} + /// After a successful fuzzed call, the document still round-trips and exports. #[test] fn fuzzed_calls_keep_documents_serializable() { - let path = safe_path(); + let dir = vectorcraft_testkit::TempDir::new("sweep"); + let path = safe_path(&dir); let mut failures = vec![]; for c in command_specs() { - if heavy(c.id) || c.id.starts_with("file.") { - continue; - } - for v in junk_values().iter().take(8) { - for k in param_keys(c.params) { - let k = if k == "path" { continue } else { k }; - let mut s = Fixture::Multi.session(); - let p = json!({ k.clone(): v }); - let ok = catch_quiet(|| s.execute(c.id, &p)).map(|r| r.is_ok()).unwrap_or(false); - if ok && let Err(e) = catch_quiet(|| check_all(&mut s)).unwrap_or_else(|m| Err(format!("panic in checks: {m}"))) { - failures.push(format!("{} {p}: {e}", c.id)); - } + for p in serializable_cases(c, &path) { + let mut s = Fixture::Multi.session(); + let ok = catch_quiet(|| s.execute(c.id, &p)).map(|r| r.is_ok()).unwrap_or(false); + if ok && let Err(e) = catch_quiet(|| check_all(&mut s)).unwrap_or_else(|m| Err(format!("panic in checks: {m}"))) { + failures.push(format!("{} {p}: {e}", c.id)); } } } - let _ = path; failures.sort(); failures.dedup(); assert!(failures.is_empty(), "{} failures:\n{}", failures.len(), failures.iter().take(40).cloned().collect::>().join("\n")); @@ -1079,11 +1199,12 @@ fn recovery_commands_with_a_damaged_store_and_junk_params() { ] { store.write(name, bytes).unwrap(); } - let path = safe_path(); + let dir = vectorcraft_testkit::TempDir::new("sweep"); + let path = safe_path(&dir); for fx in Fixture::ALL { for id in ["file.recovery.save", "file.recovery.list", "file.recovery.restore", "file.recovery.discard"] { let spec = command_specs().iter().find(|c| c.id == id).unwrap(); - for p in std::iter::once(json!({})).chain(junk_params(spec.params, &path)) { + for p in std::iter::once(json!({})).chain(junk_params_for_command(spec, &path)) { let mut s = fx.session(); s.recovery.set_store(store.clone()); let r = catch_quiet(|| no_panic(s.execute(id, &p))); @@ -1099,7 +1220,8 @@ fn recovery_commands_with_a_damaged_store_and_junk_params() { /// interaction or a broken tree. #[test] fn envelope_commands_with_junk_params_on_envelopes() { - let path = safe_path(); + let dir = vectorcraft_testkit::TempDir::new("sweep"); + let path = safe_path(&dir); let makes: [(&str, Value); 3] = [ ("object.envelope.makeWithWarp", json!({"style": "twist", "bend": 80})), ("object.envelope.makeWithMesh", json!({"rows": 2, "cols": 3})), @@ -1112,7 +1234,7 @@ fn envelope_commands_with_junk_params_on_envelopes() { command_specs().iter().map(|c| c.id).filter(|id| id.starts_with("object.envelope.") || id.starts_with("object.mesh.")).collect(); for id in ids { let spec = command_specs().iter().find(|c| c.id == id).unwrap(); - for p in std::iter::once(json!({})).chain(junk_params(spec.params, &path)) { + for p in std::iter::once(json!({})).chain(junk_params_for_command(spec, &path)) { let mut s = Fixture::Multi.session(); if s.execute(make, mp).is_err() { failures.push(format!("{make} failed on the Multi fixture")); @@ -1145,7 +1267,8 @@ fn envelope_commands_with_junk_params_on_envelopes() { #[test] fn text_commands_with_junk_params_on_inline_graphics() { use vectorcraft_testkit::fixtures::{ellipse, exec, id_of, select}; - let path = safe_path(); + let dir = vectorcraft_testkit::TempDir::new("sweep"); + let path = safe_path(&dir); let setup = || { let mut s = Fixture::Multi.session(); let e = ellipse(&mut s, 400.0, 300.0, 20.0, 20.0); @@ -1209,7 +1332,7 @@ fn text_commands_with_junk_params_on_inline_graphics() { } for id in ["text.insertInline", "text.editRange", "text.getRange", "text.setRangeStyle", "type.insert"] { let spec = command_specs().iter().find(|c| c.id == id).unwrap(); - for p in std::iter::once(json!({})).chain(junk_params(spec.params, &path)) { + for p in std::iter::once(json!({})).chain(junk_params_for_command(spec, &path)) { run(id, &p); } } diff --git a/crates/engine/tests/font_folder.rs b/crates/engine/tests/font_folder.rs index b58e79fc17..db90084c5b 100644 --- a/crates/engine/tests/font_folder.rs +++ b/crates/engine/tests/font_folder.rs @@ -29,10 +29,9 @@ fn finished(s: &mut Session) -> Value { #[test] fn a_found_font_is_copied_without_replacing_a_file_and_its_type_redraws() { - let root = vectorcraft_testkit::temp_dir("font-folder"); - let _ = std::fs::remove_dir_all(&root); - std::fs::create_dir_all(root.join("Downloads/Deep")).unwrap(); - let root = plain(std::fs::canonicalize(&root).unwrap()); + let dir = vectorcraft_testkit::TempDir::new("font-folder"); + std::fs::create_dir_all(dir.join("Downloads/Deep")).unwrap(); + let root = plain(std::fs::canonicalize(&*dir).unwrap()); let fonts = root.join("App Fonts"); vectorcraft_text::set_app_font_dir(fonts.clone()); assert!(vectorcraft_text::system_font_dirs().contains(&fonts)); @@ -71,6 +70,13 @@ fn a_found_font_is_copied_without_replacing_a_file_and_its_type_redraws() { assert!(st.revision > revision && !st.is_dirty()); assert_eq!(s.execute("text.missingFonts", &json!({})).unwrap()["count"], 0); + // A caller whose read roots hold the file but not the Fonts folder: the file is kept, and the + // reply names the copy by its file name only, without the folder. + let downloads = vectorcraft_engine::file_access::AutomationRoots::new(&[&root.join("Downloads")], &[]).unwrap(); + let r = vectorcraft_engine::file_access::confine(downloads.as_ref(), || s.execute("text.addFontFiles", &json!({"files": [file]}))).unwrap(); + assert_eq!((&r["folder"], &r["kept"]), (&Value::Null, &json!([{"from": file, "to": "Findme 2.otf"}])), "{r}"); + assert!(!r.to_string().contains("App Fonts"), "{r}"); + // The same file again is kept, not copied a third time. let r = s.execute("text.addFontFiles", &json!({"files": [file]})).unwrap(); assert_eq!((r["copied"].clone(), r["kept"].clone()), (json!([]), json!([{"from": file, "to": fonts.join("Findme 2.otf")}])), "{r}"); @@ -78,5 +84,4 @@ fn a_found_font_is_copied_without_replacing_a_file_and_its_type_redraws() { // Only files the last search found are copied. let r = s.execute("text.addFontFiles", &json!({"files": [root.join("other.ttf")]})); assert!(r.as_ref().is_err_and(|e| e.to_string().contains("the last text.findFontFiles search")), "{r:?}"); - let _ = std::fs::remove_dir_all(&root); } diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index f729ed394c..04e7094f9e 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -1,9 +1,10 @@ -//! Untrusted files never crash the app: garbage, truncated, mutated and hostile SVG, PDF and DXF input, +//! Untrusted files never crash the app: garbage, truncated, mutated and hostile SVG, PDF, DXF and HP-GL input, //! mutated raster images (Photoshop documents and JPEG XL images among them) placed with File → Place, and swatch (`.vcswatches`, `.gpl`, `.ase`), graphic style (`.vcstyles`), flattener preset //! (`.vcflattener`) and export preset (`.vcexportpresets`) libraries, shortcut sets and action sets other apps save as text (`.kys`, `.aia`), and native files (compressed, damaged, saved for older versions), //! must load as an error or as a document that then renders and exports, without a panic; nor may //! bitmaps, PDF and text pasted from other apps, nor EMF and WMF pictures (damaged files, records -//! of every kind with random contents) opened, placed or pasted, nor EPS and PostScript files +//! of every kind with random contents) opened, placed or pasted, nor PICT pictures (damaged files, +//! opcodes with random contents) opened or placed, nor EPS and PostScript files //! (damaged ones, hostile programs) read by the PostScript interpreter, nor the editing data of //! Illustrator EPS and `.ai` files (the layers they carry, damaged or hostile), nor Affinity documents //! (mutated object streams, archives and indexed PNG previews, hostile image dimensions), nor the @@ -1807,6 +1808,27 @@ proptest! { }); prop_assert!(r.is_ok(), "{name}: panicked: {:?}", r.err()); } + + /// Mutated copies of the PSD and PSB samples never crash opening them with their layers, hidden + /// ones too: the PSD's layer records, channel lengths and data, and the PSB's layer count. + /// (Masks, clipping and groups are covered by `tests_psdlayers::damaged_layers_never_panic`.) + #[test] + fn mutated_layered_psds_open_without_panics(which in 6usize..8, cut in 0usize..1_000_000, edits in prop::collection::vec((0usize..1_000_000, any::()), 0..12)) { + let (name, mut bytes) = raster_samples().swap_remove(which); + let len = bytes.len(); + for (at, b) in edits { + if let Some(x) = bytes.get_mut(at % len) { + *x = b; + } + } + bytes.truncate((cut % (len + 1)).max(8)); + let r = catch_quiet(|| { + let mut s = vectorcraft_engine::Session::new(); + let p = json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(&bytes), "hiddenLayers": true}); + let _ = no_panic(s.execute("document.open", &p)); + }); + prop_assert!(r.is_ok(), "{name}: panicked: {:?}", r.err()); + } } /// 1-bit TIFFs compressed with CCITT Group 3: modified Huffman (Compression 2) in three strips, T.4 @@ -2661,7 +2683,10 @@ fn arb_ps_token() -> impl Strategy { // Local VM restored: dictionary changes undone, saves restored twice. "/a 1 def save /a 2 def", "restore", "save dup restore", "1 dict save exch /k 1 put", "cachestatus", "/n 0 def save /n n 1 add store", // Executable strings and keys other than names (PLRM 3rd ed., `cvx`, `load`). - "(>>) cvx", "(1 2 add) cvx exec", "(x) cvx dup exec", "0 load", "1 { } def", "(mark) cvx cvlit" + "(>>) cvx", "(1 2 add) cvx exec", "(x) cvx dup exec", "0 load", "1 { } def", "(mark) cvx cvlit", + // CID-keyed fonts found by name over predefined CMaps, horizontal and vertical. + "/Ryumin-Light-90ms-RKSJ-H", "/Ryumin-Light-EUC-V", "/Ryumin-Light-H", "/GBT-EUC-H", "/KSCms-UHC-V", "/UniJIS-UTF16-V", + "[/Ryumin-Light]", "composefont", "<93fa967b8540fd0d41>", "" ]) .prop_map(str::to_string), ] @@ -2914,6 +2939,180 @@ proptest! { } } +// ---------- PICT pictures: opened and placed ---------- + +fn be16(v: &[i16]) -> Vec { + v.iter().flat_map(|x| x.to_be_bytes()).collect() +} + +/// A version 2 PICT file of a 200 × 100 pt frame holding `ops`, each padded to an even length. +fn pict_of(ops: &[(u16, Vec)]) -> Vec { + let mut b = vec![0; 512]; + b.extend(be16(&[0, 0, 0, 100, 200])); + b.extend([0x00, 0x11, 0x02, 0xFF, 0x0C, 0x00]); + b.extend(be16(&[-1, 0])); + b.extend([0; 20]); + for (op, data) in ops { + b.extend(op.to_be_bytes()); + b.extend(data); + if b.len() % 2 == 1 { + b.push(0); + } + } + b.extend([0x00, 0xFF]); + b +} + +/// A picture with shapes, a region, text, a pattern and a packed pixel map. +fn pict_sample() -> Vec { + let region = [be16(&[36, 0, 0, 20, 20]), be16(&[0, 0, 20, 0x7FFF, 10, 10, 20, 0x7FFF, 20, 0, 10, 0x7FFF, 0x7FFF])].concat(); + let table = be16(&[0, 0, 0, 1, 0, -1, 0, 0, 1, 0, 0, -1]); + let pixmap = [ + be16(&[0x8008u16 as i16, 0, 0, 2, 8]), + be16(&[0, 0, 0, 0, 72, 0, 72, 0, 0, 8, 1, 8, 0, 0, 0, 0, 0, 0]), + table, + be16(&[0, 0, 2, 8, 10, 20, 14, 36, 0]), + vec![2, 0xF9, 0, 9, 7, 1, 0, 1, 0, 1, 0, 1, 0], + ] + .concat(); + pict_of(&[ + (0x1A, be16(&[-1, 0, 0])), + (0x07, be16(&[2, 2])), + (0x31, be16(&[10, 20, 50, 80])), + (0x30, be16(&[10, 20, 50, 80])), + (0x0B, be16(&[8, 8])), + (0x41, be16(&[0, 100, 40, 160])), + (0x51, be16(&[50, 100, 90, 160])), + (0x61, be16(&[0, 0, 60, 60, 30, 120])), + (0x71, be16(&[22, 0, 0, 40, 40, 0, 0, 40, 40, 0, 40])), + (0x81, region.clone()), + (0x01, region), + (0x20, be16(&[70, 10, 70, 190])), + (0x21, be16(&[90, 100])), + (0x0A, vec![0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55]), + (0x34, be16(&[0, 0, 10, 10])), + (0x2C, [be16(&[9, 3]), vec![6], b"Geneva".to_vec()].concat()), + (0x0D, be16(&[12])), + (0x28, [be16(&[80, 10]), vec![3], b"abc".to_vec()].concat()), + (0x98, pixmap), + ]) +} + +/// The sample the mutations start from opens with art and an image. +#[test] +fn the_pict_sample_opens() { + let l = vectorcraft_engine::cmd::fileio::load("x.pct", &pict_sample()).unwrap(); + assert_eq!(l.format.id, "pict"); + let (mut paths, mut images, mut texts) = (0, 0, 0); + l.doc.walk(|n| match n.kind { + vectorcraft_doc::NodeKind::Path { .. } => paths += 1, + vectorcraft_doc::NodeKind::Image(_) => images += 1, + vectorcraft_doc::NodeKind::Text(_) => texts += 1, + _ => {} + }); + assert!(paths > 8 && images == 1 && texts == 1, "{paths} paths, {images} images, {texts} texts, warnings {:?}", l.warnings); +} + +/// PICT opcodes VectorCraft reads, and reserved ones it skips. +const PICT_OPS: [u16; 40] = [ + 0x01, 0x03, 0x04, 0x07, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x12, 0x13, 0x14, 0x1A, 0x1B, 0x20, 0x21, 0x22, 0x23, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x30, + 0x31, 0x38, 0x41, 0x51, 0x61, 0x71, 0x81, 0x90, 0x91, 0x98, 0x99, 0x9A, 0x9B, 0xA1, 0x8200, 0x0024, +]; + +proptest! { + #![proptest_config(config())] + + #[test] + fn mutated_pict_pictures_never_panic(cut in 0usize..4096, edits in prop::collection::vec((0usize..4096, any::()), 0..16)) { + let mut bytes = pict_sample(); + let n = bytes.len(); + for &(at, b) in &edits { + bytes[512 + at % (n - 512)] = b; + } + bytes.truncate(cut.max(512)); + survive_metafile("mutated PICT", "x.pct", &bytes)?; + } + + #[test] + fn random_pict_opcodes_never_panic(ops in prop::collection::vec((prop::sample::select(PICT_OPS.to_vec()), arb_body()), 0..32)) { + survive_metafile("PICT opcodes", "x.pct", &pict_of(&ops))?; + } +} + +// ---------- HP-GL plot files: opened and placed ---------- + +/// A plot file with every kind of instruction the reader plays, printer escapes around it. +const HPGL_SAMPLE: &[u8] = b"\x1b%-12345X@PJL ENTER LANGUAGE=HPGL2\r\n\x1bE\x1b%0BIN;BP1,\"job\";CO\"sample\";NP16;PC9,10,20,30;CR0,100,0,100,0,100;\ +SP1;PW0.5;WU0;LA1,4,2,4,3,7;LT2,5,1;PA0,0;PD1000,0,1000,1000;PU;LT;PR;PD-500,0,0,-500;PA2000,2000;CI300,5;AA2000,2500,120;AR0,100,-90;\ +AT2500,2500,3000,2000;RT100,100,200,0;BZ0,100,100,100,100,0;BR10,10,20,10,30,0;UL3,1,2,1;LT-3,2;EA3000,3000;ER100,-100;FT10,40;RA3500,3500;\ +RR200,200;WG400,30,120;EW-400,0,360;PM0;PD4000,4000,4500,4000,4500,4500;PM1;PU4100,4100;PD4200,4100,4200,4200;PM2;FP1;EP;FT3,10,45;FP;\ +IP0,0,10160,7620;SC0,100,0,100,1,20,80;PU10,10;PD20,20;SC0,10,0,10,2;PD5,5;SC;RO90;PD100,100;RO;IR10,10,90,90;IW0,0,5000,5000;\ +DT*,1;LBlabel*SMx;PA0,0;SM;PE:\xc1<=\xbf\xc0\xc2\xc2;LB\x03PG;\x1b%0A\x1b*r1A\x1b*b4W\x01\x02\x03\x04\x1b*rC\x1b%1BPD1,1;\x1b%-12345X"; + +/// The sample the mutations start from opens as a plot with art. +#[test] +fn the_hpgl_sample_opens() { + let l = vectorcraft_engine::cmd::fileio::load("x.plt", HPGL_SAMPLE).unwrap(); + assert_eq!(l.format.id, "hpgl"); + let mut paths = 0; + l.doc.walk(|n| paths += usize::from(matches!(n.kind, vectorcraft_doc::NodeKind::Path { .. }))); + assert!(paths > 15, "{paths} paths, warnings {:?}", l.warnings); +} + +/// A wedge drawn with the adaptive line type `LT-1` and a near-zero radius (a case the fuzz test +/// found) opens and places without a panic. +#[test] +fn an_adaptive_line_type_wedge_of_almost_no_radius_opens() { + survive_metafile("HP-GL tiny adaptive wedge", "x.plt", b"IN;SP1;LT-1;EW0.000001,0,0;").unwrap(); +} + +/// A random instruction: a mnemonic the reader plays (or one it doesn't) with hostile numbers. +fn arb_hpgl_instruction() -> impl Strategy { + let op = prop::sample::select(vec![ + "IN", "DF", "PU", "PD", "PA", "PR", "SP", "PW", "WU", "NP", "PC", "CR", "LT", "UL", "LA", "FT", "SC", "IP", "IR", "RO", "CI", "AA", "AR", + "AT", "RT", "BZ", "BR", "EA", "ER", "RA", "RR", "EW", "WG", "PM", "FP", "EP", "LB", "DT", "SM", "CO", "PG", "IW", "PE", "ZZ", + ]); + let number = prop_oneof![ + Just("0".to_string()), + Just("-1".to_string()), + (-3000i32..3000).prop_map(|v| v.to_string()), + Just("99999999999999999999999".to_string()), + Just("0.000001".to_string()), + Just("32767".to_string()), + Just("-32768".to_string()), + Just("360".to_string()), + ]; + (op, prop::collection::vec(number, 0..8)).prop_map(|(o, n)| format!("{o}{};", n.join(","))) +} + +proptest! { + #![proptest_config(config())] + + #[test] + fn random_hpgl_instructions_never_panic(instructions in prop::collection::vec(arb_hpgl_instruction(), 0..40)) { + let bytes = format!("IN;SP1;{}", instructions.concat()).into_bytes(); + survive_metafile("HP-GL instructions", "x.plt", &bytes)?; + } + + #[test] + fn mutated_hpgl_files_never_panic(cut in 0usize..1200, edits in prop::collection::vec((0usize..1200, any::()), 0..16)) { + let mut bytes = HPGL_SAMPLE.to_vec(); + let n = bytes.len(); + for &(at, b) in &edits { + bytes[at % n] = b; + } + bytes.truncate(cut.max(4)); + survive_metafile("mutated HP-GL", "x.plt", &bytes)?; + } + + #[test] + fn hpgl_garbage_never_panics(bytes in prop::collection::vec(any::(), 0..400)) { + let mut b = b"IN;SP1;PD".to_vec(); + b.extend(bytes); + survive_metafile("HP-GL garbage", "x.hpgl", &b)?; + } +} + // ---------- print presets files ---------- /// Import print presets from `data`, then lay out (and print, when short) the rich document with @@ -4119,6 +4318,63 @@ proptest! { survive("style library in an EPS", || vectorcraft_engine::cmd::fileio::load("x.eps", &eps).ok().map(|l| l.doc))?; } + /// Graphic style libraries whose styles are one paint (`/SimpleStyle`): any paint operators in + /// any order, with any operands or none, `Xd` missing or repeated, and the paint left open. The + /// library is also loaded in the Graphic Style Libraries panel and its styles applied to artwork. + #[test] + fn ai_style_libraries_of_one_paint_styles_never_panic( + // Each operator, and whether it is a paint operator rather than any text. + ops in prop::collection::vec(prop_oneof![ + prop::sample::select(vec![ + "0 R", "0 O", "0 1 1 0 K", "1 0 0 0 k", "0 0 0 0 1 0 0 Xa", "0 0 0 0 1 0 0 XA", "0.5 G", "0 g", "K", "Xa", + "0 J 0 j 2 w 10 M []0 d", "-1 w", "1e400 w", "0 M", "[3 -1]0 d", "[]0 d", + "1 0 Xd", "0 1 Xd", "1 1 Xd", "0 0 Xd", "1 Xd", "Xd", "0 1 0 0 0 Xy", "1 0.5 1 1 0 Xy", "Xy", + "0 Bb", "2 (Sky) 0 0 0 100 1 0 0 1 0 0 Bg", "0 BB", "(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p", + "(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] P", "0 XR", + ]).prop_map(|op| (op.to_string(), true)), + "[ -~]{0,12}".prop_map(|text| (text, false)), + ], 0..12), + closed in any::(), + ) { + use vectorcraft_testkit::ai; + let close = if closed { "/Paint ;\n/Def ;\n" } else { "" }; + // C, a red 2 pt stroke, comes first, so that it reads whatever A holds. + let header = format!( + "%AI9_BeginArtStyles\n/KnownStyle :\n(C) /Name ,\n/SimpleStyle :\n0 R\n0 1 1 0 K\n2 w\n1 0 Xd\n/Paint ;\n/Def ;\n\ + /KnownStyle :\n(A) /Name ,\n/SimpleStyle :\n{}\n{close}/KnownStyle :\n(B) /Name ,\n/SimpleStyle :\n1 0 Xd\n/Paint ;\n/Def ;\n\ + %AI9_EndArtStyles\n%AI9_BeginArtStyleList\n(A)\n(B)\n(C)\n%AI9_EndArtStyleList\n", + ops.iter().map(|(op, _)| op.as_str()).collect::>().join("\n") + ); + let library = ai::editing_data(200.0, 100.0, &header); + survive("one-paint style library", || Some(vectorcraft_eps::layered_ai(library.as_bytes(), Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?; + let file = ai::ai(library.as_bytes(), ai::page_pdf()); + // How many objects C's look reached, what applying it answered, and whether that look is + // C's red 2 pt stroke with no fill. + let (mut styled, mut applied, mut red_stroke) = (0, Value::Null, false); + survive("one-paint styles applied", || { + let mut s = rich_session(); + let p = json!({"dataBase64": vectorcraft_format::base64_encode(&file), "name": "fuzz.ai"}); + let library = no_panic(s.execute("graphicStyle.loadLibrary", &p)).ok()?["library"].clone(); + no_panic(s.execute("select.all", &json!({}))).ok()?; + // Every style is added and the first one, A when it reads, applied; then C is applied. + let _ = no_panic(s.execute("graphicStyle.addFromLibrary", &json!({"library": library, "apply": true}))); + applied = no_panic(s.execute("graphicStyle.addFromLibrary", &json!({"library": library, "names": ["C"], "apply": true}))).ok()?; + let d = (*s.doc().ok()?.doc).clone(); + if let Some(look) = applied["applied"].as_str().and_then(|name| d.graphic_style(name)).map(|g| &g.appearance) { + let strokes = look.items.iter().filter(|i| matches!(i, vectorcraft_doc::AppearanceItem::Stroke(_))).count(); + red_stroke = look.fill().is_none() + && strokes == 1 + && look.stroke().is_some_and(|s| (s.paint.color(), s.width) == (Some(vectorcraft_color::Color::cmyk(0.0, 1.0, 1.0, 0.0)), 2.0)); + d.walk(|n| styled += usize::from(n.appearance == *look)); + } + Some(d) + })?; + // Text that isn't a paint operator can leave a string or a comment open over the style list. + if ops.iter().all(|(_, paint)| *paint) { + prop_assert!(applied["applied"].is_string() && red_stroke && styled > 0, "the stroke style wasn't applied: {applied}"); + } + } + /// Objects on Path records of any shape: ids in any order, repeated or missing, any number of /// objects, pivots and angles out of range or not finite, spacings, order tags that disagree, /// groups nested or cut short, and versioned content left open. @@ -4239,6 +4495,17 @@ proptest! { survive("mutated .ai art styles", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?; survive("mutated .ai art styles, trusted", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, true, 1.0).0))?; } + + /// A `.ai` whose brushes, as the writer writes them, are damaged: the brush art with its frame, + /// the brush manager's order, the brushes' parameters, a brushed path's style and its object, cut + /// short or edited. + #[test] + fn ai_written_brushes_never_panic(cut in 0usize..BRUSHES_FUZZ_CHARS, edits in prop::collection::vec((0usize..BRUSHES_FUZZ_CHARS, prop::sample::select(vec!['0', '1', '9', '-', '.', ' ', '\n', '(', ')', '/', ':', ';', ',', '%', '_', 'u', 'U', 'n', 'X', 'W'])), 0..12)) { + let text = mutate_text(brushes_text(), cut, &edits); + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&text)].concat(); + survive("mutated .ai brushes", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?; + survive("mutated .ai brushes, trusted", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, true, 1.0).0))?; + } } /// The range of [`ai_written_styles_never_panic`]'s cuts and edits: past the end of [`styles_text`]. @@ -4351,6 +4618,72 @@ fn the_symbol_library_fuzz_data_opens_with_its_symbols() { assert_eq!(names, ["S2", "S1"], "{warnings:?}"); } +/// The range of [`ai_written_brushes_never_panic`]'s cuts and edits: past the end of [`brushes_text`]. +const BRUSHES_FUZZ_CHARS: usize = 48_000; + +/// The editing data VectorCraft writes for a document whose brushes are a Calligraphic brush, a +/// Scatter brush in Tints and an Art brush in Tints (each art a wide block over a narrow one), with a +/// path drawn with the Calligraphic brush and one with the Art brush. +fn brushes_text() -> &'static str { + static TEXT: std::sync::OnceLock = std::sync::OnceLock::new(); + TEXT.get_or_init(|| { + use std::sync::Arc; + use vectorcraft_brush::{ArtBrush, Brush, BrushKind, Calligraphic, Colorization, Scatter, Variation}; + use vectorcraft_color::{Color, Paint}; + use vectorcraft_doc::{Appearance, Node, NodeId}; + use vectorcraft_geom::{Rect, shapes}; + let block = |id: u64, r: Rect| { + Arc::new(Node::path(NodeId(id), shapes::rectangle(r), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0))) + }; + let art = || Node::group(NodeId(1), vec![block(2, Rect::new(0.0, 0.0, 40.0, 4.0)), block(3, Rect::new(0.0, 4.0, 10.0, 8.0))]); + let nib = Calligraphic { + angle: 30.0, + roundness: 40.0, + size: 6.0, + variation: [20.0, 10.0, 2.0], + modes: Some([Variation::Rotation, Variation::Fixed, Variation::Pressure]), + }; + let lib = [ + Brush { name: "Nib".into(), kind: BrushKind::Calligraphic(nib) }, + Brush { name: "Spray".into(), kind: BrushKind::Scatter(Scatter { art: art(), colorization: Colorization::Tints, ..Scatter::default() }) }, + Brush { name: "Ribbon".into(), kind: BrushKind::Art(ArtBrush { art: art(), colorization: Colorization::Tints, ..ArtBrush::default() }) }, + ]; + let mut doc = Document::new(200.0, 100.0); + vectorcraft_brush::store(&mut doc, &lib); + let layer = doc.layers[0].id; + for (brush, y) in [("Nib", 30.0), ("Ribbon", 70.0)] { + let mut line = Node::path( + doc.alloc_id(), + shapes::line((10.0, y).into(), (190.0, y).into()), + Appearance::basic(Paint::None, Paint::solid(Color::rgb(1.0, 0.0, 0.0)), 1.0), + ); + line.appearance.stroke_mut().unwrap().brush = Some(brush.into()); + doc.insert(Some(layer), usize::MAX, line).unwrap(); + } + let out = vectorcraft_eps::export_ai_editing(&doc, &vectorcraft_eps::AiEditingOptions::default()).unwrap(); + String::from_utf8(out.program).unwrap() + }) +} + +/// The data [`ai_written_brushes_never_panic`] damages, as it is, opens with its brushes and its +/// brushed paths live, and the property's cuts and edits reach all of it. +#[test] +fn the_written_brushes_fuzz_data_opens_live() { + let text = brushes_text(); + assert!(text.chars().count() < BRUSHES_FUZZ_CHARS, "{}", text.chars().count()); + for mark in ["%AI8_BeginBrushPattern", "%AI8_BeginPluginObject", "%AI9_BeginArtStyles", "/GObjRef :", "%AI5_BeginLayer", "\n1 (Anon"] { + assert!(text.replace("\r\n", "\n").contains(mark), "{mark}"); + } + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(text)].concat(); + let (d, warnings, layered) = vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, true, 1.0); + assert!(layered, "{warnings:?}"); + let names: Vec = vectorcraft_brush::library(&d).into_iter().map(|b| b.name).collect(); + assert_eq!(names, ["Nib", "Spray", "Ribbon"]); + let art = d.layers[0].children().unwrap(); + let brushes: Vec> = art.iter().map(|n| n.appearance.stroke().and_then(|s| s.brush.as_deref())).collect(); + assert_eq!(brushes, [Some("Nib"), Some("Ribbon")]); +} + /// Editing data with symbols (S2's art holds an instance of S1, F's holds non-native art), the /// symbol list and a layer of instances, as the format writes them. fn symbols_text() -> String { @@ -5809,7 +6142,8 @@ fn findme_wanted() -> vectorcraft_text::WantedFonts { /// Whether reading `bytes` as a font file a search reads panics. fn search_reads(what: &str, bytes: &[u8]) -> Result, TestCaseError> { - let path = vectorcraft_testkit::temp_dir("font-search-fuzz").join(format!("{:?}.ttc", std::thread::current().id())); + let dir = vectorcraft_testkit::TempDir::new("font-search-fuzz"); + let path = dir.join("font.ttc"); std::fs::write(&path, bytes).unwrap(); catch_quiet(|| findme_wanted().provided_by(&path)).map_err(|e| TestCaseError::fail(format!("{what}: a search reading the file panicked: {e}"))) } diff --git a/crates/engine/tests/it/delete_path_pieces.rs b/crates/engine/tests/it/delete_path_pieces.rs index 0d8b7171f7..afc304e99f 100644 --- a/crates/engine/tests/it/delete_path_pieces.rs +++ b/crates/engine/tests/it/delete_path_pieces.rs @@ -2,7 +2,7 @@ use serde_json::json; use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, Paint}; -use vectorcraft_doc::{Appearance, NodeId, NodeKind}; +use vectorcraft_doc::{Appearance, NodeId, NodeKind, selection::Selection}; use vectorcraft_engine::Session; use vectorcraft_geom::{Affine, Anchor, PathData, Rect, SubPath}; use vectorcraft_testkit::{invariants::check_session, raster::render_artboard}; @@ -226,6 +226,151 @@ fn deletion_split_preserves_gradient_placement() { } } +/// Subpath `i` of a multi-subpath test path: four cubic anchors on their own row, so every piece +/// that survives a deletion can be matched exactly. +fn row(i: usize, closed: bool) -> SubPath { + let y = 10.0 + 3.0 * i as f64; + let anchors = (0..4) + .map(|k| { + let mut a = Anchor::corner((10.0 + 20.0 * f64::from(k), y).into()); + a.h_in = a.p + (-3.0, -1.0); + a.h_out = a.p + (3.0, 1.0); + a + }) + .collect(); + SubPath::new(anchors, closed) +} + +/// An open piece made of `indexes` of `sp`, its unused end handles retracted as deletion leaves them. +fn piece(sp: &SubPath, indexes: &[usize]) -> SubPath { + let mut run: Vec = indexes.iter().map(|&i| sp.anchors[i]).collect(); + if let Some(first) = run.first_mut() { + first.h_in = first.p; + } + if let Some(last) = run.last_mut() { + last.h_out = last.p; + } + SubPath::new(run, false) +} + +/// Put `subpaths` into a new path object and return its ID. +fn multi_subpath_path(s: &mut Session, subpaths: Vec) -> NodeId { + let id = rectangle(s); + *std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().path_data_mut().unwrap() = PathData::new(subpaths); + id +} + +/// Run `command` on the current selection, check the path's surviving subpaths and that one Undo +/// restores the document and `before_selection` and one Redo repeats the edit, then check that a +/// second Clear removes the survivors. +fn delete_and_check(s: &mut Session, command: &str, id: NodeId, expected: &[SubPath], before_selection: &Selection) { + let before_doc = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let history = s.doc().unwrap().history.undo.len(); + s.execute(command, &json!({})).unwrap(); + let st = s.doc().unwrap(); + assert_eq!(st.doc.node(id).unwrap().path_data().unwrap().subpaths, expected, "{command}"); + assert_eq!(st.selection.objects, [id], "{command}: a multi-subpath path keeps its object"); + assert!(st.selection.anchors.is_empty() && st.selection.segments.is_empty()); + assert_eq!(st.history.undo.len(), history + 1); + let after_doc = serde_json::to_value(&st.doc).unwrap(); + let after_selection = st.selection.clone(); + check_session(s).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before_doc); + assert_eq!(&s.doc().unwrap().selection, before_selection); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), after_doc); + assert_eq!(s.doc().unwrap().selection, after_selection); + s.execute("edit.clear", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.node(id).is_none(), "{command}: the second Clear removes the survivors"); +} + +/// Selected anchors on many subpaths each remove only their own subpath's anchors; anchors named on +/// a subpath or index the path does not have remove nothing. +#[test] +fn deleting_anchors_on_many_subpaths_removes_each_subpaths_own_anchors() { + for command in ["edit.clear", "path.deleteAnchors", "edit.cut"] { + let mut s = session(); + let subpaths: Vec = (0..6).map(|i| row(i, i % 2 == 1)).collect(); + let id = multi_subpath_path(&mut s, subpaths.clone()); + s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 1], [1, 2], [2, 0], [2, 9], [4, 3], [5, 1], [7, 1]]})).unwrap(); + // Subpath 3 has no selected anchor and stays closed and unchanged. + let expected = [ + piece(&subpaths[0], &[2, 3]), + piece(&subpaths[1], &[3, 0, 1]), + piece(&subpaths[2], &[1, 2, 3]), + subpaths[3].clone(), + piece(&subpaths[4], &[0, 1, 2]), + piece(&subpaths[5], &[2, 3, 0]), + ]; + let before = s.doc().unwrap().selection.clone(); + delete_and_check(&mut s, command, id, &expected, &before); + } +} + +/// Selected segments on many subpaths each cut only their own subpath; a segment reference to a +/// subpath or segment the path does not have cuts nothing. +#[test] +fn deleting_segments_on_many_subpaths_cuts_each_subpaths_own_segments() { + for command in ["edit.clear", "path.deleteAnchors", "edit.cut"] { + let mut s = session(); + let subpaths: Vec = (0..6).map(|i| row(i, i % 2 == 1)).collect(); + let id = multi_subpath_path(&mut s, subpaths.clone()); + s.execute("select.segments", &json!({"id": id.0, "segments": [[0, 1], [1, 3], [4, 0], [5, 1]]})).unwrap(); + // Undo prunes the restored selection (`Selection::prune`), which drops references to + // segments the path does not have, so it restores the selection as it is here. + let before = s.doc().unwrap().selection.clone(); + // `select.segments` refuses references to missing segments, so these are added directly. + let refs = s.doc_mut().unwrap().selection.segments.get_mut(&id).unwrap(); + refs.extend([(2, 9), (7, 0)]); + let expected = [ + piece(&subpaths[0], &[0, 1]), + piece(&subpaths[0], &[2, 3]), + piece(&subpaths[1], &[0, 1, 2, 3]), + subpaths[2].clone(), + subpaths[3].clone(), + piece(&subpaths[4], &[1, 2, 3]), + piece(&subpaths[5], &[2, 3, 0, 1]), + ]; + delete_and_check(&mut s, command, id, &expected, &before); + } +} + +/// One selected interior anchor on each of many subpaths removes exactly that anchor from each, +/// keeping the subpaths in their original order. +#[test] +fn deleting_one_anchor_on_each_of_many_subpaths_keeps_subpath_order() { + let mut s = session(); + let subpaths: Vec = (0..400).map(|i| row(i, false)).collect(); + let id = multi_subpath_path(&mut s, subpaths.clone()); + let refs: Vec<[usize; 2]> = (0..400).filter(|i| i % 7 != 3).map(|i| [i, 1]).collect(); + s.execute("select.anchors", &json!({"id": id.0, "anchors": refs})).unwrap(); + let expected: Vec = subpaths.iter().enumerate().map(|(i, sp)| if i % 7 == 3 { sp.clone() } else { piece(sp, &[2, 3]) }).collect(); + let before = s.doc().unwrap().selection.clone(); + delete_and_check(&mut s, "edit.clear", id, &expected, &before); +} + +/// Cut Path cuts each subpath of a multi-subpath path only at that subpath's selected anchors. +#[test] +fn cutting_at_anchors_on_many_subpaths_cuts_each_subpath_at_its_own_anchors() { + let mut s = session(); + let subpaths: Vec = (0..6).map(|i| row(i, i % 2 == 1)).collect(); + let id = multi_subpath_path(&mut s, subpaths.clone()); + let refs = [(0, 1), (1, 2), (2, 9), (4, 2), (5, 0), (5, 2), (7, 1)]; + s.execute("select.anchors", &json!({"id": id.0, "anchors": refs.map(|(a, b)| [a, b])})).unwrap(); + s.execute("path.cutAtAnchors", &json!({})).unwrap(); + let expected: Vec = subpaths + .iter() + .enumerate() + .flat_map(|(si, sp)| sp.cut_at(&refs.iter().filter(|r| r.0 == si).map(|r| r.1).collect::>())) + .collect(); + // Subpaths 0 and 4 become two pieces each, closed subpath 1 opens into one, closed subpath 5 + // becomes two, and subpaths 2 and 3 stay as they were. + assert_eq!(expected.len(), 9); + assert_eq!(s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths, expected); + check_session(&s).unwrap(); +} + /// A connected remainder keeps automatic fitting; pinning is needed only for separate objects. #[test] fn deleting_one_segment_keeps_unplaced_gradients() { diff --git a/crates/engine/tests/it/js_lexer_vs_scriptcheck.rs b/crates/engine/tests/it/js_lexer_vs_scriptcheck.rs index c9b5ac4665..db8696a10f 100644 --- a/crates/engine/tests/it/js_lexer_vs_scriptcheck.rs +++ b/crates/engine/tests/it/js_lexer_vs_scriptcheck.rs @@ -89,11 +89,12 @@ fn both_lexers_find_the_same_unclosed_token_on_the_same_line() { } /// Characters on both sides of the identifier rule: `Other_ID_Start`, `Other_ID_Continue`, connector -/// punctuation, marks, digits and letters of other scripts, and a superscript digit, a -/// `Pattern_Syntax` letter and punctuation that no name holds. +/// punctuation, marks, digits and letters of other scripts, a letter and a mark Unicode 17.0 +/// assigned, and a superscript digit, a `Pattern_Syntax` letter and punctuation that no name holds. const NAME_CHARS: &[char] = &[ - '\u{AA}', '\u{B2}', '\u{B7}', '\u{D7}', '\u{300}', '\u{387}', '\u{660}', '\u{1369}', '\u{1885}', '\u{19DA}', '\u{200C}', '\u{200D}', '\u{203F}', - '\u{2040}', '\u{2118}', '\u{212E}', '\u{2160}', '\u{2E2F}', '\u{3005}', '\u{309B}', '\u{30FB}', '\u{FE33}', '\u{FF10}', '\u{FF65}', + '\u{AA}', '\u{B2}', '\u{B7}', '\u{D7}', '\u{300}', '\u{387}', '\u{660}', '\u{88F}', '\u{1369}', '\u{1885}', '\u{19DA}', '\u{1ACF}', '\u{200C}', + '\u{200D}', '\u{203F}', '\u{2040}', '\u{2118}', '\u{212E}', '\u{2160}', '\u{2E2F}', '\u{3005}', '\u{309B}', '\u{30FB}', '\u{FE33}', '\u{FF10}', + '\u{FF65}', ]; /// Whether the parser reads `src` as one identifier spelling `name`. @@ -111,17 +112,30 @@ fn checker_member(src: &str, name: &str) -> bool { #[test] fn both_lexers_take_the_same_characters_into_names() { assert!(checker_member("a\u{2118}b", "a\u{2118}b") && one_identifier("a\u{2118}b", "a\u{2118}b")); + assert!(checker_member("\u{88F}\u{1ACF}", "\u{88F}\u{1ACF}") && one_identifier("\u{88F}\u{1ACF}", "\u{88F}\u{1ACF}")); for &c in NAME_CHARS { let escape = format!("\\u{:04X}", u32::from(c)); + let braced = format!("\\u{{{:X}}}", u32::from(c)); for (src, name) in [ (format!("a{c}b"), format!("a{c}b")), (format!("{c}b"), format!("{c}b")), (format!("a{escape}b"), format!("a{c}b")), (format!("{escape}b"), format!("{c}b")), + (format!("a{braced}b"), format!("a{c}b")), + (format!("{braced}b"), format!("{c}b")), ] { assert_eq!(checker_member(&src, &name), one_identifier(&src, &name), "{src:?} (U+{:04X})", u32::from(c)); } } + // Braced escapes past U+FFFF and with leading zeros are read by both. + for (src, name) in [("\\u{1D49C}b", "\u{1D49C}b"), ("a\\u{0000000062}", "ab")] { + assert!(checker_member(src, name) && one_identifier(src, name), "{src:?}"); + } + // Out of range, a surrogate and an empty one: the parser reads no identifier, and the checker's + // name ends before the escape. + for src in ["a\\u{110000}", "a\\u{D800}", "a\\u{}"] { + assert!(checker_member(src, "a") && !one_identifier(src, "a"), "{src:?}"); + } } #[test] diff --git a/crates/engine/tests/it/model_based.rs b/crates/engine/tests/it/model_based.rs index b11e3b0591..583dfda441 100644 --- a/crates/engine/tests/it/model_based.rs +++ b/crates/engine/tests/it/model_based.rs @@ -134,7 +134,8 @@ fn a_failed_batch_restores_the_file_the_history_and_a_drag_in_progress() { (doc_json(&st.doc), st.history.undo.len(), st.history.redo.len()) }; // Save As, then a failing step: the document keeps no file and stays modified. - let path = vectorcraft_testkit::temp_dir("batch-rollback").join("named.vectorcraft").to_string_lossy().to_string(); + let dir = vectorcraft_testkit::TempDir::new("batch-rollback"); + let path = dir.join("named.vectorcraft").to_string_lossy().to_string(); let save = json!({"command": "file.saveAs", "params": {"path": path}}); assert!(s.execute("command.batch", &json!({"commands": [rect(0), save, fail]})).is_err()); assert_eq!(state(&s), before); @@ -170,7 +171,7 @@ fn empty_batch_is_harmless() { #[test] fn save_open_via_commands_roundtrips() { let mut s = fixtures::rich_session(); - let dir = vectorcraft_testkit::temp_dir("engine-save"); + let dir = vectorcraft_testkit::TempDir::new("engine-save"); let path = dir.join("rich.vectorcraft"); exec(&mut s, "document.save", json!({"path": path.to_str().unwrap()})); let want = doc_json(&s.doc().unwrap().doc); diff --git a/crates/engine/tests/it/ruler_guide_nodes.rs b/crates/engine/tests/it/ruler_guide_nodes.rs index 95625d65d1..1a88377585 100644 --- a/crates/engine/tests/it/ruler_guide_nodes.rs +++ b/crates/engine/tests/it/ruler_guide_nodes.rs @@ -103,10 +103,12 @@ fn ruler_guides_are_not_art_to_select_paint_or_inspect() { let layer_row = s.execute("document.inspect", &json!({"ids": [layer.0]})).unwrap(); let listed = layer_row.to_string(); assert!(guides.iter().all(|g| !listed.contains(&format!("\"id\":{}", g.0))), "{listed}"); - // Unlock All does not reach a locked guide. + // Unlock All unlocks a guide locked on its own and selects it as a guide, not as art. Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(guides[0]).unwrap().locked = true; s.execute("object.unlockAll", &json!({})).unwrap(); - assert!(s.doc().unwrap().doc.node(guides[0]).unwrap().locked); + let st = s.doc().unwrap(); + assert!(!st.doc.node(guides[0]).unwrap().locked); + assert_eq!((st.selection.guides.clone(), st.selection.objects.clone()), (vec![guides[0]], vec![])); } #[test] @@ -257,14 +259,25 @@ fn guides_made_while_editing_a_mask_a_pattern_or_a_symbol_stay() { assert!(!in_symbol, "the guide is not part of the symbol"); } +/// `bytes` without the lines that depend on when the file was written: the PDF dates, and the XMP +/// packet (one line, with its dates and IDs) and trailer `/ID`. +fn undated(bytes: &[u8]) -> Vec { + let stamps: [&[u8]; 5] = [b"CreationDate", b"ModDate", b"xmp:CreateDate", b"xmp:ModifyDate", b"/ID["]; + let dated = |line: &&[u8]| stamps.iter().any(|s| line.windows(s.len()).any(|w| w == *s)); + bytes.split(|b| *b == b'\n').filter(|l| !dated(l)).flat_map(|l| l.iter().copied().chain(*b"\n")).collect() +} + /// The bytes of each export format (PDF without the embedded native document, which keeps the -/// guides), and the box Fit All in Window fits (the art and every artboard). -fn exports(s: &mut Session) -> (Vec<(String, String)>, Option) { +/// guides, and without its dates), and the box Fit All in Window fits (the art and every artboard). +fn exports(s: &mut Session) -> (Vec<(String, Vec)>, Option) { let files = [json!({"format": "svg"}), json!({"format": "pdf", "preserveEditing": false}), json!({"format": "png"}), json!({"format": "psd"})] .iter() .map(|p| { let out = s.execute("document.export", p).unwrap(); - (p["format"].as_str().unwrap().to_string(), out["dataBase64"].as_str().unwrap().to_string()) + let bytes = vectorcraft_format::base64_decode(out["dataBase64"].as_str().unwrap()).unwrap(); + let format = p["format"].as_str().unwrap().to_string(); + let bytes = if format == "pdf" { undated(&bytes) } else { bytes }; + (format, bytes) }) .collect(); let d = &s.doc().unwrap().doc; diff --git a/crates/engine/tests/plugin_import.rs b/crates/engine/tests/plugin_import.rs index b780c115c3..f091062308 100644 --- a/crates/engine/tests/plugin_import.rs +++ b/crates/engine/tests/plugin_import.rs @@ -326,7 +326,7 @@ fn an_importer_past_its_budget_opens_nothing() { ]; for (id, limits, _) in &cases { let wasm = wat::parse_str(tpl::module(&tpl::importer(id, r#"["tbg"]"#, "{}"), SPINS, "", 1)).unwrap(); - vectorcraft_plugins::registry::install(Plugin::load(&wasm, limits.clone()).unwrap()); + vectorcraft_plugins::registry::install(Plugin::load(&wasm, limits.clone()).unwrap()).unwrap(); } let mut s = Session::new(); for (id, _, why) in &cases { diff --git a/crates/engine/tests/removed_font.rs b/crates/engine/tests/removed_font.rs index ca5dc1f13a..da885b40b8 100644 --- a/crates/engine/tests/removed_font.rs +++ b/crates/engine/tests/removed_font.rs @@ -37,9 +37,7 @@ fn laid_out_in(s: &Session, id: u64) -> Vec { #[test] fn type_in_a_removed_font_falls_back_after_a_rescan() { - let root = vectorcraft_testkit::temp_dir("removed-font"); - let _ = std::fs::remove_dir_all(&root); - std::fs::create_dir_all(&root).unwrap(); + let root = vectorcraft_testkit::TempDir::new("removed-font"); vectorcraft_text::set_user_font_dirs(vec![root.clone()]); let file = root.join("Gonefont.otf"); std::fs::write(&file, vectorcraft_testkit::fonts::renamed(FAMILY)).unwrap(); @@ -72,5 +70,4 @@ fn type_in_a_removed_font_falls_back_after_a_rescan() { assert_eq!(status(&mut s), ("exact".into(), FAMILY.into())); assert!(listed(&mut s)); assert_eq!(laid_out_in(&s, id), [FAMILY]); - let _ = std::fs::remove_dir_all(&root); } diff --git a/crates/eps/src/ai_editing.rs b/crates/eps/src/ai_editing.rs index 3ca8a66b5f..cf068da1ef 100644 --- a/crates/eps/src/ai_editing.rs +++ b/crates/eps/src/ai_editing.rs @@ -133,6 +133,16 @@ //! A fill filter fills by the non-zero rule (`0 /Bool (UseEvenOdd)`), so a filled object that //! fills by the even-odd rule is written as its drawn look. A style is written only when the //! reader reads it back as the object's appearance (or the graphic style's). +//! - Brushes, as the reader reads them (`brush.rs`, `style.rs`): the Brushes panel's brushes as +//! plug-in objects in a non-printing block after the symbols (`%AI8_BeginPluginObject`, the +//! plug-in's name, the brush's name, its parameters in strings that `-` continues and `.` ends), +//! after the brush manager's order of them; the art of Scatter and Art brushes in a non-printing +//! block before the symbols (`%AI8_BeginBrushPattern`, its name, a group of an unpainted frame at +//! the art's bounds and the art, or the art alone when it has no width or height), when the +//! document has brushes of its own or an object is written with one. +//! A path or compound path with a brush the reader reads live is written with an art style whose +//! stroke is the brush's filter (`writer::brushes`). A brush is written only when the reader reads +//! it back with its settings. //! //! Lines end in CR LF. Strings are written in UTF-8. Art space is ruler space: y up, its origin at //! the first artboard's top-left corner. On the canvas ([`CANVAS_SIZE`] points square, y down) the @@ -162,15 +172,16 @@ //! symbols past 4,096 as their art (symbol art past [`vectorcraft_doc::MAX_SYMBOL_NODES`] objects //! in all left out), instances of symbols the document doesn't have as empty groups, symbols' 9-slice //! guides, export types and dynamic type left out, live objects (placed documents included) as their art, -//! strokes a plain line can't draw +//! strokes a plain line can't draw and the object's art style doesn't hold //! as their filled outlines, several fills or strokes as a group of a path for each, freeform //! gradient swatches, gradient swatches of more than 256 stops, swatches of patterns written as //! tiles and the placement of pattern swatches that move, turn or scale their pattern, the opacity and blending modes of single fills and strokes, opacity masks on //! layers and opacity masks nested too deep, and, on objects written without an art style, live //! effects other than geometry effects left out; graphic styles the reader wouldn't read, links to -//! graphic styles on objects not written with them, and every art style on a large canvas, are left -//! out; art past [`crate::import::MAX_EDITING_OBJECTS`] objects in all (the most the reader reads), -//! counted as the reader counts them, is left out. +//! graphic styles on objects not written with them, brushes the reader wouldn't read back, and every +//! art style and brush on a large canvas, are left out; art past +//! [`crate::import::MAX_EDITING_OBJECTS`] objects in all (the most the reader reads), counted as the +//! reader counts them, is left out. //! //! The data streams hold the program compressed with Zstandard after `%AI24_ZStandard_Data`, with //! the version numbers of the newest files users sent ([`private_data`]). @@ -288,6 +299,7 @@ fn export_within(doc: &Document, o: &AiEditingOptions, max_objects: usize) -> Re let mut w = Writer::new(doc, to_art, origin); // On a large canvas the layers' symbol instances are written as their art. w.symbols_live = scale == 1.0; + w.brushes_live = scale == 1.0; w.symbol_doc = symbol_doc; w.max_objects = max_objects; w.reserve_swatch_gradients(); @@ -305,6 +317,8 @@ fn export_within(doc: &Document, o: &AiEditingOptions, max_objects: usize) -> Re } // The symbols no instance uses too; their art adds definitions. w.symbols(); + // The brushes, once the layers have said whether an object is written with one. + let (brush_art, brush_objects) = w.brush_blocks(); // The palette first: its gradient and pattern swatches add definitions. let mut palette = String::new(); w.palette(&mut palette); @@ -323,7 +337,9 @@ fn export_within(doc: &Document, o: &AiEditingOptions, max_objects: usize) -> Re let mut s = header.clone(); s.push_str("%%BeginProlog\n%%EndProlog\n%%BeginSetup\n"); w.definitions(&mut s); + s.push_str(&brush_art); w.symbol_definitions(&mut s); + s.push_str(&brush_objects); w.art_styles(&mut s); s.push_str(&palette); w.art_style_list(&mut s); diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index a99646c9c2..1321188f12 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -294,6 +294,134 @@ fn writing_again_gives_the_same_bytes() { assert!(first.warnings.is_empty(), "{:?}", first.warnings); } +/// The CMYK equivalent written beside RGB or Lab values is the one of the values as written (to four +/// decimals, Lab clamped to the range a reader reads), so the reopened file is written with the same +/// numbers: a new document's swatches, and colors of many decimals in fills, gradient stops, global +/// process swatches (RGB and Lab), an RGB spot swatch (in a fill and in a stop), Lab spot swatches +/// and a Lab spot swatch out of range. +#[test] +fn cmyk_equivalents_are_written_again_unchanged() { + let mut doc = Document::new(300.0, 200.0); + let v = |i: u16, s: f32| (f32::from(i) * s + 0.123_456_7).fract(); + let rgb = |i: u16| Color::rgb(v(i, 0.137_911_3), v(i, 0.271_828_2), v(i, 0.314_159_3)); + let lab = |i: u16| Color::lab(v(i, 0.137_911_3) * 100.0, v(i, 0.271_828_2) * 200.0 - 100.0, v(i, 0.314_159_3) * 200.0 - 100.0); + let glaze = rgb(102); + let swatch = |name: String, c: Color, spot: bool| Swatch { name, paint: solid(c), global: true, spot }; + let mut named: Vec<(String, Color, bool)> = + vec![("Glaze".into(), glaze, true), ("Out".into(), Color::lab(104.567_89, -140.123_46, 131.987_65), true)]; + for i in 0..8u16 { + named.push((format!("Leaf {i}"), rgb(i + 110), false)); + named.push((format!("Fern {i}"), lab(i + 120), false)); + named.push((format!("Moss {i}"), lab(i + 130), true)); + } + let mut swatches: Vec = doc.swatches.iter().cloned().collect(); + swatches.extend(named.iter().map(|(name, c, spot)| swatch(name.clone(), *c, *spot))); + doc.swatches = swatches.into(); + let layer = doc.layers[0].id; + for i in 0..24u16 { + let x = f64::from(i % 8) * 30.0 + 10.0; + let y = f64::from(i / 8) * 30.0 + 10.0; + let n = square(&mut doc, Rect::new(x, y, x + 20.0, y + 20.0), rgb(i)); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + let mut stops: Vec = (0..5u16).map(|i| GradientStop::new(f32::from(i) / 5.0, rgb(i + 50))).collect(); + let out = named[1].1; + stops.push(GradientStop { swatch: Some("Out".into()), tint: 0.5, ..GradientStop::new(0.9, out.tinted(0.5)) }); + stops.push(GradientStop { swatch: Some("Glaze".into()), tint: 0.7, ..GradientStop::new(1.0, glaze.tinted(0.7)) }); + let mut fills = vec![gradient_paint(Gradient::new(GradientKind::Linear, stops), None, None)]; + fills.extend(named.iter().map(|(name, c, spot)| linked(name, *c, if *spot { 1.0 } else { 0.6 }))); + for (i, fill) in fills.into_iter().enumerate() { + let x = (i % 9) as f64 * 30.0 + 10.0; + let y = (i / 9) as f64 * 30.0 + 110.0; + let n = painted(&mut doc, shapes::rectangle(Rect::new(x, y, x + 20.0, y + 20.0)), vec![AppearanceItem::Fill(FillLayer::new(fill))]); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + let first = program(&doc); + let again = String::from_utf8(export_ai_editing(&read_back(&doc), &opts()).unwrap().program).unwrap().replace("\r\n", "\n"); + same_lines(&again.lines().map(String::from).collect::>(), &first.lines().map(String::from).collect::>()); +} + +/// With a working RGB space other than sRGB, an RGB fill, an RGB gradient stop and an RGB spot +/// color in a stop are written with their working RGB values, the values the reader reads back, so +/// the reopened file is written with the same RGB values and CMYK equivalents. +#[test] +fn rgb_values_are_written_again_unchanged_in_a_wide_gamut_working_space() { + const CHILD: &str = "VECTORCRAFT_TEST_AI_EDITING_WIDE_GAMUT"; + if std::env::var_os(CHILD).is_none() { + // Color settings are process-wide: exercise this profile in a separate test process. + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "ai_editing::tests::rgb_values_are_written_again_unchanged_in_a_wide_gamut_working_space", "--nocapture"]) + .env(CHILD, "1") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"), + "isolated color profile test failed:\n{stdout}\n{}", + String::from_utf8_lossy(&output.stderr), + ); + return; + } + use vectorcraft_color::cms; + cms::set_active(&cms::ColorSettings { rgb: cms::WIDE_GAMUT_RGB.into(), ..Default::default() }).unwrap(); + assert!(!cms::active().rgb_is_srgb()); + let mut doc = Document::new(300.0, 200.0); + let glaze = Color::rgb(0.812_345_6, 0.234_567_8, 0.456_789_1); + let mut swatches: Vec = doc.swatches.iter().cloned().collect(); + swatches.push(Swatch { name: "Glaze".into(), paint: solid(glaze), global: true, spot: true }); + doc.swatches = swatches.into(); + let layer = doc.layers[0].id; + let n = square(&mut doc, Rect::new(10.0, 10.0, 30.0, 30.0), Color::rgb(0.8, 0.4, 0.2)); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let stops = vec![ + GradientStop::new(0.0, Color::rgb(0.1, 0.7, 0.3)), + GradientStop { swatch: Some("Glaze".into()), tint: 0.7, ..GradientStop::new(1.0, glaze.tinted(0.7)) }, + ]; + let fill = gradient_paint(Gradient::new(GradientKind::Linear, stops), None, None); + let n = painted(&mut doc, shapes::rectangle(Rect::new(40.0, 10.0, 60.0, 30.0)), vec![AppearanceItem::Fill(FillLayer::new(fill))]); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let first = program(&doc); + assert!(first.contains("0.8 0.4 0.2 Xa"), "the fill's working RGB values are written"); + let again = String::from_utf8(export_ai_editing(&read_back(&doc), &opts()).unwrap().program).unwrap().replace("\r\n", "\n"); + same_lines(&again.lines().map(String::from).collect::>(), &first.lines().map(String::from).collect::>()); +} + +/// A gradient stop of a Lab spot color writes the RGB values of the Lab values as written (to four +/// decimals, clamped to the range a reader reads), the same Lab values its CMYK equivalent and the +/// palette's definition come from: for Lab values of many decimals and for Lab values out of range. +#[test] +fn a_lab_spot_stop_writes_rgb_values_of_its_lab_values_as_written() { + let mut doc = Document::new(300.0, 200.0); + let v = |i: u16, s: f32| (f32::from(i) * s + 0.123_456_7).fract(); + let mut spots: Vec<(String, Color)> = vec![("Out".into(), Color::lab(104.567_89, -140.123_46, 131.987_65))]; + spots.push(("Rim".into(), Color::lab(55.555_55, 131.234_56, -12.345_67))); + for i in 0..8u16 { + spots + .push((format!("Moss {i}"), Color::lab(v(i, 0.137_911_3) * 100.0, v(i, 0.271_828_2) * 200.0 - 100.0, v(i, 0.314_159_3) * 200.0 - 100.0))); + } + let mut swatches: Vec = doc.swatches.iter().cloned().collect(); + swatches.extend(spots.iter().map(|(name, c)| Swatch { name: name.clone(), paint: solid(*c), global: true, spot: true })); + doc.swatches = swatches.into(); + let layer = doc.layers[0].id; + for (i, (name, c)) in spots.iter().enumerate() { + let stops = vec![ + GradientStop::new(0.0, Color::rgb(0.1, 0.2, 0.3)), + GradientStop { swatch: Some(name.clone()), tint: 0.5, ..GradientStop::new(1.0, c.tinted(0.5)) }, + ]; + let fill = gradient_paint(Gradient::new(GradientKind::Linear, stops), None, None); + let x = i as f64 * 25.0 + 10.0; + let n = painted(&mut doc, shapes::rectangle(Rect::new(x, 10.0, x + 20.0, 30.0)), vec![AppearanceItem::Fill(FillLayer::new(fill))]); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + let program = program(&doc); + for (name, c) in &spots { + let mut want = String::new(); + crate::ps::push_nums(&mut want, &crate::ai_ops::as_written(*c).to_rgb().map(|v| f64::from(crate::ai_ops::unit(v)))); + want.push_str(&format!("({name}) 0.5 1 4 ")); + assert!(program.lines().any(|l| l.contains(&want)), "no stop of {name} writes {want:?}"); + } +} + #[test] fn the_data_is_zstandard_compressed_with_the_header_as_metadata() { let doc = sample(); @@ -747,6 +875,7 @@ fn art_the_slice_does_not_cover_is_written_as_plain_paths() { assert_eq!(layer[2].visual_bounds().map(|b| (r3(b.x0), r3(b.y0), r3(b.x1), r3(b.y1))), Some((r3(100.0), r3(10.0), r3(120.0), r3(20.0)))); } +/// A brushed stroke the reader reads as its drawn look (a Scatter brush's) is written as its brush's art. #[test] fn brushed_strokes_are_written_as_their_brush_art() { let mut doc = Document::new(200.0, 100.0); @@ -756,11 +885,11 @@ fn brushed_strokes_are_written_as_their_brush_art() { shapes::line((20.0, 50.0).into(), (180.0, 50.0).into()), Appearance::basic(Paint::None, solid(Color::rgb(1.0, 0.0, 0.0)), 4.0), ); - line.appearance.stroke_mut().unwrap().brush = Some("3 pt. Round".into()); + line.appearance.stroke_mut().unwrap().brush = Some("Dots".into()); doc.insert(Some(layer), usize::MAX, line).unwrap(); let pieces = vectorcraft_brush::stroke_pieces( &doc, - &vectorcraft_brush::find(&doc, "3 pt. Round").unwrap(), + &vectorcraft_brush::find(&doc, "Dots").unwrap(), &shapes::line((20.0, 50.0).into(), (180.0, 50.0).into()).to_bezpath(), doc.layers[0].children().unwrap()[0].appearance.stroke().unwrap(), ); @@ -851,6 +980,34 @@ fn a_scaled_nine_slice_symbol_instance_keeps_its_corner_size() { assert!(sizes.contains(&(200, 150)), "the frame is scaled: {sizes:?}"); } +/// A scaled instance of a symbol whose left 9-slice guide lies outside its art is written as the +/// canvas draws it: the corner square is in the center column, which runs 0..75 in the art and +/// 0..175 in the instance, so it is about 23 wide. The editing copy read alone has no guides. +#[test] +fn a_nine_slice_instance_with_a_guide_outside_its_art_is_written_as_drawn() { + let mut doc = Document::new(400.0, 400.0); + let layer = doc.layers[0].id; + let square = |doc: &mut Document, r: Rect| { + Node::path(doc.alloc_id(), shapes::rectangle(r), Appearance::basic(solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0)) + }; + let frame = Arc::new(square(&mut doc, Rect::new(0.0, 0.0, 100.0, 100.0))); + let corner = Arc::new(square(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0))); + let art = Node::group(doc.alloc_id(), vec![frame, corner]); + doc.symbols.push(Symbol { dynamic: false, name: "S".into(), art: Arc::new(art) }); + doc.set_symbol_nine_slice("S", vectorcraft_doc::SymbolNineSlice::new(-0.25, 0.25, 0.25, 0.25)); + let xf = Affine::scale_non_uniform(2.0, 1.5); + let instance = Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "S".into(), xf }); + doc.insert(Some(layer), usize::MAX, instance).unwrap(); + let back = read_back(&doc); + let mut all = vec![]; + paths(back.layers[0].children().unwrap(), &mut all); + let sizes: Vec<(i64, i64)> = + all.iter().filter_map(|p| p.geometric_bounds()).map(|b| (b.width().round() as i64, b.height().round() as i64)).collect(); + assert!(sizes.contains(&(23, 10)), "the corner stretches with the center column: {sizes:?}"); + assert!(sizes.contains(&(200, 150)), "the frame is scaled: {sizes:?}"); + assert!(back.symbol_nine_slice("S").is_none()); +} + /// Nested symbols whose instances multiply, written as their art (on a large canvas), stop at /// [`vectorcraft_doc::MAX_SYMBOL_NODES`] objects of symbol art in all, with a warning. #[test] @@ -881,7 +1038,7 @@ fn nested_symbol_instances_stop_at_the_symbol_art_limit() { /// The documents [`the_writer_counts_objects_as_the_reader_reads_them`] writes: groups, compound /// paths, guides, sublayers, clipping groups and layers, painted clipping paths, opacity masks, /// gradients, pattern definitions and tiles, images, type, symbol definitions and instances, -/// objects with art styles and objects bound to variables. +/// objects with art styles, objects bound to variables and live envelopes. fn counted() -> Vec<(&'static str, Document)> { vec![ ("sample", sample()), @@ -895,6 +1052,8 @@ fn counted() -> Vec<(&'static str, Document)> { ("styles", styles_document()), ("painted clips", painted_clips()), ("blend", blend_doc()), + ("brushes", brushes_document()), + ("envelopes", envelopes_document()), ] } @@ -2475,6 +2634,34 @@ fn gradient_options_and_links_the_data_cant_hold_are_reported() { let back = read_back(&doc); let Paint::Gradient(g) = back.layers[0].children().unwrap()[0].appearance.items[0].paint() else { panic!("a gradient") }; assert_eq!((color(&g.gradient.stops[0].color), g.gradient.stops[0].swatch.as_deref()), (color(&BRAND), None)); + // A gradient mixed around the hue wheel, either way, is written as a classic one of the stops + // on its curve, no more than the reader reads, and opens with the colors it had. + for method in [vectorcraft_color::gradient::GradientMethod::HueClockwise, vectorcraft_color::gradient::GradientMethod::HueCounterclockwise] { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut g = sunset(); + g.method = method; + let want = g.clone(); + let n = painted( + &mut doc, + shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)), + vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(g, None, None)))], + ); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::GRADIENT_HUE], "{method:?}"); + let back = read_back(&doc); + let Paint::Gradient(g) = back.layers[0].children().unwrap()[0].appearance.items[0].paint() else { panic!("a gradient") }; + assert!(g.gradient.method.is_classic(), "{method:?}"); + let written = g.gradient.stops.len(); + assert!((want.stops.len() + 1..=crate::import::MAX_GRADIENT_STOPS).contains(&written), "{method:?}: {written} stops"); + for k in 0..=100 { + let t = k as f32 / 100.0; + let ((a, ao), (b, bo)) = (want.sample(t), g.gradient.sample(t)); + let (a, b) = (a.to_rgb(), b.to_rgb()); + assert!(a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.03) && (ao - bo).abs() < 0.03, "{method:?} at {t}: {a:?} {ao} vs {b:?} {bo}"); + } + } } /// A pattern whose art reaches past its tile is written as its tiles cut to the shape: a definition @@ -3785,6 +3972,106 @@ fn an_unstroked_run_with_a_stroke_style_loses_nothing() { } } +/// The text document has no Korean Line Break Anywhere: a paragraph with it on and Hangul in it +/// is reported as left out, and comes back off; with it off, or with no Hangul, nothing is +/// reported. +#[test] +fn korean_line_break_anywhere_is_reported_only_for_korean_paragraphs() { + use vectorcraft_doc::TextObject; + for (text, on, reported) in [("가나다 라마", true, true), ("가나다 라마", false, false), ("Plain", true, false)] { + let mut t = TextObject::point(vectorcraft_geom::Point::new(20.0, 40.0), text, style(14.0, Color::BLACK)); + t.para.korean_line_break_anywhere = on; + let mut doc = Document::new(200.0, 200.0); + let layer = doc.layers[0].id; + let n = text_node(&mut doc, t); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(!out.warnings.is_empty(), reported, "{text} {on}: {:?}", out.warnings); + let mut all = vec![]; + paths(&read_back(&doc).layers, &mut all); + let paras: Vec = all + .iter() + .filter_map(|n| match &n.kind { + NodeKind::Text(t) => Some(t.para_at(0).korean_line_break_anywhere), + _ => None, + }) + .collect(); + assert_eq!(paras, [false], "{text} {on}"); + } +} + +/// The text document holds no Mojikumi set: a paragraph with any of the predefined sets other +/// than None is reported as left out, and reads back without the set; None and Line-end +/// Punctuation Half Width are not reported. +#[test] +fn predefined_mojikumi_sets_are_reported_as_left_out() { + use vectorcraft_doc::{Mojikumi, TextObject}; + for (set, reported) in [ + (Mojikumi::None, false), + (Mojikumi::LineEndHalf, false), + (Mojikumi::YakumonoHankaku, true), + (Mojikumi::GyomatsuYakumonoHankaku, true), + (Mojikumi::GyomatsuYakumonoZenkaku, true), + (Mojikumi::YakumonoZenkaku, true), + ] { + let mut t = TextObject::point(vectorcraft_geom::Point::new(20.0, 40.0), "「かな」。", style(14.0, Color::BLACK)); + t.para.mojikumi = set; + let mut doc = Document::new(200.0, 200.0); + let layer = doc.layers[0].id; + let n = text_node(&mut doc, t); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(!out.warnings.is_empty(), reported, "{set:?}: {:?}", out.warnings); + let mut all = vec![]; + paths(&read_back(&doc).layers, &mut all); + let sets: Vec = all + .iter() + .filter_map(|n| match &n.kind { + NodeKind::Text(t) => Some(t.para_at(0).mojikumi), + _ => None, + }) + .collect(); + assert_eq!(sets.len(), 1, "{set:?}"); + assert!(matches!(sets[0], Mojikumi::None | Mojikumi::LineEndHalf), "{set:?} reads back as {:?}", sets[0]); + } +} + +/// The text document has no Bunri-Kinshi: a paragraph with it on and an inseparable pair in it is +/// reported as left out, and comes back off; with it off, or with no pair, nothing is reported. +#[test] +fn bunri_kinshi_is_reported_only_for_paragraphs_with_a_pair() { + use vectorcraft_doc::TextObject; + for (text, on, reported) in [ + ("Wait——now", true, true), + ("Wait——now", false, false), + ("Wait—now", true, false), + ("Wait……now", true, true), + ("Wait‥‥now", true, true), + ("あ〳〵い", true, true), + ("あ〴〵い", true, true), + ("あ〵〳い", true, false), + ] { + let mut t = TextObject::point(vectorcraft_geom::Point::new(20.0, 40.0), text, style(14.0, Color::BLACK)); + t.para.bunri_kinshi = on; + let mut doc = Document::new(200.0, 200.0); + let layer = doc.layers[0].id; + let n = text_node(&mut doc, t); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(!out.warnings.is_empty(), reported, "{text} {on}: {:?}", out.warnings); + let mut all = vec![]; + paths(&read_back(&doc).layers, &mut all); + let paras: Vec = all + .iter() + .filter_map(|n| match &n.kind { + NodeKind::Text(t) => Some(t.para_at(0).bunri_kinshi), + _ => None, + }) + .collect(); + assert_eq!(paras, [false], "{text} {on}"); + } +} + #[test] fn type_is_written_again_as_the_same_bytes() { let doc = typed(); @@ -4229,7 +4516,7 @@ fn type_attributes_the_data_cant_hold_are_reported() { let back = read_back(&doc); assert!(matches!(back.layers[0].children().unwrap()[0].kind, NodeKind::Text(_))); // Any other attribute the text document doesn't hold is reported too: No Break, a paragraph's - // left-to-right direction set on it, Optical Margin Alignment, a font version, a font that isn't + // left-to-right direction set on it, Optical Margin Alignment, a font that isn't // installed whose name doesn't come back (a hyphen in its family), a Lab color, // small capitals at another size, right-to-left letters aligned to the start of a paragraph // without a direction of its own, tracking that isn't a whole number. @@ -4238,7 +4525,6 @@ fn type_attributes_the_data_cant_hold_are_reported() { |t| t.runs[0].style.tracking = 12.5, |t| t.para.direction = Some(vectorcraft_doc::ParaDirection::LeftToRight), |t| t.optical_margin = true, - |t| t.runs[0].style.font_version = Some("2.0".into()), |t| t.runs[0].style.font_family = "my-missing font".into(), |t| t.runs[0].style.fill = Paint::solid(MINT), |t| t.runs[0].style.small_caps = Some(80.0), @@ -4261,11 +4547,130 @@ fn type_attributes_the_data_cant_hold_are_reported() { missing.runs[0].style.font_family = "Missing Sans Probe".into(); missing.runs[0].style.font_style = "Bold Italic".into(); assert!(with(missing).is_empty()); + // A version that isn't installed draws in the face the font resolves to, and comes back in it. + let mut uninstalled = t.clone(); + uninstalled.runs[0].style.font_version = Some("2.0".into()); + assert!(with(uninstalled).is_empty()); edit(&mut t); assert_eq!(with(t), [writer::TYPE_ATTRIBUTES]); } } +/// Installs the copies of each font `copies` lists, the first of each loaded first. +fn install_copies(copies: &[(bool, vectorcraft_text::test_fonts::CopyNames<'_>)]) { + for (inter, names) in copies { + let font = vectorcraft_text::test_fonts::named_copy(*inter, *names).unwrap(); + assert_eq!(vectorcraft_text::FontDb::global().add_font(font), 1, "{names:?}"); + } +} + +/// A run's text, font family and font version, as [`fonts_saved`] reads them back. +type SavedRun = (String, String, Option); + +/// A 200 × 100 document of point type whose runs are `runs` (text, family, version). +fn runs_doc(runs: &[(&str, &str, Option<&str>)]) -> Document { + use vectorcraft_doc::{CharStyle, TextObject, TextRun}; + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut t = TextObject::point(vectorcraft_geom::Point::new(10.0, 70.0), "", style(18.0, Color::BLACK)); + t.runs = runs + .iter() + .map(|(text, family, version)| { + let st = CharStyle { font_family: (*family).into(), font_version: version.map(Into::into), ..style(18.0, Color::BLACK) }; + TextRun::new(*text, st) + }) + .collect(); + let n = text_node(&mut doc, t); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + doc +} + +/// [`runs_doc`] saved and read back: the save's warnings, and the runs read back. +fn fonts_saved(runs: &[(&str, &str, Option<&str>)]) -> (Vec, Vec) { + let doc = runs_doc(runs); + let warnings = export_ai_editing(&doc, &opts()).unwrap().warnings; + let back = read_back(&doc); + let NodeKind::Text(t) = &back.layers[0].children().unwrap()[0].kind else { panic!("type comes back as type") }; + (warnings, t.runs.iter().map(|r| (r.text.clone(), r.style.font_family.clone(), r.style.font_version.clone())).collect()) +} + +/// How many fonts the font set of [`runs_doc`] names, the hidden characters' font aside. +fn fonts_written(runs: &[(&str, &str, Option<&str>)]) -> usize { + text_document(&program(&runs_doc(runs))).matches("/CoolTypeFont").count() - 1 +} + +/// Type in a font installed beside a family spelled alike but for case and punctuation +/// (`Sample/Ink`, PostScript name `SampleInk`, beside `SAMPLE INK`), or beside a copy whose +/// PostScript name differs only in case (the type naming its version), is written under its +/// PostScript name and read back in its own family and version, so nothing about its font is +/// reported lost. +#[test] +fn type_in_a_font_beside_a_family_spelled_alike_keeps_its_font() { + install_copies(&[ + (true, ("SAVETEST INK", "Regular", "Version 1.000", "SAVETESTINK-Regular")), + (false, ("Savetest/Ink", "Regular", "Version 1.000", "SavetestInk")), + (true, ("CASESAVE INK", "Regular", "Version 1.000", "CASESAVEINK")), + (false, ("Casesave Ink", "Regular", "Version 2.000", "CasesaveInk")), + ]); + let (warnings, back) = fonts_saved(&[("Kept", "Savetest/Ink", None)]); + assert!(warnings.is_empty(), "{warnings:?}"); + assert_eq!(back, [("Kept".to_string(), "Savetest/Ink".to_string(), None)]); + let (warnings, back) = fonts_saved(&[("Kept", "Casesave Ink", Some("Version 2.000"))]); + assert!(warnings.is_empty(), "{warnings:?}"); + assert_eq!(back, [("Kept".to_string(), "Casesave Ink".to_string(), Some("Version 2.000".to_string()))]); +} + +/// Type in a static font's version that the family and style don't resolve to (two installed +/// copies of one PostScript name, family and style) is written with that version (`/5`) and comes +/// back in it, without a note; two runs in two versions are two fonts of the set. +#[test] +fn type_in_another_version_of_a_static_font_keeps_it() { + install_copies(&[(true, ("Rttest Ink", "Regular", "1.0", "RttestInk-Regular")), (false, ("Rttest Ink", "Regular", "1.1", "RttestInk-Regular"))]); + let (warnings, back) = fonts_saved(&[("Kept", "Rttest Ink", Some("1.1"))]); + assert!(warnings.is_empty(), "{warnings:?}"); + assert_eq!(back, [("Kept".to_string(), "Rttest Ink".to_string(), Some("1.1".to_string()))]); + let (warnings, back) = fonts_saved(&[("Old", "Rttest Ink", None), ("New", "Rttest Ink", Some("1.1"))]); + assert!(warnings.is_empty(), "{warnings:?}"); + assert_eq!(back, [("Old".to_string(), "Rttest Ink".to_string(), None), ("New".to_string(), "Rttest Ink".to_string(), Some("1.1".to_string()))]); + // A run naming the version its family and style resolve to anyway, or one that isn't + // installed, is in the same face as a run naming none: one font of the set, and no note. + let (warnings, back) = fonts_saved(&[("Same", "Rttest Ink", Some("1.0")), ("Gone", "Rttest Ink", Some("9.9")), ("Plain", "Rttest Ink", None)]); + assert!(warnings.is_empty(), "{warnings:?}"); + assert!(back.iter().all(|(_, family, version)| family == "Rttest Ink" && version.is_none()), "{back:?}"); + assert_eq!(fonts_written(&[("Same", "Rttest Ink", Some("1.0")), ("Gone", "Rttest Ink", Some("9.9")), ("Plain", "Rttest Ink", None)]), 1); +} + +/// Type in the copy of a font that its family names, beside a copy of the same PostScript name in +/// another family that the name alone gives first, is written with its version (`/5`), so it comes +/// back in its own copy and family, without a note. +#[test] +fn type_in_a_copy_its_postscript_name_alone_doesnt_give_keeps_it() { + install_copies(&[ + (true, ("RvdupsaveInk", "Regular", "2.0", "RvdupsaveInk-Regular")), + (false, ("Rvdupsave Ink", "Regular", "1.0", "RvdupsaveInk-Regular")), + ]); + let (warnings, back) = fonts_saved(&[("Kept", "Rvdupsave Ink", None)]); + assert!(warnings.is_empty(), "{warnings:?}"); + assert_eq!(back.iter().map(|r| r.1.as_str()).collect::>(), ["Rvdupsave Ink"]); + let (warnings, back) = fonts_saved(&[("Kept", "RvdupsaveInk", None)]); + assert!(warnings.is_empty(), "{warnings:?}"); + assert_eq!(back.iter().map(|r| r.1.as_str()).collect::>(), ["RvdupsaveInk"]); +} + +/// A version string longer than the reader takes (256 bytes) isn't one it can pick a copy by: type +/// in such a copy, which its name alone doesn't give back, is reported as losing its font. +#[test] +fn a_version_longer_than_the_reader_takes_is_reported() { + let long = "9".repeat(300); + install_copies(&[ + (true, ("Longtest Ink", "Regular", "1.0", "LongtestInk-Regular")), + (false, ("Longtest Ink", "Regular", &long, "LongtestInk-Regular")), + ]); + let (warnings, back) = fonts_saved(&[("Long", "Longtest Ink", Some(&long))]); + assert_eq!(warnings, [writer::TYPE_ATTRIBUTES]); + assert_eq!(back, [("Long".to_string(), "Longtest Ink".to_string(), None)]); +} + /// On a large canvas, area type, threaded frames and type on a path stay type: the frames and /// lengths are written at the canvas's scale. Frames of a thread at two scales, and area type /// scaled by two factors, are written as outlines. @@ -4366,6 +4771,19 @@ fn dynamic_text_is_written_at_its_drawn_sizes() { assert!(!texts[0].dynamic_text); let k = texts[0].xf.as_coeffs()[0]; assert_eq!(r3(texts[0].runs[0].style.size * k), r3(drawn)); + // Type written as outlines (here on an open path whose ends meet) loses the setting too, and + // says so. + let mut doc = Document::new(600.0, 300.0); + let layer = doc.layers[0].id; + let mut t = TextObject::point(vectorcraft_geom::Point::ZERO, "Grow", style(12.0, Color::BLACK)); + let ends_meet = [(50.0, 200.0).into(), (550.0, 200.0).into(), (300.0, 50.0).into(), (50.0, 200.0).into()]; + t.kind = TextKind::OnPath { path: PathData::new(vec![vectorcraft_geom::SubPath::polyline(&ends_meet, false)]), start: 0.0, end: None }; + t.xf = Affine::IDENTITY; + t.dynamic_text = true; + let node = text_node(&mut doc, t); + doc.insert(Some(layer), usize::MAX, node).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::TYPE) && out.warnings.iter().any(|w| w == writer::DYNAMIC_TEXT), "{:?}", out.warnings); } /// See-through type with the knockout shape flag comes back with the flag and writes no warning. @@ -5829,25 +6247,6 @@ fn outlines(doc: &Document) -> Vec { out } -/// Fails with the lines where `got` and `want` differ in more than their numbers' last written -/// decimal (a color read back from four decimals gives its other model's values again from them). -fn near_lines(got: &str, want: &str) { - let near = |a: &str, b: &str| { - let (a, b): (Vec<&str>, Vec<&str>) = (a.split(' ').collect(), b.split(' ').collect()); - a.len() == b.len() - && a.iter().zip(&b).all(|(x, y)| match (x.trim_start_matches("%_").parse::(), y.trim_start_matches("%_").parse::()) { - (Ok(x), Ok(y)) => (x - y).abs() <= 2e-3, - _ => x == y, - }) - }; - let (g, w): (Vec<&str>, Vec<&str>) = (got.lines().collect(), want.lines().collect()); - let differ: Vec = (0..g.len().max(w.len())) - .filter(|&i| !matches!((g.get(i), w.get(i)), (Some(a), Some(b)) if near(a, b))) - .map(|i| format!("line {i}:\n got {:?}\n want {:?}", g.get(i), w.get(i))) - .collect(); - assert!(differ.is_empty(), "{}", differ.join("\n")); -} - #[test] fn objects_with_live_effects_and_graphic_styles_are_read_back() { let doc = styles_document(); @@ -6169,25 +6568,7 @@ fn art_styles_write_the_same_bytes_again() { assert_eq!(private_data(&doc, &opts()).unwrap().0, private_data(&doc, &opts()).unwrap().0); // What is read back is written as it was. let again = export_ai_editing(&read_back(&doc), &opts()).unwrap().program; - near_lines(&rgb_without_cmyk(&shown(&again)), &rgb_without_cmyk(&shown(&first.program))); -} - -/// `program` with the CMYK equivalents of plain RGB colors blanked out: the first four numbers of -/// `c m y k r g b Xa` (or `XA`) and of an RGB gradient stop's `c m y k r g b 2 ... Bs`. Named and -/// spot RGB colors (`... (name) tint Xk`, `Xx` and spot stops) are not blanked; the document this -/// is used on has none. The Generic CMYK separation of a color at the edge of the press gamut can -/// land on one of two results that differ by up to 0.01 when the RGB changes in its last float -/// bits, as it does between the first save and the save of the reopened file, and the platform's -/// float math decides which. The RGB values stay compared. -fn rgb_without_cmyk(program: &str) -> String { - let blank = |line: &str| { - let (prefix, rest) = line.strip_prefix("%_").map_or(("", line), |r| ("%_", r)); - let t: Vec<&str> = rest.split(' ').collect(); - let color = t.len() == 8 && matches!(t[7], "Xa" | "XA"); - let stop = t.len() > 8 && t[7] == "2" && t.last() == Some(&"Bs"); - if color || stop { format!("{prefix}_ _ _ _ {}", t[4..].join(" ")) } else { line.to_string() } - }; - program.lines().map(blank).collect::>().join("\n") + same_lines(&shown(&again).lines().map(String::from).collect::>(), &shown(&first.program).lines().map(String::from).collect::>()); } /// `n` on the first layer of `doc`. @@ -6588,6 +6969,70 @@ fn every_effect_setting_written_on_an_object_is_read_back() { assert!(matches!(&spot.appearance.fill().unwrap().paint, Paint::Solid { swatch: Some(s), .. } if s == "Ink"), "{spot:?}"); } +/// A drawn look's strokes warn only where its art style leaves them out: a path with a drop shadow and +/// a stroke with a width profile is written with a style that holds the profile, and doesn't warn; +/// a group with a drop shadow whose member has a stroke inside the path still warns. +#[test] +fn a_drawn_looks_strokes_warn_only_where_its_style_leaves_them_out() { + let profile = vectorcraft_doc::WidthProfile { points: vec![(0.0, 1.0, 0.5), (0.5, 0.25, 0.75), (1.0, 0.0, 1.0)] }; + let (n, warnings, p) = read_one(|doc| { + let mut stroke = StrokeLayer::new(black_fill(), 4.0); + stroke.profile = Some(profile.clone()); + let ap = Appearance { items: vec![AppearanceItem::Stroke(stroke)], effects: vec![drop_shadow()], contents_index: None }; + Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 40.0)), ap) + }); + assert!(p.contains("%AI9_BeginArtStyles"), "{p}"); + assert!(!warnings.iter().any(|w| w == writer::STROKES), "{warnings:?}"); + assert_eq!(n.appearance.stroke().and_then(|s| s.profile.clone()), Some(profile)); + let (_, warnings, p) = read_one(|doc| { + let mut n = + Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 40.0)), Appearance::basic(Paint::None, black_fill(), 2.0)); + n.appearance.stroke_mut().unwrap().align = vectorcraft_doc::StrokeAlign::Inside; + let mut g = group(doc, vec![n], false); + g.appearance.effects = vec![drop_shadow()]; + g + }); + assert!(p.contains("%AI9_BeginArtStyles"), "{p}"); + assert!(warnings.iter().any(|w| w == writer::STROKES), "{warnings:?}"); +} + +/// A path linked to a graphic style with a drop shadow and a stroke with a width profile is written +/// with that style, which holds the profile, and doesn't warn; it reads back linked, with its +/// profile. A linked path whose fill is half opaque in Screen mode isn't written with its style, which +/// the reader reads on no object, and warns that the fill's transparency is left out. +#[test] +fn a_linked_paths_drawn_look_warns_only_for_what_its_style_leaves_out() { + let profile = vectorcraft_doc::WidthProfile { points: vec![(0.0, 1.0, 0.5), (0.5, 0.25, 0.75), (1.0, 0.0, 1.0)] }; + let linked = |doc: &mut Document, fill: FillLayer| { + let mut stroke = StrokeLayer::new(black_fill(), 4.0); + stroke.profile = Some(profile.clone()); + let ap = Appearance { + items: vec![AppearanceItem::Fill(fill), AppearanceItem::Stroke(stroke)], + effects: vec![drop_shadow()], + contents_index: None, + }; + let mut g = vectorcraft_doc::GraphicStyle::new("Linked", ap.clone()); + g.id = 7; + doc.graphic_styles.push(g); + let mut n = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 40.0)), ap); + n.extras_mut().graphic_style = Some(7); + n + }; + let (n, warnings, p) = read_one(|doc| linked(doc, FillLayer::new(solid(Color::rgb(0.2, 0.2, 0.9))))); + assert!(p.contains("1 (Linked) XW"), "{warnings:?}"); + assert!(!warnings.iter().any(|w| w == writer::STROKES), "{warnings:?}"); + assert!(n.extras().graphic_style.is_some(), "{n:?}"); + assert_eq!(n.appearance.stroke().and_then(|s| s.profile.clone()), Some(profile.clone())); + let (_, warnings, p) = read_one(|doc| { + let mut fill = FillLayer::new(solid(Color::rgb(0.2, 0.2, 0.9))); + fill.opacity = 0.5; + fill.blend = BlendMode::Screen; + linked(doc, fill) + }); + assert!(!p.contains("1 (Linked) XW"), "{p}"); + assert!(warnings.iter().any(|w| w == writer::ITEM_TRANSPARENCY), "{warnings:?}"); +} + /// Each effect a graphic style can hold, in a style of its own, reads back with its settings, whatever /// the writer's conversions to the file's units. #[test] @@ -6627,6 +7072,7 @@ fn every_effect_a_graphic_style_holds_is_read_back() { for id in &ids { cases.push((id, json!({"bend": 30.0, "horizontal": -10.0, "vertical": 20.0, "orientation": "vertical"}))); cases.push((id, json!({"bend": -30.0, "horizontal": 0.0, "vertical": 0.0, "orientation": "horizontal"}))); + cases.push((id, json!({"bend": 45.0, "horizontal": 15.0, "vertical": -5.0, "orientation": "horizontal", "version": 1}))); } for (id, params) in cases { let effect = fx(id, params.clone()); @@ -6643,6 +7089,10 @@ fn every_effect_a_graphic_style_holds_is_read_back() { let got = &back.graphic_styles[0].appearance.effects; assert_eq!(got.len(), 1, "{id} {params}"); assert_eq!(got[0].id, effect.id); + // A warp read from a file bends as its style's Bézier net. + if id.starts_with("warp.") { + assert_eq!(got[0].params["version"], json!(vectorcraft_doc::live::WARP_NET), "{id} {params}"); + } let (g, w) = (vectorcraft_effects::merged_params(&got[0].id, &got[0].params), vectorcraft_effects::merged_params(&effect.id, &effect.params)); for (key, value) in w.as_object().unwrap() { // Random isn't written, and a style with it isn't read; its seed is the default. @@ -6663,6 +7113,19 @@ fn every_effect_a_graphic_style_holds_is_read_back() { } } } + // A warp saved before the map version existed is written with its settings too, and reads back on + // the nets' map. + let old = vectorcraft_doc::Effect { id: "warp.flag".into(), params: json!({"bend": 40.0, "horizontal": 10.0}), visible: true }; + let mut doc = Document::new(200.0, 100.0); + let mut g = vectorcraft_doc::GraphicStyle::new("Old", Appearance { effects: vec![old], ..Appearance::basic(black_fill(), Paint::None, 0.0) }); + g.id = 3; + *doc.graphic_styles = vec![g]; + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::PANEL_STYLES), "{:?}", out.warnings); + let back = read_back(&doc); + let [warp] = back.graphic_styles[0].appearance.effects.as_slice() else { panic!("{:?}", back.graphic_styles) }; + assert_eq!((warp.id.as_str(), &warp.params["bend"], &warp.params["horizontal"]), ("warp.flag", &json!(40.0), &json!(10.0))); + assert_eq!(warp.params["version"], json!(vectorcraft_doc::live::WARP_NET)); // A Zig Zag with its 0 to 1 settings written under the size's own key, and a turn in radians. let mut doc = Document::new(200.0, 100.0); let effects = vec![ @@ -6675,6 +7138,124 @@ fn every_effect_a_graphic_style_holds_is_read_back() { assert!(p.contains("7.5 /Real (moveV_Pts) ,") && p.contains("0.5236 /Real (rotate_Radians) ,"), "{p}"); } +/// An embedded 8 × 8 image of a color ramp, `Photo`, 80 pt square at (20, 10) in `doc`, at half +/// opacity, with `effects`. +fn warped_photo(doc: &mut Document, effects: Vec) -> Node { + let ramp = image::RgbImage::from_fn(8, 8, |x, y| image::Rgb([(x * 32) as u8, (y * 32) as u8, 160])); + let mut photo = image_node(doc, ImageBlob::png(png_of(ramp.into())), (8, 8), Affine::new([10.0, 0.0, 0.0, 10.0, 20.0, 10.0]), None); + photo.name = Some("Photo".into()); + photo.opacity = 0.5; + photo.appearance = Appearance { effects, ..Appearance::default() }.into(); + photo +} + +/// A 200 × 100 document holding `photo`, made by [`warped_photo`]. +fn photo_doc(photo: impl FnOnce(&mut Document) -> Node) -> Document { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let n = photo(&mut doc); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + doc +} + +/// An embedded image with one Warp is written with an art style of that Warp, its bent pieces as its +/// drawn look and the image itself on `%_` lines: it reads back as the image, its pixels, placement, +/// name and opacity as they were, with its Warp live and its settings kept. +#[test] +fn an_image_with_a_warp_reads_back_with_its_warp_live() { + // GUARDS: an image with a Warp was written as its drawn pieces alone, and read back without its Warp. + for (id, params) in [ + ("warp.arc", serde_json::json!({"bend": 40.0})), + ("warp.flag", serde_json::json!({"bend": -30.0, "horizontal": 10.0, "vertical": 0.0, "orientation": "vertical"})), + ] { + let doc = photo_doc(|d| warped_photo(d, vec![fx(id, params.clone())])); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::EFFECTS), "{id}: {:?}", out.warnings); + let back = read_back(&doc); + let art = back.layers[0].children().unwrap(); + assert_eq!(art.len(), 1, "{id}: {:#?} {:?}", lines(&back), out.warnings); + let (mut want, mut got) = (vec![], vec![]); + pictures(&doc, doc.layers[0].children().unwrap(), "", &mut want); + pictures(&back, art, "", &mut got); + assert_eq!(got, want, "{id}"); + let [warp] = art[0].appearance.effects.as_slice() else { panic!("{id}: {:?}", art[0].appearance) }; + assert_eq!(warp.id, id); + let (w, g) = (vectorcraft_effects::merged_params(id, ¶ms), vectorcraft_effects::merged_params(&warp.id, &warp.params)); + for key in ["bend", "horizontal", "vertical"] { + assert!((g[key].as_f64().unwrap() - w[key].as_f64().unwrap()).abs() < 6e-3, "{id} {key}: {g} for {w}"); + } + assert_eq!(g["orientation"], w["orientation"], "{id}"); + } +} + +/// An image whose style's Warp bends it another way than its drawn look keeps that look, with the +/// note, and the file as written opens with the image. +#[test] +fn an_image_whose_warp_draws_otherwise_than_its_look_keeps_its_look() { + // GUARDS: an image read with its Warp live whatever its drawn look showed. + let doc = photo_doc(|d| warped_photo(d, vec![fx("warp.arc", serde_json::json!({"bend": 40.0}))])); + let program = export_ai_editing(&doc, &opts()).unwrap().program; + let (from, to) = (b"0.4 /Real (DeformValue)".as_slice(), b"-0.4 /Real (DeformValue)".as_slice()); + let at = program.windows(from.len()).position(|w| w == from).expect("the warp's bend"); + let mut other = program.clone(); + other.splice(at..at + from.len(), to.iter().copied()); + let (back, warnings) = crate::ai_alone(&other).unwrap(); + let art = back.layers[0].children().unwrap(); + assert_eq!(art.len(), 1, "{art:#?}"); + assert!(matches!(art[0].kind, NodeKind::Group { .. }), "the drawn look: {:?}", art[0].kind); + assert!(art[0].appearance.effects.is_empty(), "{:?}", art[0].appearance); + assert!(warnings.iter().any(|w| w.contains("drawn look")), "{warnings:?}"); + let (back, _) = crate::ai_alone(&program).unwrap(); + assert!(matches!(back.layers[0].children().unwrap()[0].kind, NodeKind::Image(_))); +} + +/// An image on `%_` lines is the copy of a styled object, as other objects there are: with a style +/// the file doesn't define, its drawn look stands for it, named as it is, and the image doesn't come +/// in beside the look. +#[test] +fn an_image_on_hidden_lines_does_not_come_in_beside_its_look() { + // GUARDS: an image whose samples were on `%_` lines came in as a second, visible object. + let doc = photo_doc(|d| warped_photo(d, vec![fx("warp.arc", serde_json::json!({"bend": 40.0}))])); + let program = export_ai_editing(&doc, &opts()).unwrap().program; + let (from, to) = (b"1 (Anon 1) XW".as_slice(), b"1 (Unknown) XW".as_slice()); + let at = program.windows(from.len()).position(|w| w == from).expect("the image's style"); + let mut unknown = program.clone(); + unknown.splice(at..at + from.len(), to.iter().copied()); + let (back, _) = crate::ai_alone(&unknown).unwrap(); + let art = back.layers[0].children().unwrap(); + assert_eq!(art.len(), 1, "{:#?}", lines(&back)); + assert!(matches!(art[0].kind, NodeKind::Group { .. }), "the drawn look: {:?}", art[0].kind); + assert_eq!(art[0].name.as_deref(), Some("Photo")); +} + +/// A linked image, an image with an opacity mask, and an image with a Warp and another effect are +/// written as their drawn art, with no art style. +#[test] +fn other_warped_images_are_written_as_their_drawn_art() { + let arc = || fx("warp.arc", serde_json::json!({"bend": 40.0})); + let linked = photo_doc(|d| { + let mut n = warped_photo(d, vec![arc()]); + if let NodeKind::Image(im) = &mut n.kind { + im.link = Some(vectorcraft_doc::LinkInfo::new("/art/photo.png")); + } + n + }); + let masked = photo_doc(|d| { + let mut n = warped_photo(d, vec![arc()]); + let white = + Node::path(d.alloc_id(), shapes::rectangle(Rect::new(20.0, 10.0, 100.0, 90.0)), Appearance::basic(solid(Color::WHITE), Paint::None, 0.0)); + n.extras_mut().mask = Some(Box::new(OpacityMask::new(white, false))); + n + }); + let stacked = photo_doc(|d| warped_photo(d, vec![arc(), fx("stylize.feather", serde_json::json!({"radius": 2.0}))])); + for (what, doc) in [("linked", linked), ("masked", masked), ("stacked", stacked)] { + assert!(!program_shown(&doc).contains("1 (Anon"), "{what}"); + let back = read_back(&doc); + let art = back.layers[0].children().unwrap(); + assert!(art.iter().all(|n| n.appearance.effects.is_empty()), "{what}: {art:#?}"); + } +} + /// Every kind of appearance a style isn't written for is written as its drawn look, with a warning. #[test] fn appearances_written_as_their_drawn_look() { @@ -6852,6 +7433,103 @@ fn a_link_to_a_style_that_moves_the_outline_is_kept_where_the_reader_reads_it() assert!(n.extras().mask.is_some(), "{n:?}"); } +/// An object linked to a graphic style that doesn't fit within the object limit is left out with +/// the limit's warning and the warning about links left out. +#[test] +fn a_linked_object_past_the_object_limit_warns_that_its_link_is_left_out() { + let mut doc = Document::new(200.0, 100.0); + let ap = Appearance { effects: vec![drop_shadow()], ..Appearance::basic(black_fill(), Paint::None, 0.0) }; + let mut g = vectorcraft_doc::GraphicStyle::new("Shadowed", ap.clone()); + g.id = 9; + doc.graphic_styles.push(g); + // Room for everything but the object. + let room = crate::import::objects_read(&export_ai_editing(&doc, &opts()).unwrap().program).unwrap(); + let mut n = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 40.0)), ap); + n.extras_mut().graphic_style = Some(9); + put(&mut doc, n); + let all = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!all.warnings.iter().any(|w| w == writer::OBJECT_LIMIT || w == writer::STYLE_LINKS), "{:?}", all.warnings); + let out = export_within(&doc, &opts(), room).unwrap(); + for w in [writer::OBJECT_LIMIT, writer::STYLE_LINKS] { + assert!(out.warnings.iter().any(|x| x == w), "{w}: {:?}", out.warnings); + } +} + +/// A link to a graphic style with Twist is kept where the reader reads Twist: on a curve, a curved +/// compound path or a group with nothing stroked up to a quarter turn, and on a path with straight +/// segments at any angle. A stroked curve, a group with a stroked member or a guide, or a curve, +/// compound path or group twisted further, is written without the link and warns. +#[test] +fn a_link_to_a_twist_style_is_kept_where_the_reader_reads_it() { + // A document with the object `make` builds from its appearance, `ap` with Twist at `angle`, + // linked to a graphic style of that appearance. + fn twisted(angle: f64, ap: Appearance, make: impl FnOnce(&mut Document, Appearance) -> Node) -> Document { + let mut doc = Document::new(200.0, 100.0); + let ap = Appearance { effects: vec![fx("distort.twist", serde_json::json!({"angle": angle}))], ..ap }; + let mut g = vectorcraft_doc::GraphicStyle::new("Twisted", ap.clone()); + g.id = 9; + doc.graphic_styles.push(g); + let mut n = make(&mut doc, ap); + n.extras_mut().graphic_style = Some(9); + put(&mut doc, n); + doc + } + let oval = || shapes::ellipse(Rect::new(10.0, 10.0, 90.0, 60.0)); + let square = || shapes::rectangle(Rect::new(10.0, 10.0, 90.0, 60.0)); + let red = solid(Color::rgb(1.0, 0.0, 0.0)); + let filled = || Appearance::basic(black_fill(), Paint::None, 0.0); + let path = |p: PathData| move |doc: &mut Document, ap: Appearance| Node::path(doc.alloc_id(), p, ap); + let ring = |doc: &mut Document, ap: Appearance| { + let outer = Node::path(doc.alloc_id(), oval(), Appearance::default()); + let inner = Node::path(doc.alloc_id(), shapes::ellipse(Rect::new(30.0, 20.0, 70.0, 50.0)), Appearance::default()); + let mut n = Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(inner)], rule: FillRule::NonZero }); + n.appearance = ap.into(); + n + }; + // A group of a filled square and `second`. + let group = |second: fn(&mut Document) -> Node| { + move |doc: &mut Document, ap: Appearance| { + let first = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 40.0, 40.0)), filled()); + let second = second(doc); + let mut n = Node::group(doc.alloc_id(), vec![Arc::new(first), Arc::new(second)]); + n.appearance = ap.into(); + n + } + }; + let curve = |doc: &mut Document| { + Node::path(doc.alloc_id(), shapes::ellipse(Rect::new(50.0, 10.0, 90.0, 60.0)), Appearance::basic(black_fill(), Paint::None, 0.0)) + }; + let stroked_curve = |doc: &mut Document| { + let ap = Appearance::basic(black_fill(), solid(Color::rgb(1.0, 0.0, 0.0)), 2.0); + Node::path(doc.alloc_id(), shapes::ellipse(Rect::new(50.0, 10.0, 90.0, 60.0)), ap) + }; + let guide = |doc: &mut Document| { + let path = shapes::rectangle(Rect::new(50.0, 10.0, 90.0, 60.0)); + Node::new(doc.alloc_id(), NodeKind::Path { path, rule: FillRule::NonZero, live: None, clipping: false, guide: true }) + }; + for (what, doc, kept) in [ + ("a twisted curve", twisted(45.0, filled(), path(oval())), true), + ("a curve twisted a quarter turn back", twisted(-90.0, filled(), path(oval())), true), + ("a square twisted three quarters of a turn", twisted(270.0, filled(), path(square())), true), + ("a curve twisted past a quarter turn", twisted(120.0, filled(), path(oval())), false), + ("a stroked curve", twisted(45.0, Appearance::basic(black_fill(), red.clone(), 2.0), path(oval())), false), + ("a curved compound path", twisted(-60.0, filled(), ring), true), + ("a curved compound path twisted past a quarter turn", twisted(120.0, filled(), ring), false), + ("a twisted group", twisted(90.0, Appearance::default(), group(curve)), true), + ("a group twisted past a quarter turn", twisted(135.0, Appearance::default(), group(curve)), false), + ("a group with a stroked member", twisted(45.0, Appearance::default(), group(stroked_curve)), false), + ("a group with a guide", twisted(45.0, Appearance::default(), group(guide)), false), + ] { + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings.iter().any(|w| w == writer::STYLE_LINKS), !kept, "{what}: {:?}", out.warnings); + let back = read_back(&doc); + let n = &back.layers[0].children().unwrap()[0]; + let style = n.extras().graphic_style.and_then(|id| back.graphic_style_by_id(id)).map(|g| g.name.as_str()); + assert_eq!(style, kept.then_some("Twisted"), "{what}: {n:?}"); + assert_eq!(n.appearance.effects.iter().any(|e| e.id == "distort.twist"), kept, "{what}: {n:?}"); + } +} + /// Twist and Transform on an object that isn't linked to a graphic style are not written as a style /// of its own: the object reads back without live effects. #[test] @@ -7199,6 +7877,772 @@ fn a_large_canvas_writes_every_object_as_its_look() { assert!((p.x - 10.0).abs() < 1e-2 && (p.y - 10.0).abs() < 1e-2, "{p:?}"); } +// ---------- brushes ---------- + +/// Brush art: a wide block with a narrow one below it (y down), filled black. +fn brush_art_node() -> Node { + let block = + |id: u64, r: Rect| Arc::new(Node::path(vectorcraft_doc::NodeId(id), shapes::rectangle(r), Appearance::basic(black_fill(), Paint::None, 0.0))); + Node::group(vectorcraft_doc::NodeId(1), vec![block(2, Rect::new(0.0, 0.0, 40.0, 4.0)), block(3, Rect::new(0.0, 4.0, 10.0, 8.0))]) +} + +/// A Calligraphic brush varying with the barrel's rotation and the pen's pressure, a Scatter brush in +/// Tints, an Art brush in Tints and one that keeps its art's colors. +fn brush_library() -> Vec { + use vectorcraft_brush::{ArtBrush, Brush, BrushKind, Calligraphic, Colorization, Scatter, Variation}; + let art = |colorization| BrushKind::Art(ArtBrush { art: brush_art_node(), colorization, ..ArtBrush::default() }); + vec![ + Brush { + name: "Nib".into(), + kind: BrushKind::Calligraphic(Calligraphic { + angle: 30.0, + roundness: 40.0, + size: 6.0, + variation: [20.0, 10.0, 2.0], + modes: Some([Variation::Rotation, Variation::Fixed, Variation::Pressure]), + }), + }, + Brush { + name: "Spray".into(), + kind: BrushKind::Scatter(Scatter { + art: brush_art_node(), + size: (50.0, 150.0), + spacing: (120.0, 200.0), + scatter: (-25.0, 25.0), + rotation: (-45.0, 30.0), + rotation_relative_to_path: true, + colorization: Colorization::Tints, + modes: Some([Variation::Random, Variation::Fixed, Variation::Pressure, Variation::Random]), + }), + }, + Brush { name: "Ribbon".into(), kind: art(Colorization::Tints) }, + Brush { name: "Plain ribbon".into(), kind: art(Colorization::None) }, + ] +} + +/// A path stroked red at `width` with the brush `brush`, on the first layer of `doc`. +fn brushed(doc: &mut Document, brush: &str, from: (f64, f64), to: (f64, f64), width: f64) { + let mut line = + Node::path(doc.alloc_id(), shapes::line(from.into(), to.into()), Appearance::basic(Paint::None, solid(Color::rgb(1.0, 0.0, 0.0)), width)); + line.appearance.stroke_mut().unwrap().brush = Some(brush.into()); + put(doc, line); +} + +/// [`brush_library`] and a path with the Calligraphic brush and one with the Art brush in Tints. +fn brushes_document() -> Document { + let mut doc = Document::new(300.0, 200.0); + vectorcraft_brush::store(&mut doc, &brush_library()); + brushed(&mut doc, "Nib", (20.0, 50.0), (280.0, 60.0), 2.0); + brushed(&mut doc, "Ribbon", (20.0, 120.0), (280.0, 150.0), 1.5); + doc +} + +/// Brush art `n` as a tree to compare with [`same_tree`]: each object's kind, its anchors and handles, +/// the fills and strokes that paint (a stroke with its width), and its members in order. +fn art_tree(n: &Node) -> serde_json::Value { + let kind = match &n.kind { + NodeKind::Path { .. } => "path", + NodeKind::Compound { .. } => "compound", + NodeKind::Group { clip: false, .. } => "group", + _ => "other", + }; + let anchors: Vec<[f64; 6]> = match &n.kind { + NodeKind::Path { path, .. } => { + path.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| [a.h_in.x, a.h_in.y, a.p.x, a.p.y, a.h_out.x, a.h_out.y])).collect() + } + _ => vec![], + }; + let paints: Vec = n + .appearance + .items + .iter() + .filter(|i| !i.paint().is_none()) + .map(|i| match i { + AppearanceItem::Fill(f) => serde_json::json!(["fill", f.paint]), + AppearanceItem::Stroke(s) => serde_json::json!(["stroke", s.paint, s.width]), + }) + .collect(); + let members: Vec = n.children().map(|c| c.iter().map(|m| art_tree(m)).collect()).unwrap_or_default(); + serde_json::json!({"kind": kind, "anchors": anchors, "paints": paints, "members": members}) +} + +/// Are trees `a` and `b` ([`art_tree`]) the same but for numbers within the written numbers' +/// precision (1/1000)? +fn same_tree(a: &serde_json::Value, b: &serde_json::Value) -> bool { + use serde_json::Value; + match (a, b) { + (Value::Number(x), Value::Number(y)) => (x.as_f64().unwrap() - y.as_f64().unwrap()).abs() <= 1e-3, + (Value::Array(x), Value::Array(y)) => x.len() == y.len() && x.iter().zip(y).all(|(p, q)| same_tree(p, q)), + (Value::Object(x), Value::Object(y)) => x.len() == y.len() && x.iter().all(|(k, v)| y.get(k).is_some_and(|w| same_tree(v, w))), + _ => a == b, + } +} + +/// The document's brushes come back in the Brushes panel's order with their settings and art: the +/// Calligraphic brush's channels, the Scatter brush's ranges, modes and Tints, the Art brushes' +/// colorizations. +#[test] +fn brushes_are_read_back_with_their_settings() { + use vectorcraft_brush::BrushKind; + let doc = brushes_document(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::BRUSHES), "{:?}", out.warnings); + let text = program(&doc); + assert_eq!(text.matches("%AI8_BeginPluginObject").count(), 5, "the manager's order and four brushes"); + assert_eq!(text.matches("%AI8_BeginBrushPattern").count(), 3); + let back = vectorcraft_brush::library(&read_back(&doc)); + let lib = brush_library(); + assert_eq!(back.iter().map(|b| b.name.as_str()).collect::>(), ["Nib", "Spray", "Ribbon", "Plain ribbon"]); + assert_eq!(back[0], lib[0]); + let (BrushKind::Scatter(got), BrushKind::Scatter(want)) = (&back[1].kind, &lib[1].kind) else { panic!("scatter") }; + let near = |a: (f64, f64), b: (f64, f64)| (a.0 - b.0).abs() < 1e-3 && (a.1 - b.1).abs() < 1e-3; + assert!( + near(got.size, want.size) && near(got.spacing, want.spacing) && near(got.scatter, want.scatter) && near(got.rotation, want.rotation), + "{got:?}" + ); + assert_eq!((got.modes, got.colorization, got.rotation_relative_to_path), (want.modes, want.colorization, true)); + let (g, w) = (art_tree(&got.art), art_tree(&want.art)); + assert!(same_tree(&g, &w), "the art without its frame, with its paint and members in order: {g:#} for {w:#}"); + for (i, colorization) in [(2, vectorcraft_brush::Colorization::Tints), (3, vectorcraft_brush::Colorization::None)] { + let BrushKind::Art(a) = &back[i].kind else { panic!("art") }; + assert_eq!(a.colorization, colorization); + let (g, w) = (art_tree(&a.art), art_tree(&brush_art_node())); + assert!(same_tree(&g, &w), "the narrow block stays below the wide one, and no frame stays: {g:#} for {w:#}"); + let BrushKind::Art(want) = &lib[i].kind else { panic!("art") }; + assert_eq!(ArtBrushOptions::of(a), ArtBrushOptions::of(want)); + } +} + +/// An Art brush's options, without its art. +#[derive(Debug, PartialEq)] +struct ArtBrushOptions(serde_json::Value); + +impl ArtBrushOptions { + fn of(a: &vectorcraft_brush::ArtBrush) -> Self { + let mut v = serde_json::to_value(a).unwrap(); + v.as_object_mut().unwrap().remove("art"); + Self(v) + } +} + +/// A path with the Calligraphic brush, and one with an Art brush in Tints whose art bends along the +/// path, come back as those paths with the brush on their stroke at its weight, not as their drawn +/// look; a path with the Art brush that keeps its art's colors comes back as its drawn look. +#[test] +fn brushed_paths_are_read_back_brushed() { + let mut doc = brushes_document(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::STROKES), "{:?}", out.warnings); + let back = read_back(&doc); + let art = back.layers[0].children().unwrap(); + assert_eq!(art.len(), 2); + for (n, (brush, width)) in art.iter().zip([("Nib", 2.0), ("Ribbon", 1.5)]) { + assert!(matches!(n.kind, NodeKind::Path { .. }), "{brush}: the path, not its look: {n:#?}"); + let st = n.appearance.stroke().unwrap(); + assert_eq!((st.brush.as_deref(), st.width, st.paint.color()), (Some(brush), width, Some(Color::rgb(1.0, 0.0, 0.0)))); + assert!(n.appearance.fill().is_none_or(|f| f.paint.is_none())); + } + let ours = doc.layers[0].children().unwrap(); + assert_eq!(art[0].path_data(), ours[0].path_data()); + assert_eq!(art[1].path_data(), ours[1].path_data()); + brushed(&mut doc, "Plain ribbon", (20.0, 180.0), (280.0, 180.0), 1.0); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::STROKES), "{:?}", out.warnings); + assert!(matches!(read_back(&doc).layers[0].children().unwrap()[2].kind, NodeKind::Group { .. })); +} + +/// A compound path with the Calligraphic brush comes back as that compound path with the brush on its +/// stroke; a filled ellipse with it comes back with its fill and the brush. +#[test] +fn brushed_compound_and_filled_paths_are_read_back_brushed() { + let mut doc = Document::new(300.0, 200.0); + vectorcraft_brush::store(&mut doc, &brush_library()); + let mut stroke = StrokeLayer::new(solid(Color::rgb(1.0, 0.0, 0.0)), 2.0); + stroke.brush = Some("Nib".into()); + let ring = ring(&mut doc, Appearance { items: vec![AppearanceItem::Stroke(stroke.clone())], effects: vec![], contents_index: None }); + put(&mut doc, ring); + let fill = vectorcraft_doc::FillLayer::new(solid(Color::rgb(0.2, 0.6, 0.3))); + let ap = Appearance { items: vec![AppearanceItem::Fill(fill), AppearanceItem::Stroke(stroke)], effects: vec![], contents_index: None }; + let ellipse = Node::path(doc.alloc_id(), shapes::ellipse(Rect::new(20.0, 120.0, 140.0, 180.0)), ap); + put(&mut doc, ellipse); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::STROKES || w == writer::BRUSHES), "{:?}", out.warnings); + let back = read_back(&doc); + let (art, ours) = (back.layers[0].children().unwrap(), doc.layers[0].children().unwrap()); + assert!(matches!(art[0].kind, NodeKind::Compound { .. }), "the compound path, not its look: {:#?}", art[0]); + assert!(same_tree(&art_tree(&art[0])["members"], &art_tree(&ours[0])["members"]), "{:#?}", art[0]); + assert!(matches!(art[1].kind, NodeKind::Path { .. }), "the ellipse, not its look: {:#?}", art[1]); + assert!(same_tree(&art_tree(&art[1])["anchors"], &art_tree(&ours[1])["anchors"]), "{:#?}", art[1]); + assert_eq!(art[1].appearance.fill().and_then(|f| f.paint.color()), Some(Color::rgb(0.2, 0.6, 0.3))); + for n in art { + let st = n.appearance.stroke().unwrap(); + assert_eq!((st.brush.as_deref(), st.width), (Some("Nib"), 2.0)); + } +} + +/// A path with an Art brush in Tints whose art doesn't bend along the path (its art has a painted +/// stroke) comes back as its drawn look, with the stroke warning; the brush itself comes back. +#[test] +fn an_art_brush_whose_art_doesnt_bend_keeps_its_paths_look() { + use vectorcraft_brush::{ArtBrush, Brush, BrushKind, Colorization}; + let mut art = brush_art_node(); + if let Some(c) = art.children_mut() { + for m in c.iter_mut() { + Arc::make_mut(m).appearance = Appearance::basic(black_fill(), black_fill(), 1.0).into(); + } + } + let brush = + Brush { name: "Stroked ribbon".into(), kind: BrushKind::Art(ArtBrush { art, colorization: Colorization::Tints, ..ArtBrush::default() }) }; + let mut doc = Document::new(300.0, 200.0); + vectorcraft_brush::store(&mut doc, std::slice::from_ref(&brush)); + brushed(&mut doc, "Stroked ribbon", (20.0, 120.0), (280.0, 150.0), 1.0); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::STROKES), "{:?}", out.warnings); + assert!(!out.warnings.iter().any(|w| w == writer::BRUSHES), "{:?}", out.warnings); + let back = read_back(&doc); + assert!(matches!(back.layers[0].children().unwrap()[0].kind, NodeKind::Group { .. })); + let lib = vectorcraft_brush::library(&back); + let (BrushKind::Art(got), BrushKind::Art(want)) = (&lib[0].kind, &brush.kind) else { panic!("art") }; + assert!(same_tree(&art_tree(&got.art), &art_tree(&want.art)), "{:#?}", got.art); +} + +/// Settings the other tests don't use come back: a Calligraphic brush varying with tilt and bearing, +/// a Scatter brush keeping its art's colors whose rotation doesn't follow the path, and brushes whose +/// modes aren't given (the reader gives them, the same ones). +#[test] +fn more_brush_settings_are_read_back() { + use vectorcraft_brush::{Brush, BrushKind, Calligraphic, Colorization, Scatter, Variation}; + let tilted = Calligraphic { + angle: -40.0, + roundness: 75.0, + size: 9.0, + variation: [10.0, 5.0, 3.0], + modes: Some([Variation::Tilt, Variation::Bearing, Variation::Random]), + }; + let scatter = Scatter { + art: brush_art_node(), + size: (80.0, 80.0), + spacing: (100.0, 100.0), + scatter: (0.0, 0.0), + rotation: (15.0, 15.0), + rotation_relative_to_path: false, + colorization: Colorization::None, + modes: Some([Variation::Tilt, Variation::Bearing, Variation::Fixed, Variation::Rotation]), + }; + let lib = vec![ + Brush { name: "Tilted".into(), kind: BrushKind::Calligraphic(tilted.clone()) }, + Brush { name: "Still".into(), kind: BrushKind::Scatter(scatter.clone()) }, + Brush { name: "Unset nib".into(), kind: BrushKind::Calligraphic(Calligraphic { modes: None, ..tilted }) }, + Brush { name: "Unset spray".into(), kind: BrushKind::Scatter(Scatter { modes: None, ..scatter }) }, + ]; + let mut doc = Document::new(300.0, 200.0); + vectorcraft_brush::store(&mut doc, &lib); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::BRUSHES), "{:?}", out.warnings); + let back = vectorcraft_brush::library(&read_back(&doc)); + assert_eq!(back.len(), lib.len()); + let near = |a: (f64, f64), b: (f64, f64)| (a.0 - b.0).abs() < 1e-3 && (a.1 - b.1).abs() < 1e-3; + for (got, want) in back.iter().zip(&lib) { + assert_eq!(got.name, want.name); + match (&got.kind, &want.kind) { + (BrushKind::Calligraphic(g), BrushKind::Calligraphic(w)) => { + assert_eq!(g.modes(), w.modes(), "{}", want.name); + assert_eq!(Calligraphic { modes: None, ..g.clone() }, Calligraphic { modes: None, ..w.clone() }, "{}", want.name); + } + (BrushKind::Scatter(g), BrushKind::Scatter(w)) => { + assert_eq!(g.modes(), w.modes(), "{}", want.name); + assert!(near(g.size, w.size) && near(g.spacing, w.spacing) && near(g.scatter, w.scatter) && near(g.rotation, w.rotation), "{g:?}"); + assert_eq!((g.colorization, g.rotation_relative_to_path), (Colorization::None, false), "{}", want.name); + assert!(same_tree(&art_tree(&g.art), &art_tree(&w.art)), "{}: {:#?}", want.name, g.art); + } + _ => panic!("{}: {got:?}", want.name), + } + } +} + +/// Brush art without width or height, a straight stroked line, comes back as that line, without a +/// frame or a group around it: a Scatter brush's horizontal line and an Art brush's vertical one. +#[test] +fn brush_art_of_a_straight_line_comes_back_as_the_line() { + use vectorcraft_brush::{ArtBrush, Brush, BrushKind, Scatter}; + let line = |id: u64, to: (f64, f64)| { + Node::path(vectorcraft_doc::NodeId(id), shapes::line((0.0, 0.0).into(), to.into()), Appearance::basic(Paint::None, black_fill(), 2.0)) + }; + let lib = vec![ + Brush { name: "Dash".into(), kind: BrushKind::Scatter(Scatter { art: line(1, (40.0, 0.0)), ..Scatter::default() }) }, + Brush { name: "Post".into(), kind: BrushKind::Art(ArtBrush { art: line(2, (0.0, 40.0)), ..ArtBrush::default() }) }, + ]; + let mut doc = Document::new(300.0, 200.0); + vectorcraft_brush::store(&mut doc, &lib); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::BRUSHES), "{:?}", out.warnings); + let back = vectorcraft_brush::library(&read_back(&doc)); + assert_eq!(back.len(), 2); + for (got, want) in back.iter().zip(&lib) { + let art = |b: &Brush| match &b.kind { + BrushKind::Scatter(s) => s.art.clone(), + BrushKind::Art(a) => a.art.clone(), + _ => panic!("{}", b.name), + }; + let (g, w) = (art_tree(&art(got)), art_tree(&art(want))); + assert!(same_tree(&g, &w), "{}: {g:#} for {w:#}", want.name); + } +} + +/// Brush art of a path with several subpaths is written as a compound path, which the reader reads as +/// a compound path of one path for each subpath, and is weighed as the reader weighs that against the +/// art it copies into one file's brushes: of two Art brushes whose art is a path of 30,000 squares, +/// the second is left out with a warning, so that what is written is what comes back. +#[test] +fn brush_art_of_a_path_with_subpaths_is_weighed_as_it_is_read() { + use vectorcraft_brush::{ArtBrush, Brush, BrushKind}; + let squares = |n: u32| { + let mut path = PathData::default(); + for i in 0..n { + let x = f64::from(i % 200) * 2.0; + let y = f64::from(i / 200) * 2.0; + path.subpaths.extend(shapes::rectangle(Rect::new(x, y, x + 1.0, y + 1.0)).subpaths); + } + Node::path(vectorcraft_doc::NodeId(1), path, Appearance::basic(black_fill(), Paint::None, 0.0)) + }; + let brush = |name: &str, n: u32| Brush { name: name.into(), kind: BrushKind::Art(ArtBrush { art: squares(n), ..ArtBrush::default() }) }; + let mut doc = Document::new(300.0, 200.0); + vectorcraft_brush::store(&mut doc, &[brush("Two", 2)]); + let back = vectorcraft_brush::library(&read_back(&doc)); + let BrushKind::Art(a) = &back[0].kind else { panic!("art") }; + let tree = art_tree(&a.art); + assert_eq!(tree["kind"], "compound", "{tree:#}"); + assert_eq!(tree["members"].as_array().map(Vec::len), Some(2), "{tree:#}"); + let mut doc = Document::new(300.0, 200.0); + vectorcraft_brush::store(&mut doc, &[brush("Many 1", 30_000), brush("Many 2", 30_000)]); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::BRUSHES), "{:?}", out.warnings); + let names: Vec = vectorcraft_brush::library(&read_back(&doc)).into_iter().map(|b| b.name).collect(); + assert_eq!(names, ["Many 1"]); + assert_eq!(program(&doc).matches("%AI8_BeginBrushPattern").count(), 1); +} + +/// Brush art that is a compound path is written as one path of all its members' subpaths, and is +/// weighed as the reader reads that back: a compound path of 24,000 members of two squares each is +/// read as 48,000 paths, within what the reader copies into one file's brushes, so the brush is +/// written without a warning; a compound path with one square comes back as one path. +#[test] +fn brush_art_of_a_compound_path_is_weighed_as_it_is_read() { + use vectorcraft_brush::{ArtBrush, Brush, BrushKind}; + let square = |i: u32| { + let x = f64::from(i % 400) * 2.0; + let y = f64::from(i / 400) * 2.0; + shapes::rectangle(Rect::new(x, y, x + 1.0, y + 1.0)).subpaths + }; + let compound = |members: u32, per: u32| { + let children = (0..members) + .map(|m| { + let path = PathData::new((0..per).flat_map(|k| square(m * per + k)).collect()); + Arc::new(Node::path(vectorcraft_doc::NodeId(2), path, Appearance::basic(black_fill(), Paint::None, 0.0))) + }) + .collect(); + let mut n = Node::path(vectorcraft_doc::NodeId(1), PathData::default(), Appearance::basic(black_fill(), Paint::None, 0.0)); + n.kind = NodeKind::Compound { children, rule: FillRule::NonZero }; + n + }; + let brush = |name: &str, art: Node| Brush { name: name.into(), kind: BrushKind::Art(ArtBrush { art, ..ArtBrush::default() }) }; + let mut doc = Document::new(300.0, 200.0); + vectorcraft_brush::store(&mut doc, &[brush("One", compound(1, 1))]); + let back = vectorcraft_brush::library(&read_back(&doc)); + let BrushKind::Art(a) = &back[0].kind else { panic!("art") }; + assert_eq!(art_tree(&a.art)["kind"], "path", "{:#}", art_tree(&a.art)); + let mut doc = Document::new(300.0, 200.0); + vectorcraft_brush::store(&mut doc, &[brush("Many", compound(24_000, 2))]); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::BRUSHES), "{:?}", out.warnings); + let back = vectorcraft_brush::library(&read_back(&doc)); + assert_eq!(back.len(), 1); + let BrushKind::Art(a) = &back[0].kind else { panic!("art") }; + assert_eq!(a.art.children().map(Vec::len), Some(48_000)); +} + +/// A path with a drop shadow and the Calligraphic brush keeps the brush and the effect, and its drawn +/// look doesn't warn about the brushed stroke; a group with a drop shadow whose member has the Scatter +/// brush still warns, as the member is written as its brush's art. +#[test] +fn a_brushed_path_with_effects_keeps_its_brush_without_the_stroke_warning() { + let mut doc = Document::new(300.0, 200.0); + vectorcraft_brush::store(&mut doc, &brush_library()); + let mut line = Node::path( + doc.alloc_id(), + shapes::line((20.0, 50.0).into(), (280.0, 60.0).into()), + Appearance::basic(Paint::None, solid(Color::rgb(1.0, 0.0, 0.0)), 2.0), + ); + line.appearance.stroke_mut().unwrap().brush = Some("Nib".into()); + line.appearance.effects = vec![drop_shadow()]; + put(&mut doc, line); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::STROKES), "{:?}", out.warnings); + let back = read_back(&doc); + let n = &back.layers[0].children().unwrap()[0]; + assert!(matches!(n.kind, NodeKind::Path { .. }), "the path, not its look: {n:#?}"); + assert_eq!(n.appearance.stroke().and_then(|s| s.brush.as_deref()), Some("Nib")); + assert_eq!(n.appearance.effects.len(), 1); + let mut doc = Document::new(300.0, 200.0); + vectorcraft_brush::store(&mut doc, &brush_library()); + let mut member = Node::path( + doc.alloc_id(), + shapes::line((20.0, 50.0).into(), (280.0, 60.0).into()), + Appearance::basic(Paint::None, solid(Color::rgb(1.0, 0.0, 0.0)), 2.0), + ); + member.appearance.stroke_mut().unwrap().brush = Some("Spray".into()); + let mut g = group(&mut doc, vec![member], false); + g.appearance.effects = vec![drop_shadow()]; + put(&mut doc, g); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::STROKES), "{:?}", out.warnings); +} + +/// A brushed stroke that paints nothing isn't kept by an art style: a path with only such a stroke is +/// written without a style, and a document whose brushes are a new document's writes no brushes. +#[test] +fn a_brushed_stroke_that_paints_nothing_writes_no_brushes() { + let mut doc = Document::new(300.0, 200.0); + let mut line = + Node::path(doc.alloc_id(), shapes::line((20.0, 50.0).into(), (280.0, 60.0).into()), Appearance::basic(Paint::None, Paint::None, 1.0)); + line.appearance.stroke_mut().unwrap().brush = Some("3 pt. Round".into()); + put(&mut doc, line); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::BRUSHES), "{:?}", out.warnings); + let text = program(&doc); + assert!(!text.contains("%AI8_BeginPluginObject"), "no brushes"); + assert!(!text.contains("/KnownStyle"), "no art style"); +} + +/// The lines of `program` that hold brushes and what is drawn with them: the brush art, the plug-in +/// objects, the art styles and the layers. +fn brush_lines(program: &str) -> Vec<&str> { + let mut out = vec![]; + let mut inside = false; + for line in program.lines() { + if ["%AI8_BeginBrushPattern", "%AI8_BeginPluginObject", "%AI9_BeginArtStyles", "%%EndSetup"].iter().any(|m| line.starts_with(m)) { + inside = true; + } + if inside { + out.push(line); + } + if ["%AI8_EndBrushPattern", "%AI8_EndPluginObject", "%AI9_EndArtStyles"].iter().any(|m| line.starts_with(m)) { + inside = false; + } + } + out +} + +/// A document with brushes and brushed paths is written as the same bytes again, and what the reader +/// reads back is written with the same brushes, art styles and layers. +#[test] +fn brushes_write_the_same_bytes_again() { + let doc = brushes_document(); + let first = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(first.program, export_ai_editing(&doc, &opts()).unwrap().program); + let again = String::from_utf8(export_ai_editing(&read_back(&doc), &opts()).unwrap().program).unwrap(); + let first = String::from_utf8(first.program).unwrap(); + let (again, first) = (brush_lines(&again), brush_lines(&first)); + let differ = again.iter().zip(&first).enumerate().find(|(_, (a, b))| a != b); + assert_eq!(differ, None, "the first line that differs"); + assert_eq!(again.len(), first.len()); +} + +/// Brushes the reader wouldn't read back as they are are left out with a warning, each on its own +/// beside a brush that comes back, and each changed from a brush that comes back by the one setting +/// that leaves it out: an Art brush whose art is a group with a fill of its own, a Scatter brush whose +/// art is a path without points, an Art brush whose art is a group without members, Pattern and Bristle +/// brushes, Art brushes flipped along or across, overlapping, at another width, with a width that +/// varies, in another direction or scale, Art and Scatter brushes in Tints and Shades or Hue Shift, a +/// brush whose name holds a slash and a second brush of a name. A brush left out doesn't take its +/// name from a later one. +#[test] +fn brushes_the_reader_cant_read_are_left_out() { + use vectorcraft_brush::{ArtBrush, ArtScale, Bristle, Brush, BrushKind, Colorization, Direction, PatternBrush, Variation}; + let lib = brush_library(); + let keep = lib[0].clone(); + let (BrushKind::Scatter(scatter), BrushKind::Art(art)) = (&lib[1].kind, &lib[2].kind) else { panic!("library") }; + let hue = Colorization::HueShift { key: Color::rgb(1.0, 0.0, 0.0) }; + let art_with = |f: &dyn Fn(&mut ArtBrush)| { + let mut a = art.clone(); + f(&mut a); + BrushKind::Art(a) + }; + let mut painted_group = brush_art_node(); + painted_group.appearance = Appearance::basic(black_fill(), Paint::None, 0.0).into(); + let empty_path = Node::path(vectorcraft_doc::NodeId(1), PathData::new(vec![]), Appearance::basic(black_fill(), Paint::None, 0.0)); + let cases: Vec<(&str, BrushKind)> = vec![ + ("painted group", art_with(&|a| a.art = painted_group.clone())), + ("empty path", BrushKind::Scatter(vectorcraft_brush::Scatter { art: empty_path.clone(), ..scatter.clone() })), + ("empty group", art_with(&|a| a.art = Node::group(vectorcraft_doc::NodeId(1), vec![]))), + ("pattern", BrushKind::Pattern(PatternBrush::default())), + ("bristle", BrushKind::Bristle(Bristle::default())), + ("flipped along", art_with(&|a| a.flip_along = true)), + ("flipped across", art_with(&|a| a.flip_across = true)), + ("overlap", art_with(&|a| a.overlap = true)), + ("width", art_with(&|a| a.width = 50.0)), + ("width varies", art_with(&|a| a.width_mode = Some(Variation::Pressure))), + ("direction", art_with(&|a| a.direction = Direction::RightToLeft)), + ("proportional", art_with(&|a| a.scale = ArtScale::Proportional)), + ("art tints and shades", art_with(&|a| a.colorization = Colorization::TintsAndShades)), + ("art hue shift", art_with(&|a| a.colorization = hue)), + ( + "scatter tints and shades", + BrushKind::Scatter(vectorcraft_brush::Scatter { colorization: Colorization::TintsAndShades, ..scatter.clone() }), + ), + ("scatter hue shift", BrushKind::Scatter(vectorcraft_brush::Scatter { colorization: hue, ..scatter.clone() })), + ]; + let left_out = |extra: Vec, why: &str| { + let mut doc = Document::new(300.0, 200.0); + let mut lib = vec![keep.clone()]; + lib.extend(extra); + vectorcraft_brush::store(&mut doc, &lib); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::BRUSHES), "{why}: {:?}", out.warnings); + assert_eq!(vectorcraft_brush::library(&read_back(&doc)), std::slice::from_ref(&keep), "{why}"); + }; + for (why, kind) in cases { + left_out(vec![Brush { name: "Other".into(), kind }], why); + } + left_out(vec![Brush { name: "A/B".into(), ..keep.clone() }], "slash"); + left_out(vec![Brush { kind: BrushKind::Bristle(Bristle::default()), ..keep.clone() }], "a second brush of the name"); + // A Pattern brush named "X" is left out, so a Calligraphic brush named "X" after it comes back. A + // path with "X" is drawn with the Pattern brush, so it comes back as its drawn look. + let mut doc = Document::new(300.0, 200.0); + let x = Brush { name: "X".into(), ..keep.clone() }; + vectorcraft_brush::store(&mut doc, &[Brush { name: "X".into(), kind: BrushKind::Pattern(PatternBrush::default()) }, x.clone()]); + brushed(&mut doc, "X", (20.0, 50.0), (280.0, 60.0), 2.0); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::BRUSHES), "{:?}", out.warnings); + let back = read_back(&doc); + assert_eq!(vectorcraft_brush::library(&back), [x]); + let n = &back.layers[0].children().unwrap()[0]; + assert!(n.appearance.stroke().is_none_or(|s| s.brush.is_none()), "not with the other brush of the name: {n:#?}"); +} + +/// Brushes past the most the reader reads from one file are left out with a warning: of 4,097 +/// Calligraphic brushes, the first 4,096 come back. +#[test] +fn brushes_past_the_readers_count_are_left_out() { + let nib = brush_library().remove(0); + let lib: Vec = (0..4097).map(|i| vectorcraft_brush::Brush { name: format!("Nib {i}"), ..nib.clone() }).collect(); + let mut doc = Document::new(300.0, 200.0); + vectorcraft_brush::store(&mut doc, &lib); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::BRUSHES), "{:?}", out.warnings); + let back = vectorcraft_brush::library(&read_back(&doc)); + assert_eq!(back.len(), 4096); + assert_eq!(back.last().map(|b| b.name.as_str()), Some("Nib 4095")); +} + +/// A brush whose art the editing data would change (a stroke inside the path, written as its +/// outline) is left out, also after an object on the layers was already written with that change. +#[test] +fn a_brush_whose_art_would_change_is_left_out() { + use vectorcraft_brush::{ArtBrush, Brush, BrushKind}; + let inside = |doc: &mut Document| { + let mut n = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 40.0, 8.0)), Appearance::basic(Paint::None, black_fill(), 2.0)); + n.appearance.stroke_mut().unwrap().align = vectorcraft_doc::StrokeAlign::Inside; + n + }; + let mut doc = Document::new(300.0, 200.0); + let on_layer = inside(&mut doc); + put(&mut doc, on_layer); + let keep = brush_library().remove(0); + let art = inside(&mut doc); + vectorcraft_brush::store( + &mut doc, + &[keep.clone(), Brush { name: "Outlined".into(), kind: BrushKind::Art(ArtBrush { art, ..ArtBrush::default() }) }], + ); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::STROKES), "{:?}", out.warnings); + assert!(out.warnings.iter().any(|w| w == writer::BRUSHES), "{:?}", out.warnings); + assert_eq!(vectorcraft_brush::library(&read_back(&doc)), [keep]); +} + +/// Brushes past the art the reader copies into one file's brushes are left out with a warning, so +/// that what is written is what comes back: three Art brushes of 100,000 anchors each, of which the +/// reader keeps two. +#[test] +fn brushes_past_the_readers_art_limit_are_left_out() { + use vectorcraft_brush::{ArtBrush, Brush, BrushKind}; + let heavy = |id: u64| { + let points: Vec = + (0..100_000).map(|i| vectorcraft_geom::Point::new(f64::from(i) / 1000.0, if i % 2 == 0 { 0.0 } else { 4.0 })).collect(); + let path = PathData::single(vectorcraft_geom::SubPath::polyline(&points, true)); + Node::path(vectorcraft_doc::NodeId(id), path, Appearance::basic(black_fill(), Paint::None, 0.0)) + }; + let lib: Vec = + (1..=3).map(|i| Brush { name: format!("Heavy {i}"), kind: BrushKind::Art(ArtBrush { art: heavy(i), ..ArtBrush::default() }) }).collect(); + let mut doc = Document::new(300.0, 200.0); + vectorcraft_brush::store(&mut doc, &lib); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::BRUSHES), "{:?}", out.warnings); + let back: Vec = vectorcraft_brush::library(&read_back(&doc)).into_iter().map(|b| b.name).collect(); + assert_eq!(back, ["Heavy 1", "Heavy 2"]); + assert_eq!(program(&doc).matches("%AI8_BeginBrushPattern").count(), 2); + // The art of the brush left out isn't counted: there is room for it all with room for what is read. + let read = crate::import::objects_read(&out.program).unwrap(); + let room = export_within(&doc, &opts(), read).unwrap(); + assert!(!room.warnings.iter().any(|w| w == writer::OBJECT_LIMIT), "{read}: {:?}", room.warnings); +} + +/// A brush whose art doesn't fit within the object limit is left out with the limit's warning, and +/// what its art took is given back: a later brush whose art fits comes back. +#[test] +fn a_brush_whose_art_passes_the_object_limit_leaves_room_for_the_next() { + use vectorcraft_brush::{ArtBrush, Brush, BrushKind}; + let squares = |n: u64| { + let block = |i: u64| { + let x = i as f64 * 10.0; + Arc::new(Node::path( + vectorcraft_doc::NodeId(i + 1), + shapes::rectangle(Rect::new(x, 0.0, x + 5.0, 5.0)), + Appearance::basic(black_fill(), Paint::None, 0.0), + )) + }; + Node::group(vectorcraft_doc::NodeId(100), (0..n).map(block).collect()) + }; + let art = |name: &str, n: u64| Brush { name: name.into(), kind: BrushKind::Art(ArtBrush { art: squares(n), ..ArtBrush::default() }) }; + let mut doc = Document::new(300.0, 200.0); + vectorcraft_brush::store(&mut doc, &[art("Big", 6), art("Small", 2)]); + let all = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!all.warnings.iter().any(|w| w == writer::OBJECT_LIMIT), "{:?}", all.warnings); + let mut small = Document::new(300.0, 200.0); + vectorcraft_brush::store(&mut small, &[art("Small", 2)]); + let room = crate::import::objects_read(&export_ai_editing(&small, &opts()).unwrap().program).unwrap(); + let out = export_within(&doc, &opts(), room).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::OBJECT_LIMIT), "{:?}", out.warnings); + assert!(crate::import::objects_read(&out.program).unwrap() <= room); + let mut data = ZSTD_MARKER.to_vec(); + data.extend(ruzstd::encoding::compress_to_vec(out.program.as_slice(), ruzstd::encoding::CompressionLevel::Fastest)); + let back = crate::ai_alone(&data).unwrap().0; + let names: Vec = vectorcraft_brush::library(&back).into_iter().map(|b| b.name).collect(); + assert_eq!(names, ["Small"]); +} + +/// A graphic style with a brushed stroke, which is left out, takes no room from the layers' objects: +/// a document with a new document's brushes and no brushed path writes no brush art, so with room for +/// what its layers write, every object comes back. +#[test] +fn a_graphic_style_with_a_brush_takes_no_room_from_the_layers() { + let mut doc = Document::new(300.0, 200.0); + for i in 0..3 { + let x = 20.0 + f64::from(i) * 40.0; + let square = + Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(x, 20.0, x + 30.0, 50.0)), Appearance::basic(black_fill(), Paint::None, 0.0)); + put(&mut doc, square); + } + let room = crate::import::objects_read(&export_ai_editing(&doc, &opts()).unwrap().program).unwrap(); + let mut stroke = StrokeLayer::new(solid(Color::rgb(1.0, 0.0, 0.0)), 1.0); + stroke.brush = Some("3 pt. Round".into()); + let ap = Appearance { items: vec![AppearanceItem::Stroke(stroke)], effects: vec![], contents_index: None }; + doc.graphic_styles.push(vectorcraft_doc::GraphicStyle::new("Brushed", ap)); + let out = export_within(&doc, &opts(), room).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::OBJECT_LIMIT), "{room}: {:?}", out.warnings); + let program = String::from_utf8(out.program).unwrap(); + assert!(!program.contains("%AI8_BeginBrushPattern"), "no brush art"); +} + +/// A graphic style whose brushed stroke paints nothing comes back in the Graphic Styles panel. +#[test] +fn a_graphic_style_with_an_unpainted_brushed_stroke_comes_back() { + let mut doc = Document::new(300.0, 200.0); + let mut ap = Appearance::basic(black_fill(), Paint::None, 1.0); + ap.stroke_mut().unwrap().brush = Some("3 pt. Round".into()); + doc.graphic_styles.push(vectorcraft_doc::GraphicStyle::new("Unpainted brush", ap)); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::PANEL_STYLES), "{:?}", out.warnings); + assert!(read_back(&doc).graphic_style("Unpainted brush").is_some()); +} + +/// A brush whose art doesn't fit within the object limit after a path was written with it on its +/// stroke is left out with both warnings, and the path comes back as its drawn look. +#[test] +fn a_brushed_path_whose_brush_art_doesnt_fit_comes_back_as_its_look() { + let ribbon = brush_library().remove(2); + let mut doc = Document::new(300.0, 200.0); + vectorcraft_brush::store(&mut doc, std::slice::from_ref(&ribbon)); + brushed(&mut doc, "Ribbon", (20.0, 120.0), (280.0, 150.0), 1.5); + let all = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!all.warnings.iter().any(|w| w == writer::OBJECT_LIMIT || w == writer::BRUSHES), "{:?}", all.warnings); + let room = crate::import::objects_read(&all.program).unwrap() - 1; + let out = export_within(&doc, &opts(), room).unwrap(); + for w in [writer::OBJECT_LIMIT, writer::BRUSHES] { + assert!(out.warnings.iter().any(|x| x == w), "{w}: {:?}", out.warnings); + } + assert!(crate::import::objects_read(&out.program).unwrap() <= room); + let mut data = ZSTD_MARKER.to_vec(); + data.extend(ruzstd::encoding::compress_to_vec(out.program.as_slice(), ruzstd::encoding::CompressionLevel::Fastest)); + let back = crate::ai_alone(&data).unwrap().0; + assert!(vectorcraft_brush::library(&back).is_empty()); + let n = &back.layers[0].children().unwrap()[0]; + assert!(matches!(n.kind, NodeKind::Group { .. }), "the path's drawn look: {n:#?}"); +} + +/// An empty Brushes panel comes back empty, and a document with a new document's brushes and no +/// brushed path writes no brushes (the reader gives such a file a new document's). +#[test] +fn an_empty_brushes_panel_comes_back_empty() { + let mut doc = Document::new(300.0, 200.0); + assert!(!program(&doc).contains("%AI8_BeginPluginObject")); + assert_eq!(vectorcraft_brush::library(&read_back(&doc)), vectorcraft_brush::library(&doc)); + vectorcraft_brush::store(&mut doc, &[]); + assert!(vectorcraft_brush::library(&read_back(&doc)).is_empty()); +} + +/// A path with one of a new document's brushes writes the brushes the reader reads, and keeps its +/// brush. The new document's Art brush with other options, its Pattern brushes and its Bristle +/// brushes are left out with a warning, so the file opens without them. +#[test] +fn a_new_documents_brush_on_a_path_writes_the_brushes() { + let mut doc = Document::new(300.0, 200.0); + brushed(&mut doc, "3 pt. Round", (20.0, 50.0), (280.0, 60.0), 1.0); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::BRUSHES), "{:?}", out.warnings); + let back = read_back(&doc); + let n = &back.layers[0].children().unwrap()[0]; + assert_eq!(n.appearance.stroke().and_then(|s| s.brush.as_deref()), Some("3 pt. Round")); + let left_out = ["Arrow", "Chain", "Stitches", "Diamonds", "Bristle Round", "Bristle Flat Fan"]; + let want: Vec<&str> = vectorcraft_brush::defaults().iter().map(|b| b.name.as_str()).filter(|n| !left_out.contains(n)).collect(); + let lib = vectorcraft_brush::library(&back); + assert_eq!(lib.iter().map(|b| b.name.as_str()).collect::>(), want); + assert_eq!(vectorcraft_brush::defaults().len(), want.len() + left_out.len()); +} + +/// A path with one of a new document's brushes that doesn't fit within the object limit is left +/// out, and no brushes are written: the file opens with a new document's brushes, all of them. +#[test] +fn a_new_documents_brush_on_a_path_past_the_object_limit_writes_no_brushes() { + let empty = Document::new(300.0, 200.0); + let room = crate::import::objects_read(&export_ai_editing(&empty, &opts()).unwrap().program).unwrap(); + let mut doc = Document::new(300.0, 200.0); + brushed(&mut doc, "3 pt. Round", (20.0, 50.0), (280.0, 60.0), 1.0); + let out = export_within(&doc, &opts(), room).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::OBJECT_LIMIT), "{:?}", out.warnings); + assert!(!out.warnings.iter().any(|w| w == writer::BRUSHES), "{:?}", out.warnings); + assert!(!String::from_utf8(out.program).unwrap().contains("%AI8_BeginPluginObject")); +} + +/// On a large canvas the brushes are left out with a warning, and brushed paths come back as their +/// drawn look. +#[test] +fn a_large_canvas_leaves_the_brushes_out() { + let mut doc = Document::new(20000.0, 100.0); + vectorcraft_brush::store(&mut doc, &brush_library()); + brushed(&mut doc, "Nib", (20.0, 50.0), (280.0, 60.0), 2.0); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::BRUSHES), "{:?}", out.warnings); + assert!(!program(&doc).contains("%AI8_BeginPluginObject")); + assert!(matches!(read_back(&doc).layers[0].children().unwrap()[0].kind, NodeKind::Group { .. })); + // An empty panel is kept, without a warning. + let mut doc = Document::new(20000.0, 100.0); + vectorcraft_brush::store(&mut doc, &[]); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::BRUSHES), "{:?}", out.warnings); + assert!(vectorcraft_brush::library(&read_back(&doc)).is_empty()); +} + // ---------- variables ---------- /// A 200 × 100 document with variables: a text variable `name` bound to point type, a visibility @@ -7575,3 +9019,629 @@ fn conic_gradients_are_written_as_linear_gradients_with_their_stops() { let Some(Paint::Gradient(swatch)) = back.swatch("Sweep").map(|s| &s.paint) else { panic!("the swatch is lost") }; assert_eq!(swatch.gradient.kind, GradientKind::Linear); } + +/// The data has no diamond gradient: a diamond fill is the radial gradient through its square's +/// corners (centered on it, its vector and the aspect across it), with the same stops, and so is +/// a diamond gradient swatch, with a warning. +#[test] +fn diamond_gradients_are_written_as_radial_gradients_through_their_corners() { + let stops = + vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(0.6, SKY), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))]; + let mut g = GradientPaint::new(Gradient::new(GradientKind::Diamond, stops.clone())); + let (start, end) = (vectorcraft_geom::Point::new(100.0, 50.0), vectorcraft_geom::Point::new(150.0, 50.0)); + // A focal point (a plug-in's or a file's) draws nothing on a diamond and isn't written. + let focal = Some(vectorcraft_geom::Point::new(110.0, 55.0)); + g.geom = Some(vectorcraft_color::GradientGeom { start, end, aspect: 0.5, focal }); + let mut doc = Document::new(200.0, 100.0); + let id = doc.alloc_id(); + let l = doc.layers[0].id; + let fill = Paint::Gradient(Box::new(g.clone())); + doc.insert(Some(l), 0, Node::path(id, shapes::rectangle(Rect::new(20.0, 10.0, 180.0, 90.0)), Appearance::basic(fill, Paint::None, 0.0))).unwrap(); + let mut swatches: Vec = doc.swatches.iter().cloned().collect(); + swatches.push(Swatch { name: "Gem".into(), paint: Paint::Gradient(Box::new(GradientPaint { geom: None, ..g })), global: false, spot: false }); + doc.swatches = swatches.into(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w.contains("diamond gradients are written as radial gradients")), "{:?}", out.warnings); + let back = read_back(&doc); + let mut read = None; + back.walk(|n| { + if let Paint::Gradient(g) = n.appearance.fill_paint() { + read = Some(g.clone()); + } + }); + let read = read.expect("a gradient fill"); + assert_eq!(read.gradient.kind, GradientKind::Radial); + assert_eq!( + read.gradient.stops.iter().map(|s| (s.offset, s.color.to_hex())).collect::>(), + stops.iter().map(|s| (s.offset, s.color.to_hex())).collect::>() + ); + let geom = read.geom.unwrap(); + assert!(geom.start.distance(start) < 0.01 && geom.end.distance(end) < 0.01 && (geom.aspect - 0.5).abs() < 0.01, "{geom:?}"); + assert!(geom.focal.is_none_or(|f| f.distance(start) < 0.01), "{geom:?}"); + let Some(Paint::Gradient(swatch)) = back.swatch("Gem").map(|s| &s.paint) else { panic!("the swatch is lost") }; + assert_eq!(swatch.gradient.kind, GradientKind::Radial); +} + +/// The data has no spread: a fill that repeats or reflects holds its stops repeated across the +/// shape and reads back looking as the canvas paints it; a swatch holds its stops repeated along +/// its vector; both with a warning. +#[test] +fn spread_gradients_are_written_with_their_stops_repeated() { + use vectorcraft_color::GradientSpread; + for kind in [GradientKind::Linear, GradientKind::Radial] { + 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 mut g = GradientPaint::new(Gradient { spread: GradientSpread::Reflect, repeats: 2, ..Gradient::new(kind, stops) }); + let (start, end) = (vectorcraft_geom::Point::new(60.0, 50.0), vectorcraft_geom::Point::new(120.0, 50.0)); + g.geom = Some(vectorcraft_color::GradientGeom { start, end, aspect: 1.0, focal: None }); + let mut doc = Document::new(200.0, 100.0); + let id = doc.alloc_id(); + let l = doc.layers[0].id; + let fill = Paint::Gradient(Box::new(g.clone())); + doc.insert(Some(l), 0, Node::path(id, shapes::rectangle(Rect::new(20.0, 10.0, 180.0, 90.0)), Appearance::basic(fill, Paint::None, 0.0))) + .unwrap(); + let mut swatches: Vec = doc.swatches.iter().cloned().collect(); + swatches.push(Swatch { + name: "Bands".into(), + paint: Paint::Gradient(Box::new(GradientPaint { geom: None, ..g })), + global: false, + spot: false, + }); + doc.swatches = swatches.into(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!( + out.warnings.iter().any(|w| w.contains("gradients that repeat or reflect are written with their stops repeated")), + "{:?}", + out.warnings + ); + let back = read_back(&doc); + let st = vectorcraft_testkit::raster::perceptual_diff( + &vectorcraft_testkit::raster::render_artboard(&doc), + &vectorcraft_testkit::raster::render_artboard(&back), + 8.0, + ); + assert!((st.bad_pixels as f64) < 0.02 * st.pixels as f64, "{kind:?}: {} of {} pixels differ", st.bad_pixels, st.pixels); + let Some(Paint::Gradient(swatch)) = back.swatch("Bands").map(|s| &s.paint) else { panic!("the swatch is lost") }; + let colors: Vec = swatch.gradient.stops.iter().map(|s| s.color.to_hex()).collect(); + assert_eq!(colors, ["#ff0000", "#0000ff", "#0000ff", "#ff0000"], "{kind:?}"); + } +} + +/// A stroke's gradient that repeats is written with its stops repeated as far as the stroke's +/// miter joins reach, past the box the gradient is placed on, so a sharp join's tip shows the next +/// run rather than the color the gradient pads with; a straight line, which has no joins, keeps +/// every run within the stops the reader reads. +#[test] +fn a_stroke_spread_gradient_runs_on_into_its_miter_tips() { + use vectorcraft_color::GradientSpread; + 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 mut g = GradientPaint::new(Gradient { spread: GradientSpread::Repeat, repeats: 3, ..Gradient::new(GradientKind::Linear, stops) }); + // From the top of the box the gradient is placed on (the path's box grown by half the width). + let (start, end) = (vectorcraft_geom::Point::new(100.0, 15.0), vectorcraft_geom::Point::new(100.0, 85.0)); + g.geom = Some(vectorcraft_color::GradientGeom { start, end, aspect: 1.0, focal: None }); + let mut app = Appearance::basic(Paint::None, Paint::Gradient(Box::new(g)), 10.0); + for item in &mut app.items { + if let AppearanceItem::Stroke(s) = item { + (s.join, s.miter_limit) = (LineJoin::Miter, 10.0); + } + } + // A V whose apex's miter reaches about 10 pt above it, to y = 9.9. + let pts = [vectorcraft_geom::Point::new(60.0, 90.0), vectorcraft_geom::Point::new(100.0, 20.0), vectorcraft_geom::Point::new(140.0, 90.0)]; + let mut doc = Document::new(200.0, 100.0); + let id = doc.alloc_id(); + let l = doc.layers[0].id; + doc.insert(Some(l), 0, Node::path(id, PathData::new(vec![vectorcraft_geom::SubPath::polyline(&pts, false)]), app)).unwrap(); + let back = read_back(&doc); + let mut geom = None; + back.walk(|n| { + if let Paint::Gradient(g) = n.appearance.stroke_paint() { + geom = g.geom; + } + }); + let geom = geom.expect("the stroke keeps a gradient"); + assert!(geom.start.y.min(geom.end.y) < 9.9, "the runs start at {:?}", geom); + // A straight line has no joins: its 100 runs, 200 stops, fit the 256 the reader reads. + 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 mut g = GradientPaint::new(Gradient { spread: GradientSpread::Repeat, repeats: 100, ..Gradient::new(GradientKind::Linear, stops) }); + let (start, end) = (vectorcraft_geom::Point::new(50.0, 50.0), vectorcraft_geom::Point::new(150.0, 50.0)); + g.geom = Some(vectorcraft_color::GradientGeom { start, end, aspect: 1.0, focal: None }); + let line = PathData::new(vec![vectorcraft_geom::SubPath::polyline(&[start, end], false)]); + let mut doc = Document::new(200.0, 100.0); + let id = doc.alloc_id(); + let l = doc.layers[0].id; + doc.insert(Some(l), 0, Node::path(id, line, Appearance::basic(Paint::None, Paint::Gradient(Box::new(g)), 10.0))).unwrap(); + let mut stops = None; + read_back(&doc).walk(|n| { + if let Paint::Gradient(g) = n.appearance.stroke_paint() { + stops = Some(g.gradient.stops.len()); + } + }); + assert_eq!(stops, Some(200)); +} + +/// A conic fill (written linear, its stops repeated around its turn), a diamond fill (written +/// radial) and a swatch whose stops repeat more times than the 256 stops the reader reads stay +/// gradients: each holds its stops repeated as far as 256 stops go. +#[test] +fn spread_gradients_past_the_stops_the_reader_reads_stay_gradients() { + use vectorcraft_color::GradientSpread; + let three = || { + vec![ + GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), + GradientStop::new(0.5, Color::rgb(0.0, 1.0, 0.0)), + GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0)), + ] + }; + for kind in [GradientKind::Conic, GradientKind::Diamond] { + let mut g = GradientPaint::new(Gradient { spread: GradientSpread::Repeat, repeats: 100, ..Gradient::new(kind, three()) }); + let c = vectorcraft_geom::Point::new(100.0, 50.0); + g.geom = Some(vectorcraft_color::GradientGeom { start: c, end: c + vectorcraft_geom::Vec2::new(40.0, 0.0), aspect: 1.0, focal: None }); + let mut doc = Document::new(200.0, 100.0); + let id = doc.alloc_id(); + let l = doc.layers[0].id; + let fill = Paint::Gradient(Box::new(g)); + doc.insert(Some(l), 0, Node::path(id, shapes::rectangle(Rect::new(20.0, 10.0, 180.0, 90.0)), Appearance::basic(fill, Paint::None, 0.0))) + .unwrap(); + let back = read_back(&doc); + let mut stops = None; + back.walk(|n| { + if let Paint::Gradient(g) = n.appearance.fill_paint() { + stops = Some(g.gradient.stops.len()); + } + }); + let stops = stops.unwrap_or_else(|| panic!("{kind:?}: the gradient is written as a solid color")); + assert!((200..=crate::import::MAX_GRADIENT_STOPS).contains(&stops), "{kind:?}: {stops} stops"); + } + // Stops at 0.1 and 0.9 run from 0 to 1 as four: 70 runs are 280 stops. + let stops = vec![GradientStop::new(0.1, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(0.9, Color::rgb(0.0, 0.0, 1.0))]; + let g = GradientPaint::new(Gradient { spread: GradientSpread::Reflect, repeats: 70, ..Gradient::new(GradientKind::Linear, stops) }); + let mut doc = Document::new(200.0, 100.0); + let mut swatches: Vec = doc.swatches.iter().cloned().collect(); + swatches.push(Swatch { name: "Bands".into(), paint: Paint::Gradient(Box::new(g)), global: false, spot: false }); + doc.swatches = swatches.into(); + let back = read_back(&doc); + let Some(Paint::Gradient(swatch)) = back.swatch("Bands").map(|s| &s.paint) else { panic!("the swatch is lost") }; + assert!((200..=crate::import::MAX_GRADIENT_STOPS).contains(&swatch.gradient.stops.len()), "{} stops", swatch.gradient.stops.len()); +} + +/// An envelope named `Bent` of `kind` around a red rectangle (40, 20)-(100, 80) and a blue one +/// (100, 20)-(160, 80), with Fidelity `fidelity`, Edit Contents `editing` and `options`. +fn envelope_node( + doc: &mut Document, + kind: vectorcraft_doc::live::EnvelopeKind, + fidelity: f64, + editing: bool, + options: vectorcraft_doc::live::EnvelopeOptions, +) -> Node { + let content = vec![ + Arc::new(square(doc, Rect::new(40.0, 20.0, 100.0, 80.0), Color::rgb(1.0, 0.0, 0.0))), + Arc::new(square(doc, Rect::new(100.0, 20.0, 160.0, 80.0), Color::rgb(0.0, 0.0, 1.0))), + ]; + let kind = NodeKind::Envelope { content, kind: Box::new(kind), fidelity, editing, options, frame: Box::default() }; + named(Node::new(doc.alloc_id(), kind), "Bent") +} + +/// A 200 × 100 document of envelope `kind` ([`envelope_node`]) alone. +fn envelope_doc( + kind: vectorcraft_doc::live::EnvelopeKind, + fidelity: f64, + editing: bool, + options: vectorcraft_doc::live::EnvelopeOptions, +) -> Document { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let envelope = envelope_node(&mut doc, kind, fidelity, editing, options); + doc.insert(Some(layer), usize::MAX, envelope).unwrap(); + doc +} + +/// A grid of `rows`×`cols` patches over (30, 10)-(170, 90), row by row from the top left, with its +/// sixth point moved. +fn envelope_points(rows: u32, cols: u32) -> Vec { + let mut points: Vec = (0..=rows) + .flat_map(|r| { + (0..=cols).map(move |c| kurbo::Point::new(30.0 + 140.0 * f64::from(c) / f64::from(cols), 10.0 + 80.0 * f64::from(r) / f64::from(rows))) + }) + .collect(); + points[5] += kurbo::Vec2::new(5.0, -8.0); + points +} + +/// The envelopes written live: warps (vertical, with distortions, and twisted), meshes (with +/// handles of their own, one handle uneven, and with the smooth ones), top objects (a curved top +/// side, and two segments to the top and bottom sides), with Edit Contents off and on. +fn live_envelope_kinds() -> Vec<(&'static str, vectorcraft_doc::live::EnvelopeKind)> { + use vectorcraft_doc::live::{EnvelopeKind, H_RIGHT, WARP_NET, smooth_handles}; + let warp = |style: &str, bend: f64, h: f64, v: f64, horizontal: bool| EnvelopeKind::Warp { + style: style.into(), + bend, + h, + v, + horizontal, + version: WARP_NET, + }; + let points = envelope_points(2, 3); + let mut handles = smooth_handles(2, 3, &points); + handles[5][H_RIGHT] += kurbo::Vec2::new(4.0, 6.0); + let mut curved = kurbo::BezPath::new(); + curved.move_to((30.0, 10.0)); + curved.curve_to((70.0, -5.0), (130.0, -5.0), (170.0, 10.0)); + curved.line_to((170.0, 90.0)); + curved.line_to((30.0, 90.0)); + curved.close_path(); + let mut six = kurbo::BezPath::new(); + six.move_to((30.0, 10.0)); + for p in [(100.0, 0.0), (170.0, 10.0), (170.0, 90.0), (100.0, 95.0), (30.0, 90.0)] { + six.line_to(p); + } + six.close_path(); + vec![ + ("arc", warp("arc", 50.0, -20.0, 30.0, false)), + ("twist", warp("twist", -35.0, 0.0, 0.0, true)), + ("mesh", EnvelopeKind::Mesh { rows: 2, cols: 3, points: points.clone(), handles }), + ("smooth mesh", EnvelopeKind::Mesh { rows: 2, cols: 3, points, handles: vec![] }), + ("curved top object", EnvelopeKind::TopObject { path: PathData::from_bezpath(&curved), corners: None }), + ("six-anchor top object", EnvelopeKind::TopObject { path: PathData::from_bezpath(&six), corners: None }), + ] +} + +/// `doc` written and read back from its editing data: the top object on its first layer, the +/// writer's warnings and the reader's notes. +fn envelope_back(doc: &Document) -> (Node, Vec, Vec) { + let (p, warnings) = private_data(doc, &opts()).unwrap(); + let (back, notes) = crate::ai_alone(&p.data).unwrap(); + let a = back.layers[0].children().unwrap(); + assert_eq!(a.len(), 1, "{a:#?}"); + ((*a[0]).clone(), warnings, notes) +} + +/// Does reopened envelope kind `got` have the shape of `want`: a warp's style, bend, distortions +/// and orientation; a mesh's grid and the handles that draw (those inside the grid); the patch a top +/// object's outline makes? +fn same_envelope_kind(want: &vectorcraft_doc::live::EnvelopeKind, got: &vectorcraft_doc::live::EnvelopeKind) -> bool { + use vectorcraft_doc::live::{Coons, EnvelopeKind, H_DOWN, H_LEFT, H_RIGHT, H_UP, smooth_handles}; + let near = |a: kurbo::Point, b: kurbo::Point| a.distance(b) < 1e-3; + match (want, got) { + ( + EnvelopeKind::Warp { style, bend, h, v, horizontal, version }, + EnvelopeKind::Warp { style: s, bend: b, h: dh, v: dv, horizontal: hz, version: ver }, + ) => style == s && horizontal == hz && version == ver && [(bend, b), (h, dh), (v, dv)].iter().all(|(x, y)| (*x - *y).abs() < 1e-9), + (EnvelopeKind::Mesh { rows, cols, points, handles }, EnvelopeKind::Mesh { rows: r, cols: c, points: p, handles: hs }) => { + let own = if handles.is_empty() { smooth_handles(*rows, *cols, points) } else { handles.clone() }; + let inside = |i: usize, slot: usize| { + let (row, col) = (i / (*cols as usize + 1), i % (*cols as usize + 1)); + match slot { + s if s == H_LEFT => col > 0, + s if s == H_RIGHT => col < *cols as usize, + s if s == H_UP => row > 0, + s if s == H_DOWN => row < *rows as usize, + _ => false, + } + }; + (rows, cols) == (r, c) + && points.len() == p.len() + && points.iter().zip(p).all(|(a, b)| near(*a, *b)) + && own.iter().zip(hs).enumerate().all(|(i, (a, b))| (0..4).all(|s| !inside(i, s) || near(a[s].to_point(), b[s].to_point()))) + } + (EnvelopeKind::TopObject { path, corners }, EnvelopeKind::TopObject { path: p, corners: c }) => { + let (Some(a), Some(b)) = (Coons::from_top_object(path, *corners), Coons::from_top_object(p, *c)) else { return false }; + (0..=8).all(|j| { + (0..=8).all(|i| a.eval(f64::from(i) / 8.0, f64::from(j) / 8.0).distance(b.eval(f64::from(i) / 8.0, f64::from(j) / 8.0)) < 1e-2) + }) + } + _ => false, + } +} + +/// A PDF-compatible `.ai`'s editing data keeps a warp, a mesh and a top object envelope live, with +/// Edit Contents off and on: VectorCraft's reader opens each as the same envelope, its contents, +/// Fidelity, Edit Contents, Envelope Options and shape as saved, and its name, the drawn art saved +/// with it drawing as the envelope does. +#[test] +fn envelopes_are_read_back_live() { + use vectorcraft_doc::live::EnvelopeOptions; + for (name, kind) in live_envelope_kinds() { + for editing in [false, true] { + let doc = envelope_doc(kind.clone(), 50.0, editing, EnvelopeOptions::NEW); + let (back, warnings, notes) = envelope_back(&doc); + let what = format!("{name}, editing {editing}"); + assert!(!warnings.iter().any(|w| w == writer::ENVELOPES), "{what}: {warnings:?}"); + assert!(!notes.iter().any(|w| w == crate::import::ENVELOPE_DRAWN), "{what}: {notes:?}"); + let NodeKind::Envelope { content, kind: got, fidelity, editing: e, options, frame } = &back.kind else { panic!("{what}: {back:#?}") }; + assert_eq!((*fidelity, *e, *options, **frame), (50.0, editing, EnvelopeOptions::NEW, Affine::IDENTITY), "{what}"); + assert!(same_envelope_kind(&kind, got), "{what}: {got:?}"); + assert_eq!(back.name.as_deref(), Some("Bent"), "{what}"); + let colors: Vec> = content.iter().map(|c| c.appearance.fill_paint().color()).collect(); + assert_eq!(colors, [Some(Color::rgb(1.0, 0.0, 0.0)), Some(Color::rgb(0.0, 0.0, 1.0))], "{what}"); + // Saved again as it opened (a top object now with the corners the file gives it), it + // opens as the same envelope again. + let mut again = Document::new(200.0, 100.0); + let layer = again.layers[0].id; + again.insert(Some(layer), usize::MAX, back.clone()).unwrap(); + let (twice, warnings, notes) = envelope_back(&again); + assert!(!warnings.iter().any(|w| w == writer::ENVELOPES), "{what}, saved again: {warnings:?}"); + let NodeKind::Envelope { kind: twice, .. } = &twice.kind else { panic!("{what}, saved again: {twice:#?} {notes:?}") }; + assert!(same_envelope_kind(&kind, twice), "{what}, saved again: {twice:?}"); + } + } +} + +/// An envelope that is a symbol's art is written live in the symbol's definition, and the symbol +/// opens with it as a live envelope. +#[test] +fn an_envelope_in_a_symbol_is_read_back_live() { + use vectorcraft_doc::live::EnvelopeOptions; + let kinds = live_envelope_kinds(); + for (name, kind) in kinds { + let mut doc = Document::new(200.0, 100.0); + let art = envelope_node(&mut doc, kind.clone(), 50.0, false, EnvelopeOptions::NEW); + doc.symbols.push(Symbol { dynamic: false, name: "Bent".into(), art: Arc::new(art) }); + let instance = Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "Bent".into(), xf: Affine::translate((10.0, 5.0)) }); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, instance).unwrap(); + let (p, warnings) = private_data(&doc, &opts()).unwrap(); + assert!(!warnings.iter().any(|w| w == writer::ENVELOPES), "{name}: {warnings:?}"); + let (back, notes) = crate::ai_alone(&p.data).unwrap(); + let symbol = back.symbols.iter().find(|s| s.name == "Bent").unwrap_or_else(|| panic!("{name}: {:?}", back.symbols)); + let mut envelopes = vec![]; + symbol.art.walk(&mut |n| { + if let NodeKind::Envelope { kind, .. } = &n.kind { + envelopes.push((**kind).clone()); + } + }); + assert!(matches!(envelopes.as_slice(), [k] if same_envelope_kind(&kind, k)), "{name}: {envelopes:?} {notes:?}"); + } +} + +/// An envelope with an opacity mask comes back live with its mask, and the plugin's `XP` follows +/// the envelope's dictionary rather than its mask's art. +#[test] +fn an_envelope_with_an_opacity_mask_is_read_back_live() { + use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions}; + let kind = EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] }; + let mut doc = Document::new(200.0, 100.0); + let mut envelope = envelope_node(&mut doc, kind.clone(), 50.0, false, EnvelopeOptions::NEW); + let gray = square(&mut doc, Rect::new(40.0, 20.0, 160.0, 80.0), Color::gray(0.5)); + let art = group(&mut doc, vec![gray], false); + envelope.extras_mut().mask = Some(Box::new(OpacityMask::new(art, false))); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, envelope).unwrap(); + let text = program(&doc); + let (xp, mask) = (text.find(") 1 0 0 XP").unwrap_or(0), text.find("(AI9_Mask)").unwrap_or(usize::MAX)); + assert!(mask < xp, "{text}"); + let (back, warnings, notes) = envelope_back(&doc); + assert!(!warnings.iter().any(|w| w == writer::ENVELOPES), "{warnings:?}"); + let NodeKind::Envelope { kind: got, .. } = &back.kind else { panic!("{back:#?} {notes:?}") }; + assert!(same_envelope_kind(&kind, got), "{got:?}"); + assert!(back.extras().mask.is_some(), "{back:#?}"); +} + +/// As many envelopes are written live as the reader checks in one file, and the ones after them +/// as their art, with a warning. +#[test] +fn envelopes_past_the_readers_checks_are_written_as_their_art() { + use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions}; + let limit = crate::import::ENVELOPE_CHECKS; + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + for _ in 0..=limit { + let points = [(30.0, 10.0), (170.0, 0.0), (30.0, 90.0), (170.0, 90.0)].map(kurbo::Point::from).to_vec(); + let kind = EnvelopeKind::Mesh { rows: 1, cols: 1, points, handles: vec![] }; + let envelope = envelope_node(&mut doc, kind, 50.0, false, EnvelopeOptions::NEW); + doc.insert(Some(layer), usize::MAX, envelope).unwrap(); + } + let (p, warnings) = private_data(&doc, &opts()).unwrap(); + assert!(warnings.iter().any(|w| w == writer::ENVELOPES), "{warnings:?}"); + let (back, notes) = crate::ai_alone(&p.data).unwrap(); + let a = back.layers[0].children().unwrap(); + let live = a.iter().filter(|n| matches!(n.kind, NodeKind::Envelope { .. })).count(); + assert_eq!((a.len(), live), (limit + 1, limit), "{notes:?}"); + assert!(!notes.iter().any(|n| n == crate::import::ENVELOPE_DRAWN), "{notes:?}"); +} + +/// Every Envelope Options switch and the ends of Fidelity come back as saved. +#[test] +fn envelope_options_and_fidelity_are_read_back() { + use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions, PreserveShape}; + let kind = EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] }; + let new = EnvelopeOptions::NEW; + let all = [ + (new, 50.0), + (EnvelopeOptions { anti_alias: false, ..new }, 0.0), + (EnvelopeOptions { preserve_shape: PreserveShape::Transparency, ..new }, 100.0), + (EnvelopeOptions { distort_linear_gradients: true, distort_pattern_fills: true, ..new }, 30.0), + (EnvelopeOptions { distort_appearance: false, ..new }, 50.0), + ]; + for (options, fidelity) in all { + let (back, _, notes) = envelope_back(&envelope_doc(kind.clone(), fidelity, false, options)); + let NodeKind::Envelope { options: o, fidelity: f, .. } = &back.kind else { panic!("{options:?}: {back:#?} {notes:?}") }; + assert_eq!((*o, *f), (options, fidelity)); + } +} + +/// With Distort Appearance, an envelope whose contents map from their bounds with their strokes +/// saves that box's size, and opens mapping from the same box. +#[test] +fn an_envelope_mapping_from_its_contents_strokes_is_read_back() { + use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions, envelope_content_boxes, envelope_stroke_margin}; + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut envelope = envelope_node( + &mut doc, + EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] }, + 50.0, + false, + EnvelopeOptions::NEW, + ); + let NodeKind::Envelope { content, options, .. } = &mut envelope.kind else { unreachable_envelope() }; + for c in content.iter_mut() { + let fill = Arc::make_mut(c).appearance.fill_paint(); + Arc::make_mut(c).appearance = Appearance::basic(fill, solid(Color::BLACK), 8.0).into(); + } + let (stroked, plain) = envelope_content_boxes(content, Affine::IDENTITY).unwrap(); + options.bounds_margin = envelope_stroke_margin(stroked, plain).unwrap(); + let margin = options.bounds_margin; + assert!(margin.iter().all(|m| *m > 0.0), "{margin:?}"); + doc.insert(Some(layer), usize::MAX, envelope).unwrap(); + let (back, warnings, notes) = envelope_back(&doc); + assert!(!warnings.iter().any(|w| w == writer::ENVELOPES), "{warnings:?}"); + let NodeKind::Envelope { options, .. } = &back.kind else { panic!("{back:#?} {notes:?}") }; + assert!(options.bounds_margin.iter().zip(margin).all(|(a, b)| (a - b).abs() < 1e-4), "{:?} {margin:?}", options.bounds_margin); +} + +/// A test's stand-in for a node that must be an envelope. +fn unreachable_envelope() -> ! { + panic!("not an envelope") +} + +/// The record is written in the order the reader reads it: on `%_` lines the group holding the +/// grid, its dictionary with the options, the contents' block and the kind, then the distorted art +/// on plain lines and the plugin's `XP`. While the contents are edited, the group holds them and +/// the dictionary the grid. +#[test] +fn an_envelope_is_written_in_the_order_the_reader_reads_it() { + use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions}; + let kind = EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] }; + for editing in [false, true] { + let text = program(&envelope_doc(kind.clone(), 50.0, editing, EnvelopeOptions::NEW)); + let at = |s: &str| text.find(s).unwrap_or_else(|| panic!("{s} missing: {text}")); + let (group, mesh, dictionary, block, key, style, xp) = ( + at("%_u\n"), + at("%_/Mesh X!"), + at("%_131073 /Int (AIDeformOptionsKey) ,\n%_50 /Int (AIDeformFidelityKey) ,\n"), + at("%_X=\n"), + at("%_ (AIDeformArtKey) ,\n"), + at("%_2 /Int (AIDeformStyle) ,\n%_;\n%_\n%_9 () XW\n"), + at("(Adobe Deform Plugin) 1 0 0 XP\n"), + ); + assert!(group < dictionary && dictionary < block && block < key && key < style && style < xp, "{text}"); + assert_eq!(block < mesh, editing, "{text}"); + assert!(text.contains(&format!("%_{} /Bool (AIDeformEditModeKey) ,\n", u8::from(editing))), "{text}"); + // The distorted art is one group on plain lines, named as the envelope, right before the `XP`. + let drawn = &text[style..xp]; + assert!(drawn.contains("\nu\n") && drawn.contains("(Bent) ; (AI10_ArtUID) ,"), "{drawn}"); + // The contents are on `%_` lines only: drawn once on plain lines, as the distorted art. + assert_eq!(text.matches("(Adobe Deform Plugin)").count(), 1, "{text}"); + } +} + +/// Envelopes the reader would open in another shape, or not at all, are written as their distorted +/// art with a warning, and open as that art: an envelope of type, one in a turned frame, a warp drawn +/// without its style's net, a mesh the reader would lay out the other way round, a top object +/// whose sides don't pair up, a Fidelity that isn't a whole number and bounds margins kept with +/// Distort Appearance off. Other live objects keep their own warning. +#[test] +fn envelopes_the_reader_cannot_open_live_are_written_as_their_art() { + use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions}; + let base = + || envelope_doc(EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] }, 50.0, false, EnvelopeOptions::NEW); + let change = |f: &dyn Fn(&mut NodeKind)| { + let mut doc = base(); + let id = doc.layers[0].children().unwrap()[0].id; + f(&mut doc.node_mut(id).unwrap().kind); + doc + }; + let typed = change(&|k| { + if let NodeKind::Envelope { content, .. } = k { + let t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(50.0, 50.0), "Type", vectorcraft_doc::CharStyle::default()); + content.push(Arc::new(Node::new(vectorcraft_doc::NodeId(9_000), NodeKind::Text(Box::new(t))))); + } + }); + let turned = change(&|k| { + if let NodeKind::Envelope { frame, .. } = k { + **frame = Affine::rotate(0.3); + } + }); + let old_warp = change(&|k| { + if let NodeKind::Envelope { kind, .. } = k { + **kind = EnvelopeKind::Warp { style: "arc".into(), bend: 50.0, h: 0.0, v: 0.0, horizontal: true, version: 0 }; + } + }); + // Columns down the page and rows across: the reader turns the grid round. + let sideways = change(&|k| { + if let NodeKind::Envelope { kind, .. } = k { + let points = + (0..=3).flat_map(|r| (0..=2).map(move |c| kurbo::Point::new(30.0 + 70.0 * f64::from(c), 10.0 + 80.0 * f64::from(r) / 3.0))).collect(); + **kind = EnvelopeKind::Mesh { rows: 2, cols: 3, points: transpose(points, 3, 2), handles: vec![] }; + } + }); + let mut uneven = kurbo::BezPath::new(); + uneven.move_to((30.0, 10.0)); + for p in [(100.0, 0.0), (170.0, 10.0), (170.0, 90.0), (30.0, 90.0)] { + uneven.line_to(p); + } + uneven.close_path(); + let lopsided = change(&|k| { + if let NodeKind::Envelope { kind, .. } = k { + **kind = EnvelopeKind::TopObject { path: PathData::from_bezpath(&uneven), corners: None }; + } + }); + let fractional = change(&|k| { + if let NodeKind::Envelope { fidelity, .. } = k { + *fidelity = 50.5; + } + }); + let margin_kept = change(&|k| { + if let NodeKind::Envelope { options, .. } = k { + options.distort_appearance = false; + options.bounds_margin = [0.5; 4]; + } + }); + let cases = [ + ("type", typed), + ("turned", turned), + ("old warp", old_warp), + ("sideways mesh", sideways), + ("lopsided top object", lopsided), + ("fractional fidelity", fractional), + ("margin kept", margin_kept), + ]; + for (what, doc) in cases { + let text = program(&doc); + assert!(!text.contains("AIDeformOptionsKey"), "{what}: {text}"); + let (back, warnings, _) = envelope_back(&doc); + assert!(warnings.iter().any(|w| w == writer::ENVELOPES), "{what}: {warnings:?}"); + assert!(!warnings.iter().any(|w| w == writer::LIVE), "{what}: {warnings:?}"); + assert!(matches!(back.kind, NodeKind::Group { .. }), "{what}: {back:#?}"); + } + let blend = export_ai_editing(&blend_doc(), &opts()).unwrap(); + assert!(blend.warnings.iter().any(|w| w == writer::LIVE) && !blend.warnings.iter().any(|w| w == writer::ENVELOPES), "{:?}", blend.warnings); +} + +/// `points`, a grid of `rows + 1` rows of `cols + 1` points, as `cols + 1` rows of `rows + 1`. +fn transpose(points: Vec, rows: usize, cols: usize) -> Vec { + (0..=cols).flat_map(|c| (0..=rows).map(move |r| (r, c))).map(|(r, c)| points[r * (cols + 1) + c]).collect() +} + +/// An envelope with its contents in an opacity mask's art is written as its art there, and an +/// envelope in a group stays live. +#[test] +fn envelopes_in_masks_are_written_as_their_art_and_in_groups_stay_live() { + let doc = envelopes_document(); + let (p, warnings) = private_data(&doc, &opts()).unwrap(); + let (back, notes) = crate::ai_alone(&p.data).unwrap(); + assert!(warnings.iter().any(|w| w == writer::ENVELOPES), "{warnings:?}"); + let mut live = 0; + back.walk(|n| live += usize::from(matches!(n.kind, NodeKind::Envelope { .. }))); + assert_eq!(live, 3, "{notes:?}"); +} + +/// A warp, a mesh envelope with its contents edited, a top object in a group, and an envelope in an +/// opacity mask's art. +fn envelopes_document() -> Document { + use vectorcraft_doc::live::EnvelopeOptions; + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let kinds = live_envelope_kinds(); + let kind = |name: &str| kinds.iter().find(|(n, _)| *n == name).map(|(_, k)| k.clone()).unwrap(); + let warp = envelope_node(&mut doc, kind("arc"), 50.0, false, EnvelopeOptions::NEW); + let mesh = envelope_node(&mut doc, kind("mesh"), 50.0, true, EnvelopeOptions::NEW); + let top = envelope_node(&mut doc, kind("six-anchor top object"), 50.0, false, EnvelopeOptions::NEW); + let top = group(&mut doc, vec![top], false); + let mut masked = square(&mut doc, Rect::new(0.0, 0.0, 200.0, 100.0), Color::gray(0.5)); + let mask_art = envelope_node(&mut doc, kind("twist"), 50.0, false, EnvelopeOptions::NEW); + masked.extras_mut().mask = Some(Box::new(OpacityMask::new(mask_art, false))); + for n in [warp, mesh, top, masked] { + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + doc +} diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index afa6412561..7db5d11896 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -15,6 +15,8 @@ use vectorcraft_pathops::BoolOp; use crate::ai_ops::{self, unit}; use crate::ps; +mod brushes; +mod envelopes; mod images; mod paints; mod styles; @@ -22,6 +24,10 @@ mod symbols; mod texts; mod variables; +#[cfg(test)] +pub(super) use brushes::BRUSHES; +#[cfg(test)] +pub(super) use envelopes::ENVELOPES; pub(super) use styles::{LARGE_CANVAS_STYLES, style_links, styled_objects}; #[cfg(test)] pub(super) use styles::{PANEL_EMPTY, PANEL_STYLES, STYLE_LINKS, same_appearance}; @@ -30,7 +36,7 @@ pub(super) use images::PAYLOAD; #[cfg(test)] pub(super) use images::{IMAGE_DEPTH, IMAGES, LINKS_EMBEDDED}; #[cfg(test)] -pub(super) use paints::{GRADIENT_MIX, GRADIENT_SHAPES, GRADIENTS, STOP_LINKS, SWATCH_PLACEMENT, free_gradient_name}; +pub(super) use paints::{GRADIENT_HUE, GRADIENT_MIX, GRADIENT_SHAPES, GRADIENTS, STOP_LINKS, SWATCH_PLACEMENT, free_gradient_name}; #[cfg(test)] pub(super) use symbols::{MISSING_SYMBOL, SYMBOL_ART, SYMBOL_COUNT, SYMBOL_OPTIONS}; #[cfg(test)] @@ -49,9 +55,8 @@ pub(super) const PATTERN_TILES: &str = "pattern fills with more tiles than a fil pub(super) const CLIPPING: &str = "clipping groups and clipping layers whose clipping object isn't a path, and the clipping groups inside them, are written as their art cut to that object in the editing data for other apps"; pub(super) const CLIP_PAINT: &str = "the fills and strokes of clipping paths that a plain fill and line can't draw are written as paths of their own inside the clipping (fills under the clipped art, strokes over it) in the editing data for other apps"; pub(super) const CLIP_PAINT_MASKS: &str = "the opacity masks of clipping paths whose fills and strokes are written as paths of their own stay on the clipping path, not on those paths, in the editing data for other apps"; -pub(super) const LIVE: &str = - "blends, envelopes, meshes, repeats, placed documents and intertwines are written as their art in the editing data for other apps"; -const STROKES: &str = "strokes a plain line can't draw (inside or outside the path, variable width, dots, dashes fitted to corners, gradients, patterns, arrowheads) are written as filled outlines, and brushed strokes as their brush's art, in the editing data for other apps"; +pub(super) const LIVE: &str = "blends, meshes, repeats, placed documents and intertwines are written as their art in the editing data for other apps"; +pub(super) const STROKES: &str = "strokes a plain line can't draw (inside or outside the path, variable width, dots, dashes fitted to corners, gradients, patterns, arrowheads) are written as filled outlines, and brushed strokes as their brush's art, in the editing data for other apps"; pub(super) const ITEM_TRANSPARENCY: &str = "the opacity and blending modes of single fills and strokes are left out of the editing data for other apps"; pub(super) const LAYER_MASKS: &str = "opacity masks on layers are left out of the editing data for other apps"; @@ -255,6 +260,16 @@ pub(super) struct Writer<'a> { /// An object's drawn look is being written: no object in it is written with a style, and its /// effects are the style's. in_look: bool, + /// The brushes written ([`brushes`]). + brush_set: brushes::Brushes, + /// Brushes may be written; false on a large canvas, where they are left out. + pub(super) brushes_live: bool, + /// The object just written is an envelope's distorted art, which the plugin's `XP` follows + /// ([`Self::envelope`]). + deform: bool, + /// How many more envelopes may be written live: as many as the reader checks in one file + /// ([`crate::import::ENVELOPE_CHECKS`]). + envelopes_left: usize, } impl<'a> Writer<'a> { @@ -310,6 +325,10 @@ impl<'a> Writer<'a> { styled: HashMap::new(), styles: styles::Styles::default(), in_look: false, + brush_set: brushes::Brushes::default(), + brushes_live: true, + deform: false, + envelopes_left: crate::import::ENVELOPE_CHECKS, objects: 0, left_out: 0, definition_objects: 0, @@ -635,7 +654,7 @@ impl<'a> Writer<'a> { } NodeKind::Compound { rule, .. } => self.shape(n, &compound_path(n), *rule, xy), NodeKind::Text(_) => self.text(n, xy), - NodeKind::Image(im) => self.image(im, xy), + NodeKind::Image(im) => self.image(&self.doc.shown_image(n, im), xy), NodeKind::SymbolInstance { symbol, xf } if self.live_instance_in_room(n, symbol, *xf) => self.symbol_instance(symbol, *xf, xy), NodeKind::SymbolInstance { symbol, xf } => { if !self.open_group("u") { @@ -685,29 +704,16 @@ impl<'a> Writer<'a> { } self.end_group("U", xy); } - NodeKind::Blend { .. } - | NodeKind::Envelope { .. } - | NodeKind::Mesh(_) - | NodeKind::Repeat(_) - | NodeKind::PlacedDocument(_) - | NodeKind::Intertwine { .. } => { - if !self.open_group("u") { - return; - } - self.warn(LIVE); - if self.nest < MAX_NEST { - let g = vectorcraft_effects::expand_live_deep(Some(self.doc), n); - self.nest += 1; - for c in g.children().map(Vec::as_slice).unwrap_or_default() { - self.node(c); - } - self.nest -= 1; - } - self.end_group("U", xy); + NodeKind::Envelope { .. } if self.envelope(n, xy) => {} + NodeKind::Envelope { .. } => self.drawn_art(n, xy, Some(envelopes::ENVELOPES)), + NodeKind::Blend { .. } | NodeKind::Mesh(_) | NodeKind::Repeat(_) | NodeKind::PlacedDocument(_) | NodeKind::Intertwine { .. } => { + self.drawn_art(n, xy, Some(LIVE)); } // Ruler guides are kept in the document's native copy only. NodeKind::RulerGuide { .. } => {} } + // Taken before the dictionary, whose opacity mask art may hold envelopes of its own. + let deform = std::mem::take(&mut self.deform); if self.body.len() > start { // A group's dictionary goes between its end and its state block. let block = (self.block_end == self.body.len() && self.block_start >= start).then(|| self.body.split_off(self.block_start)); @@ -717,6 +723,29 @@ impl<'a> Writer<'a> { self.body.push_str(&b); } } + // An envelope's plugin `XP` follows its distorted art, after the art's state block. + if deform { + self.line(&envelopes::plugin_line()); + } + } + + /// Live object `n`, of transparency `xy`, as a group of its art, with `warning` when it is given. + fn drawn_art(&mut self, n: &Node, xy: Xy, warning: Option<&str>) { + if !self.open_group("u") { + return; + } + if let Some(w) = warning { + self.warn(w); + } + if self.nest < MAX_NEST { + let g = vectorcraft_effects::expand_live_deep(Some(self.doc), n); + self.nest += 1; + for c in g.children().map(Vec::as_slice).unwrap_or_default() { + self.node(c); + } + self.nest -= 1; + } + self.end_group("U", xy); } /// `n`'s `/ArtDictionary`, after it, when it has a name (`AI10_ArtUID`, see [`Self::take_id`]), @@ -896,7 +925,7 @@ impl<'a> Writer<'a> { self.warn_cut(Some(first)); return self.clip_contents(children); }; - let items = self.items(first, path.to_bezpath().bounding_box()); + let items = self.items(first, &path.to_bezpath()); let painted = self.plain_paint(&items); // The clipping path goes after the others, so its objects are counted first. let subpaths: Vec<&SubPath> = path.subpaths.iter().filter(|sp| !sp.anchors.is_empty()).collect(); @@ -1004,7 +1033,7 @@ impl<'a> Writer<'a> { if path.is_empty() { return; } - let items = self.items(n, path.to_bezpath().bounding_box()); + let items = self.items(n, &path.to_bezpath()); if items.iter().any(|i| i.opacity() < 1.0 || i.blend() != BlendMode::Normal) { self.warn(ITEM_TRANSPARENCY); } @@ -1028,7 +1057,13 @@ impl<'a> Writer<'a> { AppearanceItem::Fill(f) => self.fill_object(path, rule, f, xy), AppearanceItem::Stroke(s) if self.direct_stroke(s) => self.path_object(path, rule, None, Some(s), xy), AppearanceItem::Stroke(s) => { - self.warn(STROKES); + // In a styled path's or compound path's drawn look the stroke, brushed or not, is kept + // by the object's art style, which is written only when the reader reads the object's + // appearance (and its brush) back from it. A styled group's style holds no fills or + // strokes: its members are written again after the look, and warn there. + if !self.in_look { + self.warn(STROKES); + } self.wrote_fixed = true; if self.brush_art(path, s, xy) { return; @@ -1257,6 +1292,10 @@ impl<'a> Writer<'a> { return; } self.warn(TYPE); + // The outlines keep the sizes Dynamic Text draws the type at, but not the setting. + if matches!(&n.kind, NodeKind::Text(t) if t.dynamic_text) { + self.warn(DYNAMIC_TEXT); + } let doc = self.doc; let resolved = match &n.kind { NodeKind::Text(t) => Some(doc.inline_resolved(t).into_owned()), @@ -1339,8 +1378,9 @@ impl<'a> Writer<'a> { self.plain_color(*color, stroke); } - /// A color that names no swatch: `g` (gray), `k` (CMYK), else `c m y k r g b Xa` (RGB, and - /// Lab as RGB), with its CMYK equivalent. + /// A color that names no swatch: `g` (gray), `k` (CMYK), else `c m y k r g b Xa` (RGB in the + /// working RGB space, and Lab as display RGB), with its CMYK equivalent (an RGB color's from its + /// values as written, a Lab color's from its Lab values). fn plain_color(&mut self, color: Color, stroke: bool) { let s = &mut self.body; let op = |fill: &'static str, line: &'static str| if stroke { line } else { fill }; @@ -1355,19 +1395,22 @@ impl<'a> Writer<'a> { let _ = writeln!(s, "{}", op("k", "K")); } Color::Rgb { .. } | Color::Lab { .. } => { - let cmyk = self.cms.to_cmyk(&color, self.cms.settings().intent).map(unit); + let source = if matches!(color, Color::Rgb { .. }) { ai_ops::as_written(color) } else { color }; + let cmyk = self.cms.to_cmyk(&source, self.cms.settings().intent).map(unit); ps::push_nums(s, &cmyk.map(f64::from)); - ps::push_nums(s, &color.to_rgb().map(|v| f64::from(unit(v)))); + ps::push_nums(s, &ai_ops::rgb_values(color).map(f64::from)); let _ = writeln!(s, "{}", op("Xa", "XA")); } } } /// A spot (`spot`) or global process color `name` of full color `full` at `tint`, written to - /// `s`: its CMYK equivalent, its RGB or Lab values, the name, how much lighter than the full - /// color, and for any but a CMYK spot color (`x`) the model (0 CMYK, 1 RGB, 2 Lab) before - /// `Xx` (spot) or `Xk` (global process). + /// `s`: its CMYK equivalent (from its RGB or Lab values as written), its RGB or Lab values + /// (clamped as [`ai_ops::as_written`] clamps them), the name, how much lighter than the full + /// color, and for any but a CMYK spot color (`x`) the model (0 CMYK, 1 RGB, 2 Lab) before `Xx` + /// (spot) or `Xk` (global process). fn named(&self, s: &mut String, name: &str, full: Color, tint: f32, spot: bool, stroke: bool) { + let full = ai_ops::as_written(full); let cmyk = self.cms.to_cmyk(&self.doc.linked_color(full, spot), self.cms.settings().intent).map(unit); ps::push_nums(s, &cmyk.map(f64::from)); let model = match full { @@ -1463,7 +1506,8 @@ impl<'a> Writer<'a> { true } - /// The spot color swatches, with their full colors' CMYK equivalents, for the header. + /// The spot color swatches, with their full colors' CMYK equivalents (as the palette writes + /// them), for the header. pub(super) fn spot_swatches(&self) -> Vec<(String, [f32; 4])> { let intent = self.cms.settings().intent; self.doc @@ -1471,7 +1515,7 @@ impl<'a> Writer<'a> { .filter(|sw| sw.spot) .filter_map(|sw| match sw.paint { Paint::Solid { color, swatch: None, .. } => { - Some((sw.name.clone(), self.cms.to_cmyk(&self.doc.linked_color(color, true), intent).map(unit))) + Some((sw.name.clone(), self.cms.to_cmyk(&self.doc.linked_color(ai_ops::as_written(color), true), intent).map(unit))) } _ => None, }) diff --git a/crates/eps/src/ai_editing/writer/brushes.rs b/crates/eps/src/ai_editing/writer/brushes.rs new file mode 100644 index 0000000000..2c281e702d --- /dev/null +++ b/crates/eps/src/ai_editing/writer/brushes.rs @@ -0,0 +1,558 @@ +//! Brushes: the document's brushes as the `.ai` reader reads them ([`crate::import`]'s `.ai` reader, +//! `brush.rs`), and the brush filter of a brushed stroke in an art style (`style.rs`). +//! +//! Each brush is a plug-in object (`%AI8_BeginPluginObject`, the plug-in's name, the brush's name, +//! its parameters as strings that `-` continues and `.` ends, `%AI8_EndPluginObject`), after the +//! brush manager's order of them all, in a non-printing block after the symbols. The art of a +//! Scatter or Art brush is a `%AI8_BeginBrushPattern` section (its name; a group of the art's frame, +//! an unpainted rectangle at the art's geometric bounds, and the art, or the art alone when it has no +//! width or height; its end) in a non-printing block before the symbols. Each brush is checked with +//! the reader's own reading ([`crate::import::read_brush_object`]) before it is written: one the +//! reader would read as another brush is left out. + +use std::collections::HashSet; +use std::fmt::Write; +use std::sync::Arc; + +use vectorcraft_brush::{ArtBrush, ArtScale, Brush, BrushKind, Calligraphic, Colorization, Direction, Scatter, Variation}; +use vectorcraft_color::{BlendMode, Paint}; +use vectorcraft_doc::{Appearance, AppearanceItem, Node, NodeId, NodeKind, StrokeLayer}; +use vectorcraft_geom::{Affine, PathData, SubPath}; + +use super::{Writer, Xy}; +use crate::ai_ops; +use crate::ps; + +pub(in crate::ai_editing) const BRUSHES: &str = "Pattern and Bristle brushes, Art brushes that don't stretch their art along the path from left to right at 100% unflipped without overlap, Scatter and Art brushes in Tints and Shades or Hue Shift, brushes whose art holds an empty path or group or more than paths, compound paths and groups with one solid fill and one plain stroke each, brushes whose names hold a slash or repeat an earlier brush's name, brushes that would open with other settings, brushes past the number or the amount of art one file's brushes can hold, and every brush on a large canvas are left out of the Brushes panel in the editing data for other apps"; + +/// Most brushes written (the reader's limit). +const MAX_BRUSHES: usize = 4096; + +/// Most bytes of a plug-in object's parameters in one of its strings. +const CHUNK: usize = 60; + +/// A brush written as a plug-in object. +pub(super) struct BrushOut { + pub brush: Brush, + pub plugin: &'static str, + pub params: String, + /// The art its parameters name, as the reader reads it. + pub art: Option, + /// Its art section to write ([`Writer::brush_blocks`] writes it). + section: Option, + /// A path whose art style names it at its own settings is read with the brush on its stroke. + pub live: bool, +} + +/// A brush's art section to write: its name, the art and the space it is written in +/// ([`Writer::brush_art_section`]). +type SectionArt = (String, Node, Affine); + +/// The brushes written and their art. +#[derive(Default)] +pub(super) struct Brushes { + /// The document's brushes have been worked out. + done: bool, + pub written: Vec, + /// The art sections named so far. + sections: usize, + /// A brush of the document was left out. + left_out: bool, + /// How many objects were written with a brush on their stroke. + pub live_written: usize, + /// The brushes written as the reader reads them, for checking art styles; made once, when + /// the first style is checked ([`Writer::brushed_style_reads`]). + read: Option, +} + +/// A number with at most six decimals, as brush parameters hold factors. +fn num6(s: &mut String, v: f64) { + let v = if v.is_finite() { (v * 1e6).round() / 1e6 } else { 0.0 }; + if v == v.trunc() && v.abs() < 1e15 { + let _ = write!(s, "{}", v as i64); + return; + } + let start = s.len(); + let _ = write!(s, "{v:.6}"); + let keep = s[start..].trim_end_matches('0').trim_end_matches('.').len(); + s.truncate(start + keep); +} + +/// `vs` as [`num6`] numbers separated by spaces. +fn nums6(vs: &[f64]) -> String { + let mut s = String::new(); + for (i, v) in vs.iter().enumerate() { + if i > 0 { + s.push(' '); + } + num6(&mut s, *v); + } + s +} + +/// The code a brush's parameters give how a value varies, in the order of the Brush Options menu. +fn code(v: Variation) -> f64 { + match v { + Variation::Fixed => 0.0, + Variation::Random => 1.0, + Variation::Pressure => 2.0, + Variation::Tilt => 4.0, + Variation::Bearing => 5.0, + Variation::Rotation => 6.0, + } +} + +/// The colorization code of Scatter and Art brushes' parameters: `None` for one the reader doesn't read. +fn colorization_code(c: Colorization) -> Option { + match c { + Colorization::None => Some(0.0), + Colorization::Tints => Some(1.0), + Colorization::TintsAndShades | Colorization::HueShift { .. } => None, + } +} + +/// A Calligraphic brush's parameters: 1, the diameter, roundness and angle as (low, high) pairs, +/// the codes of how the diameter, roundness and angle vary, and 0. +fn calligraphic_params(c: &Calligraphic) -> String { + let [angle, roundness, size] = [c.angle, c.roundness, c.size]; + let [av, rv, dv] = c.variation; + let [am, rm, dm] = c.modes().map(code); + nums6(&[1.0, size - dv, size + dv, roundness - rv, roundness + rv, angle - av, angle + av, dm, rm, am, 0.0]) +} + +/// A Scatter brush's parameters, its art the section `art`: `None` for a colorization the reader +/// doesn't read. +fn scatter_params(s: &Scatter, art: &str) -> Option { + let f = |v: f64| v / 100.0; + let m = s.modes().map(code); + let numbers = [ + colorization_code(s.colorization)?, + f(s.size.0), + f(s.size.1), + m[0], + f(s.spacing.0), + f(s.spacing.1), + m[1], + f(s.scatter.0), + f(s.scatter.1), + m[2], + s.rotation.0, + s.rotation.1, + m[3], + f64::from(u8::from(s.rotation_relative_to_path)), + 0.0, + ]; + Some(format!("2 /{art}/ 5 0 0 0 / {}", nums6(&numbers))) +} + +/// An Art brush's parameters, its art the section `art`: `None` for options the reader doesn't read +/// (it reads an Art brush that stretches its art along the path from left to right at 100%, +/// unflipped, without overlap, in Tints or keeping its colors). +fn art_params(a: &ArtBrush, art: &str) -> Option { + let plain = a.direction == Direction::LeftToRight + && matches!(a.scale, ArtScale::Stretch) + && a.width == 100.0 + && a.width_mode.is_none() + && !a.flip_along + && !a.flip_across + && !a.overlap; + if !plain { + return None; + } + let c = colorization_code(a.colorization)?; + let numbers = [1.0, c, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0]; + Some(format!("2 / {art}/ / / / / 0 0/ 5 0 0 0 / {}", nums6(&numbers))) +} + +/// Is `art` written as the reader reads it back, within a brush: paths and compound paths with +/// points and groups with members (not clipping, without paint of their own), each opaque in the +/// normal blending mode, without effects or opacity masks, with at most one fill and one plain +/// stroke (no brush, width profile, arrowheads, alignment off the path or dashes fitted to corners) +/// over it, each in a color or none? A path without points isn't written ([`Writer::plain_object`]). +fn plain_art(art: &Node) -> bool { + let mut plain = true; + art.walk(&mut |n| { + let kind = match &n.kind { + NodeKind::Path { path, guide: false, clipping: false, .. } => path.subpaths.iter().any(|sp| !sp.anchors.is_empty()), + NodeKind::Compound { .. } => super::compound_path(n).subpaths.iter().any(|sp| !sp.anchors.is_empty()), + NodeKind::Group { children, clip: false } => !children.is_empty(), + _ => false, + }; + let items = &n.appearance.items; + let fills = items.iter().filter(|i| matches!(i, AppearanceItem::Fill(_))).count(); + let strokes = items.iter().filter(|i| matches!(i, AppearanceItem::Stroke(_))).count(); + let order = !matches!(items.as_slice(), [AppearanceItem::Stroke(_), AppearanceItem::Fill(_)]); + let quiet = items.iter().all(|i| { + i.effects().is_empty() + && i.opacity() >= 1.0 + && i.blend() == BlendMode::Normal + && matches!(i.paint(), Paint::Solid { .. } | Paint::None) + && !matches!(i, AppearanceItem::Stroke(s) if !vectorcraft_effects::stroke::is_plain(s)) + }); + // A group's own fills and strokes aren't written. + let group_paint = matches!(n.kind, NodeKind::Group { .. }) && items.iter().any(|i| !i.paint().is_none()); + plain &= kind + && !group_paint + && fills <= 1 + && strokes <= 1 + && order + && quiet + && n.appearance.effects.is_empty() + && n.extras().mask.is_none() + && n.opacity >= 1.0 + && n.blend == BlendMode::Normal; + }); + plain +} + +/// `art` (checked by [`plain_art`]) with its structure as the reader reads it back. A path, or a +/// compound path with the subpaths of all its members as one path ([`super::compound_path`]), is +/// written as one path when it has one subpath with points and as a compound path when it has more +/// ([`Writer::plain_object`]); the reader reads that compound path as one path for each subpath, +/// each with the object's paint. +fn as_read(art: &mut Node) { + let (subpaths, rule) = match &art.kind { + NodeKind::Path { path, rule, .. } => (path.subpaths.clone(), *rule), + NodeKind::Compound { rule, .. } => (super::compound_path(art).subpaths, *rule), + _ => { + if let Some(children) = art.children_mut() { + for c in children.iter_mut() { + as_read(Arc::make_mut(c)); + } + } + return; + } + }; + let mut subpaths: Vec = subpaths.into_iter().filter(|sp| !sp.anchors.is_empty()).collect(); + let path = |sp: SubPath| { + let mut p = Node::path(art.id, PathData::single(sp), Appearance::default()); + p.appearance = art.appearance.clone(); + p + }; + match subpaths.len() { + 0 => {} + 1 => { + let Some(sp) = subpaths.pop() else { return }; + art.kind = path(sp).kind; + if let NodeKind::Path { rule: r, .. } = &mut art.kind { + *r = rule; + } + } + _ => { + let children = subpaths.into_iter().map(|sp| Arc::new(path(sp))).collect(); + art.kind = NodeKind::Compound { children, rule }; + } + } +} + +/// Do brushes `a` and `b` have the same settings, within the written numbers' precision, whatever +/// their art and however their modes are given? +fn same_settings(a: &Brush, b: &Brush) -> bool { + let norm = |b: &Brush| -> serde_json::Value { + let mut b = b.clone(); + let none = || Node::group(NodeId(0), vec![]); + match &mut b.kind { + BrushKind::Calligraphic(c) => c.modes = Some(c.modes()), + BrushKind::Scatter(s) => { + s.modes = Some(s.modes()); + s.art = none(); + } + BrushKind::Art(a) => a.art = none(), + BrushKind::Pattern(_) | BrushKind::Bristle(_) => {} + } + serde_json::to_value(&b).unwrap_or(serde_json::Value::Null) + }; + super::styles::near(&norm(a), &norm(b)) +} + +/// A plug-in object: its plug-in's name, its name, and `params` in strings of at most [`CHUNK`] bytes. +fn plugin_object(plugin: &str, name: &str, params: &str) -> String { + let mut s = format!("%AI8_BeginPluginObject\n{}\n{}\n", ps::bytes(plugin.as_bytes()), ps::bytes(name.as_bytes())); + let chunks: Vec<&[u8]> = params.as_bytes().chunks(CHUNK).collect(); + if chunks.is_empty() { + s.push_str("() .\n"); + } + for (i, c) in chunks.iter().enumerate() { + let _ = writeln!(s, "{} {}", ps::bytes(c), if i + 1 == chunks.len() { "." } else { "-" }); + } + s.push_str("%AI8_EndPluginObject\n"); + s +} + +impl Writer<'_> { + /// Work out, once, which of the document's brushes are written: each one the reader reads back + /// with its settings. Their art is written with the brushes ([`Self::brush_blocks`]). + pub(super) fn brush_set(&mut self) { + if self.brush_set.done { + return; + } + self.brush_set.done = true; + let doc = self.doc; + let lib = self.brushes.get_or_insert_with(|| vectorcraft_brush::library(doc)).clone(); + if !self.brushes_live { + self.brush_set.left_out = !lib.is_empty(); + return; + } + // A name is taken by a brush written, as the reader takes it by a brush it keeps. A brush after + // another of its name isn't the one a path of that name is drawn with, so no path is written + // with it on its stroke. + let mut names: HashSet = HashSet::new(); + let mut seen: HashSet = HashSet::new(); + for b in lib { + let fits = !b.name.contains('/') && !names.contains(&b.name) && self.brush_set.written.len() < MAX_BRUSHES; + let first = seen.insert(b.name.clone()); + match fits.then(|| self.brush_out(&b)).flatten() { + Some(mut out) => { + names.insert(b.name.clone()); + out.live &= first; + self.brush_set.written.push(out); + } + None => self.brush_set.left_out = true, + } + } + // Read together, as one file's: the reader copies only so much art into one file's brushes. + let objects: Vec<(&str, &str, &str, Option<&Node>)> = + self.brush_set.written.iter().map(|b| (b.plugin, b.brush.name.as_str(), b.params.as_str(), b.art.as_ref())).collect(); + let kept = crate::import::brushes_kept(&objects); + if kept.iter().any(|k| !k) { + self.brush_set.left_out = true; + let mut keep = kept.into_iter(); + self.brush_set.written.retain(|_| keep.next().unwrap_or(false)); + } + } + + /// Brush `b` as it is written, with its art section's name, art and placement + /// ([`Self::brush_art_section`] writes it): `None` when the reader wouldn't read it back. + fn brush_out(&mut self, b: &Brush) -> Option { + let plugin = crate::import::brush_plugin_name(&b.kind); + let section = format!("Brush Art {}", self.brush_set.sections + 1); + // The art as the reader reads it: a section is read with y down, and an Art brush's art is + // turned over after that (its section's y up is the right of the path). + let (params, art) = match &b.kind { + BrushKind::Calligraphic(c) => (calligraphic_params(c), None), + BrushKind::Scatter(s) => (scatter_params(s, §ion)?, Some((s.art.clone(), Affine::FLIP_Y))), + BrushKind::Art(a) => (art_params(a, §ion)?, Some((a.art.clone(), Affine::IDENTITY))), + BrushKind::Pattern(_) | BrushKind::Bristle(_) => return None, + }; + let read_art = match &art { + Some((a, to_section)) => { + if !plain_art(a) { + return None; + } + let mut read = a.clone(); + if *to_section == Affine::IDENTITY { + read.transform(Affine::FLIP_Y, false); + } + as_read(&mut read); + Some(read) + } + None => None, + }; + let read = crate::import::read_brush_object(plugin, &b.name, ¶ms, read_art.as_ref())?; + if !same_settings(&read.brush, b) { + return None; + } + if art.is_some() { + self.brush_set.sections += 1; + } + let section = art.map(|(a, to_section)| (section, a, to_section)); + Some(BrushOut { brush: b.clone(), plugin, params, art: read_art, section, live: read.live }) + } + + /// A brush's art section `name`: `art` written with `to_section` taking the document's space to + /// the section's (y up), from the state a definition starts in. Its objects are counted as the + /// reader counts them ([`Self::take_objects`]: the group, the frame and the art). `None` when + /// writing it warns: what it took is given back, and when it didn't fit within the object limit, + /// the limit's warning is kept. + fn brush_art_section(&mut self, name: &str, art: &Node, to_section: Affine) -> Option { + let before = self.charges(); + // The art's own warnings, apart from those the document already has (a warning is kept once). + let warnings = std::mem::take(&mut self.warnings); + let saved = ( + std::mem::take(&mut self.body), + (self.to_art, self.grad_space, self.canvas), + self.state.take(), + self.gs.replace(Xy::OPAQUE), + self.clip.take(), + (self.block_start, self.block_end), + // The art is the brush's own: not on `%_` lines, in a drawn look or in a symbol that + // first uses the brush. + (std::mem::take(&mut self.hidden), std::mem::take(&mut self.in_look), std::mem::take(&mut self.in_symbol)), + ); + (self.to_art, self.grad_space, self.canvas, self.block_end) = (to_section, to_section, to_section, usize::MAX); + self.state(false, false); + // The art in a group after its frame, an unpainted rectangle around it. Art without width or + // height (a straight line) is written alone: the reader keeps a frame of no area as art. + let frame = art + .geometric_bounds() + .filter(|b| b.width() > 0.0 && b.height() > 0.0) + .and_then(|b| vectorcraft_geom::shapes::rectangle(b).subpaths.first().cloned()); + match frame { + Some(frame) if self.take_objects(2) => { + self.line("u\n0 XR"); + ai_ops::subpath(&mut self.body, to_section, &frame); + self.line("n"); + self.nest += 1; + self.node(art); + self.nest -= 1; + self.line("U"); + } + Some(_) => {} + None => { + self.nest += 1; + self.node(art); + self.nest -= 1; + } + } + let body; + ( + body, + (self.to_art, self.grad_space, self.canvas), + self.state, + self.gs, + self.clip, + (self.block_start, self.block_end), + (self.hidden, self.in_look, self.in_symbol), + ) = saved; + let text = std::mem::replace(&mut self.body, body); + if !std::mem::replace(&mut self.warnings, warnings).is_empty() { + self.give_back(before, &text); + if self.left_out_since(before) { + self.warn(super::OBJECT_LIMIT); + } + return None; + } + self.keep_since(before); + Some(format!("%AI8_BeginBrushPattern\n{}\n{text}%AI8_EndBrushPattern\n", ps::bytes(name.as_bytes()))) + } + + /// The written brush named `name` that a path can be written with live. + pub(super) fn live_brush(&self, name: &str) -> Option<&BrushOut> { + self.brush_set.written.iter().find(|b| b.live && b.brush.name == name) + } + + /// The basic filter of stroke `st` with the brush it names: the brush's plug-in as the filter, + /// its settings for the object, the stroke's style and the brush by name. `None` when the brush + /// isn't written live. + pub(super) fn brush_filter(&mut self, s: &mut String, st: &StrokeLayer, visible: bool) -> Option<()> { + let name = st.brush.as_deref()?; + self.brush_set(); + let (plugin, kind) = self.live_brush(name).map(|b| (b.plugin, b.brush.kind.clone()))?; + if !matches!(st.paint, Paint::Solid { .. }) || st.overprint { + return None; + } + let ops = self.color_ops(&st.paint, true); + let mut d = String::new(); + let title = match &kind { + BrushKind::Calligraphic(c) => { + let modes = c.modes().map(code); + for (key, value, variation, mode) in [ + ("Diameter", c.size, c.variation[2], modes[2]), + ("Roundness", c.roundness, c.variation[1], modes[1]), + ("Angle", c.angle, c.variation[0], modes[0]), + ] { + let _ = writeln!(d, "{} /Real ({key}) ,", ps::num(value)); + let _ = writeln!(d, "{} /Real ({key}Variation) ,", ps::num(variation)); + let _ = writeln!(d, "{} /Int ({key}DependsOn) ,", mode as i64); + } + d.push_str("0 /Int (AngleRelativeTo) ,\n"); + "(Calligraphic Brush) /Title ,\n" + } + BrushKind::Art(_) => { + d.push_str("15 /Int (Adobe Effect Expand Before Version) ,\n"); // brand-ok: the entry's name in the files + for (key, value, kind) in [ + ("StartSegmentLength", "0", "Real"), + ("EndSegmentLength", "0", "Real"), + ("Counterclockwise", "0", "Int"), + ("MinScaling", "1", "Real"), + ("MaxScaling", "1", "Real"), + ("Colorization", "1", "Int"), + ("Spacing", "0", "Real"), + ("Adjustment", "1", "Int"), + ("Proportional", "0", "Bool"), + ("Segmented", "0", "Bool"), + ("UpsideDown", "0", "Int"), + ("FoldAdjustment", "1", "Bool"), + ("ScaleYDependsOn", "0", "Int"), + ("Scaling", "1", "Real"), + ] { + let _ = writeln!(d, "{value} /{kind} ({key}) ,"); + } + "(Art Brush) /Title ,\n" + } + _ => return None, + }; + super::styles::basic(s, plugin, true, visible); + s.push_str(title); + s.push_str("2 /FillOrStroke ,\n/Dictionary : /NotRecorded ,\n"); + s.push_str(&d); + s.push_str("/StrokeStyle : 0 R\n"); + s.push_str(&ops); + s.push_str("0 1 0 0 0 Xy\n"); + ai_ops::line_style(s, st); + s.push_str("0 XR\n1 0 Xd\n/Def ; \n (StrokeStyle) ,\n"); + let quoted = ps::bytes(name.as_bytes()); + let _ = + write!(s, "/GObjRef : {quoted} {} /PluginObject ; (Brush) ,\n{quoted} /UnicodeString (DisplayString) ,\n", ps::bytes(plugin.as_bytes())); + s.push_str(super::styles::END_BASIC); + Some(()) + } + + /// Does the reader read the brushed strokes of style text `text` with their brushes on them? + pub(super) fn brushed_style_reads(&mut self, text: &str) -> bool { + self.brush_set(); + let section = super::styles::known_style("x", text); + let written = &self.brush_set.written; + let read = self.brush_set.read.get_or_insert_with(|| { + let brushes: Vec<(&str, &str, &str, Option<&Node>)> = + written.iter().map(|b| (b.plugin, b.brush.name.as_str(), b.params.as_str(), b.art.as_ref())).collect(); + crate::import::BrushesRead::new(&brushes) + }); + read.style_reads(section.as_bytes(), "x") + } + + /// The brushes' art in a non-printing block, then the brush manager's order and the brushes in + /// two more, when the document has brushes of its own or an object is written with a brush on + /// its stroke (a file without brushes opens with a new document's). Warns when a brush is left + /// out. + pub(in crate::ai_editing) fn brush_blocks(&mut self) -> (String, String) { + let stored = self.doc.unknown.contains_key(vectorcraft_brush::DOC_KEY); + if !stored && self.brush_set.live_written == 0 { + return (String::new(), String::new()); + } + self.brush_set(); + // The art is written now that the file holds it, after the layers' objects. A brush whose art + // doesn't fit is left out; a path written with it on its stroke opens as its drawn look. + let mut sections = String::new(); + for mut b in std::mem::take(&mut self.brush_set.written) { + if let Some((name, art, to_section)) = b.section.take() { + let Some(text) = self.brush_art_section(&name, &art, to_section) else { + self.brush_set.left_out = true; + continue; + }; + sections.push_str(&text); + } + self.brush_set.written.push(b); + } + if self.brush_set.left_out { + self.warn(BRUSHES); + } + // On a large canvas an empty panel is still written: the manager alone, with no art to scale. + let empty = self.brushes.as_ref().is_some_and(|l| l.is_empty()); + if !self.brushes_live && !(stored && empty) { + return (String::new(), String::new()); + } + let art = if sections.is_empty() { String::new() } else { format!("%AI5_Begin_NonPrinting\nNp\n{sections}%AI5_End_NonPrinting--\n") }; + let manager = crate::import::BRUSH_MANAGER; + let order: String = self.brush_set.written.iter().map(|b| format!(" {}/ {}/", b.plugin, b.brush.name)).collect(); + let mut objects = format!("%AI5_Begin_NonPrinting\nNp\n{}%AI5_End_NonPrinting--\n", plugin_object(manager, manager, &order)); + if !self.brush_set.written.is_empty() { + objects.push_str("%AI5_Begin_NonPrinting\nNp\n"); + for b in &self.brush_set.written { + objects.push_str(&plugin_object(b.plugin, &b.brush.name, &b.params)); + } + objects.push_str("%AI5_End_NonPrinting--\n"); + } + (art, objects) + } +} diff --git a/crates/eps/src/ai_editing/writer/envelopes.rs b/crates/eps/src/ai_editing/writer/envelopes.rs new file mode 100644 index 0000000000..dcd7274291 --- /dev/null +++ b/crates/eps/src/ai_editing/writer/envelopes.rs @@ -0,0 +1,395 @@ +//! Envelopes (see [`crate::ai_editing`] for the form), written in the form VectorCraft's `.ai` +//! reader opens as live envelopes again: on `%_` lines a group holding the grid that shapes the +//! envelope (while its contents are edited, the contents), then that group's `/ArtDictionary` with +//! Envelope Options as a bit word (`AIDeformOptionsKey`), Fidelity (`AIDeformFidelityKey`), Edit +//! Contents (`AIDeformEditModeKey`), a warp's style, bend, distortions and orientation +//! (`DeformStyle`, `DeformValue`, `DeformHoriz`, `DeformVert`, `Rotate`), with Distort Appearance +//! the size of the box the contents map from (`AIDeformArtWidthKey`, `AIDeformArtHeightKey`), the +//! contents in an `X=` … `X+` block (while they are edited, the grid) as `AIDeformArtKey`, and the +//! kind (`AIDeformStyle`: 1 a warp, 2 a mesh, 3 a top object); then the distorted art on plain +//! lines, and the plugin's `XP` after it. A top object's outline is the edge of the grid written +//! for it, one grid edge to each segment of its sides. An envelope the reader would open in another +//! shape is written as its distorted art. + +use std::fmt::Write; +use std::sync::Arc; + +use kurbo::{Point, Vec2}; +use vectorcraft_doc::live::{ + Coons, EnvelopeKind, EnvelopeOptions, GradientMesh, H_DOWN, H_LEFT, H_RIGHT, H_UP, MeshPoint, PreserveShape, WARP_NET, envelope_content_boxes, + envelope_grid, envelope_stroke_margin, warp_grid, +}; +use vectorcraft_doc::{Node, NodeKind}; +use vectorcraft_geom::{Affine, PathData}; + +use super::{MAX_NEST, Writer, Xy, hide}; +use crate::import::{DEFORM_PLUGIN, EnvelopeGridPoint as GridPoint, envelope_outline, envelope_upright, warp_number}; +use crate::ps; + +pub(in crate::ai_editing) const ENVELOPES: &str = "envelopes of type, envelopes without contents, envelopes in opacity masks, pattern tiles, art cut to a clipping object or other envelopes' contents, envelopes on the layers of a large canvas or in a turned or mirrored frame, warps drawn without their style's net, meshes and top objects that the data would open in another shape, envelopes with a Fidelity that isn't a whole number, envelopes that map from a box other than their contents' bounds with or without strokes or keep bounds margins with Distort Appearance off, envelopes after the first 256, and envelopes nested more than 8 deep are written as their art in the editing data for other apps"; + +/// The most rows or columns of an envelope's grid written (Make with Mesh's own limit, and the +/// reader's). +const MAX_GRID: usize = 50; +/// How far, as a share of the diagonal of a top object's patch, the patch on the outline written for +/// it may lie from its own at any of the places checked. +const TOP_OBJECT_TOLERANCE: f64 = 1e-6; +/// How far apart two bounds margins may be and still count as the same. +const MARGIN_SLACK: f32 = 1e-5; + +/// What an envelope's dictionary holds besides its contents: the entries before the contents' block, +/// each on a line of its own, the kind (`AIDeformStyle`) and the grid that shapes it (`rows`, `cols` +/// and its points with their handles, row by row from the top left, in the document), when it has +/// one. +struct Record { + keys: String, + style: u8, + grid: Option<(usize, usize, Vec)>, +} + +/// The `XP` that ends an envelope, after its distorted art. +pub(super) fn plugin_line() -> String { + format!("{} 1 0 0 XP", ps::bytes(DEFORM_PLUGIN.as_bytes())) +} + +/// Does `n`, or anything in it, hold type? +fn holds_type(n: &Node) -> bool { + matches!(n.kind, NodeKind::Text(_)) || n.children().is_some_and(|c| c.iter().any(|k| holds_type(k))) +} + +/// The record of envelope `n` (its parts given), or `None` where the reader would open it in +/// another shape than it has, or not as an envelope. +fn record( + n: &Node, + content: &[Arc], + kind: &EnvelopeKind, + fidelity: f64, + editing: bool, + options: &EnvelopeOptions, + frame: Affine, +) -> Option { + // The reader reads Fidelity as a whole number from 0 to 100, and bounds margins only with + // Distort Appearance on. + let whole = (0.0..=100.0).contains(&fidelity) && fidelity.fract() == 0.0; + let margin_kept = !options.distort_appearance && options.bounds_margin != [0.0; 4]; + if content.is_empty() || frame != Affine::IDENTITY || !whole || margin_kept || content.iter().any(|c| holds_type(c)) { + return None; + } + let mut keys = String::new(); + let bit = |on: bool, at: u32| i64::from(on) << at; + let word = bit(options.distort_appearance, 0) + | bit(options.distort_pattern_fills, 1) + | bit(options.distort_linear_gradients, 2) + | bit(!options.anti_alias, 16) + | bit(options.preserve_shape == PreserveShape::ClippingMask, 17); + let _ = writeln!(keys, "{word} /Int (AIDeformOptionsKey) ,"); + let _ = writeln!(keys, "{} /Int (AIDeformFidelityKey) ,", fidelity as i64); + let _ = writeln!(keys, "{} /Bool (AIDeformEditModeKey) ,", u8::from(editing)); + let real = |keys: &mut String, v: f64, key: &str| { + ps::push_num_places(keys, v, 9); + let _ = writeln!(keys, " /Real ({key}) ,"); + }; + let (style, grid) = match kind { + EnvelopeKind::Warp { style, bend, h, v, horizontal, version } => { + let fraction = |p: f64| (p.is_finite() && (-100.0..=100.0).contains(&p)).then_some(p / 100.0); + let (number, bend, h, v) = (warp_number(style)?, fraction(*bend)?, fraction(*h)?, fraction(*v)?); + if *version != WARP_NET { + return None; + } + let _ = writeln!(keys, "{number} /Int (DeformStyle) ,"); + real(&mut keys, h, "DeformHoriz"); + real(&mut keys, bend, "DeformValue"); + real(&mut keys, v, "DeformVert"); + let _ = writeln!(keys, "{} /Bool (Rotate) ,", u8::from(!*horizontal)); + // The grid of the warp's shape, for apps that read it. + (1, warp_grid(n).and_then(|m| as_read(&m)).and_then(|(rows, cols, pts)| sized(rows, cols).map(|(r, c)| (r, c, pts)))) + } + EnvelopeKind::Mesh { rows, cols, points, handles } => { + let (r, c) = sized(*rows, *cols)?; + let mesh = envelope_grid(*rows, *cols, points, handles)?; + let pts = as_read(&mesh)?.2; + // The reader lays the grid out with its first row at the top and its first column at the + // left: a grid it would lay out another way round would map the contents another way. + if !reads_as_written(r, c, &pts) { + return None; + } + (2, Some((r, c, pts))) + } + EnvelopeKind::TopObject { path, corners } => (3, Some(top_object_grid(path, *corners)?)), + }; + if options.distort_appearance { + let (stroked, plain) = envelope_content_boxes(content, Affine::IDENTITY)?; + let margin = options.bounds_margin; + let same = |m: [f32; 4]| m.iter().zip(margin).all(|(a, b)| (a - b).abs() <= MARGIN_SLACK); + // The reader maps from the size written when it matches the contents' bounds with their + // strokes, and from their geometric bounds otherwise. + let size = if margin == [0.0; 4] { + plain + } else if stroked != plain && envelope_stroke_margin(stroked, plain).is_some_and(same) { + stroked + } else { + return None; + }; + real(&mut keys, size.height(), "AIDeformArtHeightKey"); + real(&mut keys, size.width(), "AIDeformArtWidthKey"); + } + Some(Record { keys, style, grid }) +} + +/// `rows` and `cols` as sizes, when the reader reads a grid of them. +fn sized(rows: u32, cols: u32) -> Option<(usize, usize)> { + let (r, c) = (usize::try_from(rows).ok()?, usize::try_from(cols).ok()?); + ((1..=MAX_GRID).contains(&r) && (1..=MAX_GRID).contains(&c)).then_some((r, c)) +} + +/// The points of grid `m` with their handles as the reader reads them back: the handles that point +/// out of the grid, which nothing draws with, are left at the point. `None` for a grid of points +/// or handles that aren't finite. +fn as_read(m: &GradientMesh) -> Option<(u32, u32, Vec)> { + let (rows, cols) = (m.rows as usize, m.cols as usize); + let finite = |v: Vec2| v.x.is_finite() && v.y.is_finite(); + let mut pts = Vec::with_capacity(m.points.len()); + for (i, q) in m.points.iter().enumerate() { + if !finite(q.p.to_vec2()) || !q.handles.iter().all(|h| finite(*h)) { + return None; + } + let (r, c) = (i / (cols + 1), i % (cols + 1)); + let mut h = q.handles; + for (slot, out) in [(H_LEFT, c == 0), (H_RIGHT, c == cols), (H_UP, r == 0), (H_DOWN, r == rows)] { + if out && let Some(h) = h.get_mut(slot) { + *h = Vec2::ZERO; + } + } + pts.push((q.p, h)); + } + Some((m.rows, m.cols, pts)) +} + +/// Does the reader lay out grid `pts` (`rows`×`cols` patches) as it is written? +fn reads_as_written(rows: usize, cols: usize, pts: &[GridPoint]) -> bool { + let points = + pts.iter().map(|(p, handles)| MeshPoint { p: *p, color: vectorcraft_color::Color::BLACK, opacity: 1.0, handles: *handles }).collect(); + let mesh = GradientMesh { rows: rows as u32, cols: cols as u32, points }; + envelope_upright(&mesh).is_some_and(|(r, c, read)| (r as usize, c as usize) == (rows, cols) && read == pts) +} + +/// The grid a top object with outline `path` and corners `corners` is written with: its edge runs +/// through the outline's anchors clockwise from the top left corner, one grid edge to a segment, so +/// the top and bottom sides need as many segments as each other, as do the left and right sides; +/// the points inside blend the sides. `None` where that grid's edge, read back as the top object's +/// outline, doesn't give the same patch ([`Coons::from_top_object`]) at every place checked. +fn top_object_grid(path: &PathData, corners: Option<[u32; 4]>) -> Option<(usize, usize, Vec)> { + let coons = Coons::from_top_object(path, corners)?; + // The outline, as the patch takes it: the largest subpath. + let mut sp = path.subpaths.iter().filter(|s| s.anchors.len() >= 2).max_by(|a, b| a.area().abs().total_cmp(&b.area().abs()))?.clone(); + let count = sp.anchors.len(); + let empty = |i: usize| { + let c = sp.segment(i); + [c.p1, c.p2, c.p3].iter().all(|p| p.distance(c.p0) <= 1e-9) + }; + if !sp.closed || count < 4 || (0..count).any(empty) { + return None; + } + let fits = |c: &[usize; 4]| { + c.iter().all(|i| *i < count) && { + let gaps = (0..4).map(|k| (c[(k + 1) % 4] + count - c[k]) % count); + gaps.clone().all(|g| g > 0) && gaps.sum::() == count + } + }; + // Stored corners that fit keep the outline as drawn; otherwise it runs clockwise, and the + // corners are the anchors the patch's corners lie on. + let at = match corners.map(|c| c.map(|i| i as usize)).filter(fits) { + Some(c) => c, + None => { + if sp.signed_area() < 0.0 { + sp.reverse(); + } + let find = |q: Point| sp.anchors.iter().position(|a| a.p.distance(q) <= 1e-9); + let [tl, tr, br, bl] = coons.corners(); + let c = [find(tl)?, find(tr)?, find(br)?, find(bl)?]; + if !fits(&c) { + return None; + } + c + } + }; + let gap = |k: usize| (at[(k + 1) % 4] + count - at[k]) % count; + let (cols, rows) = (gap(0), gap(1)); + if gap(2) != cols || gap(3) != rows || cols > MAX_GRID || rows > MAX_GRID { + return None; + } + let width = cols + 1; + let mut pts: Vec = vec![(Point::ZERO, [Vec2::ZERO; 4]); (rows + 1) * width]; + // Where the `k`th anchor from the top left corner goes, and the slots of the handles of the + // segment from it to the next anchor: its own, and the next anchor's back. + let place = |k: usize| -> (usize, usize, usize, usize) { + if k < cols { + (0, k, H_RIGHT, H_LEFT) + } else if k < cols + rows { + (k - cols, cols, H_DOWN, H_UP) + } else if k < 2 * cols + rows { + (rows, cols - (k - cols - rows), H_LEFT, H_RIGHT) + } else { + (rows - (k - 2 * cols - rows), 0, H_UP, H_DOWN) + } + }; + for k in 0..count { + let i = (at[0] + k) % count; + let seg = sp.segment(i); + // A straight segment's patch spreads evenly along it, as a cubic's with its handles a third + // of the way does. + let (p1, p2) = if sp.segment_is_line(i) { (seg.p0.lerp(seg.p3, 1.0 / 3.0), seg.p0.lerp(seg.p3, 2.0 / 3.0)) } else { (seg.p1, seg.p2) }; + let (r, c, out, into) = place(k); + let (nr, nc, _, _) = place((k + 1) % count); + if let Some(q) = pts.get_mut(r * width + c) { + q.0 = seg.p0; + q.1[out] = p1 - seg.p0; + } + if let Some(q) = pts.get_mut(nr * width + nc) { + q.1[into] = p2 - seg.p3; + } + } + // The points inside, blended from the sides. + let edge = |r: usize, c: usize| pts.get(r * width + c).map_or(Point::ZERO, |q| q.0).to_vec2(); + let mut inside = vec![]; + for r in 1..rows { + for c in 1..cols { + let (u, v) = (c as f64 / cols as f64, r as f64 / rows as f64); + let p = (1.0 - v) * edge(0, c) + v * edge(rows, c) + (1.0 - u) * edge(r, 0) + u * edge(r, cols) + - ((1.0 - u) * (1.0 - v) * edge(0, 0) + u * (1.0 - v) * edge(0, cols) + (1.0 - u) * v * edge(rows, 0) + u * v * edge(rows, cols)); + inside.push((r * width + c, p.to_point())); + } + } + for (i, p) in inside { + if let Some(q) = pts.get_mut(i) { + q.0 = p; + } + } + if !pts.iter().all(|(p, h)| p.is_finite() && h.iter().all(|h| h.is_finite())) || !reads_as_written(rows, cols, &pts) { + return None; + } + // The top object the reader makes of the grid: its edge, with the corners of the grid. + let outline = envelope_outline(rows as u32, cols as u32, &pts)?; + let corners = [0, cols, cols + rows, 2 * cols + rows].map(|c| c as u32); + let read = Coons::from_top_object(&outline, Some(corners))?; + let [tl, tr, br, bl] = coons.corners(); + let reach = tl.distance(br).max(tr.distance(bl)).max(1.0) * TOP_OBJECT_TOLERANCE; + const STEPS: usize = 8; + let at = |i: usize| i as f64 / STEPS as f64; + let same = (0..=STEPS).all(|j| (0..=STEPS).all(|i| coons.eval(at(i), at(j)).distance(read.eval(at(i), at(j))) <= reach)); + same.then_some((rows, cols, pts)) +} + +impl Writer<'_> { + /// Envelope `n`, of transparency `xy`, as a live envelope (see the module's form), outside opacity + /// masks' art, pattern tiles, art cut to a clipping object and the layers of a large canvas. False, + /// writing nothing, where it is written as its art instead: where the reader would open it in + /// another shape, or some of it is left out for the object limit ([`Self::take_objects`]). + pub(super) fn envelope(&mut self, n: &Node, xy: Xy) -> bool { + let NodeKind::Envelope { content, kind, fidelity, editing, options, frame } = &n.kind else { return false }; + if self.hidden > 0 || self.clip.is_some() || self.nest >= MAX_NEST || !self.symbols_live || self.envelopes_left == 0 { + return false; + } + let Some(record) = record(n, content, kind, *fidelity, *editing, options, **frame) else { return false }; + let start = self.body.len(); + let (state, gs, charges, bound) = (self.state, self.gs, self.charges(), self.bound.len()); + self.nest += 1; + self.hidden += 1; + // The group before the dictionary: the grid, or the contents while they are edited. + let outer = std::mem::take(&mut self.body); + let opened = self.open_group("u"); + if opened { + if *editing { + self.contents(content); + } else { + self.grid(record.grid.as_ref()); + } + self.line("U"); + } + let before = std::mem::replace(&mut self.body, outer); + hide(&before, &mut self.body); + self.body.push_str("%_/ArtDictionary :\n"); + hide(&record.keys, &mut self.body); + self.body.push_str("%_X=\n"); + // The dictionary's art starts unlocked, shown and opaque, as an opacity mask's does. + let outer = std::mem::take(&mut self.body); + let at_block = self.state; + (self.state, self.gs) = (Some((false, false)), Some(Xy::OPAQUE)); + if *editing { + self.grid(record.grid.as_ref()); + } else if self.open_group("u") { + self.contents(content); + self.end_group("U", Xy::PLAIN); + } + let block = std::mem::replace(&mut self.body, outer); + hide(&block, &mut self.body); + (self.state, self.gs, self.block_end) = (at_block, None, usize::MAX); + let _ = writeln!(self.body, "%_X+\n%_ (AIDeformArtKey) ,\n%_{} /Int (AIDeformStyle) ,\n%_;\n%_\n%_9 () XW", record.style); + self.hidden -= 1; + self.nest -= 1; + // The distorted art, which takes the envelope's lock, visibility, transparency, name and + // opacity mask. + self.state(n.locked, !n.visible); + self.drawn_art(n, xy, None); + if !opened || self.left_out_since(charges) { + let lines = self.body.split_off(start); + self.give_back(charges, &lines); + self.bound.truncate(bound); + (self.state, self.gs, self.block_end) = (state, gs, usize::MAX); + return false; + } + self.deform = true; + self.envelopes_left -= 1; + true + } + + /// An envelope's contents. + fn contents(&mut self, content: &[Arc]) { + for c in content { + self.node(c); + } + } + + /// An envelope's grid, when it has one, as a gray gradient mesh (`/Mesh X!` … `/End X!`): its + /// size (`[cols rows] /Size`), then each patch's place (`[col row] /P`), its four corners + /// (`/N`: gray, opacity, the point, the handle towards the next corner and a weight, the handle + /// towards the previous one and a weight, in art space), from its top left one down, across and + /// up, and `/E`. One object. + fn grid(&mut self, grid: Option<&(usize, usize, Vec)>) { + let Some((rows, cols, pts)) = grid else { return }; + if !self.take_objects(1) { + return; + } + let (rows, cols, width) = (*rows, *cols, cols + 1); + let to_art = self.to_art; + let s = &mut self.body; + let _ = writeln!(s, "/Mesh X!\n2 /Version X#\n/Cartesian /Type X#\n[{cols} {rows}] /Size X#\n/Data X#\n/DeviceGray /CS X#"); + let num = |s: &mut String, v: f64| { + s.push(' '); + ps::push_num(s, v); + }; + for c in 0..cols { + for r in 0..rows { + let _ = writeln!(s, "[{c} {r}] /P X#"); + // Each corner with the slots of its handles towards the next corner and the previous one. + let corners = [((r, c), H_DOWN, H_RIGHT), ((r + 1, c), H_RIGHT, H_UP), ((r + 1, c + 1), H_UP, H_LEFT), ((r, c + 1), H_LEFT, H_DOWN)]; + for ((pr, pc), next, prev) in corners { + let (p, h) = pts.get(pr * width + pc).copied().unwrap_or((Point::ZERO, [Vec2::ZERO; 4])); + let at = |v: Vec2| to_art * (p + v); + s.push_str("[0 1"); + for q in [at(Vec2::ZERO), at(h[next])] { + num(s, q.x); + num(s, q.y); + } + s.push_str(" 1"); + let q = at(h[prev]); + num(s, q.x); + num(s, q.y); + s.push_str(" 1] /N X#\n"); + } + s.push_str("/E X#\n"); + } + } + s.push_str("/End X!\n"); + } +} diff --git a/crates/eps/src/ai_editing/writer/paints.rs b/crates/eps/src/ai_editing/writer/paints.rs index 892a0d1b65..f1b52dd91b 100644 --- a/crates/eps/src/ai_editing/writer/paints.rs +++ b/crates/eps/src/ai_editing/writer/paints.rs @@ -11,7 +11,7 @@ use vectorcraft_effects::stroke; use vectorcraft_geom::{Affine, BezPath, Rect, Shape, Vec2}; use super::{MAX_NEST, Writer, Xy}; -use crate::ai_ops::{average, unit}; +use crate::ai_ops::{self, average, unit}; use crate::ps; pub(in crate::ai_editing) const GRADIENTS: &str = @@ -21,6 +21,7 @@ pub(in crate::ai_editing) const SWATCH_PLACEMENT: &str = "the placement of pattern swatches that move, turn or scale their pattern is left out of the editing data for other apps"; pub(in crate::ai_editing) const GRADIENT_MIX: &str = "gradients that mix their colors perceptually or dither are written as classic gradients in the editing data for other apps"; +pub(in crate::ai_editing) const GRADIENT_HUE: &str = "gradients mixed around the hue wheel are written in process colors, with the colors between their stops as stops of their own (at most 256), in the editing data for other apps"; pub(in crate::ai_editing) const CONIC: &str = "conic gradients are written as linear gradients along their vector, with the same stops, in the editing data for other apps"; pub(in crate::ai_editing) const STOP_LINKS: &str = @@ -45,12 +46,36 @@ pub(super) struct PatternOut { used: bool, } -/// Can `g` be written as a gradient (a linear, radial or conic one with stops, no more than the -/// `.ai` reader reads; a conic is written linear, [`CONIC`])? +pub(in crate::ai_editing) const DIAMOND: &str = + "diamond gradients are written as radial gradients through their corners, with the same stops, in the editing data for other apps"; +pub(in crate::ai_editing) const SPREAD: &str = "gradients that repeat or reflect are written with their stops repeated across the shape (at most 256 stops, padding past them) in the editing data for other apps"; + +/// Can `g` be written as a gradient (a linear, radial, conic or diamond one with stops, no more +/// than the `.ai` reader reads; a conic is written linear, [`CONIC`], and a diamond radial, +/// [`DIAMOND`])? fn writable_gradient(g: &Gradient) -> bool { g.kind != GradientKind::Freeform && !g.stops.is_empty() && g.stops.len() <= crate::import::MAX_GRADIENT_STOPS } +/// `g` as the data holds its colors: one mixed around the hue wheel (the data's gradients mix +/// their stops' colors directly) as a classic gradient of the stops on its curve +/// ([`Gradient::as_classic_curve`]), no more than the `.ai` reader reads when it pads +/// ([`GRADIENT_HUE`]); others as they are. +fn hue_as_stops(g: &Gradient) -> std::borrow::Cow<'_, Gradient> { + use std::borrow::Cow; + if !g.method.is_hue() { + return Cow::Borrowed(g); + } + let curve = g.as_classic_curve(); + Cow::Owned(if curve.is_spread() { curve } else { curve.fitted(crate::import::MAX_GRADIENT_STOPS).into_owned() }) +} + +/// Is a gradient of `kind` written as a radial one: a radial gradient, or a diamond (the ellipse +/// through its square's corners, [`DIAMOND`])? +fn written_radial(kind: GradientKind) -> bool { + matches!(kind, GradientKind::Radial | GradientKind::Diamond) +} + /// The first name of `Gradient`, `Gradient 2`, `Gradient 3`, … numbered `next` or higher for /// which `taken` returns false (`Gradient` is number 1); `next` is set past it. pub(in crate::ai_editing) fn free_gradient_name(next: &mut u64, mut taken: impl FnMut(&str) -> bool) -> String { @@ -75,11 +100,15 @@ impl Writer<'_> { pub(in crate::ai_editing) fn reserve_swatch_gradients(&mut self) { let doc = self.doc; for sw in doc.swatches_iter() { + // As `swatch_paint` writes it: one mixed around the hue wheel as the stops on its curve, + // and the stops of one that repeats or reflects repeated. if let Paint::Gradient(g) = &sw.paint - && writable_gradient(&g.gradient) + && let stops = hue_as_stops(&g.gradient) + && let gradient = stops.unrolled_within(crate::import::MAX_GRADIENT_STOPS) + && writable_gradient(&gradient) && !self.gradients.iter().any(|d| d.name == sw.name) { - self.gradients.push(GradientDef { name: sw.name.clone(), gradient: g.gradient.clone(), swatch: true, used: false }); + self.gradients.push(GradientDef { name: sw.name.clone(), gradient: gradient.into_owned(), swatch: true, used: false }); } } } @@ -125,10 +154,33 @@ impl Writer<'_> { /// placed there (it then no longer depends on the shape it paints, which may be cut); one the /// data can't hold is its average color, with a warning. pub(super) fn placed(&mut self, p: &Paint, bounds: Rect) -> Paint { + self.placed_over(p, bounds, bounds) + } + + /// [`Self::placed`] for paint that reaches `area`: a gradient that repeats or reflects is + /// written with its stops repeated over `area`. + fn placed_over(&mut self, p: &Paint, bounds: Rect, area: Rect) -> Paint { let Paint::Gradient(g) = p else { return p.clone() }; - let geom = g.resolve(bounds); + let mut geom = g.resolve(bounds); + // The data has no spread: a gradient that repeats or reflects is written with its stops + // repeated over `area` (a conic one, written linear, around its turn). + let mut g: GradientPaint = (**g).clone(); + if g.gradient.method.is_hue() { + self.warn(GRADIENT_HUE); + g.gradient = hue_as_stops(&g.gradient).into_owned(); + } + if g.gradient.is_spread() { + self.warn(SPREAD); + match g.gradient.padded_within(&geom, area, crate::import::MAX_GRADIENT_STOPS) { + Some(padded) => { + g.gradient = padded.gradient; + geom = padded.geom; + } + None => g.gradient = g.gradient.unrolled_within(crate::import::MAX_GRADIENT_STOPS).into_owned(), + } + } let finite = [geom.start.x, geom.start.y, geom.end.x, geom.end.y, geom.aspect].iter().all(|v| v.is_finite()); - let radial = g.gradient.kind == GradientKind::Radial; + let radial = written_radial(g.gradient.kind); if g.gradient.kind == GradientKind::Freeform { self.warn(GRADIENTS); return Paint::solid(average(&g.gradient)); @@ -137,13 +189,16 @@ impl Writer<'_> { self.warn(GRADIENT_SHAPES); return Paint::solid(average(&g.gradient)); } - Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..(**g).clone() })) + Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..g })) } - /// The fills and strokes of `n` that paint (outline `bounds`), their gradients placed - /// ([`Self::placed`]): a fill's on the shape's bounds, a stroke's on what it paints. A gradient - /// along or across a stroke is its average color (the stroke is written as its outline). - pub(super) fn items(&mut self, n: &vectorcraft_doc::Node, bounds: Rect) -> Vec { + /// The fills and strokes of `n` that paint (outline `bp`), their gradients placed + /// ([`Self::placed`]): a fill's on the shape's bounds, a stroke's on what it paints, the stops + /// of one that repeats or reflects repeated over the box the stroke paints, miter spikes + /// included ([`StrokeLayer::bounds_on`]). A gradient along or across a stroke is its average + /// color (the stroke is written as its outline). + pub(super) fn items(&mut self, n: &vectorcraft_doc::Node, bp: &BezPath) -> Vec { + let bounds = bp.bounding_box(); super::visible_items(n) .into_iter() .map(|i| match i { @@ -154,7 +209,11 @@ impl Writer<'_> { self.warn(GRADIENTS); Paint::solid(average(&g.gradient)) } - None => self.placed(&s.paint, s.paint_bounds(bounds)), + None => { + let spread = matches!(&s.paint, Paint::Gradient(g) if g.gradient.is_spread()); + let reach = if spread { s.bounds_on(bp, bounds) } else { bounds }; + self.placed_over(&s.paint, s.paint_bounds(bounds), reach) + } }; AppearanceItem::Stroke(StrokeLayer { paint, ..s.clone() }) } @@ -244,7 +303,7 @@ impl Writer<'_> { self.instance_head(g, clip, path); let m = self.grad_space; let u = geom.end - geom.start; - let radial = g.gradient.kind == GradientKind::Radial; + let radial = written_radial(g.gradient.kind); // The unit vector along the gradient, and across it as long. let frame = |from: f64, to: f64| { let p = geom.start + u * from; @@ -275,10 +334,15 @@ impl Writer<'_> { /// A gradient instance's focal point (`Bh`, radial gradients only) and its `Bg` line, as /// [`Self::instance`] writes them; also what a fill's art style holds after its `Bb`. pub(super) fn instance_head(&mut self, g: &GradientPaint, clip: bool, path: &BezPath) { - let Some(geom) = g.geom else { return }; + let Some(mut geom) = g.geom else { return }; + if g.gradient.kind != GradientKind::Radial { + // Only a radial gradient has a focal point (a plug-in's or a file's other kinds can + // carry one that draws nothing): a diamond's circle stays centered. + geom.focal = None; + } let name = self.define_gradient(&g.gradient, g.swatch.as_deref()); let m = self.grad_space; - let radial = g.gradient.kind == GradientKind::Radial; + let radial = written_radial(g.gradient.kind); let place = placement(&geom, radial, &(self.canvas * path.clone()), self.canvas); if radial { let c = m * geom.start; @@ -305,8 +369,11 @@ impl Writer<'_> { if d.gradient.kind == GradientKind::Conic { self.warn(CONIC); } + if d.gradient.kind == GradientKind::Diamond { + self.warn(DIAMOND); + } let name = ps::bytes(d.name.as_bytes()); - let radial = d.gradient.kind == GradientKind::Radial; + let radial = written_radial(d.gradient.kind); let _ = writeln!(s, "%AI5_BeginGradient: {name}\n{name} {} {} Bd\n[", u8::from(radial), d.gradient.stops.len()); let mut stops = sorted_stops(&d.gradient); if !radial { @@ -324,7 +391,11 @@ impl Writer<'_> { /// A stop's color and its style: gray `lightness 0`, CMYK `c m y k 1`, RGB (and Lab, as RGB) /// `c m y k r g b 2` with its CMYK equivalent; a spot color its full color's CMYK equivalent, /// then its RGB values when it isn't CMYK, its name and how much lighter than the full color, - /// then `3` (CMYK), or `1 4` (RGB, and Lab as RGB). + /// then `3` (CMYK), or `1 4` (RGB, and Lab as RGB). RGB values are an RGB color's own (in the + /// working RGB space) and a Lab color's display RGB ([`ai_ops::rgb_values`]). An RGB color's CMYK + /// equivalent is converted from its values as written ([`ai_ops::as_written`]), a Lab color's + /// from its Lab values, and a spot color's CMYK equivalent and RGB values both come from its full + /// color as the palette writes it. fn stop_color(&mut self, s: &mut String, stop: &GradientStop) { let doc = self.doc; let intent = self.cms.settings().intent; @@ -333,11 +404,12 @@ impl Writer<'_> { && let Paint::Solid { color: full, swatch: None, .. } = sw.paint { if sw.spot { + let full = ai_ops::as_written(full); let cmyk = self.cms.to_cmyk(&doc.linked_color(full, true), intent).map(unit); ps::push_nums(s, &cmyk.map(f64::from)); let rgb = !matches!(full, Color::Cmyk { .. }); if rgb { - ps::push_nums(s, &full.to_rgb().map(|v| f64::from(unit(v)))); + ps::push_nums(s, &ai_ops::rgb_values(full).map(f64::from)); } s.push_str(&ps::bytes(name.as_bytes())); s.push(' '); @@ -359,9 +431,10 @@ impl Writer<'_> { s.push_str("1 "); } color @ (Color::Rgb { .. } | Color::Lab { .. }) => { - let cmyk = self.cms.to_cmyk(&color, intent).map(unit); + let source = if matches!(color, Color::Rgb { .. }) { ai_ops::as_written(color) } else { color }; + let cmyk = self.cms.to_cmyk(&source, intent).map(unit); ps::push_nums(s, &cmyk.map(f64::from)); - ps::push_nums(s, &color.to_rgb().map(|v| f64::from(unit(v)))); + ps::push_nums(s, &ai_ops::rgb_values(color).map(f64::from)); s.push_str("2 "); } } @@ -503,12 +576,25 @@ impl Writer<'_> { /// `(name) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p`. False for other paint, and for paint that can't /// be written. pub(super) fn swatch_paint(&mut self, s: &mut String, sw: &vectorcraft_color::swatch::Swatch) -> bool { + // A swatch has no placement: one that repeats or reflects holds its stops repeated along + // its vector, and one mixed around the hue wheel the stops on its curve. + let stops = match &sw.paint { + Paint::Gradient(g) => Some(hue_as_stops(&g.gradient)), + _ => None, + }; + let unrolled = stops.as_deref().map(|g| g.unrolled_within(crate::import::MAX_GRADIENT_STOPS)); match &sw.paint { - Paint::Gradient(g) if writable_gradient(&g.gradient) => { + Paint::Gradient(g) if unrolled.as_deref().is_some_and(writable_gradient) => { + if g.gradient.method.is_hue() { + self.warn(GRADIENT_HUE); + } + if g.gradient.is_spread() { + self.warn(SPREAD); + } let swatch = Some(sw.name.as_str()); - let name = self.define_gradient(&g.gradient, swatch); + let name = self.define_gradient(unrolled.as_deref().unwrap_or(&g.gradient), swatch); s.push_str("Bb\n"); - if g.gradient.kind == GradientKind::Radial { + if written_radial(g.gradient.kind) { s.push_str("0 0 0 0 Bh\n"); } let _ = writeln!(s, "2 {} 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB", ps::bytes(name.as_bytes())); diff --git a/crates/eps/src/ai_editing/writer/styles.rs b/crates/eps/src/ai_editing/writer/styles.rs index c4ae9fda3b..fe3e68ce24 100644 --- a/crates/eps/src/ai_editing/writer/styles.rs +++ b/crates/eps/src/ai_editing/writer/styles.rs @@ -40,8 +40,10 @@ pub(in crate::ai_editing) fn style_links(doc: &Document) -> usize { } /// The objects of `doc`'s layers that may be written with an art style ([`Writer::styled_object`]), -/// by id: paths and compound paths with points and groups, with live effects or linked to a graphic -/// style, without Opacity & Mask Define Knockout Shape (the reader takes an object's transparency +/// by id: paths and compound paths with points and groups, with live effects, linked to a graphic +/// style or (paths and compound paths) with a brush on a stroke, and embedded images with one Warp +/// ([`warped_image`]), without Opacity & Mask Define +/// Knockout Shape (the reader takes an object's transparency /// from its look, which doesn't carry it). A group's members are paths, compound paths or such /// groups, none with effects or anything baking changes. pub(in crate::ai_editing) fn styled_objects(doc: &Document) -> HashMap> { @@ -76,7 +78,8 @@ fn bakes_members(n: &Node) -> bool { /// Whether `n` may be written with an art style ([`styled_objects`]). fn candidate(n: &Node) -> bool { - let styled = !n.appearance.effects.is_empty() || n.extras().graphic_style.is_some(); + let brushed = brushed(n) && matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }); + let styled = !n.appearance.effects.is_empty() || n.extras().graphic_style.is_some() || brushed; if !styled || n.knockout_shape { return false; } @@ -84,10 +87,28 @@ fn candidate(n: &Node) -> bool { NodeKind::Path { path, guide: false, clipping: false, .. } => has_points(path), NodeKind::Compound { .. } => has_points(&compound_path(n)), NodeKind::Group { children, clip: false } => !n.is_compound_shape() && children.iter().all(|c| plain_member(c)), + NodeKind::Image(_) => warped_image(n), _ => false, } } +/// Is `n` an embedded image without an opacity mask whose appearance is one Warp, with no fills or +/// strokes that paint and no effects on them: an image the reader reads with its Warp live +/// ([`crate::import::read_art_style`]'s `image_warp`)? +fn warped_image(n: &Node) -> bool { + let NodeKind::Image(im) = &n.kind else { return false }; + im.link.is_none() + && n.extras().mask.is_none() + && matches!(n.appearance.effects.as_slice(), [e] if e.id.starts_with("warp.")) + && n.appearance.items.iter().all(|i| i.paint().is_none() && i.effects().is_empty()) +} + +/// Does `n` have a stroke with a brush that paints, one that its art style holds ([`Writer::style_text`] +/// leaves out what paints nothing)? +fn brushed(n: &Node) -> bool { + n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.brush.is_some() && !s.paint.is_none())) +} + /// Does `path` write anything ([`Writer::plain_object`] skips subpaths without points)? fn has_points(path: &vectorcraft_geom::PathData) -> bool { path.subpaths.iter().any(|sp| !sp.anchors.is_empty()) @@ -144,7 +165,7 @@ impl Styles { } /// One style as the reader's section holds it: `/KnownStyle :`, `(name) /Name ,`, its text. -fn known_style(name: &str, text: &str) -> String { +pub(super) fn known_style(name: &str, text: &str) -> String { format!("/KnownStyle :\n{} /Name ,\n{text}", ps::bytes(name.as_bytes())) } @@ -172,7 +193,7 @@ const NO_LINE: &str = "0 J 0 j 1 w 10 M []0 d\n"; /// A basic filter's start: its name and kind numbers (`1 0` for an effect, `0 0` for the /// style's own filters), `/Visible` and the dictionary's start. -fn basic(s: &mut String, name: &str, effect: bool, visible: bool) { +pub(super) fn basic(s: &mut String, name: &str, effect: bool, visible: bool) { let _ = write!(s, "/BasicFilter :\n{} {} 0 /Filter ,\n{} /Visible ,\n", ps::bytes(name.as_bytes()), u8::from(effect), u8::from(visible)); } @@ -180,7 +201,7 @@ fn basic(s: &mut String, name: &str, effect: bool, visible: bool) { const CONDUIT: &str = "/BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n"; /// A basic filter's end. -const END_BASIC: &str = "; /Dict ;\n /Part ,\n"; +pub(super) const END_BASIC: &str = "; /Dict ;\n /Part ,\n"; /// The blend filter of transparency `xy`. fn blend_filter(s: &mut String, xy: Xy) { @@ -228,7 +249,7 @@ fn flag(p: &Value, key: &str) -> Option { impl Writer<'_> { /// What `paint` writes with [`Self::color`] (a color, a spot or global color), as a string. - fn color_ops(&mut self, paint: &Paint, stroke: bool) -> String { + pub(super) fn color_ops(&mut self, paint: &Paint, stroke: bool) -> String { let saved = std::mem::take(&mut self.body); self.color(paint, stroke); std::mem::replace(&mut self.body, saved) @@ -267,9 +288,12 @@ impl Writer<'_> { } /// A stroke's basic filter: a color, its line style, and its width profile as the arrays - /// `BSVariableWidthTValuesArray`, `BSLeftWidthsArray` and `BSRightWidthsArray`. `None` for - /// other paint. + /// `BSVariableWidthTValuesArray`, `BSLeftWidthsArray` and `BSRightWidthsArray`; a stroke with a + /// brush, the brush's filter ([`Self::brush_filter`]). `None` for other paint. fn stroke_filter(&mut self, s: &mut String, st: &StrokeLayer, visible: bool) -> Option<()> { + if st.brush.is_some() { + return self.brush_filter(s, st, visible); + } if !matches!(st.paint, Paint::Solid { .. }) || st.overprint { return None; } @@ -652,17 +676,19 @@ impl Writer<'_> { && let Some(text) = self.styles.known.iter().find(|(n, _)| *n == name).map(|(_, t)| t.clone()) && object_reads(orig, &text) { - self.styles.links_written += 1; return Some(name); } - if orig.appearance.effects.is_empty() || !own_style_holds(&orig.appearance) { + let brushed = brushed(orig); + if (orig.appearance.effects.is_empty() && !brushed) || !(own_style_holds(&orig.appearance) || warped_image(orig)) { return None; } let graded = orig.appearance.items.iter().any(|i| matches!(i.paint(), Paint::Gradient(_))); let saved = (graded.then(|| self.gradient_mark()), self.warnings.len()); let path = drawn_outline(n, orig); let rule = object_rule(orig); - let text = self.style_text(&orig.appearance, Xy::of(orig), path.as_ref().map(|p| (p, rule))).filter(|t| object_reads(orig, t)); + let text = self + .style_text(&orig.appearance, Xy::of(orig), path.as_ref().map(|p| (p, rule))) + .filter(|t| object_reads(orig, t) && (!brushed || self.brushed_style_reads(t))); let Some(text) = text else { if let Some(mark) = saved.0 { self.gradient_rollback(mark); @@ -691,19 +717,27 @@ impl Writer<'_> { /// glows or feathers, the object's transparency /// after the group's end, `0 0 Xd`, `6 () XW`); the object itself on `%_` lines (a path's or /// compound path's points painted with nothing, or with its gradient fill when its style has - /// one; a group with its members), its name and opacity mask; then `1 (name) XW`. + /// one; a group with its members; an image with its pixels), its name and opacity mask; then + /// `1 (name) XW`. /// The look's group and the object itself are counted first ([`Self::take_objects`]): without - /// room for them, nothing is written. + /// room for them, nothing is written, and the object counts neither as written with its graphic + /// style nor as written with a brush on its stroke. pub(super) fn styled_object(&mut self, n: &Node, orig: &Node, name: &str) { let own = match &orig.kind { NodeKind::Path { path, .. } => super::object_count(path.subpaths.iter().filter(|sp| !sp.anchors.is_empty()).count()), NodeKind::Compound { .. } => super::object_count(compound_path(orig).subpaths.iter().filter(|sp| !sp.anchors.is_empty()).count()), - NodeKind::Group { .. } => 1, + NodeKind::Group { .. } | NodeKind::Image(_) => 1, _ => 0, }; if !self.take_objects(1 + own) { return; } + let linked = orig.extras().graphic_style.and_then(|id| self.styles.panel.get(&id)).is_some_and(|p| p == name); + if linked { + self.styles.links_written += 1; + } else if brushed(orig) { + self.brush_set.live_written += 1; + } self.state(orig.locked, !orig.visible); let xy = Xy::of(orig); let was = self.in_look; @@ -732,13 +766,14 @@ impl Writer<'_> { let saved = std::mem::take(&mut self.body); self.hidden += 1; let fit = drawn_outline(n, orig).map(|p| p.bounding_box()); - // A path's objects were kept for it above; it counts them itself. + // A path's or an image's objects were kept for it above; it counts them itself. if !matches!(orig.kind, NodeKind::Group { .. }) { self.objects -= own; } match &orig.kind { NodeKind::Path { path, rule, .. } => self.styled_outline(orig, path, *rule, fit, xy), NodeKind::Compound { rule, .. } => self.styled_outline(orig, &compound_path(orig), *rule, fit, xy), + NodeKind::Image(im) => self.image(&self.doc.shown_image(orig, im), xy), NodeKind::Group { children, .. } => { self.line("u"); for c in children { @@ -827,15 +862,20 @@ fn object_rule(n: &Node) -> FillRule { /// Can appearance `ap` be written as a style of an object's own: fills and strokes that paint without /// transparency or effects of their own, and no Warp, Distort & Transform or Blur effect? Those -/// are written only in the Graphic Styles panel's styles. +/// are written only in the Graphic Styles panel's styles, apart from a Warp on an image +/// ([`warped_image`]). fn own_style_holds(ap: &Appearance) -> bool { let plain = |i: &AppearanceItem| i.opacity() >= 1.0 && i.blend() == BlendMode::Normal && i.effects().is_empty(); let panel_only = |e: &Effect| ["warp.", "distort.", "blur."].iter().any(|p| e.id.starts_with(p)); ap.items.iter().filter(|i| !i.paint().is_none()).all(plain) && !ap.effects.iter().any(panel_only) } -/// Does the reader read graphic style `g` from style text `text` as it is? +/// Does the reader read graphic style `g` from style text `text` as it is? It leaves out a graphic +/// style with a brush on a stroke that paints. fn panel_reads(g: &GraphicStyle, text: &str) -> bool { + if g.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.brush.is_some() && !s.paint.is_none())) { + return false; + } let section = known_style("x", text); let Some(read) = crate::import::read_art_style(section.as_bytes(), "x", None) else { return false }; // The opacity within the written number's precision. @@ -846,13 +886,16 @@ fn panel_reads(g: &GraphicStyle, text: &str) -> bool { /// Does the reader read object `n` written with style text `text` as it is: a path or compound /// path with a style it reads on any object, filled by the non-zero rule when the style fills it, /// or a group with no fills or strokes of its own, with effects that move the outline only where the -/// reader reads them ([`crate::import::style_moves_with`])? +/// reader reads them ([`crate::import::style_moves_with`]), or an image ([`warped_image`]) with a +/// style of one Warp? The reader takes such an image's Warp where it draws as its drawn look. fn object_reads(n: &Node, text: &str) -> bool { let section = known_style("x", text); let own = n.appearance.fill().map(|f| &f.paint).filter(|p| matches!(p, Paint::Gradient(_))); let Some(mut read) = crate::import::read_art_style(section.as_bytes(), "x", own) else { return false }; let group = matches!(n.kind, NodeKind::Group { .. }); - if !read.simple + let image = matches!(n.kind, NodeKind::Image(_)); + if (image && !(read.image_warp && warped_image(n))) + || (!image && !read.simple) || (group && !read.appearance.items.is_empty()) || (!group && read.pathfinder) || !crate::import::style_moves_with(section.as_bytes(), "x", n) @@ -889,9 +932,16 @@ pub(in crate::ai_editing) fn same_appearance(a: &Appearance, b: &Appearance) -> } /// Effect `e`'s settings with its defaults filled in, its blending mode in lower case and its color as -/// `#rrggbb`. +/// `#rrggbb`. A Warp's map `version` is left out: the file holds the warp's settings, and the reader +/// gives every warp it reads the newest map, so a warp saved before the version existed is written +/// with its settings as before. fn normalized_params(e: &Effect) -> Value { let mut p = vectorcraft_effects::merged_params(&e.id, &e.params); + if e.id.starts_with("warp.") + && let Value::Object(m) = &mut p + { + m.remove("version"); + } if let Some(m) = word(&p, "mode") { p["mode"] = Value::String(m); } @@ -911,7 +961,7 @@ fn normalized_params(e: &Effect) -> Value { const NEAR: f64 = 6e-3; /// JSON values equal but for numbers within the written numbers' precision. -fn near(a: &Value, b: &Value) -> bool { +pub(super) fn near(a: &Value, b: &Value) -> bool { match (a, b) { (Value::Number(x), Value::Number(y)) => match (x.as_f64(), y.as_f64()) { (Some(x), Some(y)) => (x - y).abs() <= NEAR, diff --git a/crates/eps/src/ai_editing/writer/texts.rs b/crates/eps/src/ai_editing/writer/texts.rs index 5ebd73de3a..b161ec636f 100644 --- a/crates/eps/src/ai_editing/writer/texts.rs +++ b/crates/eps/src/ai_editing/writer/texts.rs @@ -338,6 +338,8 @@ pub(in crate::ai_editing) fn loses(t: &TextObject) -> bool { CharStyle { font_family: s.font_family.clone(), font_style: s.font_style.clone(), + // The font record's version (`/5`) names the face; whether it comes back is `font_kept`'s. + font_version: s.font_version.clone(), size: s.size, leading: s.leading, tracking: s.tracking.round(), @@ -385,6 +387,9 @@ pub(in crate::ai_editing) fn loses(t: &TextObject) -> bool { if p.justify == Justify::Auto && p.direction.is_none() && rtl_letter { return true; } + let hangul = + text.chars().any(|c| matches!(c, '\u{1100}'..='\u{11FF}' | '\u{3130}'..='\u{318F}' | '\u{A960}'..='\u{A97F}' | '\u{AC00}'..='\u{D7FF}' | '\u{FFA0}'..='\u{FFDC}')); + let pairs = text.chars().zip(text.chars().skip(1)).any(|(a, b)| vectorcraft_text::inseparable(a, b)); let held = ParaStyle { justify: p.justify, left_indent: p.left_indent, @@ -398,6 +403,12 @@ pub(in crate::ai_editing) fn loses(t: &TextObject) -> bool { // Width, Standard burasagari) isn't reported: it changes no other script's lines. mojikumi: if p.mojikumi == Mojikumi::LineEndHalf { p.mojikumi } else { ParaStyle::default().mojikumi }, burasagari: if p.burasagari == Burasagari::Standard { p.burasagari } else { ParaStyle::default().burasagari }, + // The text document has no Korean Line Break Anywhere: it reads back off, which + // changes only the lines of a paragraph with Hangul in it. + korean_line_break_anywhere: p.korean_line_break_anywhere && !hangul, + // Nor Bunri-Kinshi: it reads back off, which changes only the lines of a paragraph + // with an inseparable pair in it. + bunri_kinshi: p.bunri_kinshi && !pairs, ..ParaStyle::default() }; *p != held @@ -443,15 +454,17 @@ struct FontRecord { /// the font's order, in the axis's own units. Empty for a static font, which has none: without /// it, an app that opens the file takes a variable font's default instance (#6388). design: Vec, - /// For a variable font, its version string (`/5`, name ID 5); empty for a static font. + /// Its version string (`/5`, name ID 5): for a variable font, and for a static font whose + /// PostScript name alone gives the reader another installed copy (two copies of one font, see + /// the reader's `document_font`); else empty. version: String, } -/// The font the font set names for style `st`: an installed face's PostScript name, and for a -/// variable font the setting of each of its axes (the named instance's, or the style's own -/// Variable Font setting, clamped to the axis as layout clamps it) and its version; else its family -/// and style as `family-style` (the family alone for Regular), the form the reader's -/// `family_style` splits. +/// The font the font set names for style `st`: an installed face's PostScript name, its version +/// for a variable font or when the name alone gives the reader another installed copy, and for a +/// variable font the setting of each of its axes (the named instance's, or the style's own Variable +/// Font setting, clamped to the axis as layout clamps it); else its family and style as +/// `family-style` (the family alone for Regular), the form the reader's `family_style` splits. fn font_name(st: &CharStyle) -> FontRecord { let db = vectorcraft_text::FontDb::global(); // The face of that family and style (the font database gives a fallback face for others). @@ -470,8 +483,11 @@ fn font_name(st: &CharStyle) -> FontRecord { set.map_or(own, |v| (v as f32).clamp(a.min.min(a.max), a.max.max(a.min))) }) .collect(); - let version = if design.is_empty() { String::new() } else { face.version.clone() }; - FontRecord { name: face.postscript_name(), truetype: face.is_truetype(), design, version } + let name = face.postscript_name(); + // The reader takes the face of a name alone as `postscript_face` finds it. + let by_name = crate::import::postscript_face(&name, None).is_some_and(|f| f.id() == face.id()); + let version = if design.is_empty() && by_name { String::new() } else { face.version.clone() }; + FontRecord { name, truetype: face.is_truetype(), design, version } } None if st.font_style.is_empty() || st.font_style == "Regular" => record(st.font_family.clone()), None => record(format!("{}-{}", st.font_family, st.font_style.replace(' ', ""))), @@ -509,12 +525,19 @@ fn fixed(v: f32) -> i64 { if v.is_finite() { (f64::from(v) * 65536.0).round() as i64 } else { 0 } } -/// Does the font of style `st` come back as itself: the family and style the reader makes of the -/// name it is written under (as its `char_style` does)? +/// Does the font of style `st` come back as itself: are the family and style the reader makes of +/// the record it is written as (its name, and its version as the reader takes it, as its +/// `char_style` does) the style's own, and the face they and the version read back resolve to the +/// face of the style? A version that isn't installed draws in the face the font resolves to anyway. fn font_kept(st: &CharStyle) -> bool { - let (family, style) = crate::family_style(&font_name(st).name); - let family = vectorcraft_text::FontDb::global().find_family(&family).unwrap_or(family); - family == st.font_family && style == st.font_style + let record = font_name(st); + let version = crate::import::record_version(&record.version); + let (family, style, read) = crate::import::document_font(&record.name, version); + let db = vectorcraft_text::FontDb::global(); + let face = |family: &str, style: &str, version: Option<&str>| db.face_version(family, style, version).map(|f| f.id()); + family == st.font_family + && style == st.font_style + && face(&family, &style, read.as_deref()) == face(&st.font_family, &st.font_style, st.font_version.as_deref()) } /// Whether `c` is a strong right-to-left letter (`Some(true)`: Hebrew, Arabic, Syriac, Thaana, NKo @@ -1013,13 +1036,13 @@ impl TextDoc { .iter() .map(|f| { let mut font = vec![(0, V::Str(f.name.clone())), (2, V::Int(i64::from(f.truetype)))]; - // A variable font's place in its design space and its version (#6388); a static - // font has neither. + // A variable font's place in its design space (#6388), and the version of a + // variable font or of a static one its name alone doesn't give back. if !f.design.is_empty() { font.push((4, V::List(f.design.iter().map(|v| V::Int(fixed(*v))).collect()))); - if !f.version.is_empty() { - font.push((5, V::Str(f.version.clone()))); - } + } + if !f.version.is_empty() { + font.push((5, V::Str(f.version.clone()))); } dict(vec![(99, V::Name("CoolTypeFont")), (0, dict(font))]) }) diff --git a/crates/eps/src/ai_ops.rs b/crates/eps/src/ai_ops.rs index 7707f4bc45..3b2bdd88d8 100644 --- a/crates/eps/src/ai_ops.rs +++ b/crates/eps/src/ai_ops.rs @@ -103,6 +103,27 @@ pub(crate) fn unit(v: f32) -> f32 { if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 } } +/// `color` as a reader reads it back from the values written for it ([`ps::written`]): RGB values +/// clamped to 0..1, L to 0..100 and a and b to -128..127, each to four decimals; other colors +/// unchanged. +pub(crate) fn as_written(color: Color) -> Color { + let w = |v: f32| ps::written(f64::from(v)) as f32; + match color { + Color::Rgb { r, g, b } => Color::rgb(w(unit(r)), w(unit(g)), w(unit(b))), + Color::Lab { l, a, b } => Color::lab(w(l.clamp(0.0, 100.0)), w(a.clamp(-128.0, 127.0)), w(b.clamp(-128.0, 127.0))), + c => c, + } +} + +/// The RGB values written for `color`, clamped to 0..1: an RGB color's own values (in the working +/// RGB space, as a reader reads them back), any other color's display RGB. +pub(crate) fn rgb_values(color: Color) -> [f32; 3] { + match color { + Color::Rgb { r, g, b } => [r, g, b].map(unit), + c => c.to_rgb().map(unit), + } +} + /// The average colour of a gradient's stops (in RGB). pub(crate) fn average(g: &Gradient) -> Color { let n = g.stops.len().max(1) as f32; diff --git a/crates/eps/src/dcs.rs b/crates/eps/src/dcs.rs new file mode 100644 index 0000000000..1de21a4afe --- /dev/null +++ b/crates/eps/src/dcs.rs @@ -0,0 +1,491 @@ +//! DCS files (Desktop Color Separation): an EPS file whose header comments point at one EPS +//! program per printing plate. A DCS 2.0 file names each plate with `%%PlateFile: (name) EPS +//! #offset size`, the plate inside the file `offset` bytes from its start, or `%%PlateFile: (name) +//! EPS Local file`, the plate in a file of its own; a DCS 1.0 file names the four process plates' +//! files with `%%CyanPlate:`, `%%MagentaPlate:`, `%%YellowPlate:` and `%%BlackPlate:`. Spot inks +//! take their process equivalents from `%%CMYKCustomColor:` (else `%%RGBCustomColor:`). The comments +//! are described at http://www.telegraphics.net/doc/DCS.txt. +//! +//! [`read`] finds those comments; [`place`] reads every plate's image (its ink amounts: a dark +//! plate pixel is ink) into one [`Separated`] image, with the clipping path the main file's +//! composite is drawn through. + +use vectorcraft_color::cms::PROCESS_PLATES; +use vectorcraft_doc::separated::{InkPlate, MAX_NAME, MAX_PLATES, MAX_SAMPLES, Separated}; +use vectorcraft_doc::{Document, Node, NodeKind}; +use vectorcraft_geom::{Affine, Rect}; + +/// Where a plate's program is. +#[derive(Clone, Debug, PartialEq)] +pub enum PlateAt { + /// In the DCS file itself: `len` bytes from byte `offset` of the file. + Here { offset: usize, len: usize }, + /// In a file of its own, as the DCS file names it (a path or a file name). + File(String), +} + +/// One plate a DCS file names. +#[derive(Clone, Debug, PartialEq)] +pub struct PlateRef { + /// "Cyan", "Magenta", "Yellow", "Black" or a spot ink's name. + pub name: String, + pub at: PlateAt, +} + +/// The DCS comments of a file. +#[derive(Clone, Debug, PartialEq)] +pub struct Dcs { + /// 1 or 2. + pub version: u8, + pub plates: Vec, + /// Spot inks' process equivalents (C, M, Y, K, 0..1), by name. + pub equivalents: Vec<(String, [f32; 4])>, +} + +impl Dcs { + /// The names of the plate files kept apart from the DCS file. + pub fn plate_files(&self) -> impl Iterator { + self.plates.iter().filter_map(|p| match &p.at { + PlateAt::File(f) => Some(f.as_str()), + PlateAt::Here { .. } => None, + }) + } +} + +/// The DCS comments of EPS file `bytes` (behind its binary header, if it has one); `None` when it +/// names no plate. +pub fn read(bytes: &[u8]) -> Option { + let (ps, _) = crate::sections(bytes)?; + if !ps.starts_with(b"%!") { + return None; + } + // The plates of the DCS 2.0 comments and of the DCS 1.0 ones. + let mut plates: Vec = vec![]; + let mut old: Vec = vec![]; + let mut equivalents: Vec<(String, [f32; 4])> = vec![]; + let mut rgb: Vec<(String, [f32; 4])> = vec![]; + // The comment a `%%+` line continues. + let mut last = String::new(); + for raw in ps.split(|b| matches!(b, b'\n' | b'\r')).filter(|l| !l.is_empty()).take(MAX_HEADER_LINES) { + let line = header_line(raw); + let line = line.trim_end(); + if line.starts_with("%%EndComments") || !line.starts_with('%') { + break; + } + let (key, value) = match line.strip_prefix("%%+") { + Some(v) => (last.clone(), v.trim()), + None => match line.split_once(':') { + Some((k, v)) => (k.to_string(), v.trim()), + None => (line.to_string(), ""), + }, + }; + match key.as_str() { + "%%PlateFile" => { + if let Some(p) = plate_file(value) + && !plates.iter().any(|q| q.name == p.name) + { + plates.push(p); + } + } + "%%CyanPlate" | "%%MagentaPlate" | "%%YellowPlate" | "%%BlackPlate" => { + let name = key.trim_start_matches("%%").trim_end_matches("Plate").to_string(); + if !value.is_empty() && !old.iter().any(|q| q.name == name) { + old.push(PlateRef { name, at: PlateAt::File(value.to_string()) }); + } + } + "%%CMYKCustomColor" => equivalents.extend(custom_colors(value, false)), + "%%RGBCustomColor" => rgb.extend(custom_colors(value, true)), + _ => {} + } + last = key; + } + // A file is one version or the other; the plate comments of DCS 2.0 win. + let version = if plates.is_empty() { + plates = old; + 1 + } else { + 2 + }; + if plates.is_empty() { + return None; + } + for (name, c) in rgb { + if !equivalents.iter().any(|(n, _)| *n == name) { + equivalents.push((name, c)); + } + } + Some(Dcs { version, plates, equivalents }) +} + +/// Most header lines looked at for the DCS comments. +const MAX_HEADER_LINES: usize = 10_000; + +/// Header line `raw` as text: UTF-8 when it is, else Latin-1 (each byte one character), as the +/// octal escapes of names are read. +fn header_line(raw: &[u8]) -> std::borrow::Cow<'_, str> { + match std::str::from_utf8(raw) { + Ok(s) => std::borrow::Cow::Borrowed(s), + Err(_) => std::borrow::Cow::Owned(raw.iter().copied().map(char::from).collect()), + } +} + +/// `s` without its first word and the whitespace around that word. +fn after_word(s: &str) -> &str { + s.trim_start().split_once(char::is_whitespace).map_or("", |(_, rest)| rest.trim_start()) +} + +/// A `%%PlateFile:` comment's plate: `(name) EPS #offset size` or `(name) EPS Local file`; `None` +/// for other locations, which only a print server reads. +fn plate_file(v: &str) -> Option { + let (name, rest) = ps_string(v)?; + let mut words = rest.split_whitespace(); + let _kind = words.next()?; + let location = words.next()?; + let name = canonical(name)?; + if let Some(offset) = location.strip_prefix('#') { + let len = words.next()?.parse().ok()?; + return Some(PlateRef { name, at: PlateAt::Here { offset: offset.parse().ok()?, len } }); + } + if !location.eq_ignore_ascii_case("Local") { + return None; + } + // The file name as it is written, its spaces kept. + let file = after_word(after_word(rest)); + (!file.is_empty()).then(|| PlateRef { name, at: PlateAt::File(file.to_string()) }) +} + +/// A plate's name as it is kept: a process ink's in its usual case ("cyan" is "Cyan"); `None` when +/// it is empty or longer than [`MAX_NAME`]. +fn canonical(name: String) -> Option { + if name.is_empty() || name.len() > MAX_NAME { + return None; + } + Some(PROCESS_PLATES.iter().find(|p| p.eq_ignore_ascii_case(&name)).map_or(name, |p| p.to_string())) +} + +/// The custom colours of a `%%CMYKCustomColor:` (four numbers then a name, repeated) or, with +/// `rgb`, a `%%RGBCustomColor:` comment (three numbers), the RGB ones as the process inks that +/// take their light away (`1 − r`, `1 − g`, `1 − b`, no black). Names may be bare words. +fn custom_colors(v: &str, rgb: bool) -> Vec<(String, [f32; 4])> { + let mut out = vec![]; + let mut rest = v.trim(); + let n = if rgb { 3 } else { 4 }; + while !rest.is_empty() && out.len() < MAX_PLATES { + let mut nums = [0.0f32; 4]; + for v in nums.iter_mut().take(n) { + let Some((word, after)) = rest.split_once(char::is_whitespace) else { return out }; + let Some(x) = word.parse::().ok().filter(|x| (0.0..=1.0).contains(x)) else { return out }; + *v = x; + rest = after.trim_start(); + } + let (name, after) = match ps_string(rest) { + Some((s, a)) => (s, a), + None => { + let (w, a) = rest.split_once(char::is_whitespace).unwrap_or((rest, "")); + (w.to_string(), a) + } + }; + rest = after.trim_start(); + let cmyk = if rgb { [1.0 - nums[0], 1.0 - nums[1], 1.0 - nums[2], 0.0] } else { nums }; + if let Some(name) = canonical(name) { + out.push((name, cmyk)); + } + } + out +} + +/// The PostScript string at the start of `v` (`(…)`, with nested parentheses and backslash +/// escapes) and what follows it. +fn ps_string(v: &str) -> Option<(String, &str)> { + let body = v.trim_start().strip_prefix('(')?; + let mut out = String::new(); + let mut depth = 0usize; + let mut chars = body.char_indices().peekable(); + while let Some((i, c)) = chars.next() { + match c { + '\\' => match chars.next()?.1 { + 'n' => out.push('\n'), + 'r' => out.push('\r'), + 't' => out.push('\t'), + d @ '0'..='7' => { + let mut code = d.to_digit(8)?; + for _ in 0..2 { + match chars.peek().and_then(|(_, e)| e.to_digit(8)) { + Some(e) => { + chars.next(); + code = code * 8 + e; + } + None => break, + } + } + // Octal escapes name bytes; names are read as Latin-1. + out.push(char::from_u32(code & 0xff)?); + } + e => out.push(e), + }, + '(' => { + depth += 1; + out.push(c); + } + ')' if depth == 0 => return Some((out, body.get(i + 1..)?)), + ')' => { + depth -= 1; + out.push(c); + } + _ => out.push(c), + } + } + None +} + +/// The main part of DCS file `bytes`: its PostScript (behind its binary header, if it has one), up +/// to the first plate it holds. +pub fn main_program<'a>(bytes: &'a [u8], dcs: &Dcs) -> Option<&'a [u8]> { + let (ps, _) = crate::sections(bytes)?; + let start = ps.as_ptr() as usize - bytes.as_ptr() as usize; + let first = dcs.plates.iter().filter_map(|p| match p.at { + PlateAt::Here { offset, .. } if offset > start => Some(offset - start), + _ => None, + }); + Some(&ps[..first.min().unwrap_or(ps.len()).min(ps.len())]) +} + +/// A DCS file read for placing. +#[derive(Debug)] +pub struct Placed { + pub separated: Separated, + /// The file's page (its bounding box) with its top-left corner at the origin. + pub page: Rect, + /// The image's pixels onto the page. + pub xf: Affine, + /// The clipping path the composite is drawn through, on the page. + pub clip: Option, + /// The resolution of the plates (pixels per inch), from how large they print. + pub ppi: Option<(f64, f64)>, + pub warnings: Vec, +} + +/// One plate's image: its ink amounts, one byte a pixel, and where its pixels print on its page. +struct PlateImage { + width: u32, + height: u32, + data: Vec, + xf: Affine, +} + +/// Read DCS file `bytes` (its comments `dcs`) for placing: every plate's image, the plates kept +/// apart read with `file` (the name the file gives → the plate file's bytes). The plates are put on +/// the pixel grid of the first plate's image, grown to hold every plate's image where it prints; +/// another plate is resampled onto it. An error when the file names more than [`MAX_PLATES`] +/// plates or a plate can't be read. +pub fn place(bytes: &[u8], dcs: &Dcs, file: &mut dyn FnMut(&str) -> Result, String>) -> Result { + if dcs.plates.len() > MAX_PLATES { + return Err(format!("it names {} plates, and at most {MAX_PLATES} are read", dcs.plates.len())); + } + let main = main_program(bytes, dcs).ok_or("the file's preview header points outside the file")?; + let page = crate::page(main)?; + let mut warnings = vec![]; + let (mut images, mut samples) = (vec![], 0u64); + for p in &dcs.plates { + let read = match &p.at { + PlateAt::Here { offset, len } => { + let eps = offset.checked_add(*len).and_then(|end| bytes.get(*offset..end)); + let eps = eps.ok_or_else(|| format!("the {} plate lies outside the file", p.name))?; + plate_image(eps) + } + PlateAt::File(f) => file(f).and_then(|eps| plate_image(&eps)), + }; + let img = read.map_err(|e| format!("the {} plate can't be read: {e}", p.name))?; + // Checked before the other plates are read. + samples += u64::from(img.width) * u64::from(img.height); + if samples > MAX_SAMPLES { + return Err(format!("its plates are too large: more than {MAX_SAMPLES} pixels together")); + } + images.push((p, img)); + } + let Some((w, h, xf)) = grid(images.iter().map(|(_, img)| img)) else { return Err("the file names no plate".into()) }; + if !Separated::fits(w, h, images.len()) { + return Err(format!("its plates are too large: {} plates of {w} × {h} pixels", images.len())); + } + let mut plates = vec![]; + for (p, img) in images { + let name = p.name.clone(); + let aligned = img.xf.as_coeffs().iter().zip(xf.as_coeffs()).all(|(a, b)| (a - b).abs() < 1e-9); + let data = if (img.width, img.height) == (w, h) && aligned { img.data } else { resample(&img, w, h, xf) }; + let cmyk = match dcs.equivalents.iter().find(|(n, _)| *n == name) { + Some((_, c)) => *c, + None if PROCESS_PLATES.contains(&name.as_str()) => [0.0; 4], + None => { + warnings.push(format!("the file gives no process equivalent for the {name} ink: it shows as black")); + [0.0, 0.0, 0.0, 1.0] + } + }; + plates.push(InkPlate { name, cmyk, data }); + } + let separated = Separated::new(w, h, plates).ok_or("its plates can't be kept together")?; + let clip = clip_path(main); + // Points one pixel spans along each axis. + let [a, b, c, d, ..] = xf.as_coeffs(); + let ppi = [a.hypot(b), c.hypot(d)].map(|l| (l > 1e-12).then(|| 72.0 / l)); + let ppi = match ppi { + [Some(x), Some(y)] => Some((x, y)), + _ => None, + }; + Ok(Placed { separated, page, xf, clip, ppi, warnings }) +} + +/// The pixel grid the plates `images` go on: the first image's pixels, grown by whole pixels to +/// hold where every image prints, as its width, height and where its pixels print; `None` without +/// an image. It is the first image's own when its transform can't be inverted. +fn grid<'a>(mut images: impl Iterator) -> Option<(u32, u32, Affine)> { + let first = images.next()?; + let own = Some((first.width, first.height, first.xf)); + if first.xf.determinant().abs() <= 1e-12 { + return own; + } + let to_first = first.xf.inverse(); + let mut r = Rect::new(0.0, 0.0, f64::from(first.width), f64::from(first.height)); + for img in images { + r = r.union((to_first * img.xf).transform_rect_bbox(Rect::new(0.0, 0.0, f64::from(img.width), f64::from(img.height)))); + } + // Edges within a millionth of a pixel of a whole one are on it. + let snap = |v: f64, up: bool| { + let n = v.round(); + if (v - n).abs() < 1e-6 { + n + } else if up { + v.ceil() + } else { + v.floor() + } + }; + let (x0, y0, x1, y1) = (snap(r.x0, false), snap(r.y0, false), snap(r.x1, true), snap(r.y1, true)); + let size = |a: f64, b: f64| Some(b - a).filter(|n| n.is_finite() && (1.0..=f64::from(u32::MAX)).contains(n)).map(|n| n as u32); + match (size(x0, x1), size(y0, y1)) { + (Some(w), Some(h)) => Some((w, h, first.xf * Affine::translate((x0, y0)))), + // Larger than any separated image may be ([`Separated::fits`]). + _ => Some((u32::MAX, u32::MAX, first.xf)), + } +} + +/// The ink amounts of `img` on the `w` × `h` pixels that `onto` puts on the page (each the +/// nearest pixel of `img` where it prints there, none outside it). When either transform can't be +/// inverted, the pixels are stretched over one another instead. +fn resample(img: &PlateImage, w: u32, h: u32, onto: Affine) -> Vec { + let (sw, sh) = (img.width as usize, img.height as usize); + let mut out = Vec::with_capacity(w as usize * h as usize); + let invertible = |m: Affine| m.determinant().abs() > 1e-12; + // From a pixel of the image made to a pixel of `img`. + let to_plate = (invertible(img.xf) && invertible(onto)).then(|| img.xf.inverse() * onto); + for y in 0..h as usize { + for x in 0..w as usize { + let at = match to_plate { + Some(m) => { + let p = m * vectorcraft_geom::Point::new(x as f64 + 0.5, y as f64 + 0.5); + let inside = p.x >= 0.0 && p.y >= 0.0 && p.x < sw as f64 && p.y < sh as f64; + inside.then(|| (p.y as usize).min(sh - 1) * sw + (p.x as usize).min(sw - 1)) + } + None => Some((y * sh / h as usize).min(sh - 1) * sw + (x * sw / w as usize).min(sw - 1)), + }; + out.push(at.and_then(|i| img.data.get(i).copied()).unwrap_or(0)); + } + } + out +} + +/// Is an image under `n` (itself included) drawn through a clipping path: inside a clipping group +/// or layer, or `inside` one already? +fn clips_an_image(n: &Node, inside: bool) -> bool { + let inside = inside || matches!(n.kind, NodeKind::Group { clip: true, .. } | NodeKind::Layer { clip: true, .. }); + match &n.kind { + NodeKind::Image(_) => inside, + _ => n.children().is_some_and(|ch| ch.iter().any(|c| clips_an_image(c, inside))), + } +} + +/// The image plate program `eps` draws, as ink amounts (how dark each pixel is: 255 less its +/// luma), and where it prints on its page; an error when it draws more than one image, or art +/// besides it. +fn plate_image(eps: &[u8]) -> Result { + let r = crate::import_with(eps, false)?; + if r.preview { + return Err(r.warnings.first().cloned().unwrap_or_else(|| "its PostScript can't be read".into())); + } + // A plate is one image: one that draws more (several images, or art) would lose ink. + let (mut found, mut images, mut art) = (None, 0usize, false); + r.document.walk(|n| match &n.kind { + NodeKind::Image(im) => { + images += 1; + found.get_or_insert((im.key.clone(), im.xf, im.width, im.height)); + } + NodeKind::Path { clipping: true, .. } | NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::RulerGuide { .. } => {} + NodeKind::Path { .. } | NodeKind::Compound { .. } => { + art |= n.visible && n.appearance.items.iter().any(|i| i.visible() && !matches!(i.paint(), vectorcraft_color::Paint::None)) + } + _ => art |= n.visible, + }); + if images > 1 || (art && images == 1) { + return Err(if images > 1 { "it draws more than one image".into() } else { "it draws art besides its image".into() }); + } + // Ink outside a clipping path would print: a plate whose image is clipped is refused. + if images == 1 && r.document.layers.iter().any(|l| clips_an_image(l, false)) { + return Err("it draws its image through a clipping path".into()); + } + let (key, xf, iw, ih) = found.ok_or("it draws no image")?; + let blob = r.document.images.get(&key).ok_or("it draws no image")?; + let (width, height, data) = blob.coverage().ok_or("its image is too large to read")?; + // The object's pixel space may differ from the pixels it keeps. + let xf = xf * Affine::scale_non_uniform(f64::from(iw) / f64::from(width.max(1)), f64::from(ih) / f64::from(height.max(1))); + Ok(PlateImage { width, height, data, xf }) +} + +/// The clipping path the first image of `main` is drawn through, when it is drawn through one. +fn clip_path(main: &[u8]) -> Option { + let r = crate::import_with(main, false).ok().filter(|r| !r.preview)?; + first_clip(&r.document) +} + +/// The clipping path the first image of `d` is drawn through: the clipping path of the innermost +/// clipping group that holds an image, cut to the clipping paths of the clipping groups around it. +fn first_clip(d: &Document) -> Option { + /// The clipping paths around the innermost clipping group under `n` that holds an image, + /// outermost first. + fn find(n: &Node) -> Option> { + let NodeKind::Group { children, clip } = &n.kind else { + return n.children().and_then(|ch| ch.iter().find_map(|c| find(c))); + }; + let first = children.first().filter(|f| *clip && matches!(f.kind, NodeKind::Path { clipping: true, .. })); + if let Some(mut inner) = children.iter().find_map(|c| find(c)) { + if let Some(f) = first { + inner.insert(0, (**f).clone()); + } + return Some(inner); + } + let holds_image = || { + let mut any = false; + n.walk(&mut |c: &Node| any |= matches!(c.kind, NodeKind::Image(_))); + any + }; + first.filter(|_| holds_image()).map(|f| vec![(**f).clone()]) + } + let mut clips = d.layers.iter().find_map(|l| find(l))?; + let mut innermost = clips.pop()?; + // The clipping paths together clip to where they overlap. + for outer in clips.iter().rev() { + if let (NodeKind::Path { path: o, rule: or, .. }, NodeKind::Path { path, rule, .. }) = (&outer.kind, &mut innermost.kind) { + *path = vectorcraft_pathops::boolean(path, *rule, o, *or, vectorcraft_pathops::BoolOp::Intersect); + *rule = vectorcraft_geom::FillRule::NonZero; + } + } + // An even-odd clipping path is kept as the same area under the nonzero rule, the rule of the + // clip groups the Links commands make and match again. + if let NodeKind::Path { path, rule: rule @ vectorcraft_geom::FillRule::EvenOdd, .. } = &mut innermost.kind + && let Ok(nonzero) = vectorcraft_pathops::try_boolean_n(&[(&*path, vectorcraft_geom::FillRule::EvenOdd)], |inside| !inside.is_empty()) + { + (*path, *rule) = (nonzero, vectorcraft_geom::FillRule::NonZero); + } + Some(innermost) +} + +#[cfg(test)] +mod tests; diff --git a/crates/eps/src/dcs/tests.rs b/crates/eps/src/dcs/tests.rs new file mode 100644 index 0000000000..b55fea0b84 --- /dev/null +++ b/crates/eps/src/dcs/tests.rs @@ -0,0 +1,283 @@ +//! DCS files made from scratch as http://www.telegraphics.net/doc/DCS.txt describes them: a main +//! EPS file whose header names its plates, each plate an EPS program drawing one grayscale image. + +use std::collections::HashMap; + +use vectorcraft_doc::NodeKind; + +use super::*; + +/// A plate program: one `w` × `h` grayscale image (`gray`, row by row from the top) on a 20 × 10 +/// pt page. +pub(crate) fn plate_eps(w: u32, h: u32, gray: &[u8]) -> String { + let hex: String = gray.iter().map(|g| format!("{g:02x}")).collect(); + format!( + "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 20 10\n%%EndComments\n20 10 scale\n{w} {h} 8 [{w} 0 0 -{h} 0 {h}] <{hex}> image\nshowpage\n%%Trailer\n%%EOF\n" + ) +} + +/// The composite: the image `w` × `h` drawn through a clipping path, the left half of the page. +fn composite(w: u32, h: u32) -> String { + let hex = "80".repeat((w * h * 3) as usize); + format!( + "gsave newpath 0 0 moveto 10 0 lineto 10 10 lineto 0 10 lineto closepath clip newpath\n20 10 scale\n{w} {h} 8 [{w} 0 0 -{h} 0 {h}] <{hex}> false 3 colorimage\ngrestore\nshowpage\n%%EOF\n" + ) +} + +/// A single-file DCS 2.0 file of `plates` (name, plate program), with the header lines `extra`. +pub(crate) fn single_file(plates: &[(&str, String)], extra: &str) -> Vec { + // Offsets and sizes are written ten digits wide, so the header's length is known first. + let header = |offsets: &[usize]| { + let mut s = String::from("%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 20 10\n"); + s.push_str(extra); + for ((name, eps), at) in plates.iter().zip(offsets) { + s.push_str(&format!("%%PlateFile: ({name}) EPS #{at:010} {:010}\n", eps.len())); + } + s.push_str("%%EndComments\n"); + s.push_str(&composite(2, 2)); + s + }; + let main = header(&vec![0; plates.len()]).len(); + let mut offsets = vec![]; + let mut at = main; + for (_, eps) in plates { + offsets.push(at); + at += eps.len(); + } + let mut out = header(&offsets).into_bytes(); + assert_eq!(out.len(), main); + for (_, eps) in plates { + out.extend(eps.as_bytes()); + } + out +} + +#[test] +fn single_file_plates_and_equivalents_are_read() { + let plate = plate_eps(1, 1, &[0]); + let extra = "%%DocumentCustomColors: (PANTONE 185 C)\n%%+ (Gr\\374n \\(A\\))\n%%CMYKCustomColor: 0 .91 .76 0 (PANTONE 185 C)\n%%+ .5 0 1 0 (Gr\\374n \\(A\\))\n%%RGBCustomColor: 1 1 0 (Lemon)\n"; + let bytes = single_file(&[("cyan", plate.clone()), ("PANTONE 185 C", plate.clone()), ("Grün (A)", plate.clone())], extra); + let dcs = read(&bytes).unwrap(); + assert_eq!(dcs.version, 2); + let names: Vec<&str> = dcs.plates.iter().map(|p| p.name.as_str()).collect(); + assert_eq!(names, ["Cyan", "PANTONE 185 C", "Grün (A)"], "a process ink in its usual case; escapes read"); + let PlateAt::Here { offset, len } = dcs.plates[1].at else { panic!("in the file: {:?}", dcs.plates[1]) }; + assert_eq!(&bytes[offset..offset + len], plate.as_bytes()); + assert_eq!( + dcs.equivalents, + [ + ("PANTONE 185 C".to_string(), [0.0, 0.91, 0.76, 0.0]), + ("Grün (A)".to_string(), [0.5, 0.0, 1.0, 0.0]), + ("Lemon".to_string(), [0.0, 0.0, 1.0, 0.0]) + ] + ); + assert_eq!(dcs.plate_files().count(), 0); + let main = main_program(&bytes, &dcs).unwrap(); + assert!(main.ends_with(b"%%EOF\n"), "up to the first plate"); + let PlateAt::Here { offset: first, .. } = dcs.plates[0].at else { panic!("in the file") }; + assert_eq!(main.len(), first); +} + +#[test] +fn plate_files_of_both_versions_are_read() { + let two = "%!PS-Adobe-3.0 EPSF-3.0\n%%PlateFile: (Black) EPS Local pic.K\n%%PlateFile: (Black) TIFF NewServe c:\\scans\\a0K.scn\n%%PlateFile: (TRUMATCH 1-a5) EPS Local my pic.9\n%%EndComments\n"; + let dcs = read(two.as_bytes()).unwrap(); + assert_eq!(dcs.version, 2); + assert_eq!( + dcs.plates, + [ + PlateRef { name: "Black".into(), at: PlateAt::File("pic.K".into()) }, + PlateRef { name: "TRUMATCH 1-a5".into(), at: PlateAt::File("my pic.9".into()) }, + ] + ); + let one = "%!PS-Adobe-2.0 EPSF-1.2\n%%CyanPlate: pic.C\n%%MagentaPlate: pic.M\n%%YellowPlate: pic.Y\n%%BlackPlate: pic.K\n%%EndComments\n"; + let dcs = read(one.as_bytes()).unwrap(); + assert_eq!(dcs.version, 1); + assert_eq!(dcs.plate_files().collect::>(), ["pic.C", "pic.M", "pic.Y", "pic.K"]); + let both = "%!PS-Adobe-2.0 EPSF-1.2\n%%CyanPlate: old.C\n%%PlateFile: (Cyan) EPS Local new.C\n%%EndComments\n"; + assert_eq!(read(both.as_bytes()).unwrap().plate_files().collect::>(), ["new.C"], "the DCS 2.0 comments win"); + // Comments after the header are not the file's. + assert!(read(b"%!PS-Adobe-3.0 EPSF-3.0\n%%EndComments\n%%PlateFile: (Cyan) EPS Local a.C\n").is_none()); + assert!(read(plate_eps(1, 1, &[0]).as_bytes()).is_none(), "a plain EPS file"); + assert!(read(b"\x89PNG").is_none()); +} + +#[test] +fn a_plate_program_drawing_more_than_its_image_is_an_error() { + let plate = plate_eps(1, 1, &[0]); + // Two image tiles, and an image with a filled square beside it. + let tiles = plate.replacen("showpage", "1 1 8 [1 0 0 -1 0 1] <00> image\nshowpage", 1); + let art = plate.replacen("20 10 scale", "0 0 moveto 5 0 lineto 5 5 lineto closepath fill\n20 10 scale", 1); + for (eps, why) in [(tiles, "more than one image"), (art, "art besides its image")] { + let bytes = single_file(&[("Cyan", eps)], ""); + let err = place(&bytes, &read(&bytes).unwrap(), &mut |_| Err("no files".into())).unwrap_err(); + assert!(err.contains("the Cyan plate can't be read") && err.contains(why), "{err}"); + } + let bytes = single_file(&[("Cyan", plate)], ""); + assert!(place(&bytes, &read(&bytes).unwrap(), &mut |_| Err("no files".into())).is_ok(), "one image alone"); +} + +#[test] +fn a_plate_program_clipping_its_image_is_an_error() { + let clipped = plate_eps(1, 1, &[0]).replacen("20 10 scale", "newpath 0 0 moveto 5 0 lineto 5 5 lineto closepath clip newpath\n20 10 scale", 1); + let bytes = single_file(&[("Cyan", clipped)], ""); + let err = place(&bytes, &read(&bytes).unwrap(), &mut |_| Err("no files".into())).unwrap_err(); + assert!(err.contains("the Cyan plate can't be read") && err.contains("clipping path"), "{err}"); +} + +#[test] +fn only_an_image_inside_a_clipping_group_or_layer_is_clipped() { + use std::sync::Arc; + use vectorcraft_color::Paint; + use vectorcraft_doc::NodeId; + let clip_path = || { + let rect = vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)); + let mut p = Node::path(NodeId(1), rect, vectorcraft_doc::Appearance::basic(Paint::None, Paint::None, 0.0)); + if let NodeKind::Path { clipping, .. } = &mut p.kind { + *clipping = true; + } + Arc::new(p) + }; + let image = || { + let im = vectorcraft_doc::ImageObject { + key: "k".into(), + width: 1, + height: 1, + xf: Affine::IDENTITY, + link: None, + placement: Default::default(), + pixels: None, + }; + Arc::new(Node::new(NodeId(2), NodeKind::Image(Box::new(im)))) + }; + let group = |children: Vec>, clip| Node::new(NodeId(3), NodeKind::Group { children, clip }); + let beside = group(vec![Arc::new(group(vec![clip_path()], true)), image()], false); + assert!(!clips_an_image(&beside, false), "a clipping group beside the image"); + assert!(clips_an_image(&group(vec![clip_path(), image()], true), false), "the image inside the clipping group"); + assert!(clips_an_image(&group(vec![image()], false), true), "inside a clipping layer"); +} + +#[test] +fn nested_clips_around_the_composite_clip_it_together() { + // The left two thirds of the page, then the right three quarters inside it: 5 to 13 pt. + let main = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 20 10\n%%EndComments\n\ + gsave newpath 0 0 moveto 13 0 lineto 13 10 lineto 0 10 lineto closepath clip newpath\n\ + gsave newpath 5 0 moveto 20 0 lineto 20 10 lineto 5 10 lineto closepath clip newpath\n\ + 20 10 scale 2 2 8 [2 0 0 -2 0 2] <808080808080808080808080> false 3 colorimage grestore grestore showpage\n%%EOF\n"; + let clip = clip_path(main.as_bytes()).expect("a clipping path"); + let b = clip.geometric_bounds().expect("bounds"); + assert!((b.x0 - 5.0).abs() < 1e-6 && (b.x1 - 13.0).abs() < 1e-6, "where both clips overlap: {b:?}"); +} + +#[test] +fn plate_file_names_keep_their_spaces() { + let two = "%!PS-Adobe-3.0 EPSF-3.0\n%%PlateFile: (Cyan) EPS Local my pic .C\n%%EndComments\n"; + assert_eq!(read(two.as_bytes()).unwrap().plate_files().collect::>(), ["my pic .C"]); +} + +#[test] +fn header_bytes_that_are_not_utf8_are_latin1() { + // `Grün` with a raw Latin-1 ü (0xFC), in a plate name and in a custom color's name. + let mut two = b"%!PS-Adobe-3.0 EPSF-3.0\n%%CMYKCustomColor: .5 0 1 0 (Gr\xfcn)\n%%PlateFile: (Gr\xfcn) EPS Local a.9\n".to_vec(); + two.extend(b"%%PlateFile: (Grau \xc3\xa9) EPS Local b.9\n%%EndComments\n"); + let dcs = read(&two).unwrap(); + let names: Vec<&str> = dcs.plates.iter().map(|p| p.name.as_str()).collect(); + assert_eq!(names, ["Grün", "Grau é"], "a line that is UTF-8 is read as UTF-8"); + assert_eq!(dcs.equivalents, [("Grün".to_string(), [0.5, 0.0, 1.0, 0.0])]); +} + +#[test] +fn every_plate_is_read_with_the_clipping_path() { + // 2 × 2 pixels: cyan solid on the top row, the spot ink at 50% on the first column. + let bytes = single_file( + &[("Cyan", plate_eps(2, 2, &[0, 0, 255, 255])), ("PANTONE 185 C", plate_eps(2, 2, &[127, 255, 127, 255]))], + "%%CMYKCustomColor: 0 .91 .76 0 (PANTONE 185 C)\n", + ); + let dcs = read(&bytes).unwrap(); + let p = place(&bytes, &dcs, &mut |_| Err("no files".into())).unwrap(); + assert!(p.warnings.is_empty(), "{:?}", p.warnings); + assert_eq!(p.page, Rect::new(0.0, 0.0, 20.0, 10.0)); + let s = &p.separated; + assert_eq!((s.width, s.height), (2, 2)); + assert_eq!(s.plates[0].data, [255, 255, 0, 0], "a dark plate pixel is ink"); + assert_eq!(s.plates[1].data, [128, 0, 128, 0]); + assert_eq!(s.plates[1].cmyk, [0.0, 0.91, 0.76, 0.0]); + assert_eq!(p.xf * vectorcraft_geom::Point::new(2.0, 2.0), vectorcraft_geom::Point::new(20.0, 10.0)); + assert_eq!(p.ppi, Some((7.2, 14.4))); + let clip = p.clip.expect("the composite's clipping path"); + assert!(matches!(clip.kind, NodeKind::Path { clipping: true, .. })); + assert_eq!(clip.geometric_bounds().map(|b| b.width().round()), Some(10.0), "the left half of the page"); +} + +#[test] +fn plate_files_are_read_with_the_callback() { + let main = "%!PS-Adobe-2.0 EPSF-1.2\n%%BoundingBox: 0 0 20 10\n%%CyanPlate: pic.C\n%%BlackPlate: pic.K\n%%EndComments\nshowpage\n"; + let files: HashMap<&str, String> = [("pic.C", plate_eps(1, 1, &[0])), ("pic.K", plate_eps(2, 1, &[255, 0]))].into(); + let dcs = read(main.as_bytes()).unwrap(); + let mut asked = vec![]; + let p = place(main.as_bytes(), &dcs, &mut |f| { + asked.push(f.to_string()); + files.get(f).map(|e| e.as_bytes().to_vec()).ok_or_else(|| "missing".into()) + }) + .unwrap(); + assert_eq!(asked, ["pic.C", "pic.K"]); + assert!(p.clip.is_none(), "no composite, no clipping path"); + assert_eq!((p.separated.width, p.separated.height), (1, 1), "the first plate's size"); + assert_eq!(p.separated.plates[1].data, [255], "resampled to it: the pixel at its centre"); + let err = place(main.as_bytes(), &dcs, &mut |_| Err("not found".into())).unwrap_err(); + assert_eq!(err, "the Cyan plate can't be read: not found"); +} + +#[test] +fn plates_printing_elsewhere_on_the_page_stay_in_register() { + // The Black plate's one solid pixel prints on the right half of the page only. + let right = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 20 10\n%%EndComments\n10 0 translate 10 10 scale\n1 1 8 [1 0 0 -1 0 1] <00> image\nshowpage\n%%EOF\n"; + let bytes = single_file(&[("Cyan", plate_eps(2, 1, &[255, 255])), ("Black", right.to_string())], ""); + let p = place(&bytes, &read(&bytes).unwrap(), &mut |_| Err("no files".into())).unwrap(); + assert_eq!((p.separated.width, p.separated.height), (2, 1)); + assert_eq!(p.separated.plates[1].data, [0, 255], "the ink lands on the right pixel only"); +} + +/// A plate program whose one solid pixel prints on a 10 × 10 pt square `x` pt from the page's left. +fn square_at(x: u32) -> String { + format!( + "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 20 10\n%%EndComments\n{x} 0 translate 10 10 scale\n1 1 8 [1 0 0 -1 0 1] <00> image\nshowpage\n%%EOF\n" + ) +} + +#[test] +fn the_plates_grid_grows_to_hold_every_plate() { + let bytes = single_file(&[("Cyan", square_at(0)), ("Black", square_at(10))], ""); + let p = place(&bytes, &read(&bytes).unwrap(), &mut |_| Err("no files".into())).unwrap(); + assert_eq!((p.separated.width, p.separated.height), (2, 1), "the first plate's pixels, grown over the second"); + assert_eq!(p.separated.plates[0].data, [255, 0]); + assert_eq!(p.separated.plates[1].data, [0, 255], "nothing of the second plate is cut off"); + assert_eq!(p.xf * vectorcraft_geom::Point::new(2.0, 1.0), vectorcraft_geom::Point::new(20.0, 10.0)); +} + +#[test] +fn a_file_naming_more_plates_than_are_read_is_an_error() { + let plate = plate_eps(1, 1, &[0]); + let names: Vec = (0..=MAX_PLATES).map(|i| format!("Ink {i}")).collect(); + let plates: Vec<(&str, String)> = names.iter().map(|n| (n.as_str(), plate.clone())).collect(); + let bytes = single_file(&plates, ""); + let dcs = read(&bytes).unwrap(); + assert_eq!(dcs.plates.len(), MAX_PLATES + 1, "every plate named"); + let err = place(&bytes, &dcs, &mut |_| Err("no files".into())).unwrap_err(); + assert_eq!(err, "it names 65 plates, and at most 64 are read"); +} + +#[test] +fn bad_plates_are_errors_and_missing_equivalents_warnings() { + let mut bytes = single_file(&[("Cyan", plate_eps(1, 1, &[0]))], ""); + let dcs = read(&bytes).unwrap(); + bytes.truncate(bytes.len() - 5); + assert_eq!(place(&bytes, &dcs, &mut |_| Err(String::new())).unwrap_err(), "the Cyan plate lies outside the file"); + let text = single_file(&[("Cyan", "%!PS-Adobe-3.0\n0 0 moveto 1 1 lineto stroke\n".to_string())], ""); + let err = place(&text, &read(&text).unwrap(), &mut |_| Err(String::new())).unwrap_err(); + assert_eq!(err, "the Cyan plate can't be read: it draws no image"); + let spot = single_file(&[("Mystery", plate_eps(1, 1, &[0]))], ""); + let p = place(&spot, &read(&spot).unwrap(), &mut |_| Err(String::new())).unwrap(); + assert_eq!(p.separated.plates[0].cmyk, [0.0, 0.0, 0.0, 1.0]); + assert_eq!(p.warnings, ["the file gives no process equivalent for the Mystery ink: it shows as black"]); +} diff --git a/crates/eps/src/import.rs b/crates/eps/src/import.rs index 0a5799ddf9..bdb3b9cf50 100644 --- a/crates/eps/src/import.rs +++ b/crates/eps/src/import.rs @@ -42,6 +42,7 @@ mod interp; mod lex; mod native; mod obj; +mod predefined_cmap; mod preview; mod shading; mod text; @@ -81,17 +82,21 @@ use graphics::{GState, Out}; use interp::{Fault, Interp}; use obj::PsError; +#[cfg(test)] +pub(crate) use ai::ENVELOPE_DRAWN; pub use ai::NameEncoding; #[cfg(test)] pub(crate) use ai::objects_read; pub(crate) use ai::{ - MAX_EDITING_OBJECTS, MAX_GRADIENT_STOPS, MAX_LISTED, MAX_LISTED_NAME, MAX_SYMBOLS, read_art_style, read_style_list, style_moves_with, - symbol_art_member, warp_number, + BRUSH_MANAGER, BrushesRead, DEFORM_PLUGIN, EnvelopeGridPoint, MAX_CHECKED as ENVELOPE_CHECKS, MAX_EDITING_OBJECTS, MAX_GRADIENT_STOPS, + MAX_LISTED, MAX_LISTED_NAME, MAX_SYMBOLS, brush_plugin_name, brushes_kept, envelope_outline, envelope_upright, read_art_style, read_brush_object, + read_style_list, style_moves_with, symbol_art_member, warp_number, }; -pub(crate) use ate::{MAX_BYTES as MAX_TEXT_DOCUMENT, MAX_FRAMES, MAX_SEGMENTS, MAX_STORY, MAX_VALUES as MAX_TEXT_VALUES}; +pub(crate) use ate::{MAX_BYTES as MAX_TEXT_DOCUMENT, MAX_FRAMES, MAX_SEGMENTS, MAX_STORY, MAX_VALUES as MAX_TEXT_VALUES, record_version}; pub use native::{AiLayers, ai_alone, ai_alone_on_page, ai_alone_with, ai_layers_alone, ai_opened_artboard, is_loss, layered_ai, layered_ai_from}; pub(crate) use native::{MAX_TEXT, scale_document}; pub use text::family_style; +pub(crate) use text::{document_font, postscript_face}; /// The page of a PostScript file without a bounding box (US Letter). const LETTER: [f64; 4] = [0.0, 0.0, 612.0, 792.0]; diff --git a/crates/eps/src/import/ai.rs b/crates/eps/src/import/ai.rs index be2d679a78..4595061151 100644 --- a/crates/eps/src/import/ai.rs +++ b/crates/eps/src/import/ai.rs @@ -34,10 +34,12 @@ use std::io::Read as _; use super::lex::find; use crate::ps; +pub(crate) use brush::{BrushesRead, MANAGER_NAME as BRUSH_MANAGER, brushes_kept, plugin_name as brush_plugin_name, read_brush_object}; pub(crate) use envelope::DRAWN as ENVELOPE_DRAWN; -#[cfg(test)] pub(crate) use envelope::MAX_CHECKED; pub(crate) use envelope::TYPE_DRAWN as ENVELOPE_TYPE_DRAWN; +pub(crate) use envelope::{GridPoint as EnvelopeGridPoint, PLUGIN as DEFORM_PLUGIN, outline as envelope_outline, upright as envelope_upright}; +pub(crate) use envelope::{MAX_ANY as ENVELOPE_MAX_ANY, MAX_SOLID as ENVELOPE_MAX_SOLID}; pub(crate) use envelope::{WARPED_TYPE_DRAWN, WarpedType}; pub(crate) use frames::text_frames; pub use obj::{NameEncoding, Names}; diff --git a/crates/eps/src/import/ai/brush.rs b/crates/eps/src/import/ai/brush.rs index dc94ff7927..5a5db47114 100644 --- a/crates/eps/src/import/ai/brush.rs +++ b/crates/eps/src/import/ai/brush.rs @@ -563,3 +563,127 @@ pub(super) fn without_frame(art: Node) -> Node { } out } + +/// The plug-in name the objects of brushes of kind `kind` have, for writers. +pub(crate) fn plugin_name(kind: &BrushKind) -> &'static str { + let tool = match kind { + BrushKind::Calligraphic(_) => Tool::Calligraphic, + BrushKind::Scatter(_) => Tool::Scatter, + BrushKind::Art(_) => Tool::Art, + BrushKind::Pattern(_) => Tool::Pattern, + BrushKind::Bristle(_) => Tool::Bristle, + }; + TOOLS.iter().find(|(_, t)| *t == tool).map_or("", |(n, _)| *n) +} + +/// The plug-in name of the brush manager's order, for writers. +pub(crate) const MANAGER_NAME: &str = MANAGER; + +/// A brush object as the reader reads it, for writers that check a brush before they write it. +#[derive(Clone, Debug)] +pub(crate) struct BrushRead { + /// The brush the Brushes panel gets. + pub brush: Brush, + /// A path whose art style names the brush, at the brush's own settings, opens with the brush on + /// its stroke: a Calligraphic brush, or an Art brush whose art an Art brush draws as the file + /// does ([`art_bends`]) and whose numbers are those of a brush that stretches its art along the + /// path, unflipped, at 100% in Tints. + pub live: bool, +} + +/// The brush named `name` whose object has the plug-in name `plugin` and the parameters `params`, +/// with `art` as the art its parameters name (as the reader reads that art), as the reader reads +/// it: `None` when the reader doesn't make a brush of it. +pub(crate) fn read_brush_object(plugin: &str, name: &str, params: &str, art: Option<&Node>) -> Option { + let draft = parse_tool_object(tool(plugin)?, name, params).ok()?; + let mut sections = HashMap::new(); + if let (DraftKind::Scatter { art: section, .. } | DraftKind::Art { art: section, .. }, Some(a)) = (&draft.kind, art) { + sections.insert(section.clone(), a.clone()); + } + let drafts = [draft]; + let live = kept(&drafts, §ions).first().copied().unwrap_or(false) + && match &drafts[0].kind { + DraftKind::Calligraphic(_) => true, + DraftKind::Art { plain: true, art: section, .. } => bending_art(&drafts, §ions).contains(section), + _ => false, + }; + let [draft] = drafts; + let (mut brushes, _) = finish_brushes(vec![draft], §ions, None); + Some(BrushRead { brush: brushes.pop()?, live }) +} + +/// Which of the brush objects `brushes` (plug-in name, name, parameters, the art each names as the +/// reader reads it) the reader makes into brushes when one file holds them all: not one it can't read, +/// nor one past the art the reader copies into one file's brushes ([`kept`]). +pub(crate) fn brushes_kept(brushes: &[(&str, &str, &str, Option<&Node>)]) -> Vec { + let mut drafts = vec![]; + let mut at = vec![]; + let mut sections = HashMap::new(); + for (i, (plugin, name, params, art)) in brushes.iter().enumerate() { + let Some(d) = tool(plugin).and_then(|t| parse_tool_object(t, name, params).ok()) else { continue }; + if let (DraftKind::Scatter { art: s, .. } | DraftKind::Art { art: s, .. }, Some(a)) = (&d.kind, art) { + sections.insert(s.clone(), (*a).clone()); + } + drafts.push(d); + at.push(i); + } + let mut out = vec![false; brushes.len()]; + for (i, k) in at.into_iter().zip(kept(&drafts, §ions)) { + if let Some(slot) = out.get_mut(i) { + *slot = k; + } + } + out +} + +/// Brush objects a writer writes, as the reader reads them together from one file, for checking +/// the art styles that name them ([`Self::style_reads`]). +pub(crate) struct BrushesRead { + drafts: Vec, + /// The brush a stroke that names a brush is drawn with, by name: the first one kept + /// ([`kept`]), as an index in [`Self::drafts`]. + by_name: HashMap, + /// The art an Art brush draws as the file does ([`bending_art`]). + bending: HashSet, +} + +impl BrushesRead { + /// `brushes`: the brush objects written (plug-in name, name, parameters) and the art each names, + /// as the reader reads it. + pub(crate) fn new(brushes: &[(&str, &str, &str, Option<&Node>)]) -> Self { + let mut drafts = vec![]; + let mut sections = HashMap::new(); + for (plugin, name, params, art) in brushes { + let Some(d) = tool(plugin).and_then(|t| parse_tool_object(t, name, params).ok()) else { continue }; + if let (DraftKind::Scatter { art: s, .. } | DraftKind::Art { art: s, .. }, Some(a)) = (&d.kind, art) { + sections.insert(s.clone(), (*a).clone()); + } + drafts.push(d); + } + let mut by_name = HashMap::new(); + for (i, (d, k)) in drafts.iter().zip(kept(&drafts, §ions)).enumerate() { + if k { + by_name.entry(d.name.clone()).or_insert(i); + } + } + let bending = bending_art(&drafts, §ions); + Self { drafts, by_name, bending } + } + + /// Does the reader read every stroke of art style `style` in `section` (the text between + /// `%AI9_BeginArtStyles` and its end) that names a brush with that brush on it, at the brush's + /// own settings? A style the reader doesn't read, or that names a brush no object gives, or an + /// Art brush in a style with effects, isn't read so. + pub(crate) fn style_reads(&self, section: &[u8], style: &str) -> bool { + use super::style::StyleItem; + let styles = super::style::art_styles(section); + let Some(st) = styles.get(style).filter(|st| st.plain) else { return false }; + st.items.iter().all(|item| match item { + StyleItem::Stroke { brush: Some((name, settings)), .. } => { + let Some(draft) = self.by_name.get(name).and_then(|i| self.drafts.get(*i)) else { return false }; + draws_as(draft, settings, &self.bending) && !(matches!(settings, PathBrush::Art) && !st.effects.is_empty()) + } + _ => true, + }) + } +} diff --git a/crates/eps/src/import/ai/envelope.rs b/crates/eps/src/import/ai/envelope.rs index 8b3fceecf3..3ae753b7d5 100644 --- a/crates/eps/src/import/ai/envelope.rs +++ b/crates/eps/src/import/ai/envelope.rs @@ -32,7 +32,7 @@ use std::sync::Arc; use kurbo::{Affine, BezPath, Point, Rect, Vec2}; use vectorcraft_doc::live::{ EnvelopeKind, EnvelopeOptions, GradientMesh, H_DOWN, H_LEFT, H_RIGHT, H_UP, PreserveShape, default_fidelity, envelope_content_boxes, - envelope_stroke_margin, + envelope_content_boxes_with, envelope_stroke_margin, }; use vectorcraft_doc::{Appearance, Document, Effect, ImageBlob, LayerColor, Node, NodeId, NodeKind, PatternDef}; use vectorcraft_geom::PathData; @@ -41,7 +41,7 @@ use super::obj::Obj; use crate::import::native::compare::{MAX_DIFFERENCE, MAX_SOLID_DIFFERENCE, compare_scale, differ, differ_in_colour, differ_on_black}; /// The plugin that writes envelopes. -pub(super) const PLUGIN: &str = "Adobe Deform Plugin"; // brand-ok: the plugin name the files use +pub(crate) const PLUGIN: &str = "Adobe Deform Plugin"; // brand-ok: the plugin name the files use /// The note for an envelope that keeps its drawn art. pub(crate) const DRAWN: &str = "an envelope VectorCraft couldn't read as a live envelope comes in as its drawn art"; /// The note for an envelope of type, which keeps its drawn art with its type hidden (unless the @@ -73,9 +73,9 @@ const MOVED_SLACK: f64 = 0.5; const KNOWN_BITS: i64 = 0b111 | 1 << 16 | 1 << 17; /// More of the inked pixels than this differing, each with all its neighbours, and the envelope /// doesn't come out as drawn. -const MAX_SOLID: f64 = 0.03; +pub(crate) const MAX_SOLID: f64 = 0.03; /// More of the inked pixels than this differing at all, and the envelope doesn't come out as drawn. -const MAX_ANY: f64 = 0.1; +pub(crate) const MAX_ANY: f64 = 0.1; /// The whole number of entry `key`: `None` when it is missing, `Some(None)` when it isn't one. fn whole(o: &Obj, key: &str) -> Option> { @@ -150,23 +150,31 @@ fn half_stroked_box(content: &[Arc]) -> Option { fn grown(r: Rect, by: f64) -> Rect { if by.is_finite() && by > 0.0 { r.inflate(by, by) } else { r } } - fn walk(n: &Arc, acc: Option) -> Option { + /// `n`'s box, with type that draws nothing given its laid-out box only with `blank`. + fn walk(n: &Arc, acc: Option, blank: bool) -> Option { let one = std::slice::from_ref(n); match &n.kind { NodeKind::Text(t) => { - let Some((_, ink)) = envelope_content_boxes(one, Affine::IDENTITY) else { return acc }; + let Some((_, ink)) = envelope_content_boxes_with(one, Affine::IDENTITY, blank) else { return acc }; // The characters' own strokes as the type's bounds with strokes measure them (they // have no miter allowance there), and the strokes of its appearance along a side. vectorcraft_geom::union_opt(acc, Some(grown(ink, t.char_stroke_outset().max(along(&n.appearance))))) } NodeKind::Group { children, clip: false } => { - let members = children.iter().fold(None, |acc, c| walk(c, acc)); + let members = children.iter().fold(None, |acc, c| walk(c, acc, blank)); vectorcraft_geom::union_opt(acc, members.map(|b| grown(b, along(&n.appearance)))) } - _ => vectorcraft_geom::union_opt(acc, envelope_content_boxes(one, Affine::IDENTITY).map(|(stroked, _)| stroked)), + _ => vectorcraft_geom::union_opt(acc, envelope_content_boxes_with(one, Affine::IDENTITY, blank).map(|(stroked, _)| stroked)), } } - content.iter().fold(None, |acc, c| walk(c, acc)) + let blank = blank_type_box(content); + content.iter().fold(None, |acc, c| walk(c, acc, blank)) +} + +/// Do the contents of an envelope give type that draws nothing its laid-out box: has nothing else +/// in `content` a box ([`envelope_content_boxes_with`])? +fn blank_type_box(content: &[Arc]) -> bool { + envelope_content_boxes_with(content, Affine::IDENTITY, false).is_none() } /// Envelope `kind` mapping from its contents' glyphs grown by as far as their strokes paint along a @@ -189,6 +197,116 @@ fn with_strokes(kind: &NodeKind) -> Option { Some(kind) } +/// How far, in points, the sides of two boxes may lie apart and still count as the same side: the +/// glyphs' box (from type's ink) and the box of what type paints (from its outlines) measure one +/// outline two ways, and where they meet they differ by rounding only ([`painted_margin`], +/// [`same_box`]). +const PAINTED_SLACK: f64 = 1e-4; + +/// The box of what the pieces of type's outlines `outlines` ([`vectorcraft_effects::outline_text`]) +/// paint as an envelope with Distort Appearance bends them: each piece baked as the envelope bakes +/// it ([`vectorcraft_effects::bake_type_appearance`]: geometry effects on its fills and strokes +/// applied, so a stroke a Transform effect moves counts where it is moved to), measured by its +/// visual bounds. Those are exact for miter joins (a tip counts where the miter limit keeps it) and +/// round joins, and an upper bound for bevel joins, miters the limit cuts, width profiles and +/// square-capped dashes; a contour of zero length, which paints nothing, doesn't count. Effects on +/// the type object itself are left out: VectorCraft applies them after the envelope bends the type. +/// `None` when nothing in it has bounds. +fn painted_outlines(outlines: &Node) -> Option { + outlines.children().into_iter().flatten().fold(None, |acc, piece| { + let baked = vectorcraft_effects::bake_type_appearance(None, piece); + vectorcraft_geom::union_opt(acc, baked.as_ref().unwrap_or(piece).visual_bounds()) + }) +} + +/// The box of `content` an envelope of type with Distort Appearance may map from in a file besides +/// [`half_stroked_box`]: what it paints, type by its outlines ([`painted_outlines`]), groups by +/// their members grown by as far as their own strokes paint along a side, other objects by their +/// bounds with strokes. `None` when nothing in it has bounds. +fn painted_box(content: &[Arc]) -> Option { + /// `n`'s box, with type that draws nothing given its laid-out box only with `blank`. + fn walk(n: &Arc, acc: Option, blank: bool) -> Option { + match &n.kind { + NodeKind::Text(_) => vectorcraft_geom::union_opt(acc, vectorcraft_effects::outline_text(n).as_ref().and_then(painted_outlines)), + NodeKind::Group { children, clip: false } => { + let along = n.appearance.painted_strokes().map(|s| s.side_reach(true)).fold(0.0, f64::max); + let members = children.iter().fold(None, |acc, c| walk(c, acc, blank)); + let grown = |r: Rect| if along.is_finite() && along > 0.0 { r.inflate(along, along) } else { r }; + vectorcraft_geom::union_opt(acc, members.map(grown)) + } + _ => vectorcraft_geom::union_opt( + acc, + envelope_content_boxes_with(std::slice::from_ref(n), Affine::IDENTITY, blank).map(|(stroked, _)| stroked), + ), + } + } + let blank = blank_type_box(content); + content.iter().fold(None, |acc, c| walk(c, acc, blank)) +} + +/// The bounds margin of `painted`, the box of what contents with geometric box `plain` paint, a side +/// within [`PAINTED_SLACK`] of the geometric box's counting as that side. `None` where it lies +/// inside the geometric box on a side, where it is that box, and for margins that don't fit. +fn painted_margin(painted: Rect, plain: Rect) -> Option<[f32; 4]> { + let side = |p: f64, g: f64| if (p - g).abs() <= PAINTED_SLACK { g } else { p }; + let painted = Rect::new(side(painted.x0, plain.x0), side(painted.y0, plain.y0), side(painted.x1, plain.x1), side(painted.y1, plain.y1)); + let margin = envelope_stroke_margin(painted, plain)?; + (margin.iter().all(|m| *m >= 0.0) && margin.iter().any(|m| *m > 0.0)).then_some(margin) +} + +/// Do bounds margins `a` and `b` give contents with geometric box `plain` the same box, each side +/// within [`PAINTED_SLACK`]? +fn same_box(a: [f32; 4], b: [f32; 4], plain: Rect) -> bool { + let sizes = [plain.height(), plain.height(), plain.width(), plain.width()]; + a.iter().zip(b).zip(sizes).all(|((a, b), size)| (f64::from(*a) - f64::from(b)).abs() * size <= PAINTED_SLACK) +} + +/// What the contents of an envelope of type paint ([`painted_box`]): their geometric box and the +/// bounds margin of what they paint from it. +#[derive(Clone, Copy)] +struct Painted { + plain: Rect, + margin: [f32; 4], +} + +/// [`Painted`] for envelope `kind` with Distort Appearance; `None` without it, and where +/// [`painted_margin`] gives none. +fn painted_of(kind: &NodeKind) -> Option { + let NodeKind::Envelope { content, options, .. } = kind else { return None }; + if !options.distort_appearance { + return None; + } + let (_, plain) = envelope_content_boxes(content, Affine::IDENTITY)?; + Some(Painted { plain, margin: painted_margin(painted_box(content)?, plain)? }) +} + +/// Envelope `kind` mapping from what its contents paint (`painted`, [`painted_of`]), for an +/// envelope with Distort Appearance where that box is neither the one it maps from already nor its +/// contents' glyphs grown by half their strokes' weight ([`with_strokes`]); `None` otherwise. +fn as_painted(kind: &NodeKind, painted: &Painted) -> Option { + let NodeKind::Envelope { options, .. } = kind else { return None }; + let half = match with_strokes(kind) { + Some(NodeKind::Envelope { options, .. }) => Some(options.bounds_margin), + _ => None, + }; + let Painted { plain, margin } = *painted; + if !options.distort_appearance || same_box(margin, options.bounds_margin, plain) || half.is_some_and(|h| same_box(margin, h, plain)) { + return None; + } + let mut kind = kind.clone(); + if let NodeKind::Envelope { options, .. } = &mut kind { + options.bounds_margin = margin; + } + Some(kind) +} + +/// A way an envelope of type is tried: a kind, or a kind mapping from what its type paints +/// ([`as_painted`]), worked out when its turn comes. +enum Way { + As(NodeKind), + Painted(NodeKind), +} + /// The kind of `envelope`, a mesh or a top object in Edit Contents, with its grid moved onto /// `drawn`, the drawn art the file saves for it, where what it draws is as large as that art (within /// [`MOVED_SLACK`]) but lies elsewhere (further than that): moved by as far as the drawn art's box @@ -244,6 +362,7 @@ fn warp(o: &Obj) -> Option { h: percent("DeformHoriz")?, v: percent("DeformVert")?, horizontal: !vertical, + version: vectorcraft_doc::live::WARP_NET, }) } @@ -260,12 +379,12 @@ fn only_mesh(n: &Node) -> Option<&GradientMesh> { } /// A grid point and its handles. -type GridPoint = (Point, [Vec2; 4]); +pub(crate) type GridPoint = (Point, [Vec2; 4]); /// The points of mesh `m` as a `rows`×`cols` grid with its first row at the top and its first /// column at the left (y down), as an envelope's mesh lays them out; `None` for a grid out of range /// or with points that aren't finite. -fn upright(m: &GradientMesh) -> Option<(u32, u32, Vec)> { +pub(crate) fn upright(m: &GradientMesh) -> Option<(u32, u32, Vec)> { let (mut rows, mut cols) = (m.rows, m.cols); if rows == 0 || cols == 0 || rows > MAX_GRID || cols > MAX_GRID { return None; @@ -345,7 +464,7 @@ fn upright(m: &GradientMesh) -> Option<(u32, u32, Vec)> { } /// The outline of an upright grid: its edge, clockwise from the top left corner. -fn outline(rows: u32, cols: u32, pts: &[GridPoint]) -> Option { +pub(crate) fn outline(rows: u32, cols: u32, pts: &[GridPoint]) -> Option { let at = |r: u32, c: u32| pts.get((r * (cols + 1) + c) as usize).copied(); // Each edge: from a point by one of its handles to the next point by one of its handles. type Edge = ((u32, u32), usize, (u32, u32), usize); @@ -542,6 +661,9 @@ pub(crate) enum TypeKept { Budget, /// Its live envelope doesn't draw as its drawn art. Differs, + /// A page that the layers, which don't draw as it, were compared with holds it against them + /// ([`WarpedType::open_alone`]). + Page, } /// What [`WarpedType::settle_envelopes`] did. @@ -551,9 +673,10 @@ pub(crate) struct TypedSettled { pub(crate) live: usize, /// Why each of the others kept its drawn art. pub(crate) kept: Vec, - /// Each live envelope's id, with what takes its place again when the layers with it don't draw - /// as the page: its hidden type, then its drawn art. - pub(crate) put_back: Vec<(NodeId, Vec)>, + /// Each live envelope's place among the envelopes of type (in the order they were read) and + /// id, with what takes its place again when the layers with it don't draw as the page: its + /// hidden type, then its drawn art. + pub(crate) put_back: Vec<(usize, NodeId, Vec)>, } /// The text objects read with a Warp and the envelopes of type, and what the import has left of the @@ -566,6 +689,9 @@ pub struct WarpedType { pub(super) checks: usize, pub(super) spent: Spent, pub(super) page: Option, + /// The envelopes of type that may open live in layers built without a page, by their place + /// among them ([`Self::open_alone`]): none when `None`. + pub(super) alone: Option>, } impl WarpedType { @@ -576,14 +702,33 @@ impl WarpedType { /// These, for layers `compared` with a page. Layers that aren't leave the envelopes of type /// their drawn art and their hidden type, with the note ([`TYPE_DRAWN`]) added to `notes`: a - /// live envelope opens only where the page chooses it. + /// live envelope opens only where the page chooses it. Unless [`Self::open_alone`] names some: + /// then they all wait, as with a page, and only those named may stay live. pub(crate) fn compared(mut self, compared: bool, notes: &mut Vec) -> Self { - if !compared && !std::mem::take(&mut self.envelopes).is_empty() && !notes.iter().any(|n| n == TYPE_DRAWN) { + if !compared && self.alone.is_none() && !std::mem::take(&mut self.envelopes).is_empty() && !notes.iter().any(|n| n == TYPE_DRAWN) { notes.push(TYPE_DRAWN.into()); } self } + /// Let the envelopes of type at `places` (among them, in the order they were read) open live in + /// layers built without a page, where they draw as their drawn art: a page these same layers, + /// read the same way, were compared with weighed them and didn't hold them against the layers' + /// difference from it. All the envelopes of type are settled as they were then, in the same + /// order and with the same checks, so each that opens live draws as it was weighed; then the + /// others get their drawn art back ([`Self::settle_envelopes`]). `count` is how many envelopes + /// of type that reading had: a reading with another number of them names none. + pub(crate) fn open_alone(&mut self, places: &[usize], count: usize) { + if self.envelopes.len() == count { + self.alone = Some(places.iter().copied().filter(|i| *i < count).collect()); + } + } + + /// How many envelopes of type wait for their type. + pub(crate) fn envelope_count(&self) -> usize { + self.envelopes.len() + } + /// Make each envelope of type live where it draws as its drawn art, its contents' text slots /// holding their type: `type_of` gives, for a slot's id, the hidden text object it became in /// `doc` and the type the contents take in its place (the slot's visibility and lock are the @@ -592,7 +737,8 @@ impl WarpedType { /// for it ([`live_on_saved_grid`]), which opens in its place where it does: its type stays /// editable in that shape, and the warp's style and bend are lost. With Distort Appearance, each /// is also checked mapping from its type's glyphs grown by half their strokes' weight - /// ([`with_strokes`]). In Edit Contents, a mesh or top object whose grid draws the type + /// ([`with_strokes`]) and, after all of those, from what its type paints where that is another + /// box ([`as_painted`]). In Edit Contents, a mesh or top object whose grid draws the type /// elsewhere than its drawn art is checked last moved onto that art ([`moved_onto`]). Each /// check uses one of the import's checks and, for an envelope that shows, adds to what the page /// check allows ([`drawn_alike`]). Elsewhere, and where the type is set in a font that isn't @@ -606,16 +752,28 @@ impl WarpedType { doc.layers.iter().for_each(|l| collect_shown(l, &mut shown)); let envelopes = std::mem::take(&mut self.envelopes); let mut waiting = envelopes.len(); - for envelope in envelopes { + for (place, envelope) in envelopes.into_iter().enumerate() { waiting -= 1; match self.typed_live(doc, envelope, &type_of, &shown, waiting) { - Ok(put_back) => { + Ok((id, put_back)) => { settled.live += 1; - settled.put_back.push(put_back); + settled.put_back.push((place, id, put_back)); } Err(why) => settled.kept.push(why), } } + // Built without a page, the envelopes [`Self::open_alone`] doesn't name get their drawn art + // and hidden type back. One inside another that got its own back went with that art. + if let Some(free) = &self.alone { + let (stay, back): (Vec<_>, Vec<_>) = std::mem::take(&mut settled.put_back).into_iter().partition(|(place, ..)| free.contains(place)); + for (_, id, nodes) in back { + if doc.insert_beside(vec![(id, nodes)], true).is_ok() || doc.node(id).is_none() { + settled.live = settled.live.saturating_sub(1); + settled.kept.push(TypeKept::Page); + } + } + settled.put_back = stay; + } settled } @@ -659,17 +817,16 @@ impl WarpedType { // With Distort Appearance, a file's envelope may map its type from its glyphs grown by half // their strokes' weight or from the glyphs alone, and for type the size the file saves for // that box is often out of date (not the size of the type there now): each is checked. - let kinds: Vec = live(&obj, before, inner) - .into_iter() - .chain(on_grid) - .flat_map(|k| { - let stroked = with_strokes(&k); - std::iter::once(k).chain(stroked) - }) - .collect(); + // After all of those, each is checked mapping from what its type paints, where that box is + // another: it is measured only when such a check comes and one is left. + let kinds: Vec = live(&obj, before, inner).into_iter().chain(on_grid).collect(); if kinds.is_empty() { return Err(TypeKept::Read); } + let mut ways: Vec = kinds.iter().flat_map(|k| std::iter::once(Way::As(k.clone())).chain(with_strokes(k).map(Way::As))).collect(); + ways.extend(kinds.into_iter().map(Way::Painted)); + // What the type paints, measured once: the kinds share their contents. + let mut painted: Option> = None; let (id, layer) = (doc.alloc_id(), doc.alloc_id()); let mut plain = art.clone(); (plain.visible, plain.opacity) = (true, 1.0); @@ -677,9 +834,9 @@ impl WarpedType { let mut alike = None; // In Edit Contents, a grid that draws the type elsewhere than its drawn art is tried again // moved onto that art ([`moved_onto`]), after every other way. - let (mut tries, mut moved, mut again, mut i) = (kinds.into_iter(), vec![], false, 0); + let (mut tries, mut moved, mut again, mut i) = (ways.into_iter(), vec![], false, 0); loop { - let Some(kind) = tries.next() else { + let Some(way) = tries.next() else { if again || moved.is_empty() { break; } @@ -692,6 +849,13 @@ impl WarpedType { if self.checks == 0 || (i > 0 && self.checks <= waiting + self.looks.len()) { return Err(TypeKept::Budget); } + let kind = match way { + Way::As(kind) => kind, + Way::Painted(base) => match painted.get_or_insert_with(|| painted_of(&base)).as_ref().and_then(|p| as_painted(&base, p)) { + Some(kind) => kind, + None => continue, + }, + }; self.checks -= 1; i += 1; let mut envelope = art.clone(); @@ -704,7 +868,7 @@ impl WarpedType { break; } if !again && let Some(kind) = moved_onto(&live_one, &plain) { - moved.push(kind); + moved.push(Way::As(kind)); } } let envelope = alike.ok_or(TypeKept::Differs)?; @@ -866,7 +1030,7 @@ fn alike_within(live: &Node, drawn: &Node, reach: Option, layer: NodeId, s mod tests { use super::*; use vectorcraft_color::{Color, Paint}; - use vectorcraft_doc::{AppearanceItem, CharStyle, LineJoin, StrokeLayer, TextObject}; + use vectorcraft_doc::{AppearanceItem, CharStyle, LineCap, LineJoin, StrokeLayer, TextObject}; /// An envelope of `content` with Distort Appearance, on a flat one-patch mesh. fn envelope_of(content: Vec>) -> NodeKind { @@ -906,6 +1070,7 @@ mod tests { /// miter join may at a corner. #[test] fn stroked_type_is_tried_mapped_from_its_glyphs_grown_by_half_its_stroke() { + vectorcraft_text::register_envelope_ink(); let mut text = type_node(1, CharStyle::default()); let mut appearance = (*text.appearance).clone(); appearance.items.push(AppearanceItem::Stroke(mitred())); @@ -921,6 +1086,7 @@ mod tests { /// turned and stretched as well as upright. #[test] fn type_with_a_character_stroke_is_tried_mapped_from_its_bounds_with_strokes() { + vectorcraft_text::register_envelope_ink(); let style = CharStyle { stroke: Paint::solid(Color::BLACK), stroke_width: 4.0, ..CharStyle::default() }; for xf in [ Affine::IDENTITY, @@ -940,6 +1106,7 @@ mod tests { /// A stroke on a group's own appearance round type grows the box by half its weight too. #[test] fn a_stroke_on_a_group_of_type_grows_the_box_by_half_its_weight() { + vectorcraft_text::register_envelope_ink(); let mut group = Node::new(NodeId(2), NodeKind::Group { children: vec![Arc::new(type_node(1, CharStyle::default()))], clip: false }); let mut appearance = (*group.appearance).clone(); appearance.items.push(AppearanceItem::Stroke(mitred())); @@ -948,4 +1115,225 @@ mod tests { let (_, glyphs) = envelope_content_boxes(&content, Affine::IDENTITY).unwrap(); assert_eq!(stroked_margin(content), envelope_stroke_margin(glyphs.inflate(2.0, 2.0), glyphs)); } + + /// Is the font type takes by default installed? Type that must draw as itself is tested only + /// where it is: the tests below measure its glyphs. + fn default_font() -> bool { + vectorcraft_text::FontDb::global().has_family(&CharStyle::default().font_family) + } + + /// The bounds margin of the candidate mapping from what `content` paints, for an envelope of it, + /// type measured by its glyphs as the import measures it; `None` where there is none. + fn painted_candidate(content: Vec>) -> Option<[f32; 4]> { + vectorcraft_text::register_envelope_ink(); + let kind = envelope_of(content); + match as_painted(&kind, &painted_of(&kind)?) { + Some(NodeKind::Envelope { options, .. }) => Some(options.bounds_margin), + _ => None, + } + } + + /// The box contents with geometric box `plain` map from with bounds margin `m`. + fn box_of(m: [f32; 4], plain: Rect) -> Rect { + let [top, bottom, left, right] = m.map(f64::from); + Rect::new( + plain.x0 - left * plain.width(), + plain.y0 - top * plain.height(), + plain.x1 + right * plain.width(), + plain.y1 + bottom * plain.height(), + ) + } + + /// Are the sides of `a` and `b` within `tol` of each other? + fn close(a: Rect, b: Rect, tol: f64) -> bool { + [a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().all(|d| d.abs() <= tol) + } + + /// The geometric box of `content`, type measured by its glyphs as the import measures it. + fn glyphs_of(content: &[Arc]) -> (Rect, Rect) { + vectorcraft_text::register_envelope_ink(); + envelope_content_boxes(content, Affine::IDENTITY).unwrap() + } + + /// What the type in `content` paints, measured apart from the import's own measure: each piece + /// of its outlines filled, and outlined by kurbo's stroker with each of its strokes' weight, + /// join and miter limit. + fn stroked_by_kurbo(content: &[Arc]) -> Rect { + use kurbo::Shape; + let mut out: Option = None; + for n in content { + let outlines = vectorcraft_effects::outline_text(n).unwrap(); + for piece in outlines.children().unwrap() { + let bp = piece.stroke_path().unwrap(); + out = vectorcraft_geom::union_opt(out, Some(bp.bounding_box())); + for s in piece.appearance.painted_strokes() { + let join = match s.join { + LineJoin::Miter => kurbo::Join::Miter, + LineJoin::Round => kurbo::Join::Round, + LineJoin::Bevel => kurbo::Join::Bevel, + }; + let stroke = kurbo::Stroke::new(s.width).with_join(join).with_miter_limit(s.miter_limit); + let outline = kurbo::stroke(bp.iter(), &stroke, &kurbo::StrokeOpts::default(), 1e-4); + out = vectorcraft_geom::union_opt(out, Some(outline.bounding_box())); + } + } + } + out.unwrap() + } + + /// Type with Distort Appearance and a stroke with miter joins on its appearance is also tried + /// mapped from what that stroke paints: past half its weight where a miter tip pokes out at a + /// sharp corner (the feet of the A's), though not as far as its bounds with strokes, which allow + /// for a miter as long as the limit lets one be at every corner. + #[test] + fn mitred_type_is_also_tried_mapped_from_what_its_stroke_paints_miter_tips_included() { + if !default_font() { + return; + } + let mut text = type_node(1, CharStyle::default()); + let mut appearance = (*text.appearance).clone(); + appearance.items.push(AppearanceItem::Stroke(mitred())); + text.appearance = appearance.into(); + let content = vec![Arc::new(text)]; + let (with, glyphs) = glyphs_of(&content); + let (half, painted) = (glyphs.inflate(2.0, 2.0), stroked_by_kurbo(&content)); + assert!(painted.x0 < half.x0 - 0.5 && painted.x1 > half.x1 + 0.5, "{painted:?} {half:?}"); + assert!(painted.width() < with.width() - 0.5, "{painted:?} {with:?}"); + let from = box_of(painted_candidate(content).unwrap(), glyphs); + assert!(close(from, painted, 0.01), "{from:?} {painted:?}"); + } + + /// Type stroked by its characters with miter joins is also tried mapped from what those strokes + /// paint, turned and stretched as well as upright. + #[test] + fn type_with_a_mitred_character_stroke_is_also_tried_mapped_from_what_it_paints() { + if !default_font() { + return; + } + let style = CharStyle { stroke: Paint::solid(Color::BLACK), stroke_width: 4.0, stroke_join: LineJoin::Miter, ..CharStyle::default() }; + for xf in [ + Affine::IDENTITY, + Affine::rotate(std::f64::consts::FRAC_PI_4), + Affine::scale_non_uniform(std::f64::consts::SQRT_2, std::f64::consts::FRAC_1_SQRT_2), + ] { + let mut text = type_node(1, style.clone()); + if let NodeKind::Text(t) = &mut text.kind { + t.xf = xf * t.xf; + } + let content = vec![Arc::new(text)]; + let (_, glyphs) = glyphs_of(&content); + let painted = stroked_by_kurbo(&content); + let from = box_of(painted_candidate(content).unwrap(), glyphs); + assert!(close(from, painted, 0.01), "{xf:?}: {from:?} {painted:?}"); + } + } + + /// A stroke that a Transform effect moves paints where it is moved to: type filled over its + /// glyphs with a round 4 point stroke moved 10 points down is also tried mapped from its glyphs + /// grown by 2 points on the left and right and 12 at the bottom, and not at the top. + #[test] + fn a_stroke_moved_by_a_transform_effect_counts_where_it_paints() { + if !default_font() { + return; + } + let mut text = type_node(1, CharStyle::default()); + let mut stroke = StrokeLayer::new(Paint::solid(Color::BLACK), 4.0); + (stroke.join, stroke.cap) = (LineJoin::Round, LineCap::Round); + stroke.effects.push(Effect { id: "distort.transform".into(), params: serde_json::json!({ "moveV": 10.0 }), visible: true }); + let mut appearance = (*text.appearance).clone(); + appearance.items.push(AppearanceItem::Stroke(stroke)); + text.appearance = appearance.into(); + let content = vec![Arc::new(text)]; + let (_, glyphs) = glyphs_of(&content); + let painted = Rect::new(glyphs.x0 - 2.0, glyphs.y0, glyphs.x1 + 2.0, glyphs.y1 + 12.0); + let from = box_of(painted_candidate(content).unwrap(), glyphs); + assert!(close(from, painted, 0.01), "{from:?} {painted:?}"); + } + + /// Type whose round-joined stroke paints half its weight past its glyphs everywhere is not tried + /// a second time mapped from what it paints: that is the box of its glyphs grown by half the + /// weight, already tried. + #[test] + fn round_joined_type_is_not_tried_twice_for_the_same_box() { + if !default_font() { + return; + } + let style = CharStyle { stroke: Paint::solid(Color::BLACK), stroke_width: 4.0, stroke_join: LineJoin::Round, ..CharStyle::default() }; + let content = vec![Arc::new(type_node(1, style))]; + vectorcraft_text::register_envelope_ink(); + assert!(with_strokes(&envelope_of(content.clone())).is_some()); + assert_eq!(painted_candidate(content), None); + } + + /// A contour of zero length paints nothing, so it isn't part of what type's outlines paint: a + /// filled square with a round 2 point stroke and such a contour 5 points above it paints the + /// square grown by 1 point. + #[test] + fn a_contour_of_zero_length_paints_nothing() { + let mut bp = BezPath::new(); + bp.move_to((10.0, 10.0)); + bp.line_to((20.0, 10.0)); + bp.line_to((20.0, 20.0)); + bp.line_to((10.0, 20.0)); + bp.close_path(); + bp.move_to((15.0, 5.0)); + bp.line_to((15.0, 5.0)); + bp.close_path(); + let mut stroke = StrokeLayer::new(Paint::solid(Color::BLACK), 2.0); + (stroke.join, stroke.cap) = (LineJoin::Round, LineCap::Round); + let mut appearance = Appearance::default(); + appearance.items.push(AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::solid(Color::BLACK)))); + appearance.items.push(AppearanceItem::Stroke(stroke)); + let piece = Node::path(NodeId(1), PathData::from_bezpath(&bp), appearance); + let outlines = Node::group(NodeId(2), vec![Arc::new(piece)]); + assert_eq!(painted_outlines(&outlines), Some(Rect::new(9.0, 9.0, 21.0, 21.0))); + } + + /// Type that draws nothing adds no box next to other content in the boxes the import tries an + /// envelope with Distort Appearance mapped from, loose and in a group, as it adds none to the + /// contents' geometric box: a rectangle with a round 4 point stroke beside type of only spaces + /// gives the rectangle's bounds with strokes. + #[test] + fn type_that_draws_nothing_adds_no_box_to_the_stroked_boxes() { + use kurbo::Shape; + vectorcraft_text::register_envelope_ink(); + let mut stroke = StrokeLayer::new(Paint::solid(Color::BLACK), 4.0); + (stroke.join, stroke.cap) = (LineJoin::Round, LineCap::Round); + let mut appearance = Appearance::default(); + appearance.items.push(AppearanceItem::Stroke(stroke)); + let square = Arc::new(Node::path(NodeId(1), PathData::from_bezpath(&Rect::new(10.0, 10.0, 110.0, 60.0).to_path(0.1)), appearance)); + let blank = Node::new( + NodeId(2), + NodeKind::Text(Box::new(TextObject::point(Point::new(400.0, 450.0), " ", CharStyle { size: 96.0, ..CharStyle::default() }))), + ); + let laid = blank.geometric_bounds().unwrap(); + assert!(laid.x1 > 110.0 && laid.y1 > 60.0, "the laid-out box {laid:?} reaches past the rectangle"); + let want = Rect::new(8.0, 8.0, 112.0, 62.0); + let blank = Arc::new(blank); + for content in [vec![square.clone(), blank.clone()], vec![Arc::new(Node::group(NodeId(3), vec![square.clone(), blank.clone()]))]] { + let (_, plain) = envelope_content_boxes(&content, Affine::IDENTITY).unwrap(); + assert!(close(plain, Rect::new(10.0, 10.0, 110.0, 60.0), 1e-6), "{plain:?}"); + let half = half_stroked_box(&content).unwrap(); + assert!(close(half, want, 1e-6), "{half:?}"); + let painted = painted_box(&content).unwrap(); + assert!(close(painted, want, 1e-6), "{painted:?}"); + } + // With nothing else in the envelope, the type keeps its laid-out box. + assert_eq!(half_stroked_box(&[blank]), Some(laid)); + } + + /// A side of what contents paint within a ten-thousandth of a point of their geometric box's is + /// that side, inside it or out: the two boxes measure the same outline two ways. Further inside, + /// there is no box; further out, it counts. + #[test] + fn a_side_within_the_slack_of_the_geometric_box_is_that_side() { + let plain = Rect::new(10.0, 20.0, 110.0, 70.0); + let painted = Rect::new(8.0, 20.0 + 1e-9, 112.0, 72.0); + assert_eq!(painted_margin(painted, plain), Some([0.0, 0.04, 0.02, 0.02])); + assert_eq!(painted_margin(Rect::new(8.0, 20.001, 112.0, 72.0), plain), None); + assert_eq!(painted_margin(plain, plain), None); + let half = [0.04_f32, 0.04, 0.02, 0.02]; + assert!(same_box(half, [0.04 + 1e-7, 0.04, 0.02, 0.02], plain)); + assert!(!same_box(half, [0.041, 0.04, 0.02, 0.02], plain)); + } } diff --git a/crates/eps/src/import/ai/legacy_text.rs b/crates/eps/src/import/ai/legacy_text.rs index a1b24662ec..043d6f2e4d 100644 --- a/crates/eps/src/import/ai/legacy_text.rs +++ b/crates/eps/src/import/ai/legacy_text.rs @@ -14,12 +14,12 @@ use std::sync::Arc; -use craft_pdf::interpret::hayro_cmap::{BfString, CMap, CMapName, load_embedded}; use kurbo::{Affine, BezPath, ParamCurve, ParamCurveArclen}; use vectorcraft_color::Paint; use vectorcraft_doc::{Burasagari, CharStyle, Justify, NodeKind, ParaStyle, TabAlign, TabStop, TextKind, TextObject, TextRun}; use vectorcraft_geom::AnchorKind; +use super::super::super::predefined_cmap::{self, CMapCodes, composite_font}; use super::super::obj::V; use super::art::path_data; use super::{FLIP, GState, HashSet, Kind, Node, NodeId, Reader}; @@ -284,259 +284,15 @@ impl TypeState { /// How strings in a font with predefined CMap `cmap` decode; `None` when the CMap can't be read. fn cmap_codes(&mut self, cmap: &str) -> Option> { - if let Some(form) = unicode_cmap(cmap) { - return Some(Arc::new(CMapCodes::Unicode(form))); - } if let Some((_, codes)) = self.cmaps.iter().find(|(n, _)| n == cmap) { return codes.clone(); } - let codes = cid_codes(cmap).map(Arc::new); + let codes = predefined_cmap::codes(cmap).map(Arc::new); self.cmaps.push((cmap.to_string(), codes.clone())); codes } } -/// How a composite font's strings decode. -#[derive(Debug)] -enum CMapCodes { - /// By a predefined CMap's codes to CIDs, then by its character collection's CID → Unicode CMap; - /// with `high_bit`, each byte 0x21 to 0x7E gets its high bit set first. `space` is the CMap's - /// code space ([`code_space`]). - Cids { codes: Box, unicode: Box, high_bit: bool, space: Option }, - /// A predefined Unicode CMap: the codes are the characters. - Unicode(Unicode), -} - -/// A CMap's code space: ranges of codes, each given by its lowest and highest code, both with the -/// code's length in bytes. -type CodeSpace = &'static [(&'static [u8], &'static [u8])]; - -/// What control byte `b` is in a composite font's string: `\r` a paragraph break, `\t` a tab. -fn control(b: u8) -> Option { - match b { - b'\r' => Some('\n'), - b'\t' => Some('\t'), - _ => None, - } -} - -impl CMapCodes { - /// The characters of string `bytes`, leaving out codes the CMaps don't map; a `\r` is a - /// paragraph break and a `\t` a tab (also as a byte left over after the last whole code of a - /// UTF-16 or UTF-32 string). - fn decode(&self, bytes: &[u8]) -> String { - let (codes, unicode, high_bit, space) = match self { - Self::Unicode(form) => { - let unit = match form { - Unicode::Utf16 => 2, - Unicode::Utf8 => 1, - Unicode::Utf32 => 4, - }; - let (whole, rest) = bytes.split_at_checked(bytes.len() - bytes.len() % unit).unwrap_or((bytes, &[])); - let mut text = unicode_text(whole, *form).replace('\r', "\n"); - text.extend(rest.last().copied().and_then(control)); - return text; - } - Self::Cids { codes, unicode, high_bit, space } => (codes, unicode, *high_bit, space), - }; - let euc: Vec; - let bytes = if high_bit { - euc = bytes.iter().map(|&b| if (0x21..0x7f).contains(&b) { b | 0x80 } else { b }).collect(); - euc.as_slice() - } else { - bytes - }; - let mut out = String::new(); - let mut at = 0; - while let Some(&first) = bytes.get(at) { - // VectorCraft reads a 0x0D byte as a paragraph break and a 0x09 byte as a tab in every - // CMap, as in other fonts' strings, including the row-and-cell CMaps, whose code space - // has no one-byte codes. - if let Some(control) = control(first) { - out.push(control); - at += 1; - continue; - } - let rest = bytes.get(at..).unwrap_or_default(); - let code = |len: u8| rest.get(..usize::from(len)).map(|b| b.iter().fold(0u32, |c, &b| c << 8 | u32::from(b))); - let found = match space { - // The code is as long as the code space range it falls in; a byte that starts no - // code in the code space is skipped. - Some(space) => { - let Some(len) = code_len(space, rest) else { - at += 1; - continue; - }; - code(len).map(|c| (len, codes.lookup_cid_code(c, len))) - } - None => (1..=4u8).find_map(|len| Some((len, Some(codes.lookup_cid_code(code(len)?, len)?)))), - }; - let Some((len, cid)) = found else { - at += 1; - continue; - }; - at += usize::from(len); - // A code the CMap leaves out is dropped. - let Some(cid) = cid else { continue }; - match unicode.lookup_bf_string(cid) { - // A one-byte Roman code whose CID the table gives as a combining mark alone (0x7E in - // the Mac Shift-JIS CMaps, U+0303): the ASCII character, as Adobe's cid2code.txt lists first. - Some(BfString::Char('\u{300}'..='\u{36f}')) if len == 1 && (0x20..0x7f).contains(&first) => out.push(char::from(first)), - Some(BfString::Char(c)) if c != char::REPLACEMENT_CHARACTER => out.push(c), - Some(BfString::String(s)) => out.extend(s.chars().filter(|c| *c != char::REPLACEMENT_CHARACTER)), - _ => {} - } - } - out - } -} - -/// How a predefined Unicode CMap's codes encode their characters. -#[derive(Clone, Copy, PartialEq, Debug)] -enum Unicode { - /// Two bytes a character (`UCS2`) or a UTF-16 surrogate pair, the high byte first. - Utf16, - Utf8, - /// Four bytes, the high byte first. - Utf32, -} - -/// The encoding of predefined Unicode CMap `name`: `Uni` and a character collection, then `-UCS2`, -/// `-UTF8`, `-UTF16` or `-UTF32` (and `-HW` for half-width forms), then `-H` or `-V` -/// (`UniJIS-UCS2-H`, `UniGB-UTF16-V`: ). -fn unicode_cmap(name: &str) -> Option { - let rest = name.strip_suffix("-H").or_else(|| name.strip_suffix("-V"))?; - let rest = rest.strip_suffix("-HW").unwrap_or(rest); - let (collection, form) = rest.rsplit_once('-')?; - let collections = ["UniJIS", "UniJISPro", "UniJIS2004", "UniJISX0213", "UniJISX02132004", "UniHojo", "UniGB", "UniCNS", "UniKS", "UniAKR"]; - if !collections.contains(&collection) { - return None; - } - match form { - "UCS2" | "UTF16" => Some(Unicode::Utf16), - "UTF8" => Some(Unicode::Utf8), - "UTF32" => Some(Unicode::Utf32), - _ => None, - } -} - -/// The characters string `s` encodes in Unicode form `form` (invalid codes left out). -fn unicode_text(s: &[u8], form: Unicode) -> String { - match form { - Unicode::Utf16 => { - let units = s.as_chunks::<2>().0.iter().map(|b| u16::from_be_bytes(*b)); - char::decode_utf16(units).filter_map(Result::ok).collect() - } - Unicode::Utf8 => s.utf8_chunks().map(|chunk| chunk.valid()).collect(), - Unicode::Utf32 => s.as_chunks::<4>().0.iter().filter_map(|b| char::from_u32(u32::from_be_bytes(*b))).collect(), - } -} - -/// Predefined CMap `name` among those VectorCraft carries, leaving out the Identity CMaps, whose -/// codes are CIDs of no known character collection. -fn predefined(name: &str) -> Option> { - match CMapName::from_bytes(name.as_bytes()) { - CMapName::Custom(_) | CMapName::IdentityH | CMapName::IdentityV => None, - name => Some(name), - } -} - -/// Adobe's predefined CMaps that VectorCraft doesn't carry, by name without `-H` or `-V` -/// (): the nearest carried CMap with the same -/// code space, and whether each byte of a row-and-cell code gets its high bit set first (the EUC -/// form of the same code; `GB-H`, `CNS1-H` and `KSC-H` have no one-byte codes, their code space -/// is `<2121>` to `<7E7E>`); `None` for those no carried CMap reads. -fn stand_in(stem: &str) -> Option> { - Some(match stem { - "RKSJ" | "78-RKSJ" | "78ms-RKSJ" => Some(("90ms-RKSJ-H", false)), - "78-EUC" => Some(("EUC-H", false)), - "78" | "Add" | "Ext" | "NWP" => Some(("H", false)), - "GB" => Some(("GB-EUC-H", true)), - "CNS1" => Some(("CNS-EUC-H", true)), - "KSC" => Some(("KSC-EUC-H", true)), - "B5" => Some(("ETen-B5-H", false)), - "ETHK-B5" | "HKdla-B5" | "HKdlb-B5" | "HKgccs-B5" | "HKm314-B5" | "HKm471-B5" => Some(("HKscs-B5-H", false)), - "GBT" | "GBT-EUC" | "GBTpc-EUC" | "CNS2" | "KSC-Johab" => None, - _ => return None, - }) -} - -/// Predefined CMap `cmap`'s codes to CIDs, and its character collection's CID → Unicode CMap. A -/// vertical CMap's codes are read with its horizontal CMap when VectorCraft carries that: the two -/// differ only in the CIDs of vertical glyph forms. A CMap VectorCraft doesn't carry is read with -/// its [`stand_in`]. -fn cid_codes(cmap: &str) -> Option { - let read = |name: &str| CMap::parse(load_embedded(predefined(name)?)?, load_embedded); - let horizontal = cmap.strip_suffix('V').map(|stem| format!("{stem}H")); - let stem = cmap.strip_suffix("-H").or_else(|| cmap.strip_suffix("-V")); - let (codes, high_bit) = horizontal.iter().map(String::as_str).chain([cmap]).find_map(|n| Some((read(n)?, false))).or_else(|| { - let (name, high_bit) = stand_in(stem?).flatten()?; - Some((read(name)?, high_bit)) - })?; - let table = codes.metadata().character_collection.as_ref()?.family.ucs2_cmap()?; - let unicode = CMap::parse(load_embedded(table)?, load_embedded)?; - // A row-and-cell code read in its EUC form falls in the EUC CMap's code space. - let space = if high_bit { stand_in(stem?).flatten().and_then(|(name, _)| code_space(name)) } else { code_space(cmap) }; - Some(CMapCodes::Cids { codes: Box::new(codes), unicode: Box::new(unicode), high_bit, space }) -} - -/// The code space of predefined CMap `cmap`, as Adobe's CMap files give it -/// (); a CMap's vertical form has its -/// horizontal form's. `None` for a CMap not listed here. -fn code_space(cmap: &str) -> Option { - const RKSJ: CodeSpace = &[(b"\x00", b"\x80"), (b"\xa0", b"\xdf"), (b"\x81\x40", b"\x9f\xfc"), (b"\xe0\x40", b"\xfc\xfc")]; - const RKSJ_MAC: CodeSpace = &[(b"\x00", b"\x80"), (b"\xa0", b"\xdf"), (b"\xfd", b"\xff"), (b"\x81\x40", b"\x9f\xfc"), (b"\xe0\x40", b"\xfc\xfc")]; - const EUC_JP: CodeSpace = &[(b"\x00", b"\x80"), (b"\x8e\xa0", b"\x8e\xdf"), (b"\xa1\xa1", b"\xfe\xfe")]; - const ROW_CELL: CodeSpace = &[(b"\x21\x21", b"\x7e\x7e")]; - const EUC: CodeSpace = &[(b"\x00", b"\x80"), (b"\xa1\xa1", b"\xfe\xfe")]; - const GB_PC: CodeSpace = &[(b"\x00", b"\x80"), (b"\xfd", b"\xff"), (b"\xa1\xa1", b"\xfc\xfe")]; - const GBK: CodeSpace = &[(b"\x00", b"\x80"), (b"\x81\x40", b"\xfe\xfe")]; - const GBK2K: CodeSpace = &[(b"\x00", b"\x7f"), (b"\x81\x40", b"\xfe\xfe"), (b"\x81\x30\x81\x30", b"\xfe\x39\xfe\x39")]; - const B5_PC: CodeSpace = &[(b"\x00", b"\x80"), (b"\xfd", b"\xff"), (b"\xa1\x40", b"\xfc\xfe")]; - const B5: CodeSpace = &[(b"\x00", b"\x80"), (b"\xa1\x40", b"\xfe\xfe")]; - const HKSCS: CodeSpace = &[(b"\x00", b"\x80"), (b"\x87\x40", b"\xfe\xfe")]; - const HKDLB: CodeSpace = &[(b"\x00", b"\x80"), (b"\x8e\x40", b"\xfe\xfe")]; - const HKGCCS: CodeSpace = &[(b"\x00", b"\x80"), (b"\x8a\x40", b"\xfe\xfe")]; - const CNS_EUC: CodeSpace = &[(b"\x00", b"\x80"), (b"\xa1\xa1", b"\xfe\xfe"), (b"\x8e\xa1\xa1\xa1", b"\x8e\xa3\xfe\xfe")]; - const KSC_PC: CodeSpace = &[(b"\x00", b"\x84"), (b"\xfe", b"\xff"), (b"\xa1\x41", b"\xfd\xfe")]; - const UHC: CodeSpace = &[(b"\x00", b"\x80"), (b"\x81\x41", b"\xfe\xfe")]; - let stem = match cmap { - "H" | "V" => "", - _ => cmap.strip_suffix("-H").or_else(|| cmap.strip_suffix("-V"))?, - }; - let stem = stem.strip_suffix("-HW").unwrap_or(stem); - Some(match stem { - "83pv-RKSJ" | "90pv-RKSJ" => RKSJ_MAC, - _ if stem.ends_with("RKSJ") => RKSJ, - "EUC" | "78-EUC" => EUC_JP, - "" | "78" | "Add" | "Ext" | "NWP" => ROW_CELL, - "GB-EUC" | "GBT-EUC" | "KSC-EUC" => EUC, - "GBpc-EUC" | "GBTpc-EUC" => GB_PC, - "GBK-EUC" | "GBKp-EUC" => GBK, - "GBK2K" => GBK2K, - "B5pc" => B5_PC, - "B5" | "ETen-B5" | "ETenms-B5" | "HKdla-B5" | "HKm314-B5" | "HKm471-B5" => B5, - "HKscs-B5" | "ETHK-B5" => HKSCS, - "HKdlb-B5" => HKDLB, - "HKgccs-B5" => HKGCCS, - "CNS-EUC" => CNS_EUC, - "KSCpc-EUC" => KSC_PC, - "KSCms-UHC" => UHC, - _ => return None, - }) -} - -/// The length of the code string `bytes` starts with: the length of the code space range whose -/// lowest and highest codes hold each of its bytes between them. `None` when no range does. -fn code_len(space: CodeSpace, bytes: &[u8]) -> Option { - space - .iter() - .filter(|(lo, hi)| bytes.get(..lo.len()).is_some_and(|b| b.iter().zip(lo.iter().zip(hi.iter())).all(|(b, (lo, hi))| (lo..=hi).contains(&b)))) - .map(|(lo, _)| lo.len()) - .min() - .and_then(|len| u8::try_from(len).ok()) -} - /// Encoding pairs (§3.3.1): codes, each followed by the glyph names from it on, into `table`. fn encoding_pairs(table: &mut [Option], vals: &[V]) { let mut code: Option = None; @@ -556,36 +312,6 @@ fn encoding_pairs(table: &mut [Option], vals: &[V]) { } } -/// A composite font's name `base-CMap`: the base font's name and its CMap's name, when that is a -/// predefined Unicode CMap ([`unicode_cmap`]), one of the predefined CMaps VectorCraft carries -/// ([`predefined`]) or one of the others ([`stand_in`]), in its horizontal (`-H`) or vertical -/// (`-V`) form. A name ending in an Identity CMap is not read as one, nor is one that ends in an -/// unknown CMap name with an encoding part (`UniFoo-UTF8-H`), which would otherwise end in `H`. -fn composite_font(name: &str) -> Option<(&str, &str)> { - if !(name.ends_with("-H") || name.ends_with("-V")) { - return None; - } - // The longest CMap name first: `83pv-RKSJ-H` before `H`. - // No predefined CMap name is longer than 32 bytes. - for (at, _) in name.match_indices('-').filter(|(at, _)| name.len() - at <= 33) { - let (Some(base), Some(cmap)) = (name.get(..at).filter(|b| !b.is_empty()), name.get(at + 1..)) else { continue }; - if matches!(cmap, "Identity-H" | "Identity-V") { - return None; - } - let encoding_part = - base.rsplit('-').next().is_some_and(|part| ["UCS2", "UTF8", "UTF16", "UTF32", "HW", "EUC", "RKSJ", "B5", "UHC", "Johab"].contains(&part)); - if matches!(cmap, "H" | "V") && encoding_part { - return None; - } - let vertical_of_predefined = || cmap.strip_suffix('V').is_some_and(|stem| predefined(&format!("{stem}H")).is_some()); - let other = || cmap.strip_suffix("-H").or_else(|| cmap.strip_suffix("-V")).is_some_and(|stem| stand_in(stem).is_some()); - if unicode_cmap(cmap).is_some() || predefined(cmap).is_some() || vertical_of_predefined() || other() { - return Some((base, cmap)); - } - } - None -} - /// An operator's `N` operands, the last `N` values before it, when each is a finite number. fn nums(vals: &[V]) -> Option<[f64; N]> { let operands = vals.get(vals.len().checked_sub(N)?..)?; @@ -782,10 +508,16 @@ impl Reader<'_> { None => (full.as_str(), None), }; st.cmap = cmap; - let (family, style) = super::super::super::text::family_style(name); + // The installed face of that PostScript name, as type from a text document + // takes it; else the name split into a family and style. + let text = super::super::super::text::named_font(name, None); + let (family, style, version) = text.unwrap_or_else(|| { + let (family, style) = super::super::super::text::family_style(name); + (family, style, None) + }); st.style.font_family = family; st.style.font_style = style; - st.style.font_version = None; + st.style.font_version = version; } if let Some(size) = vals.get(at + 1).and_then(V::num).filter(|s| s.is_finite() && *s > 0.0) { st.style.size = size.min(MAX_SIZE); diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index 5a253f21a3..4b2936f56e 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -205,6 +205,10 @@ pub struct Structure { pub warped_type: super::envelope::WarpedType, /// The document's graphic styles are those of the file's style list, in place of the defaults. pub styles_read: bool, + /// The patterns that paint the text document's characters, placed in the document, by the + /// name of the art style that gives each: the styles that are one paint, a pattern this read + /// (see `ate::Texts::with_patterns`). + pub text_patterns: HashMap, /// The file's `%AI24_LargeCanvasScale` (1 when it declares none), applied or not. pub canvas_scale: f64, /// The objects by their XML id (`AI10_ArtUID`), a text object by its slot's id: `None` for an @@ -479,6 +483,9 @@ struct Reader<'a> { /// a global process colour, so these make swatches only for names no colour operator defines. stop_spots: Vec, raster: Option, + /// The samples of the image being read are on `%_` lines (`%_%%BeginData`): it is the copy of + /// a styled object there, as the other objects on those lines are. + image_hidden: bool, /// The file `XG` names for the image after it (`XF`), until an image is read. image_link: Option, /// The placed file being read (`%AI5_BeginPlace` … `~`). @@ -732,6 +739,7 @@ impl<'a> Reader<'a> { spots: Vec::new(), stop_spots: Vec::new(), raster: None, + image_hidden: false, image_link: None, place: None, foreign_data: None, @@ -842,7 +850,7 @@ impl<'a> Reader<'a> { self.op(w, hidden)?; } Tok::Comment(c) => self.comment(c, hidden)?, - Tok::Data(d) => self.image(d)?, + Tok::Data(d) => self.image(d, hidden)?, Tok::Preview(d) => { if let Some(p) = self.place.as_mut() { p.preview = preview_png(d); diff --git a/crates/eps/src/import/ai/read/art.rs b/crates/eps/src/import/ai/read/art.rs index 3d859bf74e..7e0f91e993 100644 --- a/crates/eps/src/import/ai/read/art.rs +++ b/crates/eps/src/import/ai/read/art.rs @@ -370,15 +370,18 @@ impl<'a> Reader<'a> { // ---- images ---------------------------------------------------------------------------- - /// The samples after `XI`, its operands on the stack. - pub(super) fn image(&mut self, data: &[u8]) -> Result<(), String> { + /// The samples after `XI`, its operands on the stack; `hidden` when they are on `%_` lines. + pub(super) fn image(&mut self, data: &[u8], hidden: bool) -> Result<(), String> { let vals = self.operands(); // Operands that came before an `XI` on their own line. let vals = match self.raster.as_mut().and_then(|r| r.operands.take()) { Some(before) if !vals.iter().any(|v| matches!(v, V::Arr(_))) => before, _ => vals, }; - self.image_from(vals, data, false) + self.image_hidden = hidden; + let read = self.image_from(vals, data, false); + self.image_hidden = false; + read } /// The matrix and the numbers of an image's operands (`[a b c d tx ty] llx lly urx ury w h bits @@ -713,7 +716,8 @@ impl<'a> Reader<'a> { /// Add the image `blob` (`w` × `h` pixels), which the matrix `m` maps into art space, with /// `alpha` (its alpha channel, one byte a pixel) as its opacity mask when it hides part of the - /// image, and `colorize` as the color that colorizes it. + /// image, and `colorize` as the color that colorizes it. It is on `%_` lines when its samples + /// are ([`Self::image`]). fn add_raster(&mut self, blob: ImageBlob, alpha: Option<&[u8]>, m: &[f64], (w, h): (u32, u32), colorize: Option) -> Result<(), String> { // The matrix is an art-space matrix (y up) applied to the pixels with their rows running // downwards, (u, -v): pixels → (u, -v) → art space. Flipping the matrix's result instead @@ -735,7 +739,8 @@ impl<'a> Reader<'a> { let key = blob.content_key(); self.doc.images.entry(key.clone()).or_insert(blob); let im = ImageObject { key, width: w, height: h, xf, link: None, placement: Default::default(), pixels: None }; - self.add_image_colorized(im, mask, colorize, false) + // An image on `%_` lines is the copy of a styled object, as the other objects there are. + self.add_image_colorized(im, mask, colorize, self.image_hidden) } /// An image that isn't read is left out, with `warning`; in a symbol's art, the symbol isn't diff --git a/crates/eps/src/import/ai/read/directives.rs b/crates/eps/src/import/ai/read/directives.rs index f7df4f35d6..911d8340cc 100644 --- a/crates/eps/src/import/ai/read/directives.rs +++ b/crates/eps/src/import/ai/read/directives.rs @@ -1259,7 +1259,7 @@ mod tests { fn envelopes_in_symbol_definitions_spend_the_imports_checks() { use crate::import::ai::tests::{drawn_content, envelope_content, envelope_of, straight_mesh, warp_keys}; use vectorcraft_doc::live::EnvelopeKind; - let want = EnvelopeKind::Warp { style: "arc".into(), bend: 50.0, h: 0.0, v: 0.0, horizontal: true }; + let want = EnvelopeKind::Warp { style: "arc".into(), bend: 50.0, h: 0.0, v: 0.0, horizontal: true, version: vectorcraft_doc::live::WARP_NET }; let envelope = envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), &warp_keys(1, 0.5, 0.0, 0.0, 0), &envelope_content(), 1, &drawn_content(&want)); let mut reader = Reader::new(b""); diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index ad7f266036..0bcae74b32 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -1335,6 +1335,17 @@ impl<'a> Reader<'a> { doc.limit_depth_noting(&mut warnings); } warnings.extend(self.names.notes()); + // The patterns of the styles that are one paint, which the text document's characters + // name for their fills and strokes: those that place in the document. + let text_patterns = self + .styles + .iter() + .filter_map(|(style, st)| { + let Some(crate::import::ai::style::StyleItem::Pattern { name, matrix, controls }) = &st.simple_pattern else { return None }; + let paint = super::ops::style_pattern(name, *matrix, controls, &self.pattern_tiles, &self.v7_patterns, &self.global_names, to_doc)?; + Some((style.clone(), paint)) + }) + .collect(); Ok(Structure { doc, to_doc, @@ -1356,8 +1367,10 @@ impl<'a> Reader<'a> { checks: self.envelope_checks, spent: self.envelope_spent, page, + alone: None, }, styles_read, + text_patterns, canvas_scale: self.canvas_scale, xml_ids: self.xml_ids, bindings, diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index c0d9852d88..f79e7b9108 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -748,6 +748,7 @@ impl<'a> Reader<'a> { } let space = self.space(); self.note_brushes_kept(); + let page = self.page_in_doc(); let Some(f) = self.frames.last_mut() else { return }; let n = f.children.len(); let (Some(object), Some(look)) = (n.checked_sub(1).and_then(|i| f.children.get(i)), n.checked_sub(2).and_then(|i| f.children.get(i))) else { @@ -780,7 +781,7 @@ impl<'a> Reader<'a> { look }; // A style read here: the object, painted as it says. - if let Some(mut appearance) = self.styles.get(&style).and_then(|st| { + let appearance = self.styles.get(&style).and_then(|st| { styled( object, look, @@ -796,13 +797,32 @@ impl<'a> Reader<'a> { space, }, ) - }) { - // Strokes and effects at the document's scale, as the art (a Large Canvas copy's is scaled up). - let k = space.determinant().abs().sqrt(); - if k.is_finite() && k > 0.0 && (k - 1.0).abs() > 1e-9 { - appearance.scale_strokes(k); - appearance.scale_effects(k, vectorcraft_effects::scale_effect); + .map(|mut appearance| { + // Strokes and effects at the document's scale, as the art (a Large Canvas copy's is scaled up). + let k = space.determinant().abs().sqrt(); + if k.is_finite() && k > 0.0 && (k - 1.0).abs() > 1e-9 { + appearance.scale_strokes(k); + appearance.scale_effects(k, vectorcraft_effects::scale_effect); + } + appearance + }) + }); + // An image with a Warp is the object only where its live warp draws as its drawn look, and + // while the import has a check left for it; otherwise its drawn look stays. + let appearance = match appearance { + Some(ap) if matches!(object.kind, NodeKind::Image(_)) && ap.effects.iter().any(|e| e.id.starts_with("warp.")) => { + let alike = self.envelope_checks > 0 && { + self.envelope_checks -= 1; + let layer = self.doc.alloc_id(); + let shared = crate::import::ai::envelope::Shared { patterns: &self.doc.patterns, images: &self.doc.images }; + let shown = !hidden && object.visible && look.visible; + image_warp_alike(object, &ap, look, &self.hidden_ids, hidden, layer, &shared, page.filter(|_| shown), &mut self.envelope_spent) + }; + alike.then_some(ap) } + other => other, + }; + if let Some(appearance) = appearance { let Some(mut object) = f.children.pop() else { return }; let Some(look) = f.children.pop() else { return }; let left_out = look.visual_bounds().filter(|_| !hidden && object.visible && look.visible); @@ -943,6 +963,29 @@ fn pattern_xf(space: Affine, matrix: Option, tile: Rect) -> Option= 1e-12 && xf.as_coeffs().iter().all(|v| v.is_finite())).then_some(xf) } +/// A style's pattern (`StyleItem::Pattern`): the file's pattern `name` placed by `matrix` (its +/// space → art space; `controls` apply first for a pattern defined in the version 7 form, `v7` +/// those patterns' names) and carried into the document by `space`, with the name `names` give +/// it there. `None` when the pattern wasn't read (`tiles`: the tiles of those that were, by their +/// names in the file) or doesn't place. +pub(super) fn style_pattern( + name: &str, + matrix: Option<[f64; 6]>, + controls: &[f64], + tiles: &HashMap, + v7: &HashSet, + names: &ShownNames, + space: Affine, +) -> Option { + let tile = tiles.get(name).copied()?; + let mut matrix = matrix.and_then(|m| paint::affine(&m)); + if v7.contains(name) { + matrix = Some(matrix.unwrap_or(Affine::IDENTITY) * pattern_controls(controls)?); + } + let xf = pattern_xf(space, matrix, tile)?; + Some(Paint::Pattern { pattern: names.get(Global::Pattern, name).to_string(), xf }) +} + /// A pattern fill's `x y scaleX scaleY angle reflect axis shear shearAxis` as one transform of the /// pattern's space, applied before its initial matrix: the shear (by `shear` degrees along the line /// at `shearAxis` degrees), the reflection about the line at `axis` degrees when `reflect` isn't @@ -1044,7 +1087,8 @@ fn strokes(n: &Node, depth: usize) -> bool { || n.children().into_iter().flatten().any(|c| strokes(c, depth + 1)) } -/// Are all of path or compound path `n`'s segments straight, each anchor's handles on it? +/// Are all of path or compound path `n`'s segments straight, each anchor's handles on it? Any other +/// object, a group included, counts as no. fn straight(n: &Node) -> bool { match &n.kind { NodeKind::Path { path, .. } => path.subpaths.iter().flat_map(|s| &s.anchors).all(|a| a.h_in == a.p && a.h_out == a.p), @@ -1053,10 +1097,21 @@ fn straight(n: &Node) -> bool { } } +/// Is neither `n` nor anything in it a guide? Deeper than [`MAX_DEPTH`] counts as no. +fn no_guides(n: &Node, depth: usize) -> bool { + depth <= MAX_DEPTH && !n.is_guide() && n.children().into_iter().flatten().all(|c| no_guides(c, depth + 1)) +} + +/// The largest Twist angle, in degrees either way, read as a live effect on an object that isn't a +/// path or compound path with straight segments: VectorCraft's own limit. An object with a larger +/// Twist keeps the file's drawn look. +const MAX_TWIST: f64 = 90.0; + /// Is `object` one that style `st`, whose effect moves the outline, is read on? It and everything -/// in it [`moves_alike`], and the style paints no gradient. Twist is read only on an unstroked path -/// or compound path with straight segments, and Transform that scales, turns or reflects only when -/// nothing is stroked (its reference point lies on the bounds without strokes). +/// in it [`moves_alike`], and the style paints no gradient. Twist is read only when nothing is +/// stroked: on a path or compound path with straight segments at any angle, or up to [`MAX_TWIST`] +/// degrees either way on another object with no guide in it. Transform that scales, turns or reflects +/// is read only when nothing is stroked (its reference point lies on the bounds without strokes). fn moves_with(object: &Node, st: &crate::import::ai::style::ArtStyle) -> bool { use crate::import::ai::style::StyleItem; let stroked = st.items.iter().any(|i| matches!(i, StyleItem::Stroke { paint, .. } if !paint.is_none())) @@ -1065,7 +1120,9 @@ fn moves_with(object: &Node, st: &crate::import::ai::style::ArtStyle) -> bool { && outlines_only(object) && object.children().into_iter().flatten().all(|c| moves_alike(c, 1)) && st.effects.iter().all(|e| match e.id.as_str() { - "distort.twist" => !stroked && matches!(object.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && straight(object), + "distort.twist" => { + !stroked && (straight(object) || (no_guides(object, 0) && e.params["angle"].as_f64().is_some_and(|a| a.abs() <= MAX_TWIST))) + } "distort.transform" => { let p = &e.params; !stroked @@ -1079,6 +1136,41 @@ fn moves_with(object: &Node, st: &crate::import::ai::style::ArtStyle) -> bool { }) } +/// Is `object` an image without an opacity mask, and `st` one Warp on it with nothing else that +/// paints ([`crate::import::ai::style::ArtStyle::image_warp`])? Such an image is read with its Warp +/// live where that draws as its drawn look ([`image_warp_alike`]). +fn image_warps(object: &Node, st: &crate::import::ai::style::ArtStyle) -> bool { + matches!(object.kind, NodeKind::Image(_)) && object.extras().mask.is_none() && st.image_warp +} + +/// Does image `object` with `appearance` (its style's Warp) draw as `look`, its drawn look, compared +/// over all that the warp draws ([`crate::import::ai::envelope::warped_alike`]) on `layer`, a layer +/// id no other node has? Both are drawn shown, opaque and in the Normal mode. Unless the look is on +/// `%_` lines itself (`hidden`), the copies in it that are on `%_` lines (`hidden_ids`) are left out. +#[allow(clippy::too_many_arguments)] +fn image_warp_alike( + object: &Node, + appearance: &Appearance, + look: &Node, + hidden_ids: &HashSet, + hidden: bool, + layer: NodeId, + shared: &crate::import::ai::envelope::Shared<'_>, + page: Option, + spent: &mut crate::import::ai::envelope::Spent, +) -> bool { + let mut live = object.clone(); + live.appearance = appearance.clone().into(); + let mut plain = look.clone(); + if !hidden { + strip(&mut plain, hidden_ids); + } + for n in [&mut live, &mut plain] { + (n.visible, n.opacity, n.blend) = (true, 1.0, BlendMode::Normal); + } + crate::import::ai::envelope::warped_alike(&live, &plain, layer, shared, page, spent) +} + /// What [`placed_paints`] keys a pattern's name with, apart from the gradients' names. const PATTERN_KEY: &str = "\u{1}pattern "; @@ -1091,11 +1183,13 @@ fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, p let slot = slot_of(object.name.as_deref()).is_some(); // Several fills and strokes, on a path or a compound path. let stacked = !slot && !st.simple && st.stacked && matches!(object.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }); + // One Warp on an image, checked against its drawn look by the caller ([`image_warp_alike`]). + let image_warp = !st.simple && image_warps(object, st); // A symbol instance draws its symbol's art: it keeps its drawn look. if !st.plain || matches!(object.kind, NodeKind::SymbolInstance { .. }) // A look with no outline in it to keep takes a variable-width stroke as the object's own. - || (!slot && !st.simple && !stacked && (!st.uneven || draws(look, &HashSet::new()))) + || (!slot && !st.simple && !stacked && !image_warp && (!st.uneven || draws(look, &HashSet::new()))) || (object.is_container() && !slot && !matches!(object.kind, NodeKind::Compound { .. }) && !st.items.is_empty()) || (st.pathfinder && (slot || !st.items.is_empty() || object.is_compound_shape() || !matches!(object.kind, NodeKind::Group { clip: false, .. }))) @@ -1147,15 +1241,15 @@ fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, p } StyleItem::Pattern { name, matrix, controls } => match placed.get(&format!("{PATTERN_KEY}{}", paints.names.get(Global::Pattern, name))) { Some(p) => AppearanceItem::Fill(FillLayer::new(p.clone())), - None => { - let tile = paints.patterns.get(name).copied()?; - let mut matrix = matrix.and_then(|m| paint::affine(&m)); - if paints.v7_patterns.contains(name) { - matrix = Some(matrix.unwrap_or(Affine::IDENTITY) * pattern_controls(controls)?); - } - let xf = pattern_xf(paints.space, matrix, tile)?; - AppearanceItem::Fill(FillLayer::new(Paint::Pattern { pattern: paints.names.get(Global::Pattern, name).to_string(), xf })) - } + None => AppearanceItem::Fill(FillLayer::new(style_pattern( + name, + *matrix, + controls, + paints.patterns, + paints.v7_patterns, + paints.names, + paints.space, + )?)), }, StyleItem::Stroke { brush, .. } => { // A brushed stroke draws as its look only with the brush the Brushes panel keeps @@ -1194,13 +1288,18 @@ fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, p /// A graphic style's appearance from art style `st`, on no object: `None` when the style isn't one /// this reads, or paints with a gradient or a pattern (placed on each object as its drawn look has them). +/// A style that is one paint is its fill and stroke ([`crate::import::ai::style::ArtStyle::one_paint`]). pub(super) fn appearance_from_art_style(st: &crate::import::ai::style::ArtStyle) -> Option { use crate::import::ai::style::StyleItem; if !st.plain { return None; } + let style_items = match &st.one_paint { + Some(one) => one.as_ref().ok()?, + None => &st.items, + }; let mut items = vec![]; - for (n, item) in st.items.iter().enumerate() { + for (n, item) in style_items.iter().enumerate() { let mut layer = match item { StyleItem::Fill(paint) => AppearanceItem::Fill(FillLayer::new(paint.clone())), // A graphic style's brush isn't checked against the file's brushes: it is left out. @@ -1224,6 +1323,9 @@ pub(crate) struct StyleRead { pub appearance: Appearance, /// An object other than type is read with it ([`crate::import::ai::style::ArtStyle::simple`]). pub simple: bool, + /// An image without an opacity mask is read with it where its live warp draws as its drawn + /// look ([`crate::import::ai::style::ArtStyle::image_warp`]). + pub image_warp: bool, /// It has Effect › Pathfinder effects, which only a group with no fills or strokes is read with. pub pathfinder: bool, /// The opacity, blending mode, isolation and knockout its blend filter gives. @@ -1237,8 +1339,11 @@ pub(crate) fn read_style_list(section: &[u8]) -> Vec { /// Art style `name` of `section` as the reader reads it ([`StyleRead`]): [`appearance_from_art_style`], /// with a style's one gradient fill as `own_gradient`, the object's own gradient, as [`styled`] reads -/// it on objects other than type. `None` when the section doesn't define it, the reader doesn't read -/// it, or it paints with a pattern, a brush or a gradient that isn't the object's own. +/// it on objects other than type. A stroke that names a brush is read with that brush's name, as +/// [`styled`] reads it on a path or compound path when the Brushes panel keeps that brush at those +/// settings, which [`crate::import::ai::brush::BrushesRead::style_reads`] checks. `None` when the section +/// doesn't define it, the reader doesn't read it, or it paints with a pattern or a gradient that +/// isn't the object's own. pub(crate) fn read_art_style(section: &[u8], name: &str, own_gradient: Option<&Paint>) -> Option { use crate::import::ai::style::StyleItem; let mut st = crate::import::ai::style::art_styles(section).remove(name)?; @@ -1250,8 +1355,22 @@ pub(crate) fn read_art_style(section: &[u8], name: &str, own_gradient: Option<&P } } } - let appearance = appearance_from_art_style(&st)?; - Some(StyleRead { appearance, simple: st.simple, pathfinder: st.pathfinder, transparency: st.transparency }) + // The brush names, by item; `appearance_from_art_style` reads a style's items in order. + let brushes: Vec> = st + .items + .iter_mut() + .map(|item| match item { + StyleItem::Stroke { brush, .. } => brush.take().map(|(name, _)| name), + _ => None, + }) + .collect(); + let mut appearance = appearance_from_art_style(&st)?; + for (item, brush) in appearance.items.iter_mut().zip(brushes) { + if let (AppearanceItem::Stroke(s), Some(brush)) = (item, brush) { + s.brush = Some(brush); + } + } + Some(StyleRead { appearance, simple: st.simple, image_warp: st.image_warp, pathfinder: st.pathfinder, transparency: st.transparency }) } /// Is art style `name` of `section` read on `object` as far as an effect that moves the outline @@ -1460,6 +1579,79 @@ mod tests { assert!(styled(&Node::new(NodeId(4), NodeKind::Image(Box::new(image))), &look, st, &paints).is_none()); } + /// The style `Fx`: `effects` (each a filter's name and its dictionary's keys) on the whole + /// object, over a fill and a stroke that `paints` turns on (`0 1`: the fill paints blue). + fn effects_style(effects: &[(&str, &str)], paints: &str) -> crate::import::ai::style::ArtStyle { + let filters: String = effects + .iter() + .map(|(name, keys)| { + format!("/BasicFilter :\n({name}) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n{keys}; /Dict ;\n /Part ,\n") + }) + .collect(); + let text = format!( + "%AI9_BeginArtStyles\n/KnownStyle :\n(Fx) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + {filters}/CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Stroke Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/StrokeStyle : 0 1 0 0 0 Xy\n0 0 Xd\n/Def ;\n (StrokeStyle) ,\n; /Dict ;\n /Part ,\n\ + /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n\ + /BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n0 0 0 0 0 0 1 Xa\n{paints} Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n\ + ;\n /Part ,\n;\n%AI9_EndArtStyles\n" + ); + crate::import::ai::style::art_styles(text.as_bytes()).remove("Fx").unwrap_or_default() + } + + /// An image takes a style of one Warp, under fills and strokes that paint nothing, and no + /// other style with a geometry effect: those keep its drawn look. A path, and an image with an + /// opacity mask, keep their drawn look with the Warp too. + #[test] + fn an_image_takes_a_style_of_one_warp_alone() { + // GUARDS: an image with a Warp in its art style came in as its drawn look. + let warp = ("Adobe Deform", "1 /Int (DeformStyle) ,\n0.4 /Real (DeformValue) ,\n"); // brand-ok: the filter's name in the files + let (gradients, patterns, names, v7_patterns, bending) = + (HashMap::new(), HashMap::new(), ShownNames::default(), HashSet::new(), HashSet::new()); + let paints = StylePaints { + gradients: &gradients, + patterns: &patterns, + names: &names, + v7_patterns: &v7_patterns, + brushes: &[], + kept: &[], + bending: &bending, + space: Affine::IDENTITY, + }; + let look = Node::group(NodeId(1), vec![square(2, Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)))]); + let image = + ImageObject { key: "a".into(), width: 1, height: 1, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None }; + let image = Node::new(NodeId(4), NodeKind::Image(Box::new(image))); + let st = effects_style(&[warp], "0 0"); + assert!(st.image_warp && !st.simple, "{st:?}"); + let ap = styled(&image, &look, &st, &paints).expect("an image takes one Warp"); + let ids: Vec<&str> = ap.effects.iter().map(|e| e.id.as_str()).collect(); + assert_eq!(ids, ["warp.arc"]); + assert!(ap.items.iter().all(|i| i.paint().is_none()), "{ap:?}"); + // Not on a path, nor on an image with an opacity mask. + assert!(styled(&square(3, Paint::None), &look, &st, &paints).is_none()); + let mut masked = image.clone(); + masked.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(Node::group(NodeId(7), vec![]), true))); + assert!(styled(&masked, &look, &st, &paints).is_none()); + // A Warp over a fill that paints, a Warp with another effect, and the other geometry effects. + let still = ("Adobe Punk and Bloat", "0 /Real (d_factor) ,\n"); + let others: [(&[(&str, &str)], &str); 8] = [ + (&[warp], "0 1"), + (&[warp, still], "0 0"), + (&[still, warp], "0 0"), + (&[("Adobe Twirl", "45 /Real (angle) ,\n")], "0 0"), + (&[("Adobe Free Distort", "")], "0 0"), + (&[("Adobe Punk and Bloat", "-50 /Real (d_factor) ,\n")], "0 0"), + (&[("Adobe Zigzag", "3 /Real (amount) ,\n1 /Real (absoluteness) ,\n")], "0 0"), + (&[("Adobe Transform", "5 /Real (moveH_Pts) ,\n0.5 /Real (rotate_Radians) ,\n0 /Bool (transformPatterns) ,\n")], "0 0"), + ]; + for (effects, painted) in others { + let st = effects_style(effects, painted); + assert!(!st.image_warp, "{effects:?} {painted}"); + assert!(styled(&image, &look, &st, &paints).is_none(), "{effects:?} {painted}"); + } + } + #[test] fn data_stops_at_its_end_or_a_marker_of_the_section() { let section = Some(("BeginTextDocument", "EndTextDocument")); diff --git a/crates/eps/src/import/ai/style.rs b/crates/eps/src/import/ai/style.rs index f15744f30c..d27a297925 100644 --- a/crates/eps/src/import/ai/style.rs +++ b/crates/eps/src/import/ai/style.rs @@ -32,6 +32,10 @@ //! gradient (`Bb` … `flag (name) x y angle length … Bg` … `BB`); `stroke fill Xd` says whether it //! paints at all. A blend filter's `mode opacity isolate knockout shape Xy` is its transparency. //! +//! A style with no filters is one paint (`/SimpleStyle :` … `/Paint ;` in place of `/ActiveStyle`): +//! the fill's and stroke's colors and the stroke's style as an object's own paint operators write +//! them, `stroke fill Xd` turning each on, and an `Xy` for its transparency. +//! //! A stroke with a Calligraphic or Art brush is its own basic filter, `(Adobe Calligraphic Brush //! Tool)` or `(Adobe ArtOnPath Brush Tool)`, with its stroke's style and the brush's settings for //! the object as entries (see [`super::brush`]). @@ -189,6 +193,10 @@ pub(super) struct ArtStyle { /// the effects any object takes that don't move the outline: what a path or compound path is /// read with when each gradient is placed as its drawn look has it (`read::ops`' `styled`). pub stacked: bool, + /// It is one Warp on the whole object, under fills and strokes that paint nothing and have no + /// effects of their own: what an image is read with when its live warp draws as its drawn look + /// (`read::ops`' `styled`). + pub image_warp: bool, /// Its fills and strokes, bottom first. pub items: Vec, /// Each item's own visibility, transparency and effects, in the order of [`Self::items`]. @@ -202,6 +210,15 @@ pub(super) struct ArtStyle { pub transparency: Option<(f32, BlendMode, bool, Knockout)>, /// [`Self::effects`] holds Effect › Pathfinder effects, which only a group is read with. pub pathfinder: bool, + /// A style that is one paint (`/SimpleStyle :`, its paint's operators, `/Paint ;`), when that + /// paint is a pattern: its [`StyleItem::Pattern`]. A text document's characters name such + /// styles for their fills and strokes (`ate`). `None` for any other paint or style. + pub simple_pattern: Option, + /// A style that is one paint: its fill and stroke, bottom first, each there when its + /// `stroke fill Xd` turns it on (none when neither is on). `Err` when it turns on a fill or + /// stroke whose paint isn't read here (a gradient, a pattern, a color that isn't read) or has + /// no `Xd`. `None` for a style with filters, whose paint is [`Self::items`]. + pub one_paint: Option, ()>>, } impl ArtStyle { @@ -406,9 +423,24 @@ pub(super) fn art_styles_in(data: &[u8], names: &mut Names) -> HashMap = vec![]; let mut pending: Option = None; let mut in_basic = false; - let mut finish = |name: Option, filters: &mut Vec| { + // A style that is one paint being read, and its pattern so far. + let mut simple: Option> = None; + // The same style's paint operators so far. + let mut one_paint: Option = None; + let mut finish = |name: Option, filters: &mut Vec, simple_pattern: Option, one_paint: Option| { if let Some(name) = name { - styles.insert(name, style(filters)); + // Only a style that is one paint holds a pattern for type: one with filters as well + // paints with more than that. + let simple_pattern = simple_pattern.filter(|_| filters.is_empty()); + let mut st = ArtStyle { simple_pattern, ..style(filters) }; + if let Some(one) = one_paint.filter(|_| filters.is_empty()) { + if let Some((mode, opacity)) = one.paint.xy { + let (isolate, knockout) = one.paint.xy_group.unwrap_or((false, Knockout::Off)); + st.transparency = Some((opacity, super::read::blend_mode(mode), isolate, knockout)); + } + st.one_paint = Some(one.items()); + } + styles.insert(name, st); } filters.clear(); }; @@ -445,11 +477,12 @@ pub(super) fn art_styles_in(data: &[u8], names: &mut Names) -> HashMap match n { b"KnownStyle" => { - finish(name.take(), &mut filters); + finish(name.take(), &mut filters, simple.take().flatten(), one_paint.take()); operands.clear(); open.clear(); (pending, in_basic, style_entry, other_entry) = (None, false, None, None); } + b"SimpleStyle" if filters.is_empty() => (simple, one_paint) = (Some(None), Some(OnePaint::default())), b"FillStyle" => style_entry = Some(Kind::Fill), b"StrokeStyle" | b"BlendStyle" => style_entry = Some(Kind::Other), b"Name" if name.is_none() && filters.is_empty() => name = operands.iter().rev().find_map(|v| names.text(v)), @@ -549,9 +582,7 @@ pub(super) fn art_styles_in(data: &[u8], names: &mut Names) -> HashMap HashMap { - let name = vals.iter().find(|v| matches!(v, V::Str(_))).and_then(|v| names.text(v)); - let matrix = vals.iter().rev().find_map(|v| match v { - V::Arr(a) => { - let n: Vec = a.iter().filter_map(V::num).collect(); - <[f64; 6]>::try_from(n.as_slice()).ok().filter(|m| m.iter().all(|v| v.is_finite())) - } - _ => None, - }); - let controls: Vec = - vals.iter().skip_while(|v| !matches!(v, V::Str(_))).skip(1).take_while(|v| !matches!(v, V::Arr(_))).filter_map(V::num).collect(); - if let Some(name) = name { - f.pattern = Some((name, matrix, controls)); + if let Some(pattern) = pattern_operands(vals, names) { + f.pattern = Some(pattern); } } _ => {} } } +/// The operands of `(name) … [matrix] p`: the pattern's name read by `names`, its matrix (six +/// finite numbers) and the numbers between the name and the matrix. `None` without a name. +fn pattern_operands(vals: &[V], names: &mut Names) -> Option<(String, Option<[f64; 6]>, Vec)> { + let name = vals.iter().find(|v| matches!(v, V::Str(_))).and_then(|v| names.text(v))?; + let matrix = vals.iter().rev().find_map(|v| match v { + V::Arr(a) => { + let n: Vec = a.iter().filter_map(V::num).collect(); + <[f64; 6]>::try_from(n.as_slice()).ok().filter(|m| m.iter().all(|v| v.is_finite())) + } + _ => None, + }); + let controls: Vec = + vals.iter().skip_while(|v| !matches!(v, V::Str(_))).skip(1).take_while(|v| !matches!(v, V::Arr(_))).filter_map(V::num).collect(); + Some((name, matrix, controls)) +} + +/// A paint operator in a style being read: one of the last filter's (`filters`), else one of a style +/// that is one paint (`simple` and `one_paint`, while one is read). +fn style_paint_op( + filters: &mut [Filter], + simple: &mut Option>, + one_paint: &mut Option, + op: &str, + vals: &[V], + names: &mut Names, +) { + if let Some(f) = filters.last_mut() { + paint_op(f, op, vals, names); + return; + } + if let Some(paint) = simple.as_mut() { + simple_paint_op(paint, op, vals, names); + } + if let Some(one) = one_paint.as_mut() { + one.op(op, vals, names); + } +} + +/// The paint operators of a style that is one paint (`/SimpleStyle :` … `/Paint ;`), read as a +/// fill's or stroke's style reads them. +#[derive(Default)] +struct OnePaint { + paint: Filter, + /// Its `stroke fill Xd` was read. + xd: bool, + /// Its last fill paint is a pattern (`p`) or may be a gradient (`Bg`). + fill_unread: bool, + /// Its last stroke paint is a pattern (`P`) or may be a gradient (`Bg`). + stroke_unread: bool, + /// Inside a gradient instance (`flag Bb` … `BB`): whether it paints the stroke (flag 1). + instance: Option, +} + +impl OnePaint { + fn op(&mut self, op: &str, vals: &[V], names: &mut Names) { + match op { + "Xd" => self.xd |= vals.iter().filter_map(V::num).count() >= 2, + "p" => self.fill_unread = true, + "P" => self.stroke_unread = true, + // The flag of the instance it is in says which one it paints, as an object's does + // (`Instance::begin` in `paint.rs`); outside one it is read as either one's. + "Bb" => self.instance = Some(vals.iter().filter_map(V::num).next_back() == Some(1.0)), + "BB" => self.instance = None, + "Bg" => match self.instance { + Some(true) => self.stroke_unread = true, + Some(false) => self.fill_unread = true, + None => (self.fill_unread, self.stroke_unread) = (true, true), + }, + // A color replaces what came before it; one that isn't read leaves none. + "Xa" | "k" | "g" | "x" | "Xx" | "Xk" | "Xs" | "Xz" | "xa" | "xx" | "xk" | "xs" | "xz" => { + (self.fill_unread, self.paint.fill) = (false, None); + } + "XA" | "K" | "G" | "X" | "XX" | "XK" | "XS" | "XZ" => (self.stroke_unread, self.paint.stroke) = (false, None), + _ => {} + } + paint_op(&mut self.paint, op, vals, names); + } + + /// Its fill and stroke ([`ArtStyle::one_paint`]). + fn items(&self) -> Result, ()> { + let f = &self.paint; + if !self.xd { + return Err(()); + } + let (stroked, filled) = f.paints; + let mut items = vec![]; + if filled { + match &f.fill { + Some(p) if !self.fill_unread => items.push(StyleItem::Fill(p.clone())), + _ => return Err(()), + } + } + if stroked { + match &f.stroke { + Some(p) if !self.stroke_unread => items.push(StyleItem::Stroke { + paint: p.clone(), + width: f.width, + cap: f.cap, + join: f.join, + miter: f.miter, + dash: f.dash.clone(), + profile: None, + align: StrokeAlign::Center, + brush: None, + }), + _ => return Err(()), + } + } + Ok(items) + } +} + +/// A paint operator of a style that is one paint: a pattern (`p`) is kept as its +/// [`StyleItem::Pattern`], and any other paint after it (a colour, a stroke's pattern or a +/// gradient) leaves the style without one. +fn simple_paint_op(paint: &mut Option, op: &str, vals: &[V], names: &mut Names) { + match op { + "p" => *paint = pattern_operands(vals, names).map(|(name, matrix, controls)| StyleItem::Pattern { name, matrix, controls }), + "Xa" | "k" | "g" | "x" | "Xx" | "Xk" | "Xs" | "Xz" | "XA" | "K" | "G" | "X" | "XX" | "XK" | "XS" | "XZ" | "xa" | "xx" | "xk" | "xs" + | "xz" | "P" | "Bg" => *paint = None, + _ => {} + } +} + /// A variable-width stroke's profile: its widths (fractions of the stroke's) at positions along the /// path, the same both sides unless it gives each side's. fn width_profile(arrays: &HashMap>) -> Option { @@ -792,6 +937,8 @@ const ANYTHING: Under = Under { strokes: true, patterns: true }; /// The Transform effect `f` (the factor and radian entries; the percent and degree ones are what /// its dialog shows). `None` keeps the drawn look: an entry not read, Random (the file holds no /// seed), or a missing Scale Strokes & Effects or Transform Patterns that would change `under`. +/// The keys are LiveEffect XML's +/// (https://community.adobe.com/questions-652/how-to-define-values-in-action-menu-command-816878). fn transform(f: &Filter, under: Under) -> Option { for key in ["scaleH_Percent", "scaleV_Percent", "rotate_Degrees"] { entry(f, key, Kind::Real).ok()?; @@ -841,6 +988,9 @@ fn transform(f: &Filter, under: Under) -> Option { /// corners are measured in: the distorted box is laid over the object's own bounds, as the catalog /// effect lays it, also when the frame is another size (a unit square, or bounds with the stroke). /// No corners is no change; some but not all, or a frame that isn't an upright rectangle, isn't read. +/// The keys are LiveEffect XML's (https://community.adobe.com/questions-652/pageitem-applyeffect-liveeffectxml-769450), +/// with the corners in that order +/// (https://raw.githubusercontent.com/mark1bean/live-effect-functions-for-illustrator/master/scripts/LE_Functions.js). fn free_distort(f: &Filter) -> Option { let mut corners = [[[0.0; 2]; 4]; 2]; let mut held = 0; @@ -895,8 +1045,10 @@ fn points(f: &Filter) -> Option<&'static str> { Some(if switch(f, "roundness", Kind::Real).ok()?.unwrap_or(false) { "smooth" } else { "corner" }) } -/// The Tweak effect `f` (`Adobe Scribble and Tweak`): relative unless `absoluteness` says otherwise, -/// moving anchors and both handles unless the dictionary turns them off. +/// The Tweak effect `f` (`TWEAK`): relative unless `absoluteness` says otherwise, +/// moving anchors and both handles unless the dictionary turns them off. The keys are LiveEffect +/// XML's: `horz` and `vert` relative, `ahor` and `aver` absolute, and `anch`, `in` and `out` +/// (https://raw.githubusercontent.com/mark1bean/live-effect-functions-for-illustrator/master/scripts/LE_Functions.js). fn tweak(f: &Filter) -> Option { let (absolute, h) = sized(f, false, "horz", "ahor")?; let (_, v) = sized(f, false, "vert", "aver")?; @@ -906,7 +1058,9 @@ fn tweak(f: &Filter) -> Option { } /// The Zig Zag effect `f`: absolute unless `absoluteness` says otherwise, 4 ridges and Corner points -/// when they are missing. +/// when they are missing. The keys are LiveEffect XML's: `amount` absolute, `relAmount` relative, +/// `ridges` and `roundness` (https://community.adobe.com/questions-652/pageitem-applyeffect-liveeffectxml-769450, +/// https://raw.githubusercontent.com/mark1bean/live-effect-functions-for-illustrator/master/scripts/LE_Functions.js). fn zig_zag(f: &Filter) -> Option { let (absolute, size) = sized(f, true, "relAmount", "amount")?; let ridges = real(f, "ridges", 4.0, 0.0..=100.0).filter(|r| r.fract() == 0.0)?; @@ -1159,6 +1313,7 @@ fn effect(f: &Filter, under: Under) -> Option { "horizontal": pct("DeformHoriz"), "vertical": pct("DeformVert"), "orientation": if flag("Rotate") { "vertical" } else { "horizontal" }, + "version": vectorcraft_doc::live::WARP_NET, }), ) } @@ -1166,6 +1321,8 @@ fn effect(f: &Filter, under: Under) -> Option { TRANSFORM => ("distort.transform", transform(f, under)?), FREE_DISTORT => ("distort.freeDistort", free_distort(f)?), // Negative puckers (https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html). + // Pucker & Bloat's `d_factor` and Twist's `angle` are LiveEffect XML's keys + // (https://community.adobe.com/questions-652/pageitem-applyeffect-liveeffectxml-769450). PUCKER_BLOAT => ("distort.puckerBloat", json!({"amount": real(f, "d_factor", 0.0, -200.0..=200.0)?})), TWEAK => ("distort.tweak", tweak(f).filter(still)?), // A positive angle turns clockwise in both. @@ -1625,6 +1782,10 @@ fn style(filters: &[Filter]) -> ArtStyle { && st.items.iter().all(|i| matches!(i, StyleItem::Fill(_) | StyleItem::Gradient { .. } | StyleItem::Stroke { brush: None, .. })) && st.looks.iter().all(|l| l.effects.is_empty()) && st.effects.iter().all(any_object_takes); + st.image_warp = st.plain + && matches!(st.effects.as_slice(), [e] if e.id.starts_with("warp.")) + && st.items.iter().all(|i| matches!(i, StyleItem::Fill(p) | StyleItem::Stroke { paint: p, .. } if p.is_none())) + && st.looks.iter().all(|l| l.effects.is_empty()); st } diff --git a/crates/eps/src/import/ai/style/tests.rs b/crates/eps/src/import/ai/style/tests.rs index d39a87b5c0..ea8428809c 100644 --- a/crates/eps/src/import/ai/style/tests.rs +++ b/crates/eps/src/import/ai/style/tests.rs @@ -495,6 +495,8 @@ fn a_stack_of_fills_with_effects_of_their_own_is_read_as_itself() { // The warp is the whole object's; the characters paint below every item. let [warp] = st.effects.as_slice() else { panic!("{:?}", st.effects) }; assert_eq!((warp.id.as_str(), &warp.params["bend"], &warp.params["orientation"]), ("warp.arch", &json!(5.0), &json!("horizontal"))); + // A file's warp bends as its style's Bézier net. + assert_eq!(warp.params["version"], json!(vectorcraft_doc::live::WARP_NET)); assert_eq!(st.contents_index, None); } @@ -1025,8 +1027,7 @@ fn affine_corners_are_a_parallelogram_however_far_they_reach() { #[test] fn roughen_keeps_the_drawn_look() { - // Its outline is random and the file holds no seed; at a size of 0 the effect still redraws the - // path's segments. + // Its outline is random and the file holds no seed. assert_eq!(read_effect("Adobe Roughen", "30 /Real (size) ,\n"), None); assert_eq!(read_effect("Adobe Roughen", ""), None); } @@ -1496,3 +1497,63 @@ fn art_styles_read_registration_and_named_colors() { let [StyleItem::Stroke { paint: Paint::Solid { swatch, tint, .. }, .. }] = st_stroke.items.as_slice() else { panic!("{st_stroke:?}") }; assert_eq!((swatch.as_deref(), *tint), (Some(vectorcraft_color::swatch::REGISTRATION), 0.0)); } + +/// Only a style that is one paint holds a pattern for type: the same pattern paint in a style that +/// also has filters gives none, whichever comes first. +#[test] +fn only_a_style_of_one_pattern_paint_holds_a_pattern_for_type() { + let simple = "/SimpleStyle :\n0 O\n(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n0 1 0 0 0 Xy\n0 J 0 j 1 w 10 M []0 d\n0 XR\n0 1 Xd\n/Paint ;\n"; + let active = "/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n1 /FillOrStroke ,\n/Dictionary : /NotRecorded ,\n\ + /FillStyle : 0 O\n1 0 0 0 k\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n;\n"; + let styles = |body: &str| art_styles_in(format!("/KnownStyle :\n(S) /Name ,\n{body} /Def ;\n").as_bytes(), &mut Names::default()); + assert!(styles(simple).get("S").is_some_and(|s| s.simple_pattern.is_some())); + for body in [format!("{simple}{active}"), format!("{active}{simple}")] { + assert!(styles(&body).get("S").is_none_or(|s| s.simple_pattern.is_none()), "{body}"); + } +} + +/// A style that is one paint reads as the fill and stroke its `Xd` turns on, in the paint's colors +/// and the stroke's style; one that turns on a paint not read here, or has no `Xd`, isn't read. +#[test] +fn a_style_of_one_paint_reads_as_the_fill_and_stroke_its_xd_turns_on() { + let one = |paint: &str| { + let data = format!("/KnownStyle :\n(S) /Name ,\n/SimpleStyle :\n{paint}/Paint ;\n/Def ;\n"); + art_styles_in(data.as_bytes(), &mut Names::default()).remove("S").and_then(|s| s.one_paint) + }; + let stroke = "0 R\n0 1 1 0 K\n1 J 2 j 3 w 4 M [2 1]0 d\n"; + let Some(Ok(items)) = one(&format!("0 O\n0 0 1 0 k\n{stroke}1 1 Xd\n")) else { panic!("{:?}", one(stroke)) }; + let [StyleItem::Fill(fill), StyleItem::Stroke { paint, width, cap, join, miter, dash, profile: None, align: StrokeAlign::Center, brush: None }] = + items.as_slice() + else { + panic!("{items:?}") + }; + assert_eq!((fill.color(), paint.color()), (Some(Color::cmyk(0.0, 0.0, 1.0, 0.0)), Some(Color::cmyk(0.0, 1.0, 1.0, 0.0)))); + assert_eq!((*width, *cap, *join, *miter), (3.0, LineCap::Round, LineJoin::Bevel, 4.0)); + assert_eq!(dash.as_ref().map(|d| d.pattern.clone()), Some(vec![2.0, 1.0])); + // Only what `Xd` turns on; nothing when it turns on neither. + assert!(matches!(one(&format!("0 0 1 0 k\n{stroke}1 0 Xd\n")), Some(Ok(i)) if matches!(i.as_slice(), [StyleItem::Stroke { .. }]))); + assert_eq!(one(&format!("0 0 1 0 k\n{stroke}0 0 Xd\n")), Some(Ok(vec![]))); + // The last paint of each one counts: a solid color after a pattern or a gradient replaces it. + let solid_fill = |before: &str| one(&format!("{before}\n0 0 1 0 k\n0 1 Xd\n")); + for before in ["(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p", "0 Bb\n2 (Sky) 0 0 0 100 1 0 0 1 0 0 Bg\n0 BB"] { + assert!(matches!(solid_fill(before), Some(Ok(i)) if matches!(i.as_slice(), [StyleItem::Fill(_)])), "{before}"); + } + let solid_stroke = one("(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] P\n0 1 1 0 K\n1 0 Xd\n"); + assert!(matches!(solid_stroke, Some(Ok(i)) if matches!(i.as_slice(), [StyleItem::Stroke { .. }]))); + // A gradient instance's flag says which one it paints: a stroke gradient leaves a solid fill read. + let fill_and_stroke_gradient = one("0 0 1 0 k\n1 Bb\n2 (Ramp) 0 0 90 1 1 0 0 1 0 0 1 Bg\n0 BB\n0 1 Xd\n"); + assert!(matches!(fill_and_stroke_gradient, Some(Ok(i)) if matches!(i.as_slice(), [StyleItem::Fill(_)]))); + // Not read: no `Xd`, a gradient or pattern fill, a pattern stroke, a gradient stroke after a solid one, a paint + // turned on with no color. + for paint in [ + format!("0 0 1 0 k\n{stroke}"), + "0 Bb\n2 (Sky) 0 0 0 100 1 0 0 1 0 0 Bg\n0 BB\n0 1 Xd\n".to_string(), + "(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n0 1 Xd\n".to_string(), + "(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] P\n1 0 Xd\n".to_string(), + "0 R\n0 1 1 0 K\n1 Bb\n0 0 0 0 Bh\n2 (Ramp) 0 0 90 1 1 0 0 1 0 0 1 Bg\n0 BB\n2 w\n1 0 Xd\n".to_string(), + "0 0 1 0 k\n1 1 Xd\n".to_string(), + ] { + assert_eq!(one(&paint), Some(Err(())), "{paint}"); + } +} diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 46386d2200..f2a0a41ca7 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -5,6 +5,7 @@ use std::sync::Arc; use kurbo::{Affine, Point, Rect}; use vectorcraft_color::gradient::GradientKind; use vectorcraft_color::{BlendMode, Color, Paint}; +use vectorcraft_doc::live::WARP_NET; use vectorcraft_doc::{AppearanceItem, ColorMode, Document, Guide, Knockout, LayerColor, LineCap, LineJoin, Node, NodeKind, Unit}; use super::*; @@ -3929,6 +3930,28 @@ fn point_type(attrs: &str, text: &str) -> String { format!("0 To\n1 0 0 1 10 50 0 Tp\nTP\n0 Tr\n0 0 0 1 k\n/_Helvetica 12 Tf\n{attrs}\n({text}) Tx\nTO\n") } +/// Legacy type is set in the installed face of exactly the PostScript name its `Tf` gives, as type +/// from a text document is: not a face whose name differs only in case and loads first, nor the +/// copy the family and style resolve to when the name's own is another (it names its version). +#[test] +fn legacy_type_takes_the_face_of_its_exact_postscript_name() { + use vectorcraft_text::test_fonts::named_copy; + let db = vectorcraft_text::FontDb::global(); + for (inter, names) in [ + (true, ("TWINLEGACY INK", "Regular", "Version 1.000", "TWINLEGACYINK-Regular")), + (false, ("Twinlegacy Ink", "Regular", "Version 2.000", "TwinlegacyInk-Regular")), + ] { + assert_eq!(db.add_font(named_copy(inter, names).unwrap()), 1, "{names:?}"); + } + let face = |font: &str| { + let texts = legacy_texts(&point_type("", "Hi").replace("/_Helvetica 12 Tf", &format!("/_{font} 12 Tf"))); + let f = db.style_face(&texts[0].runs[0].style).unwrap(); + (f.postscript_name(), f.version.clone()) + }; + assert_eq!(face("TwinlegacyInk-Regular"), ("TwinlegacyInk-Regular".to_string(), "Version 2.000".to_string())); + assert_eq!(face("TWINLEGACYINK-Regular"), ("TWINLEGACYINK-Regular".to_string(), "Version 1.000".to_string())); +} + /// `TC` and `TW` (§15.4.7) set the paragraph's letter and word spacing, `Tq` its hanging /// punctuation and `Th` (§22) its hyphenation; each paragraph keeps the values in force at its /// first character, and they last into the next text object. @@ -7091,13 +7114,12 @@ fn with_red_stroke(styles: &str) -> String { #[test] fn twist_and_a_scaling_transform_are_read_only_where_their_outline_is_known() { - // GUARDS: Twist was read on curves, strokes and groups, and Transform scaling a stroked object, - // where the outline VectorCraft draws hasn't been checked. + // GUARDS: Twist was read on strokes, and Transform scaling a stroked object, where the outline + // VectorCraft draws hasn't been checked. let object = |hidden: &str| { format!("0 Ae\nu\n{RED}{}f\nU\n%_Bb\n%_{}f\n%_0 BB\n1 (Bent) XW\n", rect_path(16.0, 16.0, 64.0, 54.0), hidden.replace('\n', "\n%_")) }; let square = object(&rect_path(20.0, 20.0, 60.0, 50.0)); - let curved = object("20 35 m\n20 45 60 45 60 35 c\n60 25 20 25 20 35 c\n"); let twist = distort_styles("Adobe Twirl", "45 /Real (angle) ,\n", BLUE_FILL); let scale = "0.5 /Real (scaleH_Factor) ,\n0 /Bool (scaleLines) ,\n0 /Bool (transformPatterns) ,\n"; let corner = distort_styles("Adobe Transform", &format!("0 /Int (pinPoint) ,\n{scale}"), BLUE_FILL); @@ -7105,9 +7127,7 @@ fn twist_and_a_scaling_transform_are_read_only_where_their_outline_is_known() { let moved = distort_styles("Adobe Transform", "0 /Int (pinPoint) ,\n5 /Real (moveH_Pts) ,\n0 /Bool (transformPatterns) ,\n", BLUE_FILL); let read = |styles: &str, art_: &str| read_ok(&format!("{styles}{}", layer(art_))); for (what, r) in [ - ("a twisted curve", read(&twist, &curved)), ("a twisted stroke", read(&with_red_stroke(&twist), &square)), - ("a twisted group", read(&distort_styles("Adobe Twirl", "45 /Real (angle) ,\n", None), &distort_group())), ("a stroke scaled from a corner", read(&with_red_stroke(&corner), &square)), ("a stroke scaled from the center", read(&with_red_stroke(¢er), &square)), ] { @@ -7132,6 +7152,67 @@ fn twist_and_a_scaling_transform_are_read_only_where_their_outline_is_known() { assert_eq!((e.id.as_str(), e.params["angle"].as_f64()), ("distort.twist", Some(45.0))); } +#[test] +fn twist_is_read_on_curves_compound_paths_and_groups_with_nothing_stroked_up_to_a_quarter_turn() { + // GUARDS: Twist was read only on paths and compound paths with straight segments. + // The object, `hidden` painted with its style, under its drawn look. + let object = |hidden: &str| { + format!("0 Ae\nu\n{RED}{}f\nU\n%_Bb\n%_{}0 BB\n1 (Bent) XW\n", rect_path(16.0, 16.0, 64.0, 54.0), hidden.replace('\n', "\n%_")) + }; + let square = object(&format!("{}f\n", rect_path(20.0, 20.0, 60.0, 50.0))); + let oval = "20 35 m\n20 45 60 45 60 35 c\n60 25 20 25 20 35 c\n"; + let curved = object(&format!("{oval}f\n")); + let ring = object(&format!("*u\n{oval}f\n30 35 m\n30 40 50 40 50 35 c\n50 30 30 30 30 35 c\nf\n*U\n")); + let twist = |angle: f64, paint| distort_styles("Adobe Twirl", &format!("{angle} /Real (angle) ,\n"), paint); + let read = |styles: &str, art_: &str| read_ok(&format!("{styles}{}", layer(art_))); + // The first member of a group, and a second one. + let group = |second: &str| { + let member = |s: String| s.replace('\n', "\n%_"); + format!( + "0 Ae\nu\n{RED}{}f\nU\n%_0 Ae\n%_u\n%_{}{}U\n1 (Bent) XW\n", + rect_path(-1.0, -1.0, 16.0, 11.0), + member(format!("{RED}{}f\n", rect_path(0.0, 0.0, 10.0, 10.0))), + member(second.to_string()) + ) + }; + let hidden_member = group(&format!("1 Xw\n{RED}{}f\n0 Xw\n", rect_path(5.0, 0.0, 15.0, 10.0))); + // A compound path, its first subpath `first` and a guide. + let with_guide = |first: &str| object(&format!("*u\n{first}f\n5 0 m\n15 10 L\n(N) *\n*U\n")); + for (what, r, members) in [ + ("a twisted curve", read(&twist(45.0, BLUE_FILL), &curved), 0), + ("a curved compound path", read(&twist(-60.0, BLUE_FILL), &ring), 2), + ("a twisted group", read(&twist(90.0, None), &distort_group()), 2), + ("a group with a hidden member", read(&twist(45.0, None), &hidden_member), 2), + ("a curve twisted a quarter turn back", read(&twist(-90.0, BLUE_FILL), &curved), 0), + ("a square twisted three quarters of a turn, as before", read(&twist(270.0, BLUE_FILL), &square), 0), + ("a straight compound path with a guide, as before", read(&twist(45.0, BLUE_FILL), &with_guide(&rect_path(20.0, 20.0, 60.0, 50.0))), 2), + ] { + assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{what}: {:?}", r.warnings); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{what}: {a:#?}"); + assert_eq!(a[0].children().map_or(0, |c| c.len()), members, "{what}: the object, not its look: {a:#?}"); + let [e] = a[0].appearance.effects.as_slice() else { panic!("{what}: {:?}", a[0].appearance) }; + assert_eq!(e.id, "distort.twist", "{what}"); + } + // A group with a stroked member or a guide, a curved compound path with a guide, and curves and + // groups twisted past a quarter turn, keep the drawn look. + let stroked_member = group(&format!("0 1 1 0 1 0 0 XA\n2 w\n{}S\n", rect_path(5.0, 0.0, 15.0, 10.0))); + let guide_member = group("5 0 m\n15 10 L\n(N) *\n"); + for (what, r) in [ + ("a group with a stroked member", read(&twist(45.0, None), &stroked_member)), + ("a group with a guide", read(&twist(45.0, None), &guide_member)), + ("a curved compound path with a guide", read(&twist(45.0, BLUE_FILL), &with_guide(oval))), + ("a curve twisted past a quarter turn", read(&twist(91.0, BLUE_FILL), &curved)), + ("a curve twisted half a turn back", read(&twist(-180.0, BLUE_FILL), &curved)), + ("a group twisted past a quarter turn", read(&twist(135.0, None), &distort_group())), + ] { + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{what}: {a:#?}"); + assert!(a[0].appearance.effects.is_empty(), "{what}: the drawn look: {a:#?}"); + assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{what}: {:?}", r.warnings); + } +} + #[test] fn a_bare_comment_line_in_a_prolog_leaves_its_end_alone() { // GUARDS: a bare `%` line's empty marker matched the empty begin marker of a section that has none. @@ -7403,15 +7484,16 @@ fn a_warp_envelope_opens_live() { for (style, bend, h, v, rotate, id) in [(1, 0.5, 0.0, 0.0, 0, "arc"), (1, 0.5, -0.2, 0.3, 1, "arc"), (8, 0.5, 0.0, 0.0, 0, "flag"), (15, 0.5, 0.0, 0.0, 0, "twist")] { - let want = EnvelopeKind::Warp { style: id.into(), bend: bend * 100.0, h: h * 100.0, v: v * 100.0, horizontal: rotate == 0 }; + let want = + EnvelopeKind::Warp { style: id.into(), bend: bend * 100.0, h: h * 100.0, v: v * 100.0, horizontal: rotate == 0, version: WARP_NET }; let body = envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), &warp_keys(style, bend, h, v, rotate), &envelope_content(), 1, &drawn_content(&want)); let r = read_ok(&layer(&body)); let a = art(&r.doc); assert_eq!(a.len(), 1, "{a:#?}"); let (content, kind, fidelity, editing, options) = live_envelope(&a[0]); - let EnvelopeKind::Warp { style: s, bend: b, h: dh, v: dv, horizontal } = kind else { panic!("{kind:?}") }; - assert_eq!((s.as_str(), *horizontal), (id, rotate == 0)); + let EnvelopeKind::Warp { style: s, bend: b, h: dh, v: dv, horizontal, version } = kind else { panic!("{kind:?}") }; + assert_eq!((s.as_str(), *horizontal, *version), (id, rotate == 0, WARP_NET)); assert!([(*b, bend), (*dh, h), (*dv, v)].iter().all(|(got, f)| (got - f * 100.0).abs() < 1e-9), "{kind:?}"); assert_eq!((fidelity, editing, options), (50.0, false, vectorcraft_doc::live::EnvelopeOptions::NEW)); assert_eq!(content.len(), 1, "{content:#?}"); @@ -7443,7 +7525,7 @@ fn warp_envelopes_read_every_style() { "twist", ]; for (n, id) in ids.iter().enumerate() { - let want = EnvelopeKind::Warp { style: (*id).into(), bend: 30.0, h: 0.0, v: 0.0, horizontal: true }; + let want = EnvelopeKind::Warp { style: (*id).into(), bend: 30.0, h: 0.0, v: 0.0, horizontal: true, version: WARP_NET }; let keys = warp_keys(n as u32 + 1, 0.3, 0.0, 0.0, 0); let r = read_ok(&layer(&envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), &keys, &envelope_content(), 1, &drawn_content(&want)))); let a = art(&r.doc); @@ -7648,6 +7730,55 @@ fn a_top_object_envelope_opens_live_with_its_outline() { assert!(r.warnings.is_empty(), "{:?}", r.warnings); } +/// A top object whose saved grid has three patches across, its top edge one curve split into +/// thirds, maps its contents along that one curve. In this synthetic file the drawn art is drawn by +/// VectorCraft's own map of the unsplit curve, so the envelope opens live only when the split side +/// maps the same way, and the contents' first quarter ends a quarter of the way along the curve. +#[test] +fn a_top_object_whose_top_is_one_curve_split_in_thirds_opens_live() { + use kurbo::{CubicBez, ParamCurve}; + use vectorcraft_doc::live::EnvelopeKind; + // In the document: the top runs from (40, 20) to (160, 20), its parameter fast at the start. + let top = CubicBez::new((40.0, 20.0), (112.0, -16.0), (154.0, 2.0), (160.0, 20.0)); + let thirds = [top.subsegment(0.0..1.0 / 3.0), top.subsegment(1.0 / 3.0..2.0 / 3.0), top.subsegment(2.0 / 3.0..1.0)]; + // Art space has y up: row 1 is the top. The bottom row and the columns are straight. + let up = |p: Point| (p.x, 100.0 - p.y); + let at = move |(i, j): (usize, usize)| { + if j == 1 { up(if i == 0 { top.p0 } else { thirds[i - 1].p3 }) } else { (40.0 + 40.0 * i as f64, 20.0) } + }; + let handle = move |p: (usize, usize), q: (usize, usize)| match (p, q) { + ((i, 1), (k, 1)) if k == i + 1 => up(thirds[i].p1), + ((i, 1), (k, 1)) if k + 1 == i => up(thirds[k].p2), + _ => { + let ((x, y), (u, v)) = (at(p), at(q)); + (x + (u - x) / 3.0, y + (v - y) / 3.0) + } + }; + let shape = mesh_text(3, 1, &at, &handle, None); + // The contents: two red bars at the box's left and right ends, drawn by the unsplit curve. + let mut bp = kurbo::BezPath::new(); + bp.move_to(top.p0); + bp.curve_to(top.p1, top.p2, top.p3); + bp.line_to((160.0, 80.0)); + bp.line_to((40.0, 80.0)); + bp.close_path(); + let one_curve = EnvelopeKind::TopObject { path: vectorcraft_geom::PathData::from_bezpath(&bp), corners: Some([0, 1, 2, 3]) }; + let src = Rect::new(40.0, 20.0, 160.0, 80.0); + let bars = [Rect::new(40.0, 20.0, 70.0, 80.0), Rect::new(130.0, 20.0, 160.0, 80.0)]; + let content: String = bars.iter().map(|b| format!("{RED}{}f\n", rect_path(b.x0, b.y0, b.x1, b.y1))).collect(); + let drawn: String = bars.iter().map(|b| drawn_box(&one_curve, src, *b)).collect(); + let r = read_ok(&layer(&envelope_of(&shape, ENVELOPE_KEYS, &content, 3, &drawn))); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + let (_, kind, ..) = live_envelope(&a[0]); + let EnvelopeKind::TopObject { path, .. } = kind else { panic!("{kind:?}") }; + assert_eq!(path.anchor_count(), 8, "{path:?}"); + let map = vectorcraft_doc::live::envelope_mapper(kind, src); + let (p, want) = (map(Point::new(70.0, 20.0)), top.eval(0.25)); + assert!((p - want).hypot() < 0.02, "{p:?}, want {want:?}"); +} + /// Envelope Options come from the options word, Fidelity from its own key. #[test] fn an_envelope_reads_its_options_and_fidelity() { @@ -7974,7 +8105,7 @@ fn an_envelope_that_doesnt_read_keeps_its_drawn_art() { #[test] fn an_envelope_that_doesnt_come_out_as_drawn_keeps_its_drawn_art() { use vectorcraft_doc::live::EnvelopeKind; - let other = EnvelopeKind::Warp { style: "arc".into(), bend: -50.0, h: 0.0, v: 0.0, horizontal: true }; + let other = EnvelopeKind::Warp { style: "arc".into(), bend: -50.0, h: 0.0, v: 0.0, horizontal: true, version: WARP_NET }; let body = envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), &warp_keys(1, 0.5, 0.0, 0.0, 0), &envelope_content(), 1, &drawn_content(&other)); let r = read_ok(&layer(&body)); let a = art(&r.doc); @@ -7989,7 +8120,7 @@ fn an_envelope_that_doesnt_come_out_as_drawn_keeps_its_drawn_art() { fn a_white_envelope_that_doesnt_come_out_as_drawn_keeps_its_drawn_art() { use vectorcraft_doc::live::EnvelopeKind; const WHITE: &str = "0 0 0 0 1 1 1 Xa\n"; - let other = EnvelopeKind::Warp { style: "arc".into(), bend: -50.0, h: 0.0, v: 0.0, horizontal: true }; + let other = EnvelopeKind::Warp { style: "arc".into(), bend: -50.0, h: 0.0, v: 0.0, horizontal: true, version: WARP_NET }; let content = envelope_content().replace(RED, WHITE); let drawn = drawn_content(&other).replace(RED, WHITE); let body = envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), &warp_keys(1, 0.5, 0.0, 0.0, 0), &content, 1, &drawn); @@ -8149,7 +8280,7 @@ fn warped_type_on_the_page_spends_what_is_left_of_the_budget() { let copy = |w: &super::envelope::WarpedLook| super::envelope::WarpedLook { slot: w.slot, look: w.look.clone(), left_out: None }; let page = Some(Rect::new(0.0, 60.0, 60.0, 100.0)); let settle = |w: &super::envelope::WarpedLook, spent| { - let warped = super::envelope::WarpedType { looks: vec![copy(w)], envelopes: vec![], checks: 1, spent, page }; + let warped = super::envelope::WarpedType { looks: vec![copy(w)], envelopes: vec![], checks: 1, spent, page, alone: None }; warped.settle(&mut doc.clone(), Some, &Default::default(), &mut vec![]) }; let spent = || super::envelope::Spent { any: MAX_DIFFERENCE / 2.0, solid: MAX_SOLID_DIFFERENCE / 2.0 }; diff --git a/crates/eps/src/import/ate.rs b/crates/eps/src/import/ate.rs index 194c0ff1e2..8d01b141d0 100644 --- a/crates/eps/src/import/ate.rs +++ b/crates/eps/src/import/ate.rs @@ -21,7 +21,7 @@ //! side; the canvas's centre, 8191.5, is the centre of the file's `%AI3_TemplateBox`. A story without //! a layout has its point type's anchor at its frame's point. See [`Story::place`]. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, HashMap}; use kurbo::{BezPath, CubicBez, ParamCurve, ParamCurveArclen}; use vectorcraft_color::{Color, Paint}; @@ -244,6 +244,10 @@ fn read(bytes: &[u8]) -> Option { const MAX_SHEETS: usize = 4096; const MAX_SHEETS_BASED_ON: usize = 16; +/// Most runs of manual kerning read of one story; the characters past them keep the automatic +/// kerning. +const MAX_KERN_RUNS: usize = 1 << 16; + /// Most frames read of one story, and most path segments of a frame. pub(crate) const MAX_FRAMES: usize = 4096; pub(crate) const MAX_SEGMENTS: usize = 1 << 16; @@ -428,6 +432,10 @@ pub(super) struct Story { paras: Vec<(usize, Para)>, /// `(characters, style)` in order. runs: Vec<(usize, Style)>, + /// `(characters, manual kerning)` in order: thousandths of an em after each of those characters + /// (key 8 of the story's text, a run's value its key 0), `None` where the automatic kerning + /// applies. Empty when the story has none. + kerns: Vec<(usize, Option)>, /// Type on a path: the spacing its first frame's layout implies ([`path_spacing`]). path_spacing: f64, /// Vertical type (Type › Type Orientation › Vertical): its lines are columns, from right to @@ -451,7 +459,8 @@ fn spend_tabs(tabs: &mut Vec, budget: &mut usize) -> bool { #[derive(Clone, Debug)] struct Style { - font: Option, + /// The font its record names, as the fonts the app has set it ([`DocFont::font`]). + font: Option, size: f64, /// `None`: auto. leading: Option, @@ -461,6 +470,11 @@ struct Style { v_scale: f64, fill: Option, stroke: Option, + /// The pattern that paints the fill or the stroke in place of its colour: the one the art + /// style named by key 5 of its paint gives ([`Texts::with_patterns`]), placed in the document. + /// `None` for any other paint, which keeps its colour. + fill_pattern: Option, + stroke_pattern: Option, stroke_width: f64, /// Key 61, the stroke's cap: 0 butt, 1 round, 2 projecting (square). stroke_cap: LineCap, @@ -477,10 +491,44 @@ struct Style { standard_vertical_roman: bool, } +/// The longest font version string read from a font record: name ID 5 strings are short (`Version +/// 7.200`, or with the tools that built the font, some 80 characters). +const MAX_FONT_VERSION: usize = 256; + +/// The version a font record's key 5 gives `v`, as the reader takes it: `None` when it is empty or +/// longer than [`MAX_FONT_VERSION`] bytes. The `.ai` save checks a record it writes against this. +pub(crate) fn record_version(v: &str) -> Option<&str> { + (!v.is_empty() && v.len() <= MAX_FONT_VERSION).then_some(v) +} + +/// A font as type is set in it: family, style and the version it names +/// ([`super::text::document_font`]). +type Font = (String, String, Option); + +/// A font of a text document's font list, as its record (a `CoolTypeFont`) names it. +#[derive(Debug, Default)] +struct DocFont { + /// Key 0: the PostScript name. + name: String, + /// Key 5, when the record keeps it: the font's version string (name ID 5), which tells installed + /// copies of one font apart. + version: Option, + /// [`Self::font`]'s answer, found once for every run that names the record. + font: std::sync::OnceLock, +} + +impl DocFont { + /// The font type set in this record's font takes: the installed copy it names + /// ([`super::text::document_font`]). + fn font(&self) -> &Font { + self.font.get_or_init(|| super::text::document_font(&self.name, self.version.as_deref())) + } +} + /// The text document of an editing copy. pub(super) struct Texts { stories: Vec, - fonts: Vec, + fonts: Vec, /// The character and paragraph styles a story starts from. defaults: Val, para_defaults: Val, @@ -491,9 +539,23 @@ pub(super) struct Texts { /// attributes (key 5) and the paragraph style it is based on (key 6, an index into these). para_sheets: Vec, frames: Vec, + /// The patterns that paint characters, by the name of the art style that gives each + /// ([`Self::with_patterns`]). + patterns: HashMap, } impl Texts { + /// The text document with its characters painted by `patterns`: the patterns of the editing + /// data's art styles that paint with one, each placed in the document, by the style's name. + /// A run's fill or stroke (key 53 or 54) is a paint whose key 0 is a colour and whose key 5 + /// names the art style that paints it. In users' files (used locally, never committed), such a + /// style is one paint: a colour, which key 0 already has, or a pattern, whose key 0 is black + /// (`/0 0 /1 [ 1 0 ]`). The pattern's matrix is in art space, as a path's pattern fill has it: + /// the files' own pages tile the type with the matrix a path's fill would get there. + pub(super) fn with_patterns(self, patterns: HashMap) -> Texts { + Texts { patterns, ..self } + } + /// The text document in the editing copy `data`, if it has one that can be read. pub(super) fn read(data: &[u8]) -> Option { fn find(h: &[u8], n: &[u8], from: usize) -> Option { @@ -525,7 +587,15 @@ impl Texts { .get("0")? .list() .iter() - .map(|f| f.get("0").and_then(|f| f.get("0")).and_then(|f| f.get("0")).and_then(Val::str).unwrap_or_default().to_string()) + .map(|f| { + let record = f.get("0").and_then(|f| f.get("0")); + let text = |k: &str| record.and_then(|r| r.get(k)).and_then(Val::str); + DocFont { + name: text("0").unwrap_or_default().to_string(), + version: text("5").and_then(record_version).map(str::to_string), + font: std::sync::OnceLock::new(), + } + }) .collect(); let main = doc.get("1")?; let sheets = |key: &str| -> Vec { @@ -540,6 +610,7 @@ impl Texts { char_sheets: sheets("5"), para_sheets: sheets("6"), frames: doc.get("0")?.get("8")?.get("0")?.list().to_vec(), + patterns: HashMap::new(), }) } @@ -655,12 +726,13 @@ impl Texts { if runs.is_empty() { runs.push((text.chars().count(), self.style(None))); } + let kerns = manual_kerning(s.get("0")?.get("8")); let mut budget = MAX_STORY_TABS; let mut tabs_left_out = false; for (_, p) in &mut paras { tabs_left_out |= p.tabs_truncated | spend_tabs(&mut p.tabs, &mut budget); } - Some(Story { text, anchor, lines, frames, paras, runs, path_spacing, vertical, tabs_left_out: tabs_left_out.into() }) + Some(Story { text, anchor, lines, frames, paras, runs, kerns, path_spacing, vertical, tabs_left_out: tabs_left_out.into() }) } /// A paragraph's attributes (`run`: its attributes, key 5, and the paragraph style it is based @@ -745,10 +817,12 @@ impl Texts { let pick = |k: &str| chain.iter().find_map(|s| s.get(k)).or_else(|| self.defaults.get(k)); let num = |k: &str| pick(k).and_then(Val::num); let on = |k: &str| !matches!(pick(k), Some(Val::Bool(false))); - let font = num("0").and_then(|i| self.fonts.get(i as usize)).filter(|f| !f.is_empty()).cloned(); + let font = num("0").and_then(|i| self.fonts.get(i as usize)).filter(|f| !f.name.is_empty()); let size = num("1").filter(|v| *v > 0.0 && *v < 1e5).unwrap_or(12.0); + // Key 5 of a paint names the art style that paints it ([`Self::with_patterns`]). + let pattern = |k: &str| pick(k).and_then(|p| p.get("5")).and_then(Val::str).and_then(|name| self.patterns.get(name)).cloned(); Style { - font, + font: font.map(|f| f.font().clone()), size, leading: if on("4") { None } else { num("5").filter(|v| *v > 0.0 && *v < 1e5) }, tracking: num("8").filter(|v| v.abs() < 1e5).unwrap_or(0.0), @@ -757,6 +831,8 @@ impl Texts { v_scale: num("7").filter(|v| *v > 0.0 && *v < 100.0).unwrap_or(1.0), fill: if on("56") { Some(pick("53").and_then(paint).unwrap_or(Color::BLACK)) } else { None }, stroke: if matches!(pick("57"), Some(Val::Bool(true))) { pick("54").and_then(paint) } else { None }, + fill_pattern: pattern("53"), + stroke_pattern: pattern("54"), stroke_width: num("63").filter(|v| *v >= 0.0 && *v < 1e4).unwrap_or(1.0), // Numbered as PostScript's `setlinecap` and `setlinejoin` operators number them // (PostScript Language Reference, 3rd ed.): in users' files the page strokes type with @@ -1109,23 +1185,24 @@ impl Story { // The text document measures in the art's units too: the document's scale carries its // sizes and spacings onto the page (a Large Canvas copy is written at 1:10; #2031). let scale = scale * art_scale(to_doc); + // Patterns stay where the document has them, wherever the type's text space is (`xf`'s + // determinant is 1, so it can be inverted; a pattern that still doesn't map to finite + // numbers keeps its colour, see `char_style`). + let to_text = xf.inverse(); let chars: Vec = text.chars().collect(); let mut runs = vec![]; + let mut kerns = Kerns::new(&self.kerns); let mut from = 0usize; for (n, st) in &self.runs { let to = from.saturating_add(*n).min(chars.len()); - let piece: String = chars.get(from..to).unwrap_or_default().iter().collect(); + kerns.split(&chars, from, to, &char_style(st, scale, to_text), &mut runs); from = to; - if piece.is_empty() { - continue; - } - runs.push(TextRun::new(piece, char_style(st, scale))); } if from < chars.len() { let last = self.runs.last().map(|r| &r.1)?; - runs.push(TextRun::new(chars.get(from..).unwrap_or_default().iter().collect::(), char_style(last, scale))); + kerns.split(&chars, from, chars.len(), &char_style(last, scale, to_text), &mut runs); } - let first = self.runs.first().map(|r| char_style(&r.1, scale))?; + let first = self.runs.first().map(|r| char_style(&r.1, scale, to_text))?; let mut t = TextObject::point(Point::ZERO, "", first); if !runs.is_empty() { t.runs = runs; @@ -1259,6 +1336,64 @@ impl Story { } } +/// The manual kerning of a story (`list`: key 8 of its text): each run's characters and value +/// (thousandths of an em), `None` for a run without one (the automatic kerning) or with a value +/// that can't be read. Neighbouring runs of one value are one run. Empty without the key, and past +/// [`MAX_KERN_RUNS`] runs the characters keep the automatic kerning. +fn manual_kerning(list: Option<&Val>) -> Vec<(usize, Option)> { + let mut kerns: Vec<(usize, Option)> = vec![]; + for run in list.and_then(|k| k.get("0")).map(Val::list).unwrap_or_default().iter().take(MAX_KERN_RUNS) { + let Some(n) = run.get("1").and_then(Val::num).filter(|n| *n >= 0.0 && n.fract() == 0.0) else { break }; + let value = run.get("0").and_then(|v| v.get("0")).and_then(Val::num).filter(|v| v.abs() < 1e5); + match kerns.last_mut() { + Some((count, last)) if *last == value => *count = count.saturating_add(n as usize), + _ => kerns.push((n as usize, value)), + } + } + if kerns.iter().all(|(_, v)| v.is_none()) { + kerns.clear(); + } + kerns +} + +/// A walk along a story's manual kerning runs ([`Story::kerns`]), as its style runs are made into +/// text runs. +struct Kerns<'a> { + runs: &'a [(usize, Option)], + /// The run at the walk and the character it starts at. + at: usize, + start: usize, +} + +impl<'a> Kerns<'a> { + fn new(runs: &'a [(usize, Option)]) -> Self { + Self { runs, at: 0, start: 0 } + } + + /// Push the characters `from..to` of `chars` (`from` no earlier than any before) onto `out`, + /// in style `style`, as a text run for each manual kerning they have. + fn split(&mut self, chars: &[char], from: usize, to: usize, style: &CharStyle, out: &mut Vec) { + let mut at = from; + while at < to { + while let Some((n, _)) = self.runs.get(self.at) + && self.start.saturating_add(*n) <= at + { + self.start = self.start.saturating_add(*n); + self.at += 1; + } + let (end, kerning) = match self.runs.get(self.at) { + Some((n, kerning)) => (self.start.saturating_add(*n).min(to), *kerning), + None => (to, None), + }; + let piece: String = chars.get(at..end).unwrap_or_default().iter().collect(); + if !piece.is_empty() { + out.push(TextRun::new(piece, CharStyle { kerning, ..style.clone() })); + } + at = end; + } + } +} + /// The paragraph style of paragraph attributes `p`, its lengths (indents, spacing, the /// hyphenation zone) scaled by `scale`, as sizes are. fn para_style(p: &Para, scale: f64) -> ParaStyle { @@ -1294,17 +1429,27 @@ fn para_style(p: &Para, scale: f64) -> ParaStyle { } } -/// The character style of character attributes `s`: its font from the fonts the app has, its -/// lengths (size, leading, baseline shift, stroke width) scaled by `scale`. -fn char_style(s: &Style, scale: f64) -> CharStyle { - let (family, style) = s.font.as_deref().map_or_else(|| (CharStyle::default().font_family, "Regular".to_string()), crate::family_style); - let family = vectorcraft_text::FontDb::global().find_family(&family).unwrap_or(family); +/// The character style of character attributes `s`: its font from the fonts the app has (the +/// installed copy its font record names, [`DocFont::font`]), its lengths (size, leading, baseline +/// shift, stroke width) scaled by `scale`, and its patterns placed in the type's text space by +/// `to_text` (the document → its text space), where they stay as the document has them. +fn char_style(s: &Style, scale: f64, to_text: Affine) -> CharStyle { + let (family, style, version) = s.font.clone().unwrap_or_else(|| (CharStyle::default().font_family, "Regular".to_string(), None)); + // A fill or stroke that is on takes its pattern in place of its colour. + let paint = |color: Option, pattern: &Option| match (color, pattern) { + // A pattern that can't be placed (the type's text space out of range) keeps the colour. + (Some(_), Some(Paint::Pattern { pattern, xf })) if (to_text * *xf).is_finite() => { + Paint::Pattern { pattern: pattern.clone(), xf: to_text * *xf } + } + (color, _) => color.map_or(Paint::None, Paint::solid), + }; // Type without a stroke keeps the stroke's defaults, as its weight is 0. let (stroke_cap, stroke_join, stroke_miter_limit) = if s.stroke.is_some() { (s.stroke_cap, s.stroke_join, s.stroke_miter_limit) } else { (LineCap::Butt, LineJoin::Miter, 10.0) }; CharStyle { font_family: family, font_style: style, + font_version: version, size: s.size * scale, // Auto leading stays auto: the layout gives each line the paragraph's share of the largest // type on it, as the file's own layout does ("The largest leading value in a line of type @@ -1314,8 +1459,8 @@ fn char_style(s: &Style, scale: f64) -> CharStyle { baseline_shift: s.baseline_shift * scale, h_scale: s.h_scale * 100.0, v_scale: s.v_scale * 100.0, - fill: s.fill.map_or(Paint::None, Paint::solid), - stroke: s.stroke.map_or(Paint::None, Paint::solid), + fill: paint(s.fill, &s.fill_pattern), + stroke: paint(s.stroke, &s.stroke_pattern), stroke_width: if s.stroke.is_some() { s.stroke_width * scale } else { 0.0 }, stroke_cap, stroke_join, @@ -1350,6 +1495,7 @@ mod tests { char_sheets: vec![], para_sheets: vec![], frames: vec![], + patterns: HashMap::new(), }; let justify = |own: &[u8]| para_style(&texts.para(Some(&read(&[b"/5 << ", own, b" >>"].concat()).unwrap())), 1.0).justify; // Right to left from the document's defaults, or the paragraph's own. @@ -1373,6 +1519,7 @@ mod tests { char_sheets: vec![], para_sheets: vec![], frames: vec![], + patterns: HashMap::new(), }; let auto = |own: &[u8]| para_style(&texts.para(Some(&read(&[b"/5 << ", own, b" >>"].concat()).unwrap())), 1.0).justification.auto_leading; assert_eq!(auto(b""), JustificationOptions::default().auto_leading); @@ -1395,6 +1542,7 @@ mod tests { char_sheets: vec![], para_sheets: vec![], frames: vec![], + patterns: HashMap::new(), }; let options = |own: &[u8], scale: f64| para_style(&texts.para(Some(&read(&[b"/5 << ", own, b" >>"].concat()).unwrap())), scale).hyphenation; let want = HyphenationOptions { words_longer_than: 6, after_first: 2, before_last: 2, hyphen_limit: 0, zone: 36.0, capitalized: true }; @@ -1412,6 +1560,7 @@ mod tests { char_sheets: vec![], para_sheets: vec![], frames: vec![], + patterns: HashMap::new(), }; let own = |own: &[u8]| para_style(&bare.para(Some(&read(&[b"/5 << ", own, b" >>"].concat()).unwrap())), 1.0).hyphenation; assert_eq!(own(b""), d); @@ -1431,6 +1580,7 @@ mod tests { char_sheets: vec![], para_sheets: vec![], frames: vec![], + patterns: HashMap::new(), }; let tabs = |own: &[u8], scale: f64| { para_style(&texts.para(Some(&read(&[b"/5 << ", own, b" >>"].concat()).unwrap())), scale) @@ -1497,6 +1647,7 @@ mod tests { char_sheets: vec![], para_sheets: vec![], frames: vec![], + patterns: HashMap::new(), } .para(None); let mut s = story(" 80 mm ", &[0.0], ¶); @@ -1544,6 +1695,7 @@ mod tests { char_sheets: vec![], para_sheets: vec![], frames: cases.iter().map(|c| frame(c)).collect(), + patterns: HashMap::new(), }; let vertical: Vec = (0..cases.len() + 1).map(|i| texts.frame_vertical(i)).collect(); assert_eq!(vertical, [true, false, false, false, false, false, false, false, false, false, false]); @@ -1561,6 +1713,7 @@ mod tests { char_sheets: vec![read(b"/0 ([Normal Character Style]) /6 << >>").unwrap(), read(b"/0 (Block) /6 << /35 3 >>").unwrap()], para_sheets: vec![], frames: vec![], + patterns: HashMap::new(), }; let tcy = |run: &[u8]| texts.style(Some(&read(run).unwrap())).tate_chu_yoko; assert!(tcy(b"/6 << /35 3 >>"), "the run's own"); @@ -1584,6 +1737,7 @@ mod tests { char_sheets: vec![read(b"/0 ([Normal Character Style]) /6 << >>").unwrap(), read(b"/0 (Rotated) /6 << /35 2 >>").unwrap()], para_sheets: vec![], frames: vec![], + patterns: HashMap::new(), }; let roman = |defaults: &[u8], run: &[u8]| texts(defaults).style(Some(&read(run).unwrap())).standard_vertical_roman; assert!(roman(b"/35 1", b"/6 << >>"), "the document's defaults"); @@ -1614,9 +1768,10 @@ mod tests { char_sheets: vec![read(b"/0 ([Normal Character Style]) /6 << >>").unwrap(), read(b"/0 (Rounded) /6 << /61 1 /62 1 >>").unwrap()], para_sheets: vec![], frames: vec![], + patterns: HashMap::new(), }; let stroke = |run: &[u8]| { - let s = char_style(&texts.style(Some(&read(run).unwrap())), 1.0); + let s = char_style(&texts.style(Some(&read(run).unwrap())), 1.0, Affine::IDENTITY); (s.stroke_cap, s.stroke_join, s.stroke_miter_limit) }; assert_eq!(stroke(b"/6 << /61 2 /62 2 /64 2.5 >>"), (LineCap::Square, LineJoin::Bevel, 2.5), "the run's own"); @@ -1638,6 +1793,160 @@ mod tests { assert_eq!(stroke(b"/5 1 /6 << /57 false >>"), (LineCap::Butt, LineJoin::Miter, 10.0), "no stroke"); } + /// The pattern "Dots", its tile's corner at `at`. + fn dots_at(at: (f64, f64)) -> Paint { + Paint::Pattern { pattern: "Dots".into(), xf: Affine::translate(at) } + } + + /// Texts whose characters may name the art style "Anon 1", which paints with "Dots" at (10, 20) + /// in the document, and "Solid", which isn't a pattern. + fn patterned_texts() -> Texts { + let patterns = HashMap::from([("Anon 1".to_string(), dots_at((10.0, 20.0))), ("Solid".to_string(), Paint::solid(Color::WHITE))]); + Texts { + stories: vec![], + fonts: vec![], + defaults: Val::Dict(BTreeMap::new()), + para_defaults: Val::Dict(BTreeMap::new()), + char_sheets: vec![], + para_sheets: vec![], + frames: vec![], + patterns: HashMap::new(), + } + .with_patterns(patterns) + } + + /// Key 5 of a run's fill or stroke names the art style that paints it: one that paints with a + /// pattern gives the run that pattern in place of the colour of key 0 (black), placed in the + /// type's text space where the document has it. A fill or stroke that is off stays off, and a + /// key 5 that isn't the name of such a style, or isn't a name at all, keeps the colour. + #[test] + fn a_run_painted_by_a_patterns_art_style_takes_the_pattern() { + // GUARDS: type a pattern paints came in black, the colour key 0 keeps for it. + let texts = patterned_texts(); + let black_paint = Paint::solid(Color::gray(1.0)); + let to_text = Affine::translate((-4.0, -5.0)); + let paints = |run: &str| { + let s = char_style(&texts.style(Some(&read(run.as_bytes()).unwrap())), 1.0, to_text); + (s.fill, s.stroke) + }; + let black = |style: &str| format!("<< /99 /CAITextPaint /0 << /0 0 /1 [ 1.0 0.0 ] >> {style} >>"); + let fill = |style: &str| paints(&format!("/6 << /53 {} >>", black(style))); + assert_eq!(fill("/5 (Anon 1)"), (dots_at((6.0, 15.0)), Paint::None)); + let stroke = paints(&format!("/6 << /53 {} /57 true /54 {} >>", black(""), black("/5 (Anon 1)"))); + assert_eq!(stroke, (black_paint.clone(), dots_at((6.0, 15.0)))); + // Off. + assert_eq!(paints(&format!("/6 << /56 false /53 {} >>", black("/5 (Anon 1)"))), (Paint::None, Paint::None)); + assert_eq!(paints(&format!("/6 << /57 false /54 {} >>", black("/5 (Anon 1)"))).1, Paint::None); + // A stroke whose colour can't be read paints nothing, pattern or not, as before. + assert_eq!(paints("/6 << /57 true /54 << /0 << /0 9 /1 [ 1.0 ] >> /5 (Anon 1) >> >>").1, Paint::None); + for other in ["", "/5 (Anon 2)", "/5 (Solid)", "/5 ()", "/5 /Anon", "/5 1", "/5 [ (Anon 1) ]", "/5 << /0 (Anon 1) >>", "/5 true"] { + assert_eq!(fill(other), (black_paint.clone(), Paint::None), "{other}"); + } + // A text space the pattern can't be placed in keeps the colour. + let run = read(format!("/6 << /53 {} >>", black("/5 (Anon 1)")).as_bytes()).unwrap(); + for to_text in [Affine::new([1e308, 0.0, 0.0, 1e308, 0.0, 0.0]), Affine::new([f64::NAN, 0.0, 0.0, 1.0, 0.0, 0.0])] { + assert_eq!(char_style(&texts.style(Some(&run)), 1.0, to_text).fill, black_paint.clone(), "{to_text:?}"); + } + } + + /// A run's pattern stays where the document has it whatever the type's own text space: turned + /// and moved point type, and area type, whose text space is the document's. + #[test] + fn a_runs_pattern_stays_where_the_document_has_it() { + let to_doc = Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 100.0]); + for frame in [ + FrameKind::Point([0.0, 1.0, -1.0, 0.0, 30.0, 40.0]), + FrameKind::Point([2.0, 0.0, 0.0, 2.0, -7.0, 3.0]), + FrameKind::Area(area_segments(), AreaFrame::default()), + ] { + let mut st = story("type", &[0.0], &Para::default()); + st.frames = vec![frame.clone()]; + st.runs[0].1.fill_pattern = Some(dots_at((10.0, 20.0))); + st.runs[0].1.stroke = Some(Color::BLACK); + st.runs[0].1.stroke_pattern = Some(dots_at((-3.0, 8.0))); + let node = st.node(NodeId(1), 0, (0.0, 0.0), to_doc).unwrap(); + let NodeKind::Text(t) = node.kind else { panic!("not type") }; + for (paint, at) in [(&t.runs[0].style.fill, Point::new(10.0, 20.0)), (&t.runs[0].style.stroke, Point::new(-3.0, 8.0))] { + let Paint::Pattern { pattern, xf } = paint else { panic!("{paint:?}") }; + assert_eq!(pattern, "Dots"); + let corner = t.xf * *xf * Point::ZERO; + assert!((corner - at).hypot() < 1e-9, "{frame:?}: {corner:?}"); + } + } + } + + /// Key 8 of a story's text is its manual kerning: runs of characters (key 1), each with its + /// value (key 0 of key 0, thousandths of an em) or empty where the automatic kerning applies. + /// Each character with a value takes it as the space after it, across the story's style runs; + /// a value that can't be read keeps the automatic kerning, and a run whose length can't be read + /// ends the reading there. In users' files a heading's first pair is kerned by -140 and the + /// letters of a line by 20 to 220, and the page draws those gaps that much tighter or wider. + #[test] + fn a_story_keeps_its_manual_kerning() { + // "Wave" at 20 points and a Horizontal Scale of 50%, then " tea" at 10 points. + let styles: &[u8] = b"/6 << /0 [ << /0 << /0 << /6 << /1 20.0 /6 0.5 >> >> >> /1 4 >> << /0 << /0 << /6 << /1 10.0 >> >> >> /1 5 >> ] >>"; + let texts = |kerns: &[u8]| Texts { + stories: vec![read(&[b"/0 << /0 (Wave tea\r) ", styles, b" ", kerns, b" >> /1 << /0 [ << /0 0 >> ] >>"].concat()).unwrap()], + fonts: vec![], + defaults: Val::Dict(BTreeMap::new()), + para_defaults: Val::Dict(BTreeMap::new()), + char_sheets: vec![], + para_sheets: vec![], + frames: vec![read(b"/0 << /0 [ 0 0 ] /2 << /0 0 >> >>").unwrap()], + patterns: HashMap::new(), + }; + let text = |kerns: &[u8]| -> TextObject { + let node = texts(kerns).story(0).unwrap().node(NodeId(1), 0, (0.0, 0.0), Affine::IDENTITY).unwrap(); + let NodeKind::Text(t) = node.kind else { panic!("type") }; + *t + }; + let runs = |kerns: &[u8]| -> Vec<(String, f64, Option)> { + text(kerns).runs.iter().map(|r| (r.text.clone(), r.style.size, r.style.kerning)).collect() + }; + let run = |text: &str, size: f64, kerning: Option| (text.to_string(), size, kerning); + // "W" -140, "av" none, "e t" 80 across the style runs, "e" a value that can't be read, "a" none. + let kerned: &[u8] = b"/8 << /0 [ << /0 << /0 -140 >> /1 1 >> << /0 << >> /1 2 >> << /0 << /0 80 >> /1 3 >> \ + << /0 << /0 (x) >> /1 1 >> << /0 << >> /1 2 >> ] >>"; + assert_eq!( + runs(kerned), + [run("W", 20.0, Some(-140.0)), run("av", 20.0, None), run("e", 20.0, Some(80.0)), run(" t", 10.0, Some(80.0)), run("ea", 10.0, None)] + ); + // Without the key, or with no value in it, the style runs stay as they are. + let plain = [run("Wave", 20.0, None), run(" tea", 10.0, None)]; + assert_eq!(runs(b""), plain); + assert_eq!(runs(b"/8 << /0 [ << /0 << >> /1 9 >> ] >>"), plain); + // Values out of range keep the automatic kerning, and a length that can't be read ends the runs. + let out_of_range: &[u8] = b"/8 << /0 [ << /0 << /0 1e9 >> /1 1 >> << /0 << /0 NaN >> /1 1 >> << /0 << /0 60 >> /1 1 >> ] >>"; + assert_eq!(runs(out_of_range)[..2], [run("Wa", 20.0, None), run("v", 20.0, Some(60.0))]); + for bad in [b"-1".as_slice(), b"1.5", b"(1)", b"NaN"] { + let k = [b"/8 << /0 [ << /0 << /0 60 >> /1 1 >> << /0 << /0 60 >> /1 ".as_slice(), bad, b" >> << /0 << /0 60 >> /1 2 >> ] >>"].concat(); + assert_eq!(runs(&k), [run("W", 20.0, Some(60.0)), run("ave", 20.0, None), run(" tea", 10.0, None)], "{}", String::from_utf8_lossy(bad)); + } + // Laid out, the space after "W" is 140 thousandths of the em tighter than with a value of + // 0, of the em as the run's Horizontal Scale (50%) draws it. + let db = vectorcraft_text::FontDb::global(); + let gap = |t: &TextObject| { + let laid = vectorcraft_text::layout(db, t); + laid.glyphs[1].origin.x - laid.glyphs[0].origin.x + }; + let (with, zero) = (gap(&text(kerned)), gap(&text(b"/8 << /0 [ << /0 << /0 0 >> /1 1 >> ] >>"))); + assert!((zero - with - 0.14 * 20.0 * 0.5).abs() < 1e-6, "{with} {zero}"); + } + + /// Past [`MAX_KERN_RUNS`] runs of manual kerning the characters keep the automatic kerning, so a + /// story makes no more text runs of its kerning than that. + #[test] + fn manual_kerning_reads_at_most_its_limit_of_runs() { + let dict = |entries: Vec<(&str, Val)>| Val::Dict(entries.into_iter().map(|(k, v)| (k.to_string(), v)).collect()); + // One character each, the values alternating, so no two neighbouring runs are one. + let run = |i: usize| dict(vec![("0", dict(vec![("0", Val::Num(if i.is_multiple_of(2) { 10.0 } else { 20.0 }))])), ("1", Val::Num(1.0))]); + let list = dict(vec![("0", Val::List((0..MAX_KERN_RUNS + 2).map(run).collect()))]); + let kerns = manual_kerning(Some(&list)); + assert_eq!(kerns.len(), MAX_KERN_RUNS); + assert_eq!(kerns.iter().map(|(n, _)| n).sum::(), MAX_KERN_RUNS); + assert_eq!(kerns.last(), Some(&(1, Some(20.0)))); + } + /// A right-to-left paragraph is laid out right to left even when it has no right-to-left /// letters (a dimension's label " 120.5 mm " reads "mm 120.5"); a left-to-right one, or one /// that doesn't say, goes by its letters. @@ -1651,6 +1960,7 @@ mod tests { char_sheets: vec![], para_sheets: vec![], frames: vec![], + patterns: HashMap::new(), }; let direction = |own: &[u8]| para_style(&texts.para(Some(&read(&[b"/5 << ", own, b" >>"].concat()).unwrap())), 1.0).direction; assert_eq!(direction(b"/0 2"), Some(ParaDirection::RightToLeft), "from the document's defaults"); @@ -1698,6 +2008,7 @@ mod tests { char_sheets: vec![], para_sheets: vec![], frames: vec![read(doc.as_bytes()).unwrap()], + patterns: HashMap::new(), }; texts.frame(0) } @@ -1904,6 +2215,8 @@ mod tests { v_scale: 1.0, fill: Some(Color::BLACK), stroke: None, + fill_pattern: None, + stroke_pattern: None, stroke_width: 1.0, stroke_cap: LineCap::Butt, stroke_join: LineJoin::Miter, @@ -1913,6 +2226,7 @@ mod tests { standard_vertical_roman: false, }, )], + kerns: vec![], path_spacing: 0.0, vertical: false, tabs_left_out: false.into(), @@ -2352,6 +2666,7 @@ mod tests { char_sheets: vec![], para_sheets: vec![], frames: vec![read(doc.as_bytes()).unwrap()], + patterns: HashMap::new(), }; texts.frame(0).unwrap() } diff --git a/crates/eps/src/import/cid.rs b/crates/eps/src/import/cid.rs index e2ad169f79..4c00486de9 100644 --- a/crates/eps/src/import/cid.rs +++ b/crates/eps/src/import/cid.rs @@ -210,54 +210,6 @@ fn number(data: &[u8], at: usize, n: usize) -> Option { (n <= 8).then(|| bytes.iter().fold(0u64, |v, b| v << 8 | u64::from(*b))) } -/// How a predefined Unicode CMap's codes encode their characters. -#[derive(Clone, Copy, PartialEq, Debug)] -pub(super) enum Unicode { - /// Two bytes a character (`UCS2`) or a UTF-16 surrogate pair, the high byte first. - Utf16, - Utf8, - /// Four bytes, the high byte first. - Utf32, -} - -/// The encoding of predefined Unicode CMap `name` and whether it is vertical: one of Adobe's -/// public CMap resources whose name says its codes are Unicode: `Uni` and a character -/// collection, then `-UCS2`, `-UTF8`, `-UTF16` or `-UTF32` (and `-HW` for half-width forms), -/// then `-H` or `-V` (`UniJIS-UCS2-H`, `UniGB-UTF16-V`: -/// ). -pub(super) fn unicode_cmap(name: &str) -> Option<(Unicode, bool)> { - let (rest, dir) = name.rsplit_once('-')?; - let vertical = match dir { - "H" => false, - "V" => true, - _ => return None, - }; - let rest = rest.strip_suffix("-HW").unwrap_or(rest); - let (collection, form) = rest.rsplit_once('-')?; - if !(collection.len() > 3 && collection.starts_with("Uni") && !collection.contains('-')) { - return None; - } - let form = match form { - "UCS2" | "UTF16" => Unicode::Utf16, - "UTF8" => Unicode::Utf8, - "UTF32" => Unicode::Utf32, - _ => return None, - }; - Some((form, vertical)) -} - -/// The characters show string `s` encodes in Unicode form `form` (invalid codes left out). -pub(super) fn unicode_text(s: &[u8], form: Unicode) -> String { - match form { - Unicode::Utf16 => { - let units = s.as_chunks::<2>().0.iter().map(|b| u16::from_be_bytes(*b)); - char::decode_utf16(units).filter_map(Result::ok).collect() - } - Unicode::Utf8 => String::from_utf8_lossy(s).chars().filter(|c| *c != char::REPLACEMENT_CHARACTER).collect(), - Unicode::Utf32 => s.as_chunks::<4>().0.iter().filter_map(|b| char::from_u32(u32::from_be_bytes(*b))).collect(), - } -} - /// A predefined Identity CMap: two-byte codes, each the CID of its own value; vertical for /// `Identity-V`. pub(super) fn identity(name: &str, vertical: bool) -> Obj { @@ -417,8 +369,11 @@ impl Interp<'_> { return Ok(d.clone()); } let text = name.text().map(|t| t.to_string()).unwrap_or_default(); - match unicode_cmap(&text) { - Some((_, vertical)) => { + // A predefined CMap the file doesn't define, without its mappings: its codes are read by + // its name when type is set (see `text`). + let predefined = super::predefined_cmap::known(&text).then(|| super::predefined_cmap::vertical(&text)); + match predefined { + Some(vertical) => { let mut d = Dict::new(); d.insert(Key::name("CMapName"), Obj::name(&text)); d.insert(Key::name("CMapType"), Obj::Int(1)); diff --git a/crates/eps/src/import/graphics.rs b/crates/eps/src/import/graphics.rs index 46fd148db9..3ff736d1ff 100644 --- a/crates/eps/src/import/graphics.rs +++ b/crates/eps/src/import/graphics.rs @@ -24,6 +24,8 @@ mod state; mod strips; pub(crate) use paint::collapse; +#[cfg(test)] +pub(crate) use paint::tilings_compared; pub(crate) use state::{GState, Out, Space, process}; pub(crate) use strips::merge_strips; diff --git a/crates/eps/src/import/graphics/paint.rs b/crates/eps/src/import/graphics/paint.rs index fc2490fb41..156b6e421e 100644 --- a/crates/eps/src/import/graphics/paint.rs +++ b/crates/eps/src/import/graphics/paint.rs @@ -5,6 +5,19 @@ use super::{ PsError, REGISTRATION, Rc, Rect, Res, SHADING_SAMPLES, Shared, UNKNOWN_FUNCTIONS, UNKNOWN_SHADINGS, Vec2, clamp_between, ps_err, }; +#[cfg(test)] +thread_local! { + /// How many patterns the lookups of tiling patterns on this thread compared with the pattern + /// they looked for. + static TILINGS_COMPARED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// [`TILINGS_COMPARED`] of this thread. +#[cfg(test)] +pub(crate) fn tilings_compared() -> u64 { + TILINGS_COMPARED.get() +} + impl Interp<'_> { // ---------- colour ---------- @@ -212,7 +225,13 @@ impl Interp<'_> { let proc = get("PaintProc").ok_or(PsError::Ps("undefined", "PaintProc".into()))?; let key = proc.items().cloned().ok_or(PsError::Ps("typecheck", "PaintProc".into()))?; let hash = tiling_hash(&key, tile, under.as_ref()); - let made = self.out.tilings.get(&hash).and_then(|list| list.iter().find(|(p, t, u, _)| p.same(&key) && *t == tile && *u == under)); + let made = self.out.tilings.get(&hash).and_then(|list| { + list.iter().find(|(p, t, u, _)| { + #[cfg(test)] + TILINGS_COMPARED.set(TILINGS_COMPARED.get().saturating_add(1)); + p.same(&key) && *t == tile && *u == under + }) + }); if let Some((.., name)) = made { return Ok(Paint::Pattern { pattern: name.clone(), xf }); } diff --git a/crates/eps/src/import/interp.rs b/crates/eps/src/import/interp.rs index 992a8bbcea..0ea7017c11 100644 --- a/crates/eps/src/import/interp.rs +++ b/crates/eps/src/import/interp.rs @@ -92,6 +92,15 @@ pub(crate) struct Interp<'a> { pub cid_subrs: super::cid::CidSubrs, /// The font number `usefont` gave the CMap mappings that follow. pub cmap_font: i64, + /// The predefined CMaps type was set in so far, by name, with how their strings decode + /// (`None` when one can't be read; see `text`). + pub predefined_cmaps: Vec<(Rc, Option>)>, + /// The font a `kshow` procedure sees as current while type in a CIDFont only named is set in + /// a font of its own (see `text`). + pub kshow_font: Option, + /// The `cshow` procedure running over type in a CIDFont only named, with the font it sees as + /// current (see `text`). + pub cshow: Option, pub g: GState, pub saved: Vec, pub out: Out, @@ -232,6 +241,9 @@ impl<'a> Interp<'a> { cff: vec![], cid_subrs: vec![], cmap_font: 0, + predefined_cmaps: vec![], + kshow_font: None, + cshow: None, type42_counted: HashSet::new(), g, saved: vec![], diff --git a/crates/eps/src/import/native/build.rs b/crates/eps/src/import/native/build.rs index c86cdb9516..1b212194a1 100644 --- a/crates/eps/src/import/native/build.rs +++ b/crates/eps/src/import/native/build.rs @@ -1,5 +1,6 @@ use super::compare::{ - MAX_DIFFERENCE, MAX_PAGES_COMPARED, MAX_PIXELS_COMPARED, MAX_SOLID_DIFFERENCE, PageView, compare, comparison_samples, difference, pixels_compared, + MAX_DIFFERENCE, MAX_PAGES_COMPARED, MAX_PIXELS_COMPARED, MAX_SOLID_DIFFERENCE, PAST_THE_PAGE, PageView, compare, comparison_samples, difference, + pixels_compared, }; use super::plan::{made_only, make_slots, plan, readable_all}; use super::slots::{ @@ -191,6 +192,36 @@ fn left_out_of_comparisons(page: Page, mut restyled: Vec, placeholders: Ve restyled } +/// A single PDF page capped at the format's 14,400-unit limit, without user-space scaling. +/// The other dimension must still match; unrelated page-size mismatches remain errors. +fn capped_pdf_page(doc: &Document, visible: &Document, board: Rect, page: Rect, unit: f64) -> bool { + let capped = |side: f64, pdf: f64| (pdf - 14_400.0).abs() <= 0.5 && side > pdf + 0.5; + let matching = |side: f64, pdf: f64| (side - pdf).abs() <= 0.5 || capped(side, pdf); + unit == 1.0 + && doc.artboards.len() == 1 + && visible.artboards.len() == 1 + && (capped(board.width(), page.width()) || capped(board.height(), page.height())) + && matching(board.width(), page.width()) + && matching(board.height(), page.height()) +} +/// The PDF-covered area of a trusted oversized artboard; its full artboard stays in the document. +fn compared_page_rect( + doc: &Document, + visible: &Document, + board: Rect, + pdf: Rect, + trusted_page: Option, + unit: f64, + warnings: &mut Vec, +) -> Rect { + if matches!(trusted_page, Some(Page::Artboard)) && capped_pdf_page(doc, visible, board, pdf, unit) { + warnings.push("the editing data's artboard is larger than the PDF page: the full artboard comes from its editing data".into()); + Rect::new(board.x0, board.y0, board.x0 + pdf.width(), board.y0 + pdf.height()) + } else { + board + } +} + /// [`build`] from `structure`, the editing copy `data` already read. pub(super) fn build_from( structure: Structure, @@ -200,6 +231,24 @@ pub(super) fn build_from( outlined: bool, trust: bool, unit: f64, +) -> Result<(Document, Vec), String> { + build_weighing(structure, data, visible, page, outlined, trust, unit, &mut None) +} + +/// [`build_from`]. When the layers with their live envelopes don't draw as the page, and don't with +/// the drawn art of every live envelope put back either, `free` is set to the envelopes of type +/// (by their place among them, as read) that opened live and that the page doesn't hold against +/// them ([`held_back`]), whether or not the layers are then used, and however. +#[allow(clippy::too_many_arguments)] +pub(super) fn build_weighing( + structure: Structure, + data: &[u8], + visible: Option<&Document>, + page: Page, + outlined: bool, + trust: bool, + unit: f64, + free: &mut Option>, ) -> Result<(Document, Vec), String> { let Structure { mut doc, @@ -217,12 +266,13 @@ pub(super) fn build_from( placed_pages, envelopes_drawn, styles_read, + text_patterns, canvas_scale, xml_ids, bindings, bindings_skipped, warped_type, - warnings, + mut warnings, } = structure; let mut restyled = left_out_of_comparisons(page, restyled, placeholders); // Editing data in the units of the page's user space ([`in_units`]), or at its declared large @@ -270,6 +320,7 @@ pub(super) fn build_from( { (rect, cropped) = (art, true); } + rect = compared_page_rect(&doc, visible, rect, page_rect, trust.then_some(page), unit, &mut warnings); if !fits(&rect) { // Both sizes in points as the fields show them, and the editing data's page to the // file's as a scale (1:10 is a tenth of its size) when its sides are in proportion and @@ -374,7 +425,7 @@ pub(super) fn build_from( // The page's type that needs no text object of the layers: the layers' own legacy text, or // placed files that show it. let as_outlines = page_type_elsewhere(infos.is_empty(), infos.iter().all(|i| !i.shown), &mut shown, &mut hidden, &doc, &placed_elsewhere)?; - let texts = Texts::read(data); + let texts = Texts::read(data).map(|t| t.with_patterns(text_patterns)); // Each story is read once, however many text objects name it. let mut read: std::collections::BTreeMap>> = Default::default(); let stories: Vec>> = infos @@ -436,12 +487,14 @@ pub(super) fn build_from( let warped_type = warped_type.compared(frame.is_some(), &mut notes); let bound = [&bound_text, &bound_visible]; let typed = settle_warped_type(warped_type, &mut doc, &filled, &threaded_frames, bound, &mut restyled, &mut notes)?; + // Each live envelope of type's place among the envelopes of type, by its id. + let places: Vec<(NodeId, usize)> = typed.iter().map(|(place, id, _)| (*id, *place)).collect(); // The live envelopes and what takes the place of each again, when the layers with them don't // draw as the page, with the note that says so. let envelopes_drawn: Vec<(NodeId, Vec, &str)> = envelopes_drawn .into_iter() .map(|(id, art)| (id, vec![art], ai::ENVELOPE_DRAWN)) - .chain(typed.into_iter().map(|(id, nodes)| (id, nodes, ai::ENVELOPE_TYPE_DRAWN))) + .chain(typed.into_iter().map(|(_, id, nodes)| (id, nodes, ai::ENVELOPE_TYPE_DRAWN))) .collect(); if empty > 0 { notes.push(format!("{empty} {}", if frame.is_some() { TEXT_LEFT_OUT } else { TYPE_LEFT_OUT })); @@ -493,20 +546,21 @@ pub(super) fn build_from( notes.extend(unseen_note(unseen).into_iter().chain(note)); } other => match drawn_or_trusted(&frame, &mut view, &mut doc, &envelopes_drawn, ¬es, unseen, trust, why, reflow) { - Ok(more) => notes.extend(more), + Ok((more, held)) => { + *free = held.map(|held| free_places(&places, &held)); + notes.extend(more); + } // The objects that draw differently from the page come in as its art, from // the placement that draws closer to it. The layers don't draw as the page: - // envelopes of type keep their drawn art and their type, hidden. + // the envelopes of type it holds against them keep their drawn art and their + // type, hidden. Where no placement's differing objects can then come in as the + // page's art (an object that holds type isn't replaced), every envelope of type + // keeps its drawn art, and that is tried again. Err(why) => { - let typed = type_drawn(&mut doc, &envelopes_drawn); - let other = other.map(|(_, mut other, unseen)| { - type_drawn(&mut other, &envelopes_drawn); - (other, unseen) - }); - let placements = closer_first(&frame, &mut view, (doc, unseen), other, reflow); - let Some((kept, unseen, kept_notes)) = placements.into_iter().find_map(|(base, unseen)| { - keep_differing(&base, &frame, &mut view, &threaded_frames, &shown, reflow).map(|(kept, n)| (kept, unseen, n)) - }) else { + let other = other.map(|(_, other, unseen)| (other, unseen)); + let layers = Placements { doc: &doc, unseen, other: other.as_ref(), drawn: &envelopes_drawn, places: &places }; + let found = keep_differing_typed(&frame, &mut view, &layers, &threaded_frames, &shown, reflow, free); + let Some((kept, unseen, kept_notes, typed)) = found else { return Err(why); }; doc = kept; @@ -661,8 +715,9 @@ fn bound_slots( /// anchors. Before that, the envelopes of type open live where they draw as their drawn art, with /// the type of their text slots (made type, one text object for the slot, not threaded, bound to /// no text variable and no visibility variable, `bound`'s second set, and no wrap object); the -/// others keep their drawn art, with a note. Returns each live envelope of type's id with what -/// takes its place again (its hidden type, then its drawn art). +/// others keep their drawn art, with a note. Returns each live envelope of type's place among the +/// envelopes of type (in the order they were read) and id, with what takes its place again (its +/// hidden type, then its drawn art). fn settle_warped_type( mut warped: ai::WarpedType, doc: &mut Document, @@ -671,7 +726,7 @@ fn settle_warped_type( bound: [&BTreeSet; 2], restyled: &mut Vec, notes: &mut Vec, -) -> Result)>, String> { +) -> Result)>, String> { let [bound_text, bound_visible] = bound; let made = |slot| match filled.get(&slot).map(|f| f.text.as_slice()).filter(|_| !bound_text.contains(&slot)) { Some(&[one]) => Some(one), @@ -1120,15 +1175,15 @@ const MAX_DIFFERING: usize = 64; const MAX_PATCH_PAIRS: usize = 4_000_000; /// The layers as read and at the placed files' other placement (each with its count of text -/// objects the page doesn't draw), the one that draws closer to the page first. `reflow` as in -/// [`PageView::difference`]. -fn closer_first( +/// objects the page doesn't draw, and what goes with it), the one that draws closer to the page +/// first. `reflow` as in [`PageView::difference`]. +fn closer_first( frame: &Frame<'_>, view: &mut PageView, - doc: (Document, usize), - other: Option<(Document, usize)>, + doc: (Document, usize, T), + other: Option<(Document, usize, T)>, reflow: bool, -) -> Vec<(Document, usize)> { +) -> Vec<(Document, usize, T)> { match other { Some(other) if view.difference_on_every_page(&other.0, frame.rect, reflow).any < view.difference_on_every_page(&doc.0, frame.rect, reflow).any => @@ -1246,6 +1301,73 @@ fn keep_differing( Some((kept, note.into_iter().chain([format!("{DREW_DIFFERENTLY}: {}", layers.join(", "))]).collect())) } +/// The places (among the envelopes of type, as read) of the live envelopes of type in `places` +/// (each with its id) that `held` doesn't list. +fn free_places(places: &[(NodeId, usize)], held: &BTreeSet) -> Vec { + places.iter().filter(|(id, _)| !held.contains(id)).map(|(_, place)| *place).collect() +} + +/// The layers of [`keep_differing_typed`]: `doc`, `unseen` text objects of it taken out; the placed +/// files' other placement of it, when it has one, with how many of its text objects were; its live +/// envelopes, as [`drawn_or_trusted`] takes them; and the place of each live envelope of type +/// among the envelopes of type, by its id. +struct Placements<'a> { + doc: &'a Document, + unseen: usize, + other: Option<&'a (Document, usize)>, + drawn: &'a [(NodeId, Vec, &'a str)], + places: &'a [(NodeId, usize)], +} + +/// [`keep_differing`] of the placement of `layers` that draws closer to the page, the envelopes of +/// type the page holds against that placement ([`held_back`], each placement weighed on its own: the +/// other one draws placed files elsewhere, under or over the envelopes) having their drawn art and +/// hidden type back; and where none of the placements' differing objects can then come in as the +/// page's art, every envelope of type: the document, how many of its text objects were taken out, +/// its notes, and whether an envelope of type got its drawn art back. A placement that draws as the +/// page with only the envelopes the page holds put back is used as it is, as one with all the live +/// envelopes' drawn art put back would have been ([`drawn_or_trusted`]): nothing in it differs to +/// come in as the page's art. `free` is set to the places of those the page doesn't hold against +/// the layers as read. +#[allow(clippy::too_many_arguments)] +fn keep_differing_typed( + frame: &Frame<'_>, + view: &mut PageView, + layers: &Placements<'_>, + threaded_frames: &BTreeSet, + shown: &[Vec>], + reflow: bool, + free: &mut Option>, +) -> Option<(Document, usize, Vec, bool)> { + let held = held_back(frame, view, layers.doc, layers.drawn, reflow); + *free = Some(free_places(layers.places, &held)); + let held_other = layers.other.map(|(other, _)| held_back(frame, view, other, layers.drawn, reflow)); + let all: BTreeSet = layers.places.iter().map(|(id, _)| *id).collect(); + let fewer = held.len() < all.len() || held_other.as_ref().is_some_and(|h| h.len() < all.len()); + let mut tries = vec![]; + if fewer { + tries.push((held, held_other)); + } + tries.push((all.clone(), Some(all.clone()))); + tries.into_iter().find_map(|(held, held_other)| { + // Each placement with what it put back: whether an envelope of type, and whether only some. + let mut base = layers.doc.clone(); + let typed = (type_drawn(&mut base, layers.drawn, &held), held.len() < all.len()); + let other = layers.other.map(|(other, unseen)| { + let (mut other, held) = (other.clone(), held_other.as_ref().unwrap_or(&held)); + let typed = (type_drawn(&mut other, layers.drawn, held), held.len() < all.len()); + (other, *unseen, typed) + }); + let placements = closer_first(frame, view, (base, layers.unseen, typed), other, reflow); + placements.into_iter().find_map(|(base, unseen, (typed, some))| { + if some && let Ok(notes) = compare(frame, view, &base, reflow) { + return Some((base, unseen, notes, typed)); + } + keep_differing(&base, frame, view, threaded_frames, shown, reflow).map(|(kept, notes)| (kept, unseen, notes, typed)) + }) + }) +} + /// Copy page drawing IDs, including mask art outside the ordinary child tree. pub(super) fn reid_page_art(doc: &mut Document, source: &Node) -> Node { let mut copy = doc.reid(source); @@ -1306,9 +1428,9 @@ fn slot_content( /// The layers `doc` don't draw as the page (`why`), `unseen` text objects of them taken out: the /// notes to add when `doc` with each live envelope `drawn` lists replaced by the drawn art it took /// the place of (see [`ai::Structure::envelopes_drawn`]) draws as the page, `doc` then being that; -/// else, with `trust`, the notes for `doc` as it is but for its envelopes of type, which keep their -/// drawn art ([`type_drawn`]). An error, `why`, otherwise. The envelope note is added unless -/// `notes` has it. +/// else, with `trust`, the notes for `doc` as it is but for the envelopes of type the page holds +/// against it ([`held_back`]), which keep their drawn art ([`type_drawn`]), with those envelopes. +/// An error, `why`, otherwise. The envelope note is added unless `notes` has it. #[allow(clippy::too_many_arguments)] fn drawn_or_trusted( frame: &Frame<'_>, @@ -1320,7 +1442,7 @@ fn drawn_or_trusted( trust: bool, why: String, reflow: bool, -) -> Result, String> { +) -> Result<(Vec, Option>), String> { let unseen_note = |n: usize| (n > 0).then(|| format!("{n} {UNSEEN_TEXT}")); let mut put_back = doc.clone(); // Each envelope still there, in place of the art it took the place of. @@ -1347,26 +1469,143 @@ fn drawn_or_trusted( envelope.push(say.to_string()); } } - return Ok(envelope.into_iter().chain(unseen_note(unseen + more)).chain(note).collect()); + return Ok((envelope.into_iter().chain(unseen_note(unseen + more)).chain(note).collect(), None)); } } if trust { - let typed = type_drawn(doc, drawn).then(|| ai::ENVELOPE_TYPE_DRAWN.to_string()).filter(|n| !notes.contains(n)); + let held = held_back(frame, view, doc, drawn, reflow); + let typed = type_drawn(doc, drawn, &held).then(|| ai::ENVELOPE_TYPE_DRAWN.to_string()).filter(|n| !notes.contains(n)); let trusted = format!("{why}: they come from its editing data all the same"); - return Ok(typed.into_iter().chain(unseen_note(unseen)).chain([trusted]).collect()); + return Ok((typed.into_iter().chain(unseen_note(unseen)).chain([trusted]).collect(), Some(held))); } Err(why) } +/// The live envelopes of type in `drawn` (as [`drawn_or_trusted`] takes them) that the page holds +/// against the layers `doc`, which don't draw as it even with every live envelope's drawn art put +/// back: by their ids, those where the layers don't draw as the page. The envelope and its drawn art +/// are drawn together on a layer of their own, without the rest of the layers, on the page check's +/// drawing of each page they lie on: in the pixels they ink there, the layers with the envelope may +/// differ from the page in no more than the envelope's own check allows against its drawn art (at +/// all, and with all their neighbors, away from type: [`compare`]); and in the order they were +/// read, the envelopes that stay live may differ there in no more of each page together than half +/// of what the page check allows (a budget of the same size as the one their own checks share, kept +/// apart from it). Art that differs elsewhere on the page doesn't hold them. One the layers don't +/// draw where it is and as itself ([`drawn_in_place`]) is held, wherever it lies: drawn on its own, +/// it would be weighed elsewhere than it draws, or on pixels a clip or mask hides, and what holds it +/// can draw it onto a page from off it. Another envelope on no page stays live, as the page check +/// doesn't see it, unless the page holds all the art that prints ([`Frame::whole`]), where art past +/// it is compared too: there one reaching past the page is held. Past [`MAX_WEIGHED`] of them on +/// the pages, or where the page check can't weigh one, they are all held. +fn held_back(frame: &Frame<'_>, view: &mut PageView, doc: &Document, drawn: &[(NodeId, Vec, &str)], reflow: bool) -> BTreeSet { + let typed: Vec<(NodeId, &Node, &Node)> = drawn + .iter() + .filter(|(_, _, say)| *say == ai::ENVELOPE_TYPE_DRAWN) + .filter_map(|(id, art, _)| Some((*id, doc.node(*id)?, art.last()?))) + .collect(); + let all: BTreeSet = typed.iter().map(|(id, ..)| *id).collect(); + if all.is_empty() { + return all; + } + let pages = view.regions(frame.rect); + let past = |b: Rect| frame.whole && !frame.rect.inflate(PAST_THE_PAGE, PAST_THE_PAGE).contains_rect(b); + let mut held = BTreeSet::new(); + let mut in_place = std::collections::HashMap::new(); + drawn_in_place(&doc.layers, &all, true, &mut in_place); + // Those the page check sees, by the boxes of the envelope and its drawn art. + let mut seen = vec![]; + for (id, live, art) in typed { + if !in_place.get(&id).copied().unwrap_or(false) { + held.insert(id); + continue; + } + match vectorcraft_geom::union_opt(live.visual_bounds(), art.visual_bounds()) { + Some(b) if past(b) => { + held.insert(id); + } + Some(b) if pages_touched(b, &pages, 1.0).is_empty() => {} + _ => seen.push((id, live, art)), + } + } + if seen.len() > MAX_WEIGHED { + return all; + } + // The pixels of each page where the envelopes that stay live differ from it: at all, and with + // all their neighbors. + let mut spent = vec![(0usize, 0usize); pages.len()]; + for (id, live, art) in seen { + // The envelope and its drawn art, shown, on a layer of their own in `doc`. + let mut nodes: Vec> = [live, art].into_iter().cloned().map(Arc::new).collect(); + for n in &mut nodes { + let n = Arc::make_mut(n); + (n.visible, n.opacity) = (true, 1.0); + } + let mut one = doc.clone(); + let mut layer = Node::layer(NodeId(0), "", vectorcraft_doc::LayerColor::Preset(0)); + if let Some(children) = layer.children_mut() { + *children = nodes; + } + one.layers = vec![Arc::new(layer)]; + let bounds = vectorcraft_render::encode::art_bounds(&one); + if bounds.is_some_and(past) { + held.insert(id); + continue; + } + let on = bounds.map_or(vec![], |b| pages_touched(b, &pages, 1.0)); + let mut added = spent.clone(); + let mut fits = true; + for (i, ink) in view.inked(&one, &on) { + let Some((any, solid)) = view.differing_in(doc, i, &ink, reflow) else { return all }; + let inked = ink.iter().filter(|p| **p).count() as f64; + let pixels = ink.len().max(1) as f64; + let Some((a, s)) = added.get_mut(i) else { return all }; + *a += any; + *s += solid; + fits &= any as f64 <= inked * ai::ENVELOPE_MAX_ANY + && solid as f64 <= inked * ai::ENVELOPE_MAX_SOLID + && *a as f64 <= pixels * MAX_DIFFERENCE / 2.0 + && *s as f64 <= pixels * MAX_SOLID_DIFFERENCE / 2.0; + } + if fits { + spent = added; + } else { + held.insert(id); + } + } + held +} + +/// Which of the objects `ids` among `nodes` (or what they hold) are drawn where they are and as +/// themselves (`plain`: so far, above `nodes`), into `out` by id: under layers and groups that +/// neither clip them, mask them nor have an appearance of their own (whose effects can move or copy +/// them), and in no envelope, repeat, blend or other object that draws what it holds elsewhere or +/// more than once. +fn drawn_in_place(nodes: &[Arc], ids: &BTreeSet, plain: bool, out: &mut std::collections::HashMap) { + for n in nodes { + if ids.contains(&n.id) { + out.insert(n.id, plain); + } + let Some(children) = n.children() else { continue }; + let keeps = match n.kind { + NodeKind::Layer { clip, .. } | NodeKind::Group { clip, .. } => { + !clip && n.appearance == vectorcraft_doc::Appearance::default() && n.extras().mask.is_none() + } + _ => false, + }; + drawn_in_place(children, ids, plain && keeps, out); + } +} + /// Put each live envelope of type in `drawn` (as [`drawn_or_trusted`] takes them) that `doc` still -/// has back as its hidden type and its drawn art: whether one was. An envelope of type opens live -/// only where the layers with it draw as the page, so where they don't, though they are used all -/// the same (the editing data trusted, or the objects that differ come in as the page's art), it -/// keeps its drawn art. -fn type_drawn(doc: &mut Document, drawn: &[(NodeId, Vec, &str)]) -> bool { +/// has and `held` lists back as its hidden type and its drawn art: whether one was. An envelope of +/// type opens live only where the page doesn't hold it against the layers ([`held_back`]), so where +/// they don't draw as the page though they are used all the same (the editing data trusted, or the +/// objects that differ come in as the page's art), one the page holds against them keeps its drawn +/// art. +fn type_drawn(doc: &mut Document, drawn: &[(NodeId, Vec, &str)], held: &BTreeSet) -> bool { let typed: Vec<(NodeId, Vec)> = drawn .iter() - .filter(|(id, _, say)| *say == ai::ENVELOPE_TYPE_DRAWN && doc.node(*id).is_some()) + .filter(|(id, _, say)| *say == ai::ENVELOPE_TYPE_DRAWN && held.contains(id) && doc.node(*id).is_some()) .map(|(id, art, _)| (*id, art.clone())) .collect(); if typed.is_empty() || doc.insert_beside(typed, true).is_err() { @@ -2530,4 +2769,359 @@ mod candidate_tests { replace_unread(&mut doc, &frame, &unread, &[], &BTreeSet::new(), &mut copied).unwrap(); assert!(copied.contains(&nodes[0].id) && !copied.contains(&nodes[1].id)); } + + /// A rectangle on `rect` filled with `color`, with an id of `doc`'s. + fn filled_rect(doc: &mut Document, rect: Rect, color: vectorcraft_color::Color) -> Node { + let paint = vectorcraft_color::Paint::solid(color); + Node::path( + doc.alloc_id(), + vectorcraft_geom::shapes::rectangle(rect), + vectorcraft_doc::Appearance::basic(paint, vectorcraft_color::Paint::None, 0.0), + ) + } + + /// A live envelope as [`drawn_or_trusted`] takes it: its id, what takes its place again, its note. + type Envelope = (NodeId, Vec, &'static str); + + /// The layers `doc` with a black rectangle on each of `lives` standing in for a live envelope of + /// type, its drawn art a black rectangle on the matching one of `arts`: the layers, and the + /// envelopes as [`drawn_or_trusted`] takes them. + fn stand_ins(lives: &[Rect], arts: &[Rect]) -> (Document, Vec) { + let mut doc = Document::new(100.0, 100.0); + let layer = doc.layers[0].id; + let mut drawn = vec![]; + for (live, art) in lives.iter().zip(arts) { + let n = filled_rect(&mut doc, *live, vectorcraft_color::Color::BLACK); + let id = n.id; + doc.insert(Some(layer), 0, n).unwrap(); + let art = filled_rect(&mut doc, *art, vectorcraft_color::Color::BLACK); + drawn.push((id, vec![art], ai::ENVELOPE_TYPE_DRAWN)); + } + (doc, drawn) + } + + /// The page holds an envelope of type against layers that don't draw as it only where the + /// layers with the envelope differ from the page where it or its drawn art inks: not where the + /// page draws other art that the layers don't have. + #[test] + fn the_page_holds_back_only_envelopes_of_type_where_it_differs_from_them() { + let rect = Rect::new(0.0, 0.0, 100.0, 100.0); + let mut page = Document::new(100.0, 100.0); + let layer = page.layers[0].id; + // The first two envelopes' drawn art, and a square the layers don't have. + for r in [Rect::new(10.0, 10.0, 30.0, 30.0), Rect::new(60.0, 10.0, 80.0, 30.0), Rect::new(10.0, 60.0, 30.0, 80.0)] { + let n = filled_rect(&mut page, r, vectorcraft_color::Color::BLACK); + page.insert(Some(layer), 0, n).unwrap(); + } + // Live where its drawn art is; moved off its drawn art; and where the page draws nothing. + let (doc, drawn) = stand_ins( + &[Rect::new(10.0, 10.0, 30.0, 30.0), Rect::new(66.0, 10.0, 86.0, 30.0), Rect::new(60.0, 60.0, 80.0, 80.0)], + &[Rect::new(10.0, 10.0, 30.0, 30.0), Rect::new(60.0, 10.0, 80.0, 30.0), Rect::new(60.0, 60.0, 80.0, 80.0)], + ); + let frame = Frame { page: &page, page_rect: rect, rect, whole: false, pages: vec![(rect, Affine::IDENTITY)], more: vec![] }; + let mut view = PageView::new(&frame); + assert!(compare(&frame, &mut view, &doc, false).is_err()); + assert_eq!(held_back(&frame, &mut view, &doc, &drawn, false), BTreeSet::from([drawn[1].0, drawn[2].0])); + // Only envelopes of type are weighed. + let other: Vec<_> = drawn.iter().map(|(id, art, _)| (*id, art.clone(), ai::ENVELOPE_DRAWN)).collect(); + assert!(held_back(&frame, &mut view, &doc, &other, false).is_empty()); + } + + /// The envelopes of type that stay live may together differ from the page where they ink in no + /// more than half of what the page check allows: the next one past that is held back, though + /// on its own it would stay. + #[test] + fn envelopes_of_type_stay_live_within_half_of_what_the_page_check_allows() { + let rect = Rect::new(0.0, 0.0, 100.0, 100.0); + let halves = [Rect::new(0.0, 0.0, 100.0, 25.0), Rect::new(0.0, 25.0, 100.0, 50.0)]; + let mut page = Document::new(100.0, 100.0); + let layer = page.layers[0].id; + for r in halves { + let n = filled_rect(&mut page, r, vectorcraft_color::Color::BLACK); + page.insert(Some(layer), 0, n).unwrap(); + } + // White lines two pixels high over each, 6 points apart: 8% of what each inks differs, 2% of + // the page, and none of it with all its neighbors. + for (i, y) in [3.0, 9.0, 15.0, 21.0, 28.0, 34.0, 40.0, 46.0].into_iter().enumerate() { + let n = filled_rect(&mut page, Rect::new(0.0, y, 100.0, y + 0.5), vectorcraft_color::Color::WHITE); + page.insert(Some(layer), halves.len() + i, n).unwrap(); + } + let (doc, drawn) = stand_ins(&halves, &halves); + let frame = Frame { page: &page, page_rect: rect, rect, whole: false, pages: vec![(rect, Affine::IDENTITY)], more: vec![] }; + let mut view = PageView::new(&frame); + assert_eq!(held_back(&frame, &mut view, &doc, &drawn, false), BTreeSet::from([drawn[1].0])); + assert!(held_back(&frame, &mut view, &doc, &drawn[1..], false).is_empty()); + } + + /// A page of 100 points with a black rectangle on each of `rects`, and its frame (`whole`: the + /// page holds all the art that prints). + fn black_page(rects: &[Rect]) -> Document { + let mut page = Document::new(100.0, 100.0); + let layer = page.layers[0].id; + for r in rects { + let n = filled_rect(&mut page, *r, vectorcraft_color::Color::BLACK); + page.insert(Some(layer), 0, n).unwrap(); + } + page + } + + /// The frame of `page`, its 100-point square (`whole`: the page holds all the art that prints). + fn frame_of(page: &Document, whole: bool) -> Frame<'_> { + let rect = Rect::new(0.0, 0.0, 100.0, 100.0); + Frame { page, page_rect: rect, rect, whole, pages: vec![(rect, Affine::IDENTITY)], more: vec![] } + } + + /// An envelope of type is held back where the layers with it differ from the page in more of + /// the pixels it and its drawn art ink than its own check allows against its drawn art, though + /// that is far less of the page than the page check allows. + #[test] + fn an_envelope_of_type_differing_in_more_of_its_pixels_than_its_check_allows_is_held_back() { + // Half a point off its drawn art, which the page draws: 22% of the pixels they ink differ, + // a tenth of a percent of the page, and none with all their neighbors. + let page = black_page(&[Rect::new(30.5, 10.0, 34.5, 20.0)]); + let (doc, drawn) = stand_ins(&[Rect::new(30.0, 10.0, 34.0, 20.0)], &[Rect::new(30.5, 10.0, 34.5, 20.0)]); + let frame = frame_of(&page, false); + let mut view = PageView::new(&frame); + assert_eq!(held_back(&frame, &mut view, &doc, &drawn, false), BTreeSet::from([drawn[0].0])); + } + + /// An envelope of type that the layers don't draw where it is and as itself is held back though + /// it draws as the page, wherever it lies: one that a clip group or a clipping sublayer clips, an + /// opacity mask masks, or that a group with an appearance of its own, another envelope, a repeat + /// or a blend holds. Drawn on its own, it would be weighed on pixels a clip hides, or elsewhere + /// than it draws, and what holds it can draw it onto the page from off it. One in a plain group + /// is weighed, and one off the page in a plain group stays live. + #[test] + fn envelopes_of_type_the_layers_dont_draw_in_place_are_held_back() { + let at = |i: usize| { + let (x, y) = if i < 4 { (5.0 + 20.0 * i as f64, 5.0) } else { (5.0 + 20.0 * (i - 4) as f64, 30.0) }; + Rect::new(x, y, x + 15.0, y + 15.0) + }; + let off = [Rect::new(120.0, 5.0, 135.0, 20.0), Rect::new(140.0, 5.0, 155.0, 20.0)]; + let page = black_page(&(0..8).map(at).collect::>()); + let mut doc = Document::new(100.0, 100.0); + let layer = doc.layers[0].id; + let mut drawn = vec![]; + let mut stand_in = |doc: &mut Document, r: Rect| { + let n = filled_rect(doc, r, vectorcraft_color::Color::BLACK); + drawn.push((n.id, vec![filled_rect(doc, r, vectorcraft_color::Color::BLACK)], ai::ENVELOPE_TYPE_DRAWN)); + Arc::new(n) + }; + let group = |doc: &mut Document, children: Vec>, clip: bool| Node::new(doc.alloc_id(), NodeKind::Group { children, clip }); + let fill = vectorcraft_doc::Appearance { + items: vec![vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(vectorcraft_color::Paint::solid( + vectorcraft_color::Color::BLACK, + )))], + ..Default::default() + }; + let mut objects = vec![]; + // 0: in a plain group. + let n = stand_in(&mut doc, at(0)); + objects.push(group(&mut doc, vec![n], false)); + // 1: in a clip group. + let n = stand_in(&mut doc, at(1)); + let mut clip = filled_rect(&mut doc, at(1).inflate(2.0, 2.0), vectorcraft_color::Color::BLACK); + if let NodeKind::Path { clipping, .. } = &mut clip.kind { + *clipping = true; + } + objects.push(group(&mut doc, vec![Arc::new(clip), n], true)); + // 2: in another envelope. + let n = stand_in(&mut doc, at(2)); + let r = at(2); + let points = vec![kurbo::Point::new(r.x0, r.y0), kurbo::Point::new(r.x1, r.y0), kurbo::Point::new(r.x0, r.y1), kurbo::Point::new(r.x1, r.y1)]; + let kind = Box::new(vectorcraft_doc::live::EnvelopeKind::Mesh { rows: 1, cols: 1, points, handles: vec![] }); + let options = vectorcraft_doc::live::EnvelopeOptions::NEW; + objects.push(Node::new( + doc.alloc_id(), + NodeKind::Envelope { content: vec![n], kind, fidelity: 50.0, editing: false, options, frame: Box::default() }, + )); + // 3: in a group with an appearance of its own. + let n = stand_in(&mut doc, at(3)); + let mut styled = group(&mut doc, vec![n], false); + styled.appearance = fill.clone().into(); + objects.push(styled); + // 4: in a group with an opacity mask. + let n = stand_in(&mut doc, at(4)); + let mut masked = group(&mut doc, vec![n], false); + let mask = filled_rect(&mut doc, at(4).inflate(2.0, 2.0), vectorcraft_color::Color::WHITE); + masked.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(mask, true))); + objects.push(masked); + // 5: in a clipping sublayer. + let n = stand_in(&mut doc, at(5)); + let mut clip = filled_rect(&mut doc, at(5).inflate(2.0, 2.0), vectorcraft_color::Color::BLACK); + if let NodeKind::Path { clipping, .. } = &mut clip.kind { + *clipping = true; + } + let mut sublayer = Node::layer(doc.alloc_id(), "Clipped", vectorcraft_doc::LayerColor::Preset(1)); + if let NodeKind::Layer { clip: c, children, .. } = &mut sublayer.kind { + (*c, *children) = (true, vec![Arc::new(clip), n]); + } + objects.push(sublayer); + // 6: in a repeat; 7: in a blend. + let n = stand_in(&mut doc, at(6)); + objects.push(Node::new(doc.alloc_id(), NodeKind::Repeat(vectorcraft_doc::RepeatSpec::grid(vec![n], 0.0, 0.0)))); + let n = stand_in(&mut doc, at(7)); + objects.push(Node::new(doc.alloc_id(), NodeKind::Blend { children: vec![n], spec: Box::default() })); + // 8: off the page in a group with an appearance of its own (an effect could draw it onto the + // page); 9: off the page in a plain group. + let n = stand_in(&mut doc, off[0]); + let mut styled = group(&mut doc, vec![n], false); + styled.appearance = fill.into(); + objects.push(styled); + let n = stand_in(&mut doc, off[1]); + objects.push(group(&mut doc, vec![n], false)); + for n in objects { + doc.insert(Some(layer), 0, n).unwrap(); + } + let frame = frame_of(&page, false); + let mut view = PageView::new(&frame); + let held = held_back(&frame, &mut view, &doc, &drawn, false); + assert_eq!(held, drawn[1..9].iter().map(|(id, ..)| *id).collect::>()); + } + + /// On a page that holds all the art that prints, which the page check also compares past the + /// page, an envelope of type reaching past the page, or lying off it, is held back; on another + /// page, the part on the page is weighed, and one off it stays live. + #[test] + fn on_a_page_that_holds_all_the_art_an_envelope_of_type_past_it_is_held_back() { + let on = Rect::new(10.0, 10.0, 30.0, 30.0); + let across = Rect::new(90.0, 40.0, 110.0, 60.0); + let off = Rect::new(120.0, 10.0, 140.0, 30.0); + let page = black_page(&[on, Rect::new(90.0, 40.0, 100.0, 60.0)]); + let (doc, drawn) = stand_ins(&[on, across, off], &[on, across, off]); + for (whole, held) in [(true, BTreeSet::from([drawn[1].0, drawn[2].0])), (false, BTreeSet::new())] { + let frame = frame_of(&page, whole); + let mut view = PageView::new(&frame); + assert_eq!(held_back(&frame, &mut view, &doc, &drawn, false), held, "whole: {whole}"); + } + // On the page by its box, past it by what it draws: a Transform effect of its own draws a + // copy of it 100 points to the right, off the page. + let page = black_page(&[on]); + let (mut doc, drawn) = stand_ins(&[on], &[on]); + let effect = + vectorcraft_doc::Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": 100, "copies": 1}), visible: true }; + doc.node_mut(drawn[0].0).unwrap().appearance.effects.push(effect); + for (whole, held) in [(true, BTreeSet::from([drawn[0].0])), (false, BTreeSet::new())] { + let frame = frame_of(&page, whole); + let mut view = PageView::new(&frame); + assert_eq!(held_back(&frame, &mut view, &doc, &drawn, false), held, "drawn past the page, whole: {whole}"); + } + } + + /// Where the objects that draw differently from the page are to come in as its art and the + /// envelopes of type the page doesn't hold stay live, but one of those holds the difference in + /// its box (an object that holds type isn't replaced), every envelope of type gets its drawn art + /// back and that is tried again: the layers are still used. + #[test] + fn objects_come_in_as_the_page_art_with_every_envelope_of_type_put_back_where_a_live_one_holds_a_difference() { + let (a, b, dot, other) = ( + Rect::new(10.0, 10.0, 20.0, 20.0), + Rect::new(40.0, 10.0, 50.0, 20.0), + Rect::new(27.0, 12.0, 33.0, 18.0), + Rect::new(70.0, 70.0, 90.0, 90.0), + ); + // The page draws a dot in the gap between the two rectangles of the envelope's stand-in. + let page = black_page(&[a, b, dot, other]); + let mut doc = Document::new(100.0, 100.0); + let layer = doc.layers[0].id; + let square = filled_rect(&mut doc, other, vectorcraft_color::Color::BLACK); + doc.insert(Some(layer), 0, square).unwrap(); + // The stand-in holds type, hidden; its drawn art is the two rectangles. + let style = vectorcraft_doc::CharStyle::default(); + let mut text = + Node::new(doc.alloc_id(), NodeKind::Text(Box::new(vectorcraft_doc::TextObject::point(kurbo::Point::new(12.0, 18.0), "A", style)))); + text.visible = false; + let parts = vec![ + Arc::new(filled_rect(&mut doc, a, vectorcraft_color::Color::BLACK)), + Arc::new(filled_rect(&mut doc, b, vectorcraft_color::Color::BLACK)), + ]; + let mut children = parts.clone(); + children.push(Arc::new(text)); + let live = Node::new(doc.alloc_id(), NodeKind::Group { children, clip: false }); + let id = live.id; + doc.insert(Some(layer), 0, live).unwrap(); + let art = Node::new(doc.alloc_id(), NodeKind::Group { children: parts, clip: false }); + let drawn: Vec = vec![(id, vec![art], ai::ENVELOPE_TYPE_DRAWN)]; + let frame = frame_of(&page, false); + let mut view = PageView::new(&frame); + assert!(compare(&frame, &mut view, &doc, false).is_err()); + let layers = Placements { doc: &doc, unseen: 0, other: None, drawn: &drawn, places: &[(id, 0)] }; + let mut free = None; + let found = keep_differing_typed(&frame, &mut view, &layers, &BTreeSet::new(), &[], false, &mut free); + assert_eq!(free, Some(vec![0]), "the page doesn't hold the envelope"); + let Some((kept, _, notes, typed)) = found else { panic!("the layers aren't used") }; + assert!(typed, "the envelope got its drawn art back"); + assert!(kept.node(id).is_none()); + assert!(notes.iter().any(|n| n.starts_with(DREW_DIFFERENTLY)), "{notes:?}"); + } + + /// The placed files' other placement is weighed on its own: an envelope of type that the layers + /// as read draw as the page, but that a placed file moved over it at the other placement makes + /// differ, gets its drawn art back there, where that placement's differing objects then come in + /// as the page's art. + #[test] + fn the_other_placement_of_placed_files_is_weighed_on_its_own() { + let black = vectorcraft_color::Color::BLACK; + let gray = vectorcraft_color::Color::rgb(0.5, 0.5, 0.5); + let (envelope, fillers) = (Rect::new(10.0, 10.0, 30.0, 30.0), [Rect::new(40.0, 80.0, 50.0, 90.0), Rect::new(70.0, 80.0, 80.0, 90.0)]); + let placed = Rect::new(60.0, 60.0, 76.0, 76.0); + // The page draws the envelope's drawn art in two halves. + let page = black_page(&[Rect::new(10.0, 10.0, 20.0, 30.0), Rect::new(20.0, 10.0, 30.0, 30.0), placed, fillers[0], fillers[1]]); + let (mut doc, drawn) = stand_ins(&[envelope], &[envelope]); + let layer = doc.layers[0].id; + for r in fillers { + let n = filled_rect(&mut doc, r, black); + doc.insert(Some(layer), 0, n).unwrap(); + } + // Two placed files, standing in as rectangles: one 20 points above where the page has it, one + // a gray rectangle off the art. At their other placement the first is where the page has it + // and the gray one lies over half of the envelope. + let image = filled_rect(&mut doc, Rect::new(60.0, 40.0, 76.0, 56.0), black); + let strip = filled_rect(&mut doc, Rect::new(85.0, 40.0, 95.0, 60.0), gray); + // On top of the layer: the strip covers the envelope where it lies over it. + let top = doc.layers[0].children().map_or(0, Vec::len); + let (image, strip) = (doc.insert(Some(layer), top, image).unwrap(), doc.insert(Some(layer), top + 1, strip).unwrap()); + let mut other = doc.clone(); + other.node_mut(image).unwrap().transform(Affine::translate(Vec2::new(0.0, 20.0)), PAGE_MOVE); + other.node_mut(strip).unwrap().transform(Affine::translate(Vec2::new(-65.0, -30.0)), PAGE_MOVE); + let frame = frame_of(&page, false); + let mut view = PageView::new(&frame); + assert!(held_back(&frame, &mut view, &doc, &drawn, false).is_empty()); + assert_eq!(held_back(&frame, &mut view, &other, &drawn, false), BTreeSet::from([drawn[0].0])); + let other = (other, 0); + let layers = Placements { doc: &doc, unseen: 0, other: Some(&other), drawn: &drawn, places: &[(drawn[0].0, 0)] }; + let mut free = None; + let found = keep_differing_typed(&frame, &mut view, &layers, &BTreeSet::new(), &[], false, &mut free); + assert_eq!(free, Some(vec![0]), "the layers as read don't hold the envelope"); + let Some((kept, _, notes, typed)) = found else { panic!("the layers aren't used") }; + assert!(notes.iter().any(|n| n.starts_with(DREW_DIFFERENTLY)), "{notes:?}"); + assert!(typed && kept.node(drawn[0].0).is_none(), "the envelope keeps its drawn art at the other placement"); + } + + /// Where putting back only the envelopes of type the page holds makes the layers draw as the page, + /// though putting back every live envelope's drawn art doesn't (an envelope of type the page + /// doesn't hold has stale drawn art), the layers are used as they then are: nothing differs to + /// come in as the page's art. + #[test] + fn layers_that_draw_as_the_page_with_the_held_envelopes_of_type_put_back_are_used_so() { + let (held, kept_live) = (Rect::new(10.0, 10.0, 30.0, 30.0), Rect::new(60.0, 10.0, 80.0, 30.0)); + let page = black_page(&[held, kept_live]); + // The first is drawn 6 points off its drawn art, which the page draws; the second draws as the + // page, its drawn art 6 points off. + let (doc, drawn) = stand_ins(&[Rect::new(16.0, 10.0, 36.0, 30.0), kept_live], &[held, Rect::new(66.0, 10.0, 86.0, 30.0)]); + let frame = frame_of(&page, false); + let mut view = PageView::new(&frame); + assert!(compare(&frame, &mut view, &doc, false).is_err()); + let mut all = doc.clone(); + all.insert_beside(drawn.iter().map(|(id, art, _)| (*id, art.clone())).collect(), true).unwrap(); + assert!(compare(&frame, &mut view, &all, false).is_err(), "with every drawn art put back they don't draw as the page"); + let places = [(drawn[0].0, 0), (drawn[1].0, 1)]; + let layers = Placements { doc: &doc, unseen: 0, other: None, drawn: &drawn, places: &places }; + let mut free = None; + let found = keep_differing_typed(&frame, &mut view, &layers, &BTreeSet::new(), &[], false, &mut free); + assert_eq!(free, Some(vec![1])); + let Some((kept, _, notes, typed)) = found else { panic!("the layers aren't used") }; + assert!(typed && kept.node(drawn[0].0).is_none() && kept.node(drawn[1].0).is_some()); + assert!(!notes.iter().any(|n| n.starts_with(DREW_DIFFERENTLY)), "{notes:?}"); + } } diff --git a/crates/eps/src/import/native/compare.rs b/crates/eps/src/import/native/compare.rs index 34f458f328..424ac4079a 100644 --- a/crates/eps/src/import/native/compare.rs +++ b/crates/eps/src/import/native/compare.rs @@ -570,6 +570,34 @@ impl PageView { } } } + + /// Which pixels of each of the pages `on` `art` inks (draws over with an alpha above 8 of 255), + /// drawn as the layers are drawn on them, row by row. + pub(super) fn inked(&mut self, art: &Document, on: &[usize]) -> Vec<(usize, Vec)> { + self.draw(art, on) + .into_iter() + .map(|(i, drawn)| (i, drawn.pixels.as_chunks::<4>().0.iter().map(|p| u32::from(p[3]) > WHITE).collect())) + .collect() + } + + /// Of the pixels of page `i` that `marks` marks (row by row), how many `b` draws differently from + /// the page, as [`compared`] counts them: those that differ (with `reflow`, those away from type), + /// and those that differ with all their neighbors, away from type. `None` when `marks` isn't the + /// page's size. + pub(super) fn differing_in(&mut self, b: &Document, i: usize, marks: &[bool], reflow: bool) -> Option<(usize, usize)> { + self.layered(b, &[i]); + let printed = as_printed(b); + let b = printed.as_ref().unwrap_or(b); + let page = self.pages.get(i)?; + let layered = self.drawn.last()?.pages.get(i)?.as_ref()?; + let (differs, typed, solid) = differing_pixels(&page.drawn, &layered.pixels, &page.counted_type(b, page.region, reflow), &page.skipped())?; + if marks.len() != differs.len() { + return None; + } + let any = marks.iter().zip(&differs).zip(&typed).filter(|((m, d), t)| **m && **d && !(reflow && **t)).count(); + let solid = marks.iter().zip(&solid).filter(|(m, s)| **m && **s).count(); + Some((any, solid)) + } } /// The `w` × `h` pixels of `from` from pixel (`x`, `y`): `None` unless they lie in it, from a pixel. @@ -682,8 +710,27 @@ pub(super) fn compared(x: &vectorcraft_render::Rendered, y: &vectorcraft_render: /// [`compared`], and which of the pixels (row by row) are counted in its `solid` share: none when /// the drawings can't be compared. fn compared_with_solid(x: &vectorcraft_render::Rendered, y: &vectorcraft_render::Rendered, areas: &[Rect], skip: &[Rect]) -> (Difference, Vec) { - if x.width == 0 || x.height == 0 || x.width != y.width || x.height != y.height { + let Some((differs, typed, solid)) = differing_pixels(x, y, areas, skip) else { return (Difference { any: 1.0, art: 1.0, solid: 1.0, typed: 0.0 }, vec![]); + }; + let area = (f64::from(x.width) * f64::from(x.height)).max(1.0); + let any = differs.iter().filter(|d| **d).count() as f64 / area; + let art = differs.iter().zip(&typed).filter(|(d, t)| **d && !**t).count() as f64 / area; + let shares = Difference { any, art, solid: solid.iter().filter(|s| **s).count() as f64 / area, typed: any - art }; + (shares, solid) +} + +/// Which pixels (row by row) of two drawings of the same size differ ([`differ`], those in `skip` +/// counting as alike), which of those lie in the type's `areas`, and which differ with all their +/// neighbors away from type: [`compared`]'s pixels. `None` when the drawings can't be compared. +fn differing_pixels( + x: &vectorcraft_render::Rendered, + y: &vectorcraft_render::Rendered, + areas: &[Rect], + skip: &[Rect], +) -> Option<(Vec, Vec, Vec)> { + if x.width == 0 || x.height == 0 || x.width != y.width || x.height != y.height { + return None; } let (w, h) = (x.width as usize, x.height as usize); // Pixels in `skip` count as alike. @@ -691,10 +738,9 @@ fn compared_with_solid(x: &vectorcraft_render::Rendered, y: &vectorcraft_render: let differs: Vec = x.pixels.as_chunks::<4>().0.iter().zip(y.pixels.as_chunks::<4>().0).zip(&skipped).map(|((p, q), s)| !*s && differ(p, q)).collect(); if !differs.contains(&true) { - return (Difference { any: 0.0, art: 0.0, solid: 0.0, typed: 0.0 }, vec![false; w * h]); + return Some((differs, vec![false; w * h], vec![false; w * h])); } - let typed = in_areas(areas, w, h); - let art = differs.iter().zip(&typed).filter(|(d, t)| **d && !**t).count(); + let typed: Vec = in_areas(areas, w, h).into_iter().zip(&differs).map(|(t, d)| t && *d).collect(); // Which pixels differ with their left and right neighbors. let mut across = vec![false; w * h]; for (k, a) in across.iter_mut().enumerate() { @@ -706,11 +752,7 @@ fn compared_with_solid(x: &vectorcraft_render::Rendered, y: &vectorcraft_render: for (k, s) in solid.iter_mut().enumerate().skip(w).take(w * h.saturating_sub(2)) { *s = !typed.get(k).copied().unwrap_or(true) && [k - w, k, k + w].iter().all(|n| across.get(*n).copied().unwrap_or(false)); } - let area = (w as f64 * h as f64).max(1.0); - let any = differs.iter().filter(|d| **d).count() as f64 / area; - let art = art as f64 / area; - let shares = Difference { any, art, solid: solid.iter().filter(|s| **s).count() as f64 / area, typed: any - art }; - (shares, solid) + Some((differs, typed, solid)) } /// Where the type that shows in `nodes` is, in pixels of `region` drawn at `scale` (with a margin @@ -879,7 +921,7 @@ const NOTABLE_DIFFERENCE: f64 = 0.002; pub(in crate::import) const MAX_SOLID_DIFFERENCE: f64 = 0.001; /// How far (points) the art the layers print may reach past a page that holds it all. -const PAST_THE_PAGE: f64 = 1.0; +pub(super) const PAST_THE_PAGE: f64 = 1.0; /// Do the layers' art and the page's own look alike (where the page holds all the art that prints, /// also round it), on every page the frame has ([`Frame::more`])? An error says they don't; `Ok` has diff --git a/crates/eps/src/import/native/layers.rs b/crates/eps/src/import/native/layers.rs index ee39aec1f1..d1af3301df 100644 --- a/crates/eps/src/import/native/layers.rs +++ b/crates/eps/src/import/native/layers.rs @@ -1,4 +1,4 @@ -use super::build::{PAGE_MOVE, Page, alone_scale, build, build_from, build_on_page, build_without_page, reid_page_art}; +use super::build::{PAGE_MOVE, Page, alone_scale, build, build_from, build_on_page, build_weighing, build_without_page, reid_page_art}; use super::slots::LAYERS_UNREAD; use super::{Affine, Arc, Cow, Document, Imported, Node, NodeKind, PathData, Rect, Vec2, ai}; @@ -177,15 +177,27 @@ pub fn layered_ai_from( add_notes(&mut all, read.notes()); (visible, all, false) }; - let built = structure - .unwrap_or_else(|| ai::read_over_page(&data, false, names).map(Box::new)) - .and_then(|structure| build_from(*structure, &data, Some(&visible), Page::Artboard, outlined, trust, unit)); + // The envelopes of type the page doesn't hold against layers that don't draw as it, and how many + // envelopes of type the layers had. + let (mut free, mut count) = (None, 0); + let built = structure.unwrap_or_else(|| ai::read_over_page(&data, false, names).map(Box::new)).and_then(|structure| { + count = structure.warped_type.envelope_count(); + build_weighing(*structure, &data, Some(&visible), Page::Artboard, outlined, trust, unit, &mut free) + }); // Layers that waited on the page only for their envelopes of type open alone, as they would - // have without them, each envelope keeping its drawn art, unless one opened live with the page. - let live = matches!(&built, Ok((done, _)) if holds_type_envelope(&done.layers)); + // have without them, unless one opened live with the layers drawing as the page. Alone, each + // envelope keeps its drawn art but those the page didn't hold against the layers, which open + // live as they were weighed. They were weighed on the layers as compared with the page, before + // any object of them came in as the page's art: those layers aren't used here, whatever came of + // them. + let live = free.is_none() && matches!(&built, Ok((done, _)) if holds_type_envelope(&done.layers)); if !live && let Some((mut done, notes)) = alone.and_then(|(pages, unit)| { - let structure = ai::read_over_page(&data, false, names).ok()?; + let mut structure = ai::read_over_page(&data, false, names).ok()?; + // With none free, nothing needs settling again: every envelope keeps its drawn art. + if let Some(free) = free.as_deref().filter(|free| !free.is_empty()) { + structure.warped_type.open_alone(free, count); + } build_without_page(structure, &data, &pages, unit).ok()?.ok() }) { diff --git a/crates/eps/src/import/predefined_cmap.rs b/crates/eps/src/import/predefined_cmap.rs new file mode 100644 index 0000000000..c688ebf9ae --- /dev/null +++ b/crates/eps/src/import/predefined_cmap.rs @@ -0,0 +1,381 @@ +//! Strings in fonts over Adobe's predefined CMaps () +//! read as characters: the codes of a predefined Unicode CMap are the characters; those of the +//! others map to CIDs of a character collection, whose CID → Unicode CMap gives the characters. +//! Used by legacy `.ai` type in composite fonts and by type in CID-keyed fonts found by name. + +use craft_pdf::interpret::hayro_cmap::{BfString, CMap, CMapName, load_embedded}; + +/// How a composite font's strings decode. +#[derive(Debug)] +pub(super) enum CMapCodes { + /// By a predefined CMap's codes to CIDs, then by its character collection's CID → Unicode CMap; + /// with `high_bit`, each byte 0x21 to 0x7E gets its high bit set first. `space` is the CMap's + /// code space ([`code_space`]). + Cids { codes: Box, unicode: Box, high_bit: bool, space: Option }, + /// A predefined Unicode CMap: the codes are the characters. + Unicode(Unicode), +} + +/// A CMap's code space: ranges of codes, each given by its lowest and highest code, both with the +/// code's length in bytes. +type CodeSpace = &'static [(&'static [u8], &'static [u8])]; + +/// What control byte `b` is in a composite font's string: `\r` a paragraph break, `\t` a tab. +fn control(b: u8) -> Option { + match b { + b'\r' => Some('\n'), + b'\t' => Some('\t'), + _ => None, + } +} + +impl CMapCodes { + /// The characters of string `bytes`, leaving out codes the CMaps don't map; a `\r` is a + /// paragraph break and a `\t` a tab (also as a byte left over after the last whole code of a + /// UTF-16 or UTF-32 string). + pub(super) fn decode(&self, bytes: &[u8]) -> String { + let mut text = String::new(); + self.each_code(bytes, |_, chars| text.extend(chars)); + text + } + + /// The codes of string `bytes`, each with its value and the characters it stands for (as + /// [`Self::decode`] reads them; none for a code the CMaps don't map, or for a byte that starts + /// no code, which counts as a code of its own). + pub(super) fn codes(&self, bytes: &[u8]) -> Decoded { + let mut out = Decoded::default(); + self.each_code(bytes, |code, chars| out.push(code, chars)); + out + } + + /// Calls `emit` with each code of string `bytes` in turn ([`Self::codes`]): its value and the + /// characters it stands for. + fn each_code(&self, bytes: &[u8], mut emit: impl FnMut(u32, &mut dyn Iterator)) { + let value = |b: &[u8]| b.iter().fold(0u32, |c, &b| c << 8 | u32::from(b)); + let (codes, unicode, high_bit, space) = match self { + Self::Unicode(form) => { + let unit = match form { + Unicode::Utf16 => 2, + Unicode::Utf8 => 1, + Unicode::Utf32 => 4, + }; + let (whole, rest) = bytes.split_at_checked(bytes.len() - bytes.len() % unit).unwrap_or((bytes, &[])); + unicode_codes(whole, *form, |code, c| emit(value(code), &mut c.map(|c| if c == '\r' { '\n' } else { c }).into_iter())); + if let Some(&last) = rest.last() { + emit(value(rest), &mut control(last).into_iter()); + } + return; + } + Self::Cids { codes, unicode, high_bit, space } => (codes, unicode, *high_bit, space), + }; + // A code's value is that of the string's bytes, also where they're read in their EUC form. + let original = bytes; + let value_at = |at: usize, len: usize| original.get(at..at + len).map_or(0, value); + let euc: Vec; + let bytes = if high_bit { + euc = bytes.iter().map(|&b| if (0x21..0x7f).contains(&b) { b | 0x80 } else { b }).collect(); + euc.as_slice() + } else { + bytes + }; + let mut at = 0; + while let Some(&first) = bytes.get(at) { + // VectorCraft reads a 0x0D byte as a paragraph break and a 0x09 byte as a tab in every + // CMap, as in other fonts' strings, including the row-and-cell CMaps, whose code space + // has no one-byte codes. + if let Some(control) = control(first) { + emit(value_at(at, 1), &mut Some(control).into_iter()); + at += 1; + continue; + } + let rest = bytes.get(at..).unwrap_or_default(); + let code = |len: u8| rest.get(..usize::from(len)).map(value); + let found = match space { + // The code is as long as the code space range it falls in; a byte that starts no + // code in the code space is skipped. + Some(space) => code_len(space, rest).and_then(|len| code(len).map(|c| (len, codes.lookup_cid_code(c, len)))), + None => (1..=4u8).find_map(|len| Some((len, Some(codes.lookup_cid_code(code(len)?, len)?)))), + }; + let Some((len, cid)) = found else { + emit(value_at(at, 1), &mut None.into_iter()); + at += 1; + continue; + }; + let value = value_at(at, usize::from(len)); + at += usize::from(len); + // A code the CMap leaves out stands for no character. + match cid.and_then(|cid| unicode.lookup_bf_string(cid)) { + // A one-byte Roman code whose CID the table gives as a combining mark alone (0x7E in + // the Mac Shift-JIS CMaps, U+0303): the ASCII character, as Adobe's cid2code.txt lists first. + Some(BfString::Char('\u{300}'..='\u{36f}')) if len == 1 && (0x20..0x7f).contains(&first) => { + emit(value, &mut Some(char::from(first)).into_iter()) + } + Some(BfString::Char(c)) if c != char::REPLACEMENT_CHARACTER => emit(value, &mut Some(c).into_iter()), + Some(BfString::String(s)) => emit(value, &mut s.chars().filter(|c| *c != char::REPLACEMENT_CHARACTER)), + _ => emit(value, &mut None.into_iter()), + } + } + } +} + +/// A string's characters, and its codes: each code's value and how many of the characters it +/// stands for, in order. +#[derive(Debug, Default)] +pub(super) struct Decoded { + pub text: String, + pub codes: Vec<(u32, usize)>, +} + +impl Decoded { + /// Code `code`, standing for characters `chars`. + pub(super) fn push(&mut self, code: u32, chars: impl IntoIterator) { + let before = self.text.len(); + self.text.extend(chars); + let n = self.text.get(before..).map_or(0, |added| added.chars().count()); + self.codes.push((code, n)); + } +} + +/// How strings in a font over predefined CMap `cmap` decode; `None` when the CMap can't be read. +pub(super) fn codes(cmap: &str) -> Option { + match unicode_cmap(cmap) { + Some(form) => Some(CMapCodes::Unicode(form)), + None => cid_codes(cmap), + } +} + +/// How a predefined Unicode CMap's codes encode their characters. +#[derive(Clone, Copy, PartialEq, Debug)] +pub(super) enum Unicode { + /// Two bytes a character (`UCS2`) or a UTF-16 surrogate pair, the high byte first. + Utf16, + Utf8, + /// Four bytes, the high byte first. + Utf32, +} + +/// The encoding of predefined Unicode CMap `name`: `Uni` and a character collection, then `-UCS2`, +/// `-UTF8`, `-UTF16` or `-UTF32` (and `-HW` for half-width forms), then `-H` or `-V` +/// (`UniJIS-UCS2-H`, `UniGB-UTF16-V`: ). +pub(super) fn unicode_cmap(name: &str) -> Option { + let rest = name.strip_suffix("-H").or_else(|| name.strip_suffix("-V"))?; + let rest = rest.strip_suffix("-HW").unwrap_or(rest); + let (collection, form) = rest.rsplit_once('-')?; + let collections = ["UniJIS", "UniJISPro", "UniJIS2004", "UniJISX0213", "UniJISX02132004", "UniHojo", "UniGB", "UniCNS", "UniKS", "UniAKR"]; + if !collections.contains(&collection) { + return None; + } + match form { + "UCS2" | "UTF16" => Some(Unicode::Utf16), + "UTF8" => Some(Unicode::Utf8), + "UTF32" => Some(Unicode::Utf32), + _ => None, + } +} + +/// Calls `out` with each code of string `s` in Unicode form `form` in turn, and the character it +/// encodes (none for an invalid code: a lone surrogate, a byte that starts no UTF-8 character, a +/// value past U+10FFFF). +fn unicode_codes(s: &[u8], form: Unicode, mut out: impl FnMut(&[u8], Option)) { + match form { + Unicode::Utf16 => { + let unit = |i: usize| s.get(i..i + 2).and_then(|b| <[u8; 2]>::try_from(b).ok()).map(u16::from_be_bytes); + let mut at = 0; + while let Some(u) = unit(at) { + let next = unit(at + 2); + let pair = next.filter(|n| (0xd800..0xdc00).contains(&u) && (0xdc00..0xe000).contains(n)); + let len = if pair.is_some() { 4 } else { 2 }; + let c = char::decode_utf16([u].into_iter().chain(pair)).next().and_then(Result::ok); + out(s.get(at..at + len).unwrap_or_default(), c); + at += len; + } + } + Unicode::Utf8 => { + let mut at = 0; + for chunk in s.utf8_chunks() { + for c in chunk.valid().chars() { + out(s.get(at..at + c.len_utf8()).unwrap_or_default(), Some(c)); + at += c.len_utf8(); + } + for _ in chunk.invalid() { + out(s.get(at..at + 1).unwrap_or_default(), None); + at += 1; + } + } + } + Unicode::Utf32 => { + for b in s.as_chunks::<4>().0 { + out(b.as_slice(), char::from_u32(u32::from_be_bytes(*b))); + } + } + } +} + +/// Predefined CMap `name` among those VectorCraft carries, leaving out the Identity CMaps, whose +/// codes are CIDs of no known character collection. +fn predefined(name: &str) -> Option> { + match CMapName::from_bytes(name.as_bytes()) { + CMapName::Custom(_) | CMapName::IdentityH | CMapName::IdentityV => None, + name => Some(name), + } +} + +/// Adobe's predefined CMaps that VectorCraft doesn't carry, by name without `-H` or `-V` +/// (): the nearest carried CMap with the same +/// code space, and whether each byte of a row-and-cell code gets its high bit set first (the EUC +/// form of the same code; `GB-H`, `CNS1-H` and `KSC-H` have no one-byte codes, their code space +/// is `<2121>` to `<7E7E>`); `None` for those no carried CMap reads. +fn stand_in(stem: &str) -> Option> { + Some(match stem { + "RKSJ" | "78-RKSJ" | "78ms-RKSJ" => Some(("90ms-RKSJ-H", false)), + "78-EUC" => Some(("EUC-H", false)), + "78" | "Add" | "Ext" | "NWP" => Some(("H", false)), + "GB" => Some(("GB-EUC-H", true)), + "CNS1" => Some(("CNS-EUC-H", true)), + "KSC" => Some(("KSC-EUC-H", true)), + "B5" => Some(("ETen-B5-H", false)), + "ETHK-B5" | "HKdla-B5" | "HKdlb-B5" | "HKgccs-B5" | "HKm314-B5" | "HKm471-B5" => Some(("HKscs-B5-H", false)), + "GBT" | "GBT-EUC" | "GBTpc-EUC" | "CNS2" | "KSC-Johab" => None, + _ => return None, + }) +} + +/// Predefined CMap `cmap`'s codes to CIDs, and its character collection's CID → Unicode CMap. A +/// vertical CMap's codes are read with its horizontal CMap when VectorCraft carries that: the two +/// differ only in the CIDs of vertical glyph forms. A CMap VectorCraft doesn't carry is read with +/// its [`stand_in`]. +fn cid_codes(cmap: &str) -> Option { + let read = |name: &str| CMap::parse(load_embedded(predefined(name)?)?, load_embedded); + let horizontal = cmap.strip_suffix('V').map(|stem| format!("{stem}H")); + let stem = cmap.strip_suffix("-H").or_else(|| cmap.strip_suffix("-V")); + let (codes, high_bit) = horizontal.iter().map(String::as_str).chain([cmap]).find_map(|n| Some((read(n)?, false))).or_else(|| { + let (name, high_bit) = stand_in(stem?).flatten()?; + Some((read(name)?, high_bit)) + })?; + let table = codes.metadata().character_collection.as_ref()?.family.ucs2_cmap()?; + let unicode = CMap::parse(load_embedded(table)?, load_embedded)?; + // A row-and-cell code read in its EUC form falls in the EUC CMap's code space. + let space = if high_bit { stand_in(stem?).flatten().and_then(|(name, _)| code_space(name)) } else { code_space(cmap) }; + Some(CMapCodes::Cids { codes: Box::new(codes), unicode: Box::new(unicode), high_bit, space }) +} + +/// The code space of predefined CMap `cmap`, as Adobe's CMap files give it +/// (); a CMap's vertical form has its +/// horizontal form's. `None` for a CMap not listed here. +fn code_space(cmap: &str) -> Option { + const RKSJ: CodeSpace = &[(b"\x00", b"\x80"), (b"\xa0", b"\xdf"), (b"\x81\x40", b"\x9f\xfc"), (b"\xe0\x40", b"\xfc\xfc")]; + const RKSJ_MAC: CodeSpace = &[(b"\x00", b"\x80"), (b"\xa0", b"\xdf"), (b"\xfd", b"\xff"), (b"\x81\x40", b"\x9f\xfc"), (b"\xe0\x40", b"\xfc\xfc")]; + const EUC_JP: CodeSpace = &[(b"\x00", b"\x80"), (b"\x8e\xa0", b"\x8e\xdf"), (b"\xa1\xa1", b"\xfe\xfe")]; + const ROW_CELL: CodeSpace = &[(b"\x21\x21", b"\x7e\x7e")]; + const EUC: CodeSpace = &[(b"\x00", b"\x80"), (b"\xa1\xa1", b"\xfe\xfe")]; + const GB_PC: CodeSpace = &[(b"\x00", b"\x80"), (b"\xfd", b"\xff"), (b"\xa1\xa1", b"\xfc\xfe")]; + const GBK: CodeSpace = &[(b"\x00", b"\x80"), (b"\x81\x40", b"\xfe\xfe")]; + const GBK2K: CodeSpace = &[(b"\x00", b"\x7f"), (b"\x81\x40", b"\xfe\xfe"), (b"\x81\x30\x81\x30", b"\xfe\x39\xfe\x39")]; + const B5_PC: CodeSpace = &[(b"\x00", b"\x80"), (b"\xfd", b"\xff"), (b"\xa1\x40", b"\xfc\xfe")]; + const B5: CodeSpace = &[(b"\x00", b"\x80"), (b"\xa1\x40", b"\xfe\xfe")]; + const HKSCS: CodeSpace = &[(b"\x00", b"\x80"), (b"\x87\x40", b"\xfe\xfe")]; + const HKDLB: CodeSpace = &[(b"\x00", b"\x80"), (b"\x8e\x40", b"\xfe\xfe")]; + const HKGCCS: CodeSpace = &[(b"\x00", b"\x80"), (b"\x8a\x40", b"\xfe\xfe")]; + const CNS_EUC: CodeSpace = &[(b"\x00", b"\x80"), (b"\xa1\xa1", b"\xfe\xfe"), (b"\x8e\xa1\xa1\xa1", b"\x8e\xa3\xfe\xfe")]; + const KSC_PC: CodeSpace = &[(b"\x00", b"\x84"), (b"\xfe", b"\xff"), (b"\xa1\x41", b"\xfd\xfe")]; + const UHC: CodeSpace = &[(b"\x00", b"\x80"), (b"\x81\x41", b"\xfe\xfe")]; + let stem = match cmap { + "H" | "V" => "", + _ => cmap.strip_suffix("-H").or_else(|| cmap.strip_suffix("-V"))?, + }; + let stem = stem.strip_suffix("-HW").unwrap_or(stem); + Some(match stem { + "83pv-RKSJ" | "90pv-RKSJ" => RKSJ_MAC, + _ if stem.ends_with("RKSJ") => RKSJ, + "EUC" | "78-EUC" => EUC_JP, + "" | "78" | "Add" | "Ext" | "NWP" | "GBT" | "CNS2" => ROW_CELL, + "GB-EUC" | "GBT-EUC" | "KSC-EUC" => EUC, + "GBpc-EUC" | "GBTpc-EUC" => GB_PC, + "GBK-EUC" | "GBKp-EUC" => GBK, + "GBK2K" => GBK2K, + "B5pc" => B5_PC, + "B5" | "ETen-B5" | "ETenms-B5" | "HKdla-B5" | "HKm314-B5" | "HKm471-B5" => B5, + "HKscs-B5" | "ETHK-B5" => HKSCS, + "HKdlb-B5" => HKDLB, + "HKgccs-B5" => HKGCCS, + "CNS-EUC" => CNS_EUC, + "KSCpc-EUC" => KSC_PC, + "KSCms-UHC" => UHC, + _ => return None, + }) +} + +/// The length of the code string `bytes` starts with: the length of the code space range whose +/// lowest and highest codes hold each of its bytes between them. `None` when no range does. +fn code_len(space: CodeSpace, bytes: &[u8]) -> Option { + space + .iter() + .filter(|(lo, hi)| bytes.get(..lo.len()).is_some_and(|b| b.iter().zip(lo.iter().zip(hi.iter())).all(|(b, (lo, hi))| (lo..=hi).contains(&b)))) + .map(|(lo, _)| lo.len()) + .min() + .and_then(|len| u8::try_from(len).ok()) +} + +/// Whether `cmap` names a predefined CMap: a predefined Unicode CMap ([`unicode_cmap`]), one of the +/// predefined CMaps VectorCraft carries ([`predefined`]) or one of the others ([`stand_in`]), in +/// its horizontal (`-H`) or vertical (`-V`) form. The Identity CMaps are not among them. +pub(super) fn known(cmap: &str) -> bool { + let vertical_of_predefined = || cmap.strip_suffix('V').is_some_and(|stem| predefined(&format!("{stem}H")).is_some()); + let other = || cmap.strip_suffix("-H").or_else(|| cmap.strip_suffix("-V")).is_some_and(|stem| stand_in(stem).is_some()); + unicode_cmap(cmap).is_some() || predefined(cmap).is_some() || vertical_of_predefined() || other() +} + +/// The codes of string `bytes` in predefined CMap `cmap` when its mappings can't be read, each +/// standing for no character: as long as the code space range it falls in ([`code_space`]; a byte +/// that starts no code is a code of its own, as in the row-and-cell code space of `GBT-H` and +/// `CNS2-H`), or two bytes when the code space isn't listed. A 0x0D or 0x09 byte is always a code +/// of its own. +pub(super) fn unread_codes(cmap: &str, bytes: &[u8]) -> Decoded { + let space = code_space(cmap); + let mut out = Decoded::default(); + let mut at = 0; + while let Some(rest) = bytes.get(at..).filter(|r| !r.is_empty()) { + let len = match space { + // A 0x0D or 0x09 byte is a code of its own, as [`CMapCodes::each_code`] reads it. + _ if rest.first().and_then(|&b| control(b)).is_some() => 1, + Some(space) => code_len(space, rest).map_or(1, usize::from), + None => 2, + }; + let code = rest.get(..len).unwrap_or(rest); + out.push(code.iter().fold(0u32, |c, &b| c << 8 | u32::from(b)), None); + at += code.len(); + } + out +} + +/// Whether predefined CMap `cmap` is a vertical CMap (`-V`, or the row-and-cell `V`). +pub(super) fn vertical(cmap: &str) -> bool { + cmap == "V" || cmap.ends_with("-V") +} + +/// A composite font's name `base-CMap`: the base font's name and its CMap's name, when that is a +/// predefined CMap ([`known`]). A name ending in an Identity CMap is not read as one, nor is one +/// that ends in an unknown CMap name with an encoding part (`UniFoo-UTF8-H`), which would otherwise +/// end in `H`. +pub(super) fn composite_font(name: &str) -> Option<(&str, &str)> { + if !(name.ends_with("-H") || name.ends_with("-V")) { + return None; + } + // The longest CMap name first: `83pv-RKSJ-H` before `H`. + // No predefined CMap name is longer than 32 bytes. + for (at, _) in name.match_indices('-').filter(|(at, _)| name.len() - at <= 33) { + let (Some(base), Some(cmap)) = (name.get(..at).filter(|b| !b.is_empty()), name.get(at + 1..)) else { continue }; + if matches!(cmap, "Identity-H" | "Identity-V") { + return None; + } + let encoding_part = + base.rsplit('-').next().is_some_and(|part| ["UCS2", "UTF8", "UTF16", "UTF32", "HW", "EUC", "RKSJ", "B5", "UHC", "Johab"].contains(&part)); + if matches!(cmap, "H" | "V") && encoding_part { + return None; + } + if known(cmap) { + return Some((base, cmap)); + } + } + None +} diff --git a/crates/eps/src/import/tests.rs b/crates/eps/src/import/tests.rs index 6a1df810bc..4709a3c5bf 100644 --- a/crates/eps/src/import/tests.rs +++ b/crates/eps/src/import/tests.rs @@ -7,6 +7,9 @@ use vectorcraft_color::{Color, GradientKind, Paint}; use vectorcraft_doc::{AppearanceItem, ColorMode, Document, LineCap, LineJoin, Node, NodeKind}; use vectorcraft_geom::{Point, Rect}; +use crate::import::graphics::{GState, Out, tilings_compared}; +use crate::import::interp::Interp; +use crate::import::obj::Obj; use crate::import::{Dsc, import}; use crate::{EpsOptions, Level, Preview, Raster}; @@ -369,12 +372,19 @@ fn dash_patterns_hold_at_most_65535_entries() { /// Saved and copied graphics states share the dash pattern, and `setdash`, `currentdash` and /// each stroke count the entries they read or copy against the budgets. Under a pattern of -/// 65,535 entries, 4,000,000 passes of `gsave grestore` and 2,000,000 passes of -/// `gstate currentgstate setgstate` finish, and loops of `setdash`, `currentdash` and `strokepath` -/// run out of a budget. +/// 65,535 entries, the states that `gsave`, `grestore`, `gstate`, `currentgstate` and `setgstate` +/// save, make or set hold that one pattern, 4,000,000 passes of `gsave grestore` and 2,000,000 +/// passes of `gstate currentgstate setgstate` finish, and loops of `setdash`, `currentdash` and +/// `strokepath` run out of a budget. #[test] fn work_on_the_longest_dash_pattern_ends_soon() { let dash = "0 0 10 10 rectfill /a 65535 array def 0 1 65534 { a exch 1 put } for a 0 setdash"; + let shared = run_looking(&format!("{dash} gsave gsave grestore gstate gstate currentgstate dup setgstate"), |it| { + let Some(saved) = it.saved.last().map(|g| g.dash.clone()) else { return false }; + let made: Vec<_> = it.stack.iter().filter_map(|o| if let Obj::GState(g) = o { Some(g.dash.clone()) } else { None }).collect(); + saved.len() == 65_535 && made.len() == 2 && made.iter().chain([&it.g.dash]).all(|m| std::rc::Rc::ptr_eq(m, &saved)) + }); + assert!(shared); for body in ["4000000 { gsave grestore } repeat", "2000000 { gstate currentgstate setgstate } repeat"] { let r = read_soon(&format!("{dash} {body} 20 20 10 10 rectfill")); assert_eq!(objects(&r.document).len(), 2, "{body}: {:?}", r.warnings); @@ -530,13 +540,15 @@ fn non_finite_arithmetic_is_undefinedresult() { assert!(!objects(&r.document).is_empty(), "{:?}", r.warnings); } -/// Tiling patterns and spot inks are found again through a hash of what tells them apart, so a -/// program that makes 200,000 patterns and 200,001 inks reads within [`read_soon`]'s 20 seconds. -/// Patterns are named Pattern 1, Pattern 2 and so on in the order they are made. A pattern made -/// again from its prototype is the same pattern, and so is an uncolored pattern set again in a -/// color it was set in before. +/// Tiling patterns are found again through a hash of what tells them apart. A program that sets +/// 200,000 different patterns and also sets 200,001 spot inks reads them all, and its 200,000 +/// pattern lookups compare at most 200,000 earlier patterns in all; going through every pattern +/// made so far would compare about 2 × 10^10. The test does not count or time the spot ink +/// lookups. Patterns are named Pattern 1, Pattern 2 and so on in the order they are made. A +/// pattern made again from its prototype is the same pattern, and so is an uncolored pattern set +/// again in a color it was set in before. #[test] -fn many_tiling_patterns_and_spot_inks_read_in_linear_time() { +fn many_tiling_patterns_are_found_again_through_a_hash() { let r = read( "/pp { pop 0 0 1 1 rectfill } def \ /a << /PatternType 1 /PaintType 1 /TilingType 1 /BBox [0 0 1 1] /XStep 2 /YStep 2 /PaintProc /pp load >> def \ @@ -560,7 +572,7 @@ fn many_tiling_patterns_and_spot_inks_read_in_linear_time() { assert!(names.iter().all(|n| d.swatch(n).is_some_and(|s| matches!(s.paint, Paint::Pattern { .. })))); // 100,000 patterns whose cells differ, an uncolored pattern in 100,000 tints of an ink that is // white at every tint (only the tint tells those patterns apart), and 200,000 more inks. - let r = read_soon( + let (r, compared) = read_counting_tilings( "0 1 99999 { /i exch def << /PatternType 1 /PaintType 1 /TilingType 1 /BBox [0 0 1 1] /XStep i 2 add /YStep 1 \ /PaintProc { pop 0 0 1 1 rectfill } >> matrix makepattern setpattern } for \ [/Separation (Spot) /DeviceGray { pop 1 }] setcolorspace \ @@ -568,6 +580,7 @@ fn many_tiling_patterns_and_spot_inks_read_in_linear_time() { matrix makepattern def 0 1 99999 { 100000 div p setpattern } for \ 0 1 199999 { /i exch def [/Separation i 8 string cvs /DeviceGray {}] setcolorspace } for 0 0 1 1 rectfill", ); + assert!(compared <= 200_000, "{compared} patterns compared"); let d = &r.document; assert_eq!(d.patterns.len(), 200_000); assert!(d.patterns.iter().enumerate().all(|(i, p)| p.name == format!("Pattern {}", i + 1))); @@ -1112,19 +1125,51 @@ fn hostile_executable_files_and_type_loops_are_refused() { blue("currentfile cvx exec currentfile flushfile 0 0 1 setrgbcolor"); } -/// Reads `body` as [`read`] does, on a thread of its own, and fails the test when reading takes -/// more than 20 s. +/// How long [`read_soon`] and [`read_counting_tilings`] wait, in seconds: a guard against a read +/// that never ends. The budgets, limits and counts each test names decide what it checks. +const NEVER_ENDS: u64 = 300; + +/// Reads `body` as [`read`] does, on a thread of its own, and fails the test when reading has not +/// finished after [`NEVER_ENDS`] seconds. fn read_soon(body: &str) -> crate::Imported { - read_within(body, 20) + read_within(body, NEVER_ENDS) } /// Reads `body` as [`read`] does, on a thread of its own, and fails the test when reading takes /// more than `secs` seconds. fn read_within(body: &str, secs: u64) -> crate::Imported { + read_counting(body, secs).0 +} + +/// [`read_soon`], with how many patterns the tiling pattern lookups compared while reading. +fn read_counting_tilings(body: &str) -> (crate::Imported, u64) { + read_counting(body, NEVER_ENDS) +} + +/// [`read_within`], with how many patterns the tiling pattern lookups compared while reading. +fn read_counting(body: &str, secs: u64) -> (crate::Imported, u64) { let (tx, rx) = std::sync::mpsc::channel(); let ps = eps(body); - std::thread::spawn(move || tx.send(import(&ps)).ok()); - rx.recv_timeout(std::time::Duration::from_secs(secs)).unwrap_or_else(|_| panic!("reading {body} did not finish")).unwrap() + std::thread::spawn(move || tx.send((import(&ps), tilings_compared())).ok()); + let (read, compared) = rx.recv_timeout(std::time::Duration::from_secs(secs)).unwrap_or_else(|_| panic!("reading {body} did not finish")); + (read.unwrap(), compared) +} + +/// Runs the program of `body` in an interpreter of its own on the 100 × 100 page of [`eps`]'s +/// bounding box, and returns what `look` finds in the interpreter when the program has ended. It +/// does not read the file's comments or make a document. The test fails when the program stops on +/// an error. +fn run_looking(body: &str, look: fn(&Interp) -> T) -> T { + let file = eps(body); + let ps = super::program(&file).unwrap(); + let mut doc = Document::new(100.0, 100.0); + doc.layers.clear(); + let page = vectorcraft_geom::Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 100.0]); + let mut it = Interp::new(ps, GState::default(), Out::new(doc, page, Rect::new(0.0, 0.0, 100.0, 100.0))); + assert!(it.run().is_ok(), "running {body} failed"); + let found = look(&it); + it.release(); + found } /// Reads `body` after a square: the square stays, and the program runs out of the operation diff --git a/crates/eps/src/import/tests_cid.rs b/crates/eps/src/import/tests_cid.rs index 2b01b2b4f2..8350cd514b 100644 --- a/crates/eps/src/import/tests_cid.rs +++ b/crates/eps/src/import/tests_cid.rs @@ -403,6 +403,300 @@ fn named_cidfonts_over_unicode_cmaps_set_their_characters_as_type() { check("/Ryumin-Light-UniJIS-UCS2-H findfont 20 scalefont setfont <00410042> stringwidth pop dup 5 gt exch 40 lt and"); } +/// The text objects of an import. +fn texts(r: &crate::Imported) -> Vec { + all(&r.document) + .iter() + .filter_map(|n| match &n.kind { + NodeKind::Text(t) => Some((**t).clone()), + _ => None, + }) + .collect() +} + +/// A CID-keyed font over one of the other predefined CMaps (Shift-JIS, EUC, GBK, Big Five, UHC, +/// JIS row and cell: ), the file defining +/// neither, its CIDFont only named: the codes are read by that CMap and its character +/// collection's CIDs to Unicode, and set as type in the font of the CIDFont's name, whether +/// found as `CIDFont-CMap` or composed. Codes the CMap doesn't map and control codes are left out. +#[test] +fn named_cidfonts_over_predefined_cmaps_set_their_characters_as_type() { + let cases: &[(&str, &str, &str)] = &[ + // 日 is 0x93FA and 本 0x967B in Shift-JIS. + ("83pv-RKSJ-H", "93fa967b41", "日本A"), + ("90ms-RKSJ-H", "93fa", "日"), + ("EUC-H", "c6fc", "日"), + ("GBK-EUC-H", "d6d0", "中"), + ("B5pc-H", "a4a4", "中"), + ("ETen-B5-H", "a4a4", "中"), + ("KSCms-UHC-H", "c7d1", "한"), + // A CMap read with the nearest carried one: GB 2312 row and cell in EUC form, 中 0x5650. + ("GB-H", "5650", "中"), + // 0x8540 maps to no CID, 0xFD is in no code space range, 0x0D is a control code. + ("90ms-RKSJ-H", "854093fa41fd0d42", "日AB"), + ]; + for (cmap, hex, want) in cases { + let r = super::tests::read(&format!("/Ryumin-Light-{cmap} findfont 20 scalefont setfont 10 20 moveto <{hex}> show")); + assert!(super::tests::program_warnings(&r.warnings).is_empty(), "{cmap}: {:?}", r.warnings); + let t = texts(&r); + assert_eq!(t.iter().map(|t| t.plain_text()).collect::>(), [*want], "{cmap}"); + let style = &t[0].runs[0].style; + assert_eq!((style.font_family.as_str(), style.font_style.as_str(), style.size), ("Ryumin", "Light", 20.0), "{cmap}"); + assert!(!t[0].vertical, "{cmap}"); + } + let r = super::tests::read("/X /GBK-EUC-H [/NotInFile] composefont 20 scalefont setfont 10 20 moveto show"); + assert_eq!(texts(&r).iter().map(|t| t.plain_text()).collect::(), "中A"); + // JIS row and cell: 日 is 0x467C. + let r = super::tests::read("/X /H [/Ryumin-Light] composefont 20 scalefont setfont 10 20 moveto <467c> show"); + assert_eq!(texts(&r).iter().map(|t| t.plain_text()).collect::(), "日"); + // The point moves past the type, along the line. + check("/Ryumin-Light-90ms-RKSJ-H findfont 20 scalefont setfont <93fa967b> stringwidth abs 0.01 lt exch dup 5 gt exch 60 lt and and"); +} + +/// Type in a CID-keyed font over a predefined CMap, its CIDFont only named, shown with `ashow`, +/// `widthshow` (matching a code by its value) and `xshow`, is spaced as the operator says: the +/// point moves that far, and the characters' tracking makes up the difference, as for type in a +/// font found by name. Over a vertical CMap the extra space runs down the column. +#[test] +fn named_cidfonts_over_predefined_cmaps_take_the_show_operators_spacing() { + // Measured without painting. + let measured = |body: &str| check(&format!("gsave nulldevice {body} grestore")); + let set = "/Ryumin-Light-90ms-RKSJ-H findfont 20 scalefont setfont"; + // `ashow` adds 5 to each of the two codes. + measured(&format!( + "{set} 10 20 moveto <93fa967b> show currentpoint pop 10 20 moveto 5 0 <93fa967b> ashow currentpoint pop sub -10 sub abs 0.01 lt" + )); + let r = super::tests::read(&format!("{set} 10 20 moveto 5 0 <93fa967b> ashow")); + let t = texts(&r); + assert_eq!(t.iter().map(|t| t.plain_text()).collect::>(), ["日本"]); + assert!(t[0].runs.iter().all(|run| (run.style.tracking - 250.0).abs() < 0.5), "{:?}", t[0].runs); + // `widthshow` adds 7 to the space, code 0x20. + measured(&format!( + "{set} 10 20 moveto <93fa20967b> show currentpoint pop 10 20 moveto 7 0 32 <93fa20967b> widthshow currentpoint pop sub -7 sub abs 0.01 lt" + )); + // A row-and-cell code read in its EUC form keeps the value of the string's bytes: 中 0x5650. + let gb = "/STSong-Light-GB-H findfont 20 scalefont setfont"; + measured(&format!( + "{gb} 10 20 moveto <56505650> show currentpoint pop 10 20 moveto 7 0 16#5650 <56505650> widthshow currentpoint pop sub -14 sub abs 0.01 lt" + )); + // `awidthshow` adds 5 to each code and 7 more to the space. + measured(&format!( + "{set} 10 20 moveto <93fa20967b> show currentpoint pop 10 20 moveto 7 0 32 5 0 <93fa20967b> awidthshow currentpoint pop sub -22 sub abs 0.01 lt" + )); + // `xshow` moves 30 a code, `yshow` 10 up a code, `xyshow` both. + measured(&format!("{set} 10 20 moveto <93fa967b> [30 30] xshow currentpoint pop 70 sub abs 0.01 lt")); + measured(&format!("{set} 10 20 moveto <93fa967b> [10 10] yshow currentpoint 40 sub abs 0.01 lt exch 10 sub abs 0.01 lt and")); + measured(&format!("{set} 10 20 moveto <93fa967b> [30 10 30 10] xyshow currentpoint 40 sub abs 0.01 lt exch 70 sub abs 0.01 lt and")); + // `kshow` runs its procedure between each two codes: it moves the point 100 more here. The + // current font is restored when the procedure completes (PLRM 3rd ed., `kshow`), so a font it + // sets doesn't stay current, here or for a font found by name. + measured(&format!( + "{set} 10 20 moveto <93fa967b> show currentpoint 10 20 moveto {{pop pop 100 0 rmoveto}} <93fa967b> kshow currentpoint \ + 3 -1 roll sub abs 0.01 lt 3 1 roll sub -100 sub abs 0.01 lt and" + )); + measured(&format!( + "{set} 10 20 moveto {{pop pop /Helvetica findfont 10 scalefont setfont}} <93fa967b> kshow currentfont /FontName get /Ryumin-Light-90ms-RKSJ-H eq" + )); + measured( + "/Helvetica findfont 20 scalefont setfont 10 20 moveto {pop pop /Courier findfont 10 scalefont setfont} (AB) kshow currentfont /FontName get /Helvetica eq", + ); + // Each procedure sees the font the file set as current, also after an earlier one set another. + measured(&format!("{set} 10 20 moveto {{pop pop currentfont /FontName get /seen exch def}} <93fa967b> kshow seen /Ryumin-Light-90ms-RKSJ-H eq")); + measured(&format!( + "{set} 10 20 moveto /n 0 def {{pop pop /n n 1 add def n 1 eq {{/Helvetica findfont 10 scalefont setfont}} {{currentfont /FontName get /seen exch def}} ifelse}} \ + <93fa967b41> kshow seen /Ryumin-Light-90ms-RKSJ-H eq" + )); + // A `kshow` the procedure runs in a font it set sees that font. + measured(&format!( + "{set} 10 20 moveto {{pop pop /Helvetica findfont 10 scalefont setfont {{pop pop currentfont /FontName get /seen exch def}} (AB) kshow}} \ + <93fa967b> kshow seen /Helvetica eq" + )); + // The procedure gets the two codes' values (left on the stack here). + measured(&format!( + "{set} 10 20 moveto [ {{}} <93fa967b41> kshow ] dup length 4 eq exch aload pop 65 eq exch 16#967b eq and exch 16#967b eq and exch 16#93fa eq and and" + )); + // Down the column: `ashow`'s 5 down each code. + let set = "/Ryumin-Light-90ms-RKSJ-V findfont 20 scalefont setfont"; + measured(&format!( + "{set} 10 200 moveto <93fa967b> show currentpoint exch pop 10 200 moveto 0 -5 <93fa967b> ashow currentpoint exch pop sub 10 sub abs 0.01 lt" + )); + let r = super::tests::read(&format!("{set} 10 200 moveto 0 -5 <93fa967b> ashow")); + let t = texts(&r); + assert_eq!(t.iter().map(|t| t.plain_text()).collect::(), "日本"); + assert!(t.iter().all(|t| t.vertical), "{t:?}"); +} + +/// A CID-keyed font over a vertical predefined CMap (`-V`), the file defining neither, its CIDFont +/// only named: the type is a vertical column, and the point moves down it, not along a line. +#[test] +fn named_cidfonts_over_vertical_cmaps_set_vertical_type() { + for (cmap, hex) in [("90ms-RKSJ-V", "93fa967b"), ("UniJIS-UCS2-V", "65e5672c")] { + let r = super::tests::read(&format!("/Ryumin-Light-{cmap} findfont 20 scalefont setfont 10 20 moveto <{hex}> show")); + let t = texts(&r); + assert_eq!(t.iter().map(|t| t.plain_text()).collect::>(), ["日本"], "{cmap}: {:?}", r.warnings); + assert!(t[0].vertical, "{cmap}"); + check(&format!("/Ryumin-Light-{cmap} findfont 20 scalefont setfont <{hex}> stringwidth dup -60 gt exch -5 lt and exch abs 0.01 lt and")); + } +} + +/// Down a column each code of a CID-keyed font over a vertical predefined CMap moves the point one +/// em, the default vertical displacement (PDF Reference 1.7, §5.6.3, `DW2`), also two digits that +/// vertical type sets side by side in one em: `show` and `stringwidth` move the point as far as +/// showing the codes one at a time. +#[test] +fn codes_down_a_column_each_move_the_point_one_em() { + // Measured without painting. + let set = "gsave nulldevice /Ryumin-Light-90ms-RKSJ-V findfont 20 scalefont setfont"; + check(&format!("{set} (12) stringwidth grestore -40 sub abs 0.01 lt exch abs 0.01 lt and")); + check(&format!("{set} 10 100 moveto (12) show currentpoint grestore 60 sub abs 0.01 lt exch 10 sub abs 0.01 lt and")); + check(&format!( + "{set} 10 100 moveto (1) show (2) show currentpoint 10 100 moveto (12) show currentpoint grestore \ + 3 -1 roll sub abs 0.01 lt 3 1 roll sub abs 0.01 lt and" + )); +} + +/// Type in a CID-keyed font over a predefined CMap is set the same way by `show` and by the show +/// operators that space it: characters the font would join in a ligature (`fi` in the bundled +/// Source Serif 4) are set without the ligature, and the point moves as far. +#[test] +fn named_cid_type_is_set_alike_by_every_show_operator() { + let set = "/SourceSerif4-Regular-UniJIS-UCS2-H findfont 50 scalefont setfont 10 20 moveto"; + let features = |show: &str| { + let r = super::tests::read(&format!("{set} <00660069> {show}")); + let t = texts(&r); + assert_eq!(t.iter().map(|t| t.plain_text()).collect::>(), ["fi"], "{show}"); + // Spacing that differs from the advances splits the type into runs of the same features. + let mut features = t[0].runs.iter().map(|r| r.style.features.clone()).collect::>(); + features.dedup(); + features + }; + let plain = features("show"); + for show in ["0 0 3 -1 roll ashow", "0 0 32 4 -1 roll widthshow", "0 0 32 0 0 6 -1 roll awidthshow", "[25 25] xshow", "{pop pop} exch kshow"] { + assert_eq!(plain, features(show), "{show}"); + } + assert!(plain.iter().all(|f| f.iter().any(|f| f == "-liga")), "{plain:?}"); + check(&format!( + "gsave nulldevice {set} <00660069> stringwidth 10 20 moveto 0 0 <00660069> ashow currentpoint grestore \ + 20 sub 3 -1 roll sub abs 0.01 lt 3 1 roll 10 sub sub abs 0.01 lt and" + )); +} + +/// `charpath`, `cshow` and `glyphshow` in a CID-keyed font over a predefined CMap, its CIDFont only +/// named: `charpath` adds the outlines of the characters the codes stand for and moves the point +/// as `show` does; `cshow`'s procedure gets each code's last byte with its width and runs with the +/// CIDFont current, a show in it setting the code's character; `glyphshow` sets the named +/// character itself. +#[test] +fn named_cid_type_in_charpath_cshow_and_glyphshow() { + let set = "/Ryumin-Light-90ms-RKSJ-H findfont 20 scalefont setfont"; + let r = super::tests::read(&format!("{set} 10 20 moveto <4142> true charpath fill")); + assert!(texts(&r).is_empty(), "{:?}", all(&r.document)); + assert!(all(&r.document).iter().any(|n| matches!(n.kind, NodeKind::Path { .. })), "{:?}", all(&r.document)); + check(&format!( + "gsave nulldevice {set} 10 20 moveto <93fa41> show currentpoint newpath 10 20 moveto <93fa41> false charpath currentpoint grestore \ + 3 -1 roll sub abs 0.01 lt 3 1 roll sub abs 0.01 lt and" + )); + // Down a column a code that stands for no character (0xFD) moves the outlines one em, as it + // moves the type `show` sets. + let top = |s: &str| format!("newpath 10 100 moveto <{s}> false charpath pathbbox 4 1 roll pop pop pop"); + check(&format!( + "gsave nulldevice /Ryumin-Light-90ms-RKSJ-V findfont 20 scalefont setfont {} {} grestore sub -20 sub abs 0.5 lt", + top("fd41"), + top("41") + )); + // The procedure leaves each code's last byte (PLRM 3rd ed., `cshow`): 日 (0x93FA), then A. + check(&format!("{set} [ {{pop pop}} <93fa41> cshow ] dup length 2 eq exch dup 0 get 16#fa eq exch 1 get 65 eq and and")); + check(&format!("{set} 0 {{pop exch pop add}} <93fa967b41> cshow <93fa967b41> stringwidth pop sub abs 0.01 lt")); + // While the procedure runs, the current font is the CIDFont and `rootfont` gives the composite + // font (PLRM 3rd ed., `cshow` and `rootfont`); the current font is restored after each run, + // also when the procedure sets another. + check(&format!( + "{set} {{pop pop pop currentfont dup /FontType get /t exch def /CIDFontName get /seen exch def}} <93fa> cshow \ + seen /Ryumin-Light eq t 9 eq and" + )); + check(&format!("{set} {{pop pop pop rootfont /FontName get /seen exch def}} <93fa> cshow seen /Ryumin-Light-90ms-RKSJ-H eq")); + check(&format!( + "{set} /n 0 def {{pop pop pop /n n 1 add def n 1 eq {{/Helvetica findfont 10 scalefont setfont rootfont /FontName get /r exch def}} \ + {{currentfont /CIDFontName get /seen exch def}} ifelse}} <93fa41> cshow seen /Ryumin-Light eq r /Helvetica eq and \ + currentfont /FontName get /Ryumin-Light-90ms-RKSJ-H eq and" + )); + // A show in the CIDFont shows the character of the code the procedure was given, the string + // holding its last byte, and moves the point as far as `show` does. Any other string, an + // empty one included, is a `rangecheck` error. + for s in ["()", "(AB)", "<41>"] { + check(&format!("gsave nulldevice {set} 10 20 moveto {{{{pop pop pop {s} show}} <93fa> cshow}} stopped grestore")); + } + check(&format!("gsave nulldevice {set} 10 20 moveto {{{{pop pop pop show}} <93fa> cshow}} stopped not grestore")); + let r = super::tests::read(&format!("{set} 10 20 moveto {{pop pop ( ) dup 0 4 -1 roll put show}} <93fa967b> cshow")); + assert_eq!(texts(&r).iter().map(|t| t.plain_text()).collect::(), "日本"); + check(&format!( + "gsave nulldevice {set} 10 20 moveto <93fa967b> show currentpoint 10 20 moveto {{pop pop ( ) dup 0 4 -1 roll put show}} <93fa967b> cshow \ + currentpoint grestore 3 -1 roll sub abs 0.01 lt 3 1 roll sub abs 0.01 lt and" + )); + let r = super::tests::read(&format!("{set} 10 20 moveto /uni00E9 glyphshow")); + assert_eq!(texts(&r).iter().map(|t| t.plain_text()).collect::>(), ["é"]); +} + +/// A font name ending in the row-and-cell CMap `H` or `V` stays a font of the whole name, its +/// strings read byte by byte, unless the part before the CMap names a CIDFont the file defines (or +/// an installed face that covers Japanese). Type in a predefined CMap whose mappings aren't +/// available is left out with a warning, each code moving the point one em, and a long string in a +/// CID-keyed font over a predefined CMap shown in a loop runs out of the budget. +#[test] +fn latin_names_ending_in_h_and_cmaps_that_cannot_be_read() { + for (font, family, style) in [("Futura-H", "Futura", "H"), ("Foo-Bold-H", "Foo", "Bold-H"), ("Foo-Condensed-V", "Foo", "Condensed-V")] { + let r = super::tests::read(&format!("/{font} findfont 20 scalefont setfont 10 20 moveto (AB) show")); + let t = texts(&r); + assert_eq!(t.iter().map(|t| t.plain_text()).collect::>(), ["AB"], "{font}"); + let s = &t[0].runs[0].style; + assert_eq!((s.font_family.as_str(), s.font_style.as_str()), (family, style), "{font}"); + assert!(!t[0].vertical, "{font}"); + } + // The file defines the CIDFont `Ryumin-Light`, as a resource or as a font: `Ryumin-Light-H` is + // it over the CMap `H`. + // A CIDFont name without a hyphen too, when the file defines it. + let cid_font = |name: &str| format!("/{name} << /CIDFontName /{name} /CIDFontType 0 /FontType 9 /FontMatrix [0.001 0 0 0.001 0 0] >>"); + let defines = [ + format!("{} /CIDFont defineresource pop /Ryumin-Light-H", cid_font("Ryumin-Light")), + format!("{} definefont pop /Ryumin-Light-H", cid_font("Ryumin-Light")), + format!("{} /CIDFont defineresource pop /Foo-H", cid_font("Foo")), + ]; + for define in defines { + let r = super::tests::read(&format!("{define} findfont 20 scalefont setfont 10 20 moveto <467c> show")); + assert_eq!(texts(&r).iter().map(|t| t.plain_text()).collect::>(), ["日"], "{define}: {:?}", r.warnings); + } + let r = super::tests::read("/Ryumin-Light-GBT-H findfont 20 scalefont setfont 10 20 moveto (AB) show 0 0 10 10 rectfill"); + assert!(texts(&r).is_empty(), "{:?}", all(&r.document)); + assert_eq!(super::tests::program_warnings(&r.warnings), [super::text::UNREAD_CMAP], "{:?}", r.warnings); + // Two two-byte codes: two ems along the line, or down the column (a square drawn when the + // point moved that far). + for cond in [ + "/Ryumin-Light-GBT-H findfont 20 scalefont setfont <21212121> stringwidth abs 0.01 lt exch 40 sub abs 0.01 lt and", + "/Ryumin-Light-GBT-V findfont 20 scalefont setfont 10 100 moveto <21212121> show currentpoint 60 sub abs 0.01 lt exch 10 sub abs 0.01 lt and", + // A tab is a code of its own: three codes. + "/Ryumin-Light-GBT-H findfont 20 scalefont setfont <09092121> stringwidth abs 0.01 lt exch 60 sub abs 0.01 lt and", + // A byte that starts no row-and-cell code is a code of its own, also before a tab: three. + "/Ryumin-Light-GBT-H findfont 20 scalefont setfont <21092121> stringwidth abs 0.01 lt exch 60 sub abs 0.01 lt and", + ] { + let r = super::tests::read(&format!("{cond} {{ 0 0 10 10 rectfill }} if")); + assert!(all(&r.document).iter().any(|n| matches!(n.kind, NodeKind::Path { .. })), "{cond}"); + } + super::tests::runs_out_of_budget("/Ryumin-Light-90ms-RKSJ-H findfont 20 scalefont setfont { 100000 string stringwidth pop pop } loop"); +} + +/// A string in the file, in a CID-keyed font over a predefined CMap, too long to decode within the +/// memory budget stops the program with an error before it is decoded. +#[test] +fn huge_strings_over_predefined_cmaps_count_against_the_memory_budget() { + // Codes the CMap doesn't map, so nothing is laid out when the string is decoded. + let huge = "\u{1}".repeat(17 << 20); + let r = import(&super::tests::eps(&format!( + "0 0 10 10 rectfill /Ryumin-Light-90ms-RKSJ-H findfont 20 scalefont setfont 10 20 moveto ({huge}) stringwidth" + ))) + .unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("too much memory")), "{:?}", r.warnings); +} + /// A Type 2 CIDFont the file carries (its glyph space one unit an em), over a Unicode CMap the /// file doesn't define, sets its characters as type at the font's size, not a thousand times it. #[test] diff --git a/crates/eps/src/import/tests_fontnames.rs b/crates/eps/src/import/tests_fontnames.rs index d925905ee7..a2a8d45641 100644 --- a/crates/eps/src/import/tests_fontnames.rs +++ b/crates/eps/src/import/tests_fontnames.rs @@ -63,3 +63,37 @@ fn abbreviated_styles_in_postscript_names_are_spelled_out() { fn an_installed_face_of_the_postscript_name_names_the_font() { assert_eq!(crate::family_style("ABCDEF+SourceSans3-Semibold"), ("Source Sans 3".to_string(), "Semibold".to_string())); } + +/// The PostScript name and version of the face each `show` of a program that sets `fonts` in turn +/// draws its type in. +fn faces_shown(fonts: &[&str]) -> Vec<(String, String)> { + let body: String = fonts.iter().map(|f| format!("/{f} findfont 12 scalefont setfont 10 20 moveto (Hi) show\n")).collect(); + let eps = format!("%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n{body}showpage\n%%EOF\n"); + let r = import(eps.as_bytes()).unwrap(); + let mut faces = vec![]; + r.document.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + let face = FontDb::global().style_face(&t.runs[0].style).unwrap(); + faces.push((face.postscript_name(), face.version.clone())); + } + }); + faces +} + +/// Type a PostScript program sets is drawn in the installed face of exactly the font's PostScript +/// name, as type from a text document is: not another family spelled alike but for case and +/// punctuation, nor a face whose name differs only in case and loads first. +#[test] +fn shown_type_takes_the_face_of_its_exact_postscript_name() { + use vectorcraft_text::test_fonts::named_copy; + for (inter, names) in [ + (true, ("FUZZSHOW INK", "Regular", "Version 1.000", "FUZZSHOWINK-Regular")), + (false, ("Fuzzshow/Ink", "Regular", "Version 1.000", "FuzzshowInk")), + (true, ("CASESHOW INK", "Regular", "Version 1.000", "CASESHOWINK")), + (false, ("Caseshow Ink", "Regular", "Version 2.000", "CaseshowInk")), + ] { + assert_eq!(FontDb::global().add_font(named_copy(inter, names).unwrap()), 1, "{names:?}"); + } + let names: Vec = faces_shown(&["FuzzshowInk", "CaseshowInk", "CASESHOWINK"]).into_iter().map(|f| f.0).collect(); + assert_eq!(names, ["FuzzshowInk", "CaseshowInk", "CASESHOWINK"]); +} diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index 8f64280367..1f634b3744 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -3128,6 +3128,73 @@ fn type_from_the_text_document_takes_its_character_styles_attributes() { assert_eq!(style(2), (solid(Color::cmyk(0.0, 1.0, 0.0, 0.0)), Some(18.0)), "the run's own colour"); } +/// The PostScript name and version of the face that type from a text document whose font record is +/// `record` (in place of `/0 (Helvetica)`) is set in. +fn face_set_from(record: &str) -> (String, String) { + let doc = text_document(&[("Hamburg\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]).replacen("/0 (Helvetica)", record, 1); + let art = native_with_text(&(layer("Back", true, &square(10, 10)) + &layer("Spare", false, &text_object(0))), &doc); + let r = import(&eps(&page_square(10, 10), &art)).unwrap(); + let texts = text_of(&r.document.layers[1]); + assert_eq!(texts.len(), 1, "{record}: {:?}", r.warnings); + let face = vectorcraft_text::FontDb::global().style_face(&texts[0].runs[0].style).unwrap(); + (face.postscript_name(), face.version.clone()) +} + +/// Installs the copies of each font `copies` lists, the first of each loaded first. +fn install(copies: &[(bool, vectorcraft_text::test_fonts::CopyNames<'_>)]) { + for (inter, names) in copies { + let font = vectorcraft_text::test_fonts::named_copy(*inter, *names).unwrap(); + assert_eq!(vectorcraft_text::FontDb::global().add_font(font), 1, "{names:?}"); + } +} + +/// Type from the text document is set in the installed face of exactly the PostScript name its +/// font record gives, whatever other installed copies answer to that name too: one whose family +/// is spelled alike but for case and punctuation (`SAMPLE INK` beside `Sample/Ink`, PostScript name +/// `SampleInk`), one whose PostScript name differs only in case or punctuation (in its own family or +/// another), or another copy of the same family and style under another PostScript name (an older +/// build of the font: the type names its version). Those copies set the type at other widths. +#[test] +fn type_from_the_text_document_takes_the_face_of_its_exact_postscript_name() { + install(&[ + (true, ("FUZZTEST INK", "Regular", "Version 1.000", "FUZZTESTINK-Regular")), + (false, ("Fuzztest/Ink", "Regular", "Version 1.000", "FuzztestInk")), + (true, ("CASETEST INK", "Regular", "Version 1.000", "CASETESTINK")), + (false, ("Casetest Ink", "Regular", "Version 2.000", "CasetestInk")), + (true, ("Copytest Ink", "Regular", "Version 1.000", "CopytestInk-Light")), + (false, ("Copytest Ink", "Regular", "Version 2.000", "CopytestInk-Regular")), + (true, ("NeuetestInk", "Bold", "Version 1.000", "NeuetestInkBold")), + (false, ("Neuetest Ink", "Bold", "Version 1.000", "NeuetestInk-Bold")), + ]); + assert_eq!(face_set_from("/0 (FuzztestInk)").0, "FuzztestInk", "not the family spelled alike"); + assert_eq!(face_set_from("/0 (FUZZTESTINK-Regular)").0, "FUZZTESTINK-Regular"); + assert_eq!(face_set_from("/0 (CasetestInk)").0, "CasetestInk", "not the name in other case, loaded first"); + assert_eq!(face_set_from("/0 (CASETESTINK)").0, "CASETESTINK"); + assert_eq!(face_set_from("/0 (CopytestInk-Regular)"), ("CopytestInk-Regular".to_string(), "Version 2.000".to_string())); + assert_eq!(face_set_from("/0 (CopytestInk-Light)"), ("CopytestInk-Light".to_string(), "Version 1.000".to_string())); + assert_eq!(face_set_from("/0 (NeuetestInk-Bold)").0, "NeuetestInk-Bold", "not the name without its hyphen, in another family"); + // A name in a case no installed face has still finds the font. + assert_eq!(face_set_from("/0 (casetestink)").0, "CASETESTINK"); +} + +/// A font record may keep the font's version string (key 5, name ID 5): of two installed copies +/// with one PostScript name, family and style, the type is set in that version, also when the +/// record spells the name with other punctuation. A version that isn't installed, or a record +/// without one, gives the copy the family and style resolve to. +#[test] +fn type_from_the_text_document_takes_the_version_its_font_record_keeps() { + install(&[(true, ("Vertest Ink", "Regular", "1.0", "VertestInk-Regular")), (false, ("Vertest Ink", "Regular", "1.1", "VertestInk-Regular"))]); + let version = |record: &str| face_set_from(record).1; + assert_eq!(version("/0 (VertestInk-Regular) /5 (1.1)"), "1.1"); + assert_eq!(version("/0 (VertestInk-Regular) /5 (1.0)"), "1.0"); + assert_eq!(version("/0 (VertestInk-Regular)"), "1.0"); + assert_eq!(version("/0 (VertestInk-Regular) /5 (9.9)"), "1.0"); + assert_eq!(version("/0 (VertestInk-Regular) /5 ()"), "1.0"); + // A record whose name differs from the copies' in punctuation alone still picks its version. + assert_eq!(version("/0 (Vertest-Ink-Regular) /5 (1.1)"), "1.1"); + assert_eq!(version("/0 (Vertest-Ink-Regular)"), "1.0"); +} + /// A story with no runs, and a run or paragraph that names no style, is set in `[Normal Character /// Style]` and `[Normal Paragraph Style]` before the text document's base attributes. A Large /// Canvas copy (1:10) writes the styles at the art's scale (1.2 for 12 points, 0.6 for a 6-point @@ -3366,6 +3433,90 @@ fn stroked_type_keeps_its_cap_join_and_miter_limit() { ); } +#[test] +fn type_painted_with_a_pattern_takes_it_from_the_art_style_its_paint_names() { + // GUARDS: type filled or stroked with a pattern swatch came in black: the text document keeps + // black as the paint's colour, and the pattern is in the art style that key 5 of the paint + // names, a style of one paint (`/SimpleStyle`) whose matrix is in art space. + use vectorcraft_color::{Color, Paint}; + use vectorcraft_geom::Point; + let dots = "%AI3_BeginPattern: (Dots)\n(Dots) 0 0 4 4\n%_0 0 0 1 k\n%_1 1 m\n%_3 1 L\n%_3 3 L\n%_1 3 L\n%_f\nE\n%AI3_EndPattern\n"; + let simple = |name: &str, paint: &str| { + format!( + "/KnownStyle :\n({name}) /Name ,\n/SimpleStyle :\n0 O\n{paint}\n0 1 0 0 0 Xy\n0 J 0 j 1 w 10 M []0 d\n0 XR\n0 1 Xd\n/Paint ;\n /Def ;\n" + ) + }; + let pattern = |m: &str| format!("(Dots) 0 0 1 1 0 0 0 0 0 [{m}] p"); + let styles = [ + simple("Anon 1", &pattern("1 0 0 1 0 0")), + simple("Anon 2", &pattern("2 0 0 2 10 20")), + // Styles that give no pattern: one the file doesn't define, a matrix that doesn't place, no + // name, a colour after the pattern, a colour, a gradient. + simple("Anon 3", "(Absent) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p"), + simple("Anon 4", &pattern("0 0 0 0 0 0")), + simple("Anon 5", "0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p"), + simple("Anon 6", &format!("{}\n0 0 0 1 k", pattern("1 0 0 1 0 0"))), + simple("Anon 7", "0 0 0 1 k"), + simple("Anon 8", "0 Bb\n2 (Rainbow) 0 0 0 100 1 0 0 1 0 0 Bg\n0 BB"), + ] + .concat(); + let styles = format!("%AI9_BeginArtStyles\n{styles}%AI9_EndArtStyles\n"); + let doc = text_document(&[("abcdefghijklmnopq\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]); + let one = "<< /0 << /0 << /0 () /5 0 /6 << /0 0 /1 14.0 /53 << /99 /CAITextPaint /0 << /0 2 /1 [ 1.0 0.0 1.0 0.0 0.0 ] >> >> >> >> >> /1 18 >>"; + assert!(doc.contains(one)); + let black = |style: &str| format!("<< /99 /CAITextPaint /0 << /0 0 /1 [ 1.0 0.0 ] >> /5 ({style}) >>"); + let run = |own: &str| format!("<< /0 << /0 << /0 () /5 0 /6 << /0 0 /1 14.0 {own} >> >> >> /1 2 >>"); + let mut runs = vec![run(&format!("/53 {}", black("Anon 1"))), run(&format!("/53 {} /57 true /54 {} /63 2.0", black("Anon 7"), black("Anon 2")))]; + runs.extend((3..=8).map(|n| run(&format!("/53 {}", black(&format!("Anon {n}")))))); + // A style the file doesn't have, over "q" and the story's end. + runs.push(run(&format!("/53 {}", black("Anon 9")))); + let doc = doc.replacen(one, &runs.join(" "), 1); + let art = native_with_text(&format!("{dots}{styles}{}{}", layer("Back", true, &square(10, 10)), layer("Spare", false, &text_object(0))), &doc); + let r = import(&eps(&page_square(10, 10), &art)).unwrap(); + let texts = text_of(&r.document.layers[1]); + assert_eq!(texts.len(), 1, "{:?}", r.warnings); + let t = texts[0]; + // Each character's fill and stroke, a pattern as where its tile's top left corner is. + let paint = |p: &Paint| match p { + Paint::Pattern { pattern, xf } => { + let at = t.xf * *xf * Point::ZERO; + format!("{pattern} at {:.3} {:.3}", at.x, at.y) + } + Paint::Solid { color, .. } if *color == Color::gray(1.0) => "black".into(), + Paint::None => "none".into(), + other => format!("{other:?}"), + }; + let chars: Vec<(char, String, String)> = + t.runs.iter().flat_map(|r| r.text.chars().map(|c| (c, paint(&r.style.fill), paint(&r.style.stroke))).collect::>()).collect(); + let want = |c: char, fill: &str, stroke: &str| (c, fill.to_string(), stroke.to_string()); + // The tile's top left (0, 4) in art space, on a page 100 high: (0, 96). Scaled twice and moved + // by (10, 20): (10, 28) in art space, (10, 72) in the document. + let mut expected = vec![want('a', "Dots at 0.000 96.000", "none"), want('b', "Dots at 0.000 96.000", "none")]; + expected.extend(['c', 'd'].map(|c| want(c, "black", "Dots at 10.000 72.000"))); + expected.extend("efghijklmnopq".chars().map(|c| want(c, "black", "none"))); + assert_eq!(chars, expected); + assert_eq!(r.document.pattern("Dots").map(|p| p.tile.height()), Some(4.0)); +} + +#[test] +fn type_keeps_its_manual_kerning() { + // GUARDS: the text document's manual kerning (key 8 of a story's text: runs of characters, each + // with its value or none) wasn't read, so type the file kerns by hand came in spaced by the + // font alone and drifted from the page from each kerned pair on. "Wave": "W" kerned by -140, + // "av" automatic, "e" by 60. + let doc = text_document(&[("Wave\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]); + let run = "<< /0 << /0 << /0 () /5 0 /6 << /0 0 /1 14.0 /53 << /99 /CAITextPaint /0 << /0 2 /1 [ 1.0 0.0 1.0 0.0 0.0 ] >> >> >> >> >> /1 5 >>"; + assert!(doc.contains(run)); + let kerns = "/8 << /0 [ << /0 << /0 -140 >> /1 1 >> << /0 << >> /1 2 >> << /0 << /0 60 >> /1 1 >> << /0 << >> /1 1 >> ] >>"; + let doc = doc.replacen(run, &format!("{run} ] >> {kerns}"), 1).replacen(&format!("{kerns} ] >> >>"), &format!("{kerns} >>"), 1); + let art = native_with_text(&(layer("Back", true, &square(10, 10)) + &layer("Spare", false, &text_object(0))), &doc); + let r = import(&eps(&page_square(10, 10), &art)).unwrap(); + let texts = text_of(&r.document.layers[1]); + assert_eq!(texts.len(), 1, "{:?}", r.warnings); + let runs: Vec<(String, Option)> = texts[0].runs.iter().map(|r| (r.text.clone(), r.style.kerning)).collect(); + assert_eq!(runs, [("W".to_string(), Some(-140.0)), ("av".to_string(), None), ("e".to_string(), Some(60.0))]); +} + #[test] fn orientation_and_tate_chu_yoko_values_it_cant_use_are_ignored() { for bad in ["(2)", "2.5", "1e300", "-2", "1", "true", "[ 2 ]"] { @@ -5377,6 +5528,11 @@ fn type_envelope(keys: &str, drawn: &str) -> String { /// [`type_envelope`], with `after` (on plain lines, written on `%_` ones) after the text object in /// its contents, such as the text object's XML id. fn type_envelope_with(keys: &str, drawn: &str, after: &str) -> String { + type_envelope_of(0, keys, drawn, after) +} + +/// [`type_envelope_with`] around the type of story `story`. +fn type_envelope_of(story: u32, keys: &str, drawn: &str, after: &str) -> String { let corner = |x: f64, y: f64, nx: f64, ny: f64, px: f64, py: f64| format!("[0.8 1 {x} {y} {nx} {ny} 1 {px} {py} 1] /N X#\n"); let mesh = format!( "/Mesh X!\n2 /Version X#\n/Cartesian /Type X#\n[1 1] /Size X#\n/Data X#\n/DeviceGray /CS X#\n[0 0] /P X#\n{}{}{}{}/E X#\n/End X!\n", @@ -5385,18 +5541,23 @@ fn type_envelope_with(keys: &str, drawn: &str, after: &str) -> String { corner(80.0, 70.0, 80.0, 60.0, 70.0, 70.0), corner(80.0, 40.0, 70.0, 40.0, 80.0, 50.0), ); - type_envelope_on(keys, &mesh, drawn, after) + type_envelope_on_story(story, keys, &mesh, drawn, after) } /// [`type_envelope_with`], with `shape` (on plain lines, written on `%_` ones) in the group before /// its dictionary, where the editing data saves the envelope's mesh. fn type_envelope_on(keys: &str, shape: &str, drawn: &str, after: &str) -> String { + type_envelope_on_story(0, keys, shape, drawn, after) +} + +/// [`type_envelope_on`] around the type of story `story`. +fn type_envelope_on_story(story: u32, keys: &str, shape: &str, drawn: &str, after: &str) -> String { let hidden = |s: &str| -> String { s.lines().map(|l| format!("%_{l}\n")).collect() }; format!( "{}{}%_X=\n{}%_X+\n%_ (AIDeformArtKey) ,\n%_1 /Int (AIDeformStyle) ,\n%_;\n%_\n%_9 () XW\nu\n{drawn}U\n9 () XW\n(Adobe Deform Plugin) 1 0 0 XP\n", hidden(&format!("u\n{shape}U\n")), hidden(&format!("/ArtDictionary :\n{keys}")), - hidden(&format!("u\n{}{after}U\n9 () XW\n", text_object(0))), + hidden(&format!("u\n{}{after}U\n9 () XW\n", text_object(story))), ) } @@ -5419,7 +5580,14 @@ fn type_envelope_text(family: &str, paint: Option<&str>) -> String { fn arc_envelope(text: &Node, bend: f64) -> Node { let mut text = text.clone(); text.visible = true; - let kind = vectorcraft_doc::live::EnvelopeKind::Warp { style: "arc".into(), bend, h: 0.0, v: 0.0, horizontal: true }; + let kind = vectorcraft_doc::live::EnvelopeKind::Warp { + style: "arc".into(), + bend, + h: 0.0, + v: 0.0, + horizontal: true, + version: vectorcraft_doc::live::WARP_NET, + }; Node::new( vectorcraft_doc::NodeId(1_000_000), NodeKind::Envelope { @@ -5436,7 +5604,12 @@ fn arc_envelope(text: &Node, bend: f64) -> Node { /// The type of the file with an envelope of type whose drawn art is `drawn`, read with its text /// document `doc`: the hidden text object it keeps, as the reader makes it. fn made_envelope_type(doc: &str) -> Node { - let art = native_with_text(&layer("Art", true, &type_envelope(&arc_keys(0.3), &format!("{}\n", square(10, 10)))), doc); + made_envelope_type_of(doc, 0) +} + +/// [`made_envelope_type`] of story `story`. +fn made_envelope_type_of(doc: &str, story: u32) -> Node { + let art = native_with_text(&layer("Art", true, &type_envelope_of(story, &arc_keys(0.3), &format!("{}\n", square(10, 10)), "")), doc); let r = import(&eps(&page_square(10, 10), &art)).unwrap(); let mut text = None; r.document.walk(|n| { @@ -5527,9 +5700,9 @@ fn an_envelope_of_white_type_that_draws_apart_from_its_drawn_art_keeps_it() { /// A `.ai` whose layers would open alone, without its PDF part, waits on the PDF part when an /// envelope of type is in them, as for the other live envelopes: one opens live only where the -/// layers with it draw as the page. Where they don't, they open alone as before, the envelope -/// keeping its drawn art and its type, hidden, with the note, even though it would draw as that -/// drawn art; where they do, it opens live (#3179). +/// layers with it draw as the page. Where they don't, the page drawing nothing where the envelope +/// is, they open alone as before, the envelope keeping its drawn art and its type, hidden, with the +/// note, even though it would draw as that drawn art; where they do, it opens live (#3179). #[test] fn an_envelope_of_type_waits_on_the_page_of_layers_that_would_open_alone() { let Some(family) = installed_family() else { return }; @@ -5593,9 +5766,10 @@ fn an_envelope_of_type_that_draws_apart_from_the_page_does_not_open_live() { } /// Layers used though they draw differently from the page (the editing data trusted) leave an -/// envelope of type its drawn art and its type, hidden, with the note, even where it draws as that -/// drawn art: one opens live only where the layers with it draw as the page. A `.ai` whose layers -/// would open alone then opens alone, as it would without the envelope (#3179). +/// envelope of type its drawn art and its type, hidden, with the note, where the page draws +/// nothing where the envelope is, even where it draws as that drawn art: one opens live only where +/// the layers with it draw as the page there. A `.ai` whose layers would open alone then opens +/// alone, as it would without the envelope (#3179). #[test] fn trusted_layers_that_draw_apart_from_the_page_leave_an_envelope_of_type_its_drawn_art() { let Some(family) = installed_family() else { return }; @@ -5631,19 +5805,27 @@ fn trusted_layers_that_draw_apart_from_the_page_leave_an_envelope_of_type_its_dr assert!(!notes.iter().any(|n| n.ends_with("they come from its editing data all the same")), "{notes:?}"); } -/// Layers whose objects that draw differently from the page come in as its art leave an envelope -/// of type its drawn art and its type, hidden, with the note, even where the envelope draws as the -/// page: the layers with it don't (#3179). -#[test] -fn layers_with_objects_that_come_in_as_the_page_art_leave_an_envelope_of_type_its_drawn_art() { - let Some(family) = installed_family() else { return }; - let doc = type_envelope_text(&family, None); - let (drawn, page) = drawn_envelope(&arc_envelope(&made_envelope_type(&doc), 30.0)); - // A square black in the layers and cyan on the page, away from the envelope. +/// The layers and the page of a file with an envelope of type that draws as its drawn art, and a +/// square black in the layers and cyan on the page, away from the envelope; the page draws the +/// envelope bent by `page_bend` (percent). +fn envelope_beside_a_differing_square(family: &str, page_bend: f64) -> (String, String) { + let doc = type_envelope_text(family, None); + let text = made_envelope_type(&doc); + let (drawn, _) = drawn_envelope(&arc_envelope(&text, 30.0)); + let (_, page) = drawn_envelope(&arc_envelope(&text, page_bend)); let body = format!("{}\n{}\n{}", square(10, 10), square_16(76, BLACK), type_envelope(&arc_keys(0.3), &drawn)); - let art = native_with_text(&layer("Art", true, &body), &doc); let cyan = "1 0 0 0 setcmykcolor 76 10 moveto 92 10 lineto 92 26 lineto 76 26 lineto closepath fill"; - let r = import(&eps(&format!("{}\n{cyan}\n{page}", page_square(10, 10)), &art)).unwrap(); + (native_with_text(&layer("Art", true, &body), &doc), format!("{}\n{cyan}\n{page}", page_square(10, 10))) +} + +/// Layers whose objects that draw differently from the page come in as its art keep an envelope of +/// type live where the envelope draws as the page: the art that differs isn't the envelope's, and +/// the layers with it then draw as the page (#3179). +#[test] +fn layers_with_objects_that_come_in_as_the_page_art_keep_an_envelope_of_type_that_draws_as_the_page_live() { + let Some(family) = installed_family() else { return }; + let (art, page) = envelope_beside_a_differing_square(&family, 30.0); + let r = import(&eps(&page, &art)).unwrap(); assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); assert!( r.warnings.iter().any(|n| n.starts_with("objects that drew differently from the file's own page came in as its art")), @@ -5651,12 +5833,169 @@ fn layers_with_objects_that_come_in_as_the_page_art_leave_an_envelope_of_type_it r.warnings ); let (envelopes, loose) = envelopes_and_type(&r.document); + assert_eq!(envelopes, [vec!["FLUX".to_string()]], "{:?}", r.warnings); + assert!(loose.is_empty(), "{loose:?}"); + assert!(!r.warnings.iter().any(|n| n == crate::import::ai::ENVELOPE_TYPE_DRAWN), "{:?}", r.warnings); +} + +/// Layers used though they draw differently from the page (the editing data trusted) leave an +/// envelope of type its drawn art and its type, hidden, with the note, where the page draws it +/// otherwise than they do (bent the other way), though other art differs too: the page holds the +/// envelope against them where it is (#3179). +#[test] +fn trusted_layers_leave_an_envelope_of_type_the_page_draws_otherwise_its_drawn_art() { + let Some(family) = installed_family() else { return }; + let (art, page) = envelope_beside_a_differing_square(&family, -30.0); + let r = crate::import_trusting(&eps(&page, &art), true, true).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + assert!(r.warnings.iter().any(|n| n.ends_with("they come from its editing data all the same")), "{:?}", r.warnings); + let (envelopes, loose) = envelopes_and_type(&r.document); assert!(envelopes.is_empty(), "{envelopes:?}"); assert_eq!(loose, [("FLUX".to_string(), false)], "{:?}", r.warnings); - assert_eq!(loose_type_names(&r.document), [None]); assert!(r.warnings.iter().any(|n| n == crate::import::ai::ENVELOPE_TYPE_DRAWN), "{:?}", r.warnings); } +/// Layers used though they draw differently from the page (the editing data trusted) keep an +/// envelope of type live where the page draws it as they do and the art that differs is elsewhere +/// (#3179). +#[test] +fn trusted_layers_keep_an_envelope_of_type_live_where_other_art_differs_from_the_page() { + let Some(family) = installed_family() else { return }; + let (art, page) = envelope_beside_a_differing_square(&family, 30.0); + let r = crate::import_trusting(&eps(&page, &art), true, true).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + assert!(r.warnings.iter().any(|n| n.ends_with("they come from its editing data all the same")), "{:?}", r.warnings); + let (envelopes, loose) = envelopes_and_type(&r.document); + assert_eq!(envelopes, [vec!["FLUX".to_string()]], "{:?}", r.warnings); + assert!(loose.is_empty(), "{loose:?}"); + assert!(!r.warnings.iter().any(|n| n == crate::import::ai::ENVELOPE_TYPE_DRAWN), "{:?}", r.warnings); +} + +/// A `.ai` whose layers would open alone, and that waits on its PDF part for an envelope of type, +/// opens alone with the envelope live where the page draws it as the layers do, though the page +/// also draws art the layers don't have: the envelope's drawn art put back wouldn't make the layers +/// draw as the page (#3179). +#[test] +fn layers_that_would_open_alone_keep_an_envelope_of_type_live_where_other_art_differs_from_the_page() { + let Some(family) = installed_family() else { return }; + let stories = [("FLUX\r", 0, (8170.0, 8180.0), (0.0, 0.0), 0.0), ("Note\r", 0, (8170.0, 8220.0), (0.0, 0.0), 0.0)]; + let mut doc = text_document(&stories).replace("(Helvetica)", &format!("({family})")); + // [`native_with_text`] writes 60 characters a line: the end of the data, `~>`, isn't split. + while ascii85(doc.as_bytes()).len() % 60 == 1 { + doc.push('\n'); + } + let (drawn, _) = drawn_envelope(&arc_envelope(&made_envelope_type(&doc), 30.0)); + let art = format!("u\n{}U\n{}", text_object(1), type_envelope(&arc_keys(0.3), &drawn)); + let file = private(&native_with_text(&layer("Art", true, &art), &doc)); + let names = crate::NameEncoding::default(); + let open = |page: Document| { + let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") }; + crate::layered_ai_from(layers, page, vec![], false, false, 1.0, names) + }; + // The layers alone, with the envelope's drawn art: what the page draws. + let (mut page, notes, _) = open(pdf_part(80.0, 80.0)); + assert!(envelopes_and_type(&page).0.is_empty(), "{notes:?}"); + // And a black square the layers don't have, away from the type. + add_black_square(&mut page, 80.0, 4.0); + let (d, notes, read) = open(page); + assert!(read, "{notes:?}"); + let (envelopes, loose) = envelopes_and_type(&d); + assert_eq!(envelopes, [vec!["FLUX".to_string()]], "{notes:?}"); + assert_eq!(loose, [("Note".to_string(), true)], "{notes:?}"); + assert!(!notes.iter().any(|n| n == crate::import::ai::ENVELOPE_TYPE_DRAWN), "{notes:?}"); +} + +/// A black square of 16 points at (`x`, `y`) put on top of `page`'s first layer. +fn add_black_square(page: &mut Document, x: f64, y: f64) { + let paint = vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK); + let item = vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(paint)); + let path = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(x, y, x + 16.0, y + 16.0)); + let square = Node::path(page.alloc_id(), path, vectorcraft_doc::Appearance { items: vec![item], ..Default::default() }); + let layer = page.layers[0].id; + page.insert(Some(layer), 0, square).unwrap(); +} + +/// A `.ai` whose layers would open alone, with the editing data trusted, opens alone with an +/// envelope of type live where the page draws it as the layers do, though the page also draws art +/// they don't have: not from the layers compared with the page, which would say they come from the +/// editing data all the same (#3179). +#[test] +fn trusted_layers_that_would_open_alone_open_alone_with_an_envelope_of_type_the_page_doesnt_hold_live() { + let Some(family) = installed_family() else { return }; + let stories = [("FLUX\r", 0, (8170.0, 8180.0), (0.0, 0.0), 0.0), ("Note\r", 0, (8170.0, 8220.0), (0.0, 0.0), 0.0)]; + let mut doc = text_document(&stories).replace("(Helvetica)", &format!("({family})")); + while ascii85(doc.as_bytes()).len() % 60 == 1 { + doc.push('\n'); + } + let (drawn, _) = drawn_envelope(&arc_envelope(&made_envelope_type(&doc), 30.0)); + let art = format!("u\n{}U\n{}", text_object(1), type_envelope(&arc_keys(0.3), &drawn)); + let file = private(&native_with_text(&layer("Art", true, &art), &doc)); + let names = crate::NameEncoding::default(); + let open = |page: Document, trust: bool| { + let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") }; + crate::layered_ai_from(layers, page, vec![], false, trust, 1.0, names) + }; + let (mut page, _, _) = open(pdf_part(80.0, 80.0), false); + add_black_square(&mut page, 80.0, 4.0); + let (d, notes, read) = open(page, true); + assert!(read, "{notes:?}"); + let (envelopes, loose) = envelopes_and_type(&d); + assert_eq!(envelopes, [vec!["FLUX".to_string()]], "{notes:?}"); + assert_eq!(loose, [("Note".to_string(), true)], "{notes:?}"); + assert!(notes.is_empty(), "{notes:?}"); +} + +/// Of two envelopes of type in a `.ai` whose layers would open alone, the one the page holds +/// against the layers (it draws nothing where the envelope is) keeps its drawn art and its type, +/// hidden, with the note, and the other opens live: each by its place among the envelopes of type +/// as the layers are read, both times they are (#3179). +#[test] +fn layers_that_would_open_alone_keep_live_only_the_envelopes_of_type_the_page_doesnt_hold() { + let Some(family) = installed_family() else { return }; + let stories = [ + ("FLUX\r", 0, (8170.0, 8180.0), (0.0, 0.0), 0.0), + ("HILL\r", 0, (8170.0, 8200.0), (0.0, 0.0), 0.0), + ("Note\r", 0, (8170.0, 8220.0), (0.0, 0.0), 0.0), + ]; + let mut doc = text_document(&stories).replace("(Helvetica)", &format!("({family})")); + while ascii85(doc.as_bytes()).len() % 60 == 1 { + doc.push('\n'); + } + let drawn = |story| drawn_envelope(&arc_envelope(&made_envelope_type_of(&doc, story), 30.0)).0; + let art = format!( + "u\n{}U\n{}{}", + text_object(2), + type_envelope_of(0, &arc_keys(0.3), &drawn(0), ""), + type_envelope_of(1, &arc_keys(0.3), &drawn(1), "") + ); + let file = private(&native_with_text(&layer("Art", true, &art), &doc)); + let names = crate::NameEncoding::default(); + let open = |page: Document| { + let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") }; + crate::layered_ai_from(layers, page, vec![], false, false, 1.0, names) + }; + // The layers alone, with the drawn art of both envelopes, but the first's: the page draws + // nothing where the first is. + let (mut page, notes, _) = open(pdf_part(80.0, 80.0)); + let top = page.layers[0].clone(); + let first = top + .children() + .into_iter() + .flatten() + .filter(|n| matches!(n.kind, NodeKind::Group { .. })) + .min_by(|a, b| a.visual_bounds().map_or(f64::MAX, |r| r.y0).total_cmp(&b.visual_bounds().map_or(f64::MAX, |r| r.y0))) + .map(|n| n.id) + .unwrap_or_else(|| panic!("no drawn art: {notes:?}")); + page.remove(first).unwrap(); + let (d, notes, read) = open(page); + assert!(read, "{notes:?}"); + let (envelopes, mut loose) = envelopes_and_type(&d); + assert_eq!(envelopes, [vec!["HILL".to_string()]], "{notes:?}"); + loose.sort(); + assert_eq!(loose, [("FLUX".to_string(), false), ("Note".to_string(), true)], "{notes:?}"); + assert!(notes.iter().any(|n| n == crate::import::ai::ENVELOPE_TYPE_DRAWN), "{notes:?}"); +} + /// An envelope of type whose type a visibility variable binds keeps its drawn art, as one whose type /// a text variable binds does: the binding stays the hidden type's, which the live envelope would /// take the place of (#3179). @@ -5834,6 +6173,84 @@ fn a_warp_of_stroked_type_maps_from_its_bounds_with_strokes_where_its_drawn_art_ assert_eq!(margin, Some(options.bounds_margin)); } +/// What the type in `content` paints, measured apart from the import: each piece of its outlines +/// filled, and outlined by kurbo's stroker with each of its strokes' weight, join and miter limit. +fn painted_by_kurbo(content: &[std::sync::Arc]) -> kurbo::Rect { + use kurbo::Shape; + let mut out: Option = None; + for n in content { + let outlines = vectorcraft_effects::outline_text(n).unwrap(); + for piece in outlines.children().unwrap() { + let bp = piece.stroke_path().unwrap(); + out = vectorcraft_geom::union_opt(out, Some(bp.bounding_box())); + for s in piece.appearance.painted_strokes() { + let join = match s.join { + vectorcraft_doc::LineJoin::Miter => kurbo::Join::Miter, + vectorcraft_doc::LineJoin::Round => kurbo::Join::Round, + vectorcraft_doc::LineJoin::Bevel => kurbo::Join::Bevel, + }; + let stroke = kurbo::Stroke::new(s.width).with_join(join).with_miter_limit(s.miter_limit); + let outline = kurbo::stroke(bp.iter(), &stroke, &kurbo::StrokeOpts::default(), 1e-4); + out = vectorcraft_geom::union_opt(out, Some(outline.bounding_box())); + } + } + } + out.unwrap() +} + +/// A warp of type stroked with miter joins, Distort Appearance on, whose drawn art maps the type from +/// what it paints, the miter tips at the sharp corners of its X past half the stroke's weight +/// included, as users' files map some such type, opens live as a mesh envelope on its saved grid +/// mapping from that box, where its glyphs grown by half the weight don't draw as that art (#6824). +#[test] +fn a_warp_of_mitred_type_maps_from_what_its_stroke_paints_where_its_drawn_art_does() { + use vectorcraft_doc::live::{envelope_content_boxes, envelope_stroke_margin}; + let Some(family) = installed_family() else { return }; + // "FLUX" stroked 4 points wide in black, with miter joins at a limit of 10. + let stroked = "/53 << /99 /CAITextPaint /0 << /0 2 /1 [ 1.0 0.0 1.0 0.0 0.0 ] >> >> /54 << /99 /CAITextPaint /0 << /0 2 /1 [ 1.0 0.0 0.0 0.0 1.0 ] >> >> /57 true /62 0 /63 4.0 /64 10.0"; + let doc = type_envelope_text(&family, None).replace("/53 << /99 /CAITextPaint /0 << /0 2 /1 [ 1.0 0.0 1.0 0.0 0.0 ] >> >>", stroked); + let mut text = made_envelope_type(&doc); + text.visible = true; + assert!( + matches!(&text.kind, NodeKind::Text(t) if t.runs[0].style.stroke_join == vectorcraft_doc::LineJoin::Miter && t.runs[0].style.stroke_miter_limit == 10.0), + "{text:?}" + ); + let content = vec![std::sync::Arc::new(text)]; + let (half, glyphs) = envelope_content_boxes(&content, kurbo::Affine::IDENTITY).unwrap(); + let painted = painted_by_kurbo(&content); + assert!(painted.x0 < half.x0 - 0.5 || painted.x1 > half.x1 + 0.5, "{painted:?} {half:?}"); + let mut options = vectorcraft_doc::live::EnvelopeOptions::NEW; + options.bounds_margin = envelope_stroke_margin(painted, glyphs).unwrap(); + let shaped = Node::new( + vectorcraft_doc::NodeId(1_000_000), + NodeKind::Envelope { content, kind: Box::new(rising_kind()), fidelity: 50.0, editing: false, options, frame: Box::default() }, + ); + let (drawn, page) = drawn_stroked_envelope(&shaped); + let art = + native_with_text(&layer("Art", true, &format!("{}\n{}", square(10, 10), type_envelope_on(&arc_keys(0.3), &rising_grid(), &drawn, ""))), &doc); + let r = import(&eps(&format!("{}\n{page}", page_square(10, 10)), &art)).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + let (envelopes, loose) = envelopes_and_type(&r.document); + assert_eq!(envelopes, [vec!["FLUX".to_string()]], "{:?}", r.warnings); + assert!(loose.is_empty(), "{loose:?}"); + // It maps from what the type paints, within a hundredth of a point on each side. + let mut margin = None; + r.document.walk(|n| { + if let NodeKind::Envelope { options, .. } = &n.kind { + margin = Some(options.bounds_margin); + } + }); + let [top, bottom, left, right] = margin.unwrap().map(f64::from); + let from = kurbo::Rect::new( + glyphs.x0 - left * glyphs.width(), + glyphs.y0 - top * glyphs.height(), + glyphs.x1 + right * glyphs.width(), + glyphs.y1 + bottom * glyphs.height(), + ); + let off = [from.x0 - painted.x0, from.y0 - painted.y0, from.x1 - painted.x1, from.y1 - painted.y1]; + assert!(off.iter().all(|d| d.abs() < 0.01), "{from:?} {painted:?}"); +} + /// The drawn art of `envelope` (on the page axes), an envelope of type stroked by its characters, /// as the drawn art of `.ai` files strokes type in an envelope: the bent glyph outlines the envelope /// draws of its type unstroked, each filled in its type's color, then each stroked with the type's @@ -6933,3 +7350,21 @@ fn text_a_placed_file_covers_only_at_its_first_placement_is_kept() { assert_eq!(text_of(&d.layers[0]).iter().map(|t| t.plain_text()).collect::>(), ["Hi"], "{w:?}"); assert!(!w.iter().any(|w| w.contains("doesn't draw")), "{w:?}"); } + +/// #6865: explicitly trusting editing data keeps an artboard larger than its PDF page. +#[test] +fn trusted_editing_data_keeps_an_artboard_taller_than_its_pdf_page() { + let art = native(&layer("Oversized", true, &square(10, 10))).replace(" 0 0 100 100", " 0 0 12992.726 14637.147"); + let (d, w, read) = crate::layered_ai(&private(&art), Document::new(12992.7, 14400.0), vec![], false, true, 1.0); + assert!(read, "{w:?}"); + assert_eq!(names(&d), ["Oversized"], "{w:?}"); + assert!((d.artboards[0].rect.height() - 14637.147).abs() < 0.001); + assert_eq!(kinds(&d.layers[0]), ["path"]); + assert!(w.iter().any(|w| w.contains("artboard is larger than the PDF page")), "{w:?}"); + let child = &d.layers[0].children().unwrap()[0]; + assert!(child.visual_bounds().unwrap().y0 > 14400.0, "art beyond the PDF page is kept"); + let (_, w, read) = crate::layered_ai(&private(&art), Document::new(12992.7, 14400.0), vec![], false, false, 1.0); + assert!(!read, "default import still rejects the size mismatch: {w:?}"); + let (_, w, read) = crate::layered_ai(&private(&art), Document::new(12000.0, 14400.0), vec![], false, true, 1.0); + assert!(!read, "the uncapped dimension must still match: {w:?}"); +} diff --git a/crates/eps/src/import/text.rs b/crates/eps/src/import/text.rs index 5868aa9228..515e0b12ec 100644 --- a/crates/eps/src/import/text.rs +++ b/crates/eps/src/import/text.rs @@ -15,6 +15,7 @@ use super::cid::Base; use super::graphics::MAX_APART; use super::interp::{Interp, matrix_obj, matrix_of}; use super::obj::{Dict, DictRef, Key, Obj, Op, PsError, Res, ps_err}; +use super::predefined_cmap::Decoded; use super::type1::Embedded; /// The font a program uses before it sets one. @@ -41,20 +42,75 @@ fn style_word(w: &str) -> String { .to_string() } +/// A font's PostScript name without a subset prefix (`ABCDEF+`) or the `*1` of a re-encoded copy +/// (`ABCDEF+RollerBabyBV*1` is `RollerBabyBV`). +fn bare_name(name: &str) -> &str { + let name = match name.split_once('+') { + Some((prefix, rest)) if prefix.len() == 6 && prefix.bytes().all(|b| b.is_ascii_uppercase()) => rest, + _ => name, + }; + match name.rsplit_once('*') { + Some((base, n)) if !base.is_empty() && !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()) => base, + _ => name, + } +} + +/// The font of type that a text document's font record names: by `name`, its PostScript name, and +/// `version`, the version string (name ID 5) the record keeps, if any. An installed face of that +/// name gives its font ([`named_font`]). Without one, `name` is split ([`family_style`]) and the +/// family spelled as an available family is ([`FontDb::find_family`]: `MicrosoftYaHei` is +/// Microsoft YaHei). → (family, style, version). +/// +/// [`FontDb::find_family`]: vectorcraft_text::FontDb::find_family +pub(crate) fn document_font(name: &str, version: Option<&str>) -> (String, String, Option) { + named_font(name, version).unwrap_or_else(|| { + let (family, style) = family_style(name); + let family = vectorcraft_text::FontDb::global().find_family(&family).unwrap_or(family); + (family, style, None) + }) +} + +/// The font of type set in the installed face of PostScript name `name` (a subset prefix and a +/// re-encoded copy's `*1` aside) in `version` ([`postscript_face`]): that face's own family and +/// style, and its version when the family and style alone resolve to another installed copy of +/// the font. A library can keep two copies under one family and style that differ in their +/// PostScript names or their versions, and draw the same text at different widths. → (family, +/// style, version); `None` when no installed face has the name. +pub(crate) fn named_font(name: &str, version: Option<&str>) -> Option<(String, String, Option)> { + let face = postscript_face(bare_name(name), version)?; + // As the PDF import names a version: only one that the family and style don't resolve to. + let default = vectorcraft_text::FontDb::global().face(&face.family, &face.style); + let version = default.filter(|d| d.version != face.version).map(|_| face.version.clone()); + Some((face.family.clone(), face.style.clone(), version)) +} + +/// The installed face of PostScript name `name` (without a subset prefix), among the installed +/// faces that answer to it ([`FontDb::postscript_faces`]): those of exactly that name when there +/// are any (PostScript names are case-sensitive, so `SampleSans` isn't the face named +/// `SAMPLESANS`, and `SampleSerif-Bold` isn't `SampleSerifBold`), and of those the one in +/// `version` when it is installed, else the first. `None` when no installed face has the name. +/// +/// [`FontDb::postscript_faces`]: vectorcraft_text::FontDb::postscript_faces +pub(crate) fn postscript_face(name: &str, version: Option<&str>) -> Option> { + let db = vectorcraft_text::FontDb::global(); + let found = db.find_postscript(name)?; + if found.postscript_name() == name && version.is_none_or(|v| v == found.version) { + return Some(found); + } + let faces = db.postscript_faces(name); + let named: Vec<_> = faces.iter().filter(|f| f.postscript_name() == name).cloned().collect(); + let pool = if named.is_empty() { faces } else { named }; + let in_version = version.and_then(|v| pool.iter().find(|f| f.version == v).cloned()); + Some(in_version.or_else(|| pool.into_iter().next()).unwrap_or(found)) +} + /// A font's family and style from its PostScript name, without a subset prefix (`ABCDEF+`) or the /// `*1` of a re-encoded copy (`ABCDEF+RollerBabyBV*1`): an installed or bundled face of that /// exact name gives its own (a family can hold hyphens: `rounded-x-mplus-1c-black` is Rounded-X /// M+ 1c, black); else the name is split, `Helvetica-BoldOblique` → (`Helvetica`, `Bold /// Oblique`), `TimesNewRomanPS-BoldMT` → (`Times New Roman`, `Bold`). pub fn family_style(name: &str) -> (String, String) { - let name = match name.split_once('+') { - Some((prefix, rest)) if prefix.len() == 6 && prefix.bytes().all(|b| b.is_ascii_uppercase()) => rest, - _ => name, - }; - let name = match name.rsplit_once('*') { - Some((base, n)) if !base.is_empty() && !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()) => base, - _ => name, - }; + let name = bare_name(name); if let Some(face) = vectorcraft_text::FontDb::global().find_postscript(name) { return (face.family.clone(), face.style.clone()); } @@ -170,8 +226,8 @@ impl Interp<'_> { ResourceForAll => self.resource_for_all()?, Show | AShow | WidthShow | AWidthShow | XShow | YShow | XYShow | KShow => { let (s, spacing) = self.show_operands(op)?; - if let Some((text, font)) = self.unicode_type(&s)? { - self.show_unicode(&text, &font)?; + if let Some(named) = self.named_cid_type(&s)? { + self.show_named_cid(&named, &spacing, Draw::Fill)?; } else if let Some(glyphs) = self.composite_glyphs(&s)? { self.show_composite(&glyphs, &spacing)?; } else { @@ -185,6 +241,16 @@ impl Interp<'_> { // The procedure shows or places each character: it gets its code and width. let s = self.pop_str()?.to_vec(); let proc = self.pop_proc()?; + // In a CIDFont only named, a code may be several bytes: the procedure runs once for + // each code. + if let Some(named) = self.named_cid_type(&s)? { + let root = self.g.font.clone(); + let before = self.cshow.take(); + let r = self.named_cshow(named, &proc, root.clone()); + self.cshow = before; + self.g.font = root; + return r; + } for b in s { let v = self.width_of(&[b])?; self.push(Obj::Int(i64::from(b)))?; @@ -207,7 +273,14 @@ impl Interp<'_> { } None => { let ch = glyph_char(&name); - self.show(ch.encode_utf8(&mut [0; 4]).as_bytes())?; + // In a CIDFont only named, the character is set as it is, not read through + // the CMap. + if let Some(mut named) = self.named_cid_font()? { + named.codes.push(0, Some(ch).filter(|c| !c.is_control())); + self.show_named_cid(&named, &Spacing::Plain, Draw::Fill)?; + } else { + self.show(ch.encode_utf8(&mut [0; 4]).as_bytes())?; + } } } } @@ -227,7 +300,12 @@ impl Interp<'_> { SetCharWidth => self.glyph_width = Some(self.nums::<2>()?), SetCacheDevice2 => self.glyph_width = Some(self.nums::<10>()?[..2].try_into().unwrap_or_default()), RootFont => { - let font = match self.g.font.clone() { + // Inside a `cshow` procedure the composite font, unless the procedure set a font. + let root = match (&self.cshow, &self.g.font) { + (Some(c), Some(f)) if f.same(&c.selected) => Some(c.root.clone()), + _ => None, + }; + let font = match root.or_else(|| self.g.font.clone()) { Some(f) => f, None => self.find_font(&Obj::name(DEFAULT_FONT))?, }; @@ -282,11 +360,8 @@ impl Interp<'_> { /// How far `s` moves the current point (user space). fn width_of(&mut self, s: &[u8]) -> Res { - if let Some((text, font)) = self.unicode_type(s)? { - let saved = self.g.font.replace(font); - let r = self.set_text(&text, Point::ZERO).map(|t| t.2); - self.g.font = saved; - return r; + if let Some(named) = self.named_cid_type(s)? { + return self.named_cid_width(&named, &named.codes); } if let Some(glyphs) = self.composite_glyphs(s)? { let mut w = Vec2::ZERO; @@ -395,18 +470,27 @@ impl Interp<'_> { } /// The font named `k`: one the program defined; else, for a name `CIDFont-CMap` whose CMap - /// is a predefined Unicode CMap, the CID-keyed font of those two (the usual name of a - /// CID-keyed font, as `composefont` makes them: PLRM 3rd ed., chapter 8); else a font of - /// that name. + /// is a predefined CMap, the CID-keyed font of those two (the usual name of a CID-keyed font, + /// as `composefont` makes them: PLRM 3rd ed., chapter 8; the CMaps are Adobe's public CMap + /// resources, ); else a font of that name. + /// A name that ends in a predefined CMap other than a Unicode CMap and that an installed face + /// has is that face's ([`Self::predefined_split`]). fn find_font(&mut self, k: &Obj) -> Res { let key = k.key().ok_or(PsError::Ps("typecheck", "findfont".into()))?; if let Some(Obj::Dict(d)) = self.fonts.borrow().get(&key) { return Ok(d.clone()); } let text = k.text().map(|t| t.to_string()).unwrap_or_default(); - let split = - text.match_indices('-').map(|(i, _)| i).find(|&i| i > 0 && super::cid::unicode_cmap(text.get(i + 1..).unwrap_or_default()).is_some()); - if let Some((cid_font, cmap)) = split.and_then(|i| Some((text.get(..i)?, text.get(i + 1..)?))) { + let unicode = text + .match_indices('-') + .map(|(i, _)| i) + .find(|&i| i > 0 && super::predefined_cmap::unicode_cmap(text.get(i + 1..).unwrap_or_default()).is_some()) + .and_then(|i| Some((text.get(..i)?, text.get(i + 1..)?))); + let split = match unicode { + Some(split) => Some(split), + None => self.predefined_split(&text), + }; + if let Some((cid_font, cmap)) = split { let cmap = self.find_cmap(&Obj::name(cmap))?; let dep = self.find_cid_font(&Obj::name(cid_font))?; return Ok(self.composed(key, cmap, vec![Obj::Dict(dep)])); @@ -422,6 +506,32 @@ impl Interp<'_> { Ok(font) } + /// Font name `name` as a CIDFont's name and the name of a predefined CMap other than a Unicode + /// CMap ([`super::predefined_cmap::composite_font`]), unless an installed face has the whole + /// name. A name that ends in the row-and-cell CMap `H` or `V` splits only when the part before + /// it names a CIDFont the file defines, or has a hyphen and names an installed face that covers + /// Japanese; otherwise it stays a font of the whole name (`Futura-H`, `Foo-Bold-H`), its + /// strings read byte by byte. + fn predefined_split<'a>(&mut self, name: &'a str) -> Option<(&'a str, &'a str)> { + let (cid_font, cmap) = super::predefined_cmap::composite_font(name)?; + let db = vectorcraft_text::FontDb::global(); + if db.find_postscript(name).is_some() { + return None; + } + if matches!(cmap, "H" | "V") { + let key = Key::name(cid_font); + // As a CIDFont resource, or as a font (`definefont`), as `composefont` finds it. + let cid_font_in = |d: &DictRef| matches!(d.borrow().get(&key), Some(Obj::Dict(f)) if f.borrow().contains_key(&Key::name("CIDFontType"))); + let defined = self.instances(&Obj::name("CIDFont")).is_ok_and(|d| d.borrow().contains_key(&key)) || cid_font_in(&self.fonts); + // 日 is in the row-and-cell CMaps' character set (JIS X 0208). + let installed = || db.find_postscript(cid_font).is_some_and(|face| face.covers('日')); + if !(defined || (cid_font.contains('-') && installed())) { + return None; + } + } + Some((cid_font, cmap)) + } + /// The current font's name and its matrix for a font of one unit (user space). fn font(&mut self) -> Res<(String, Affine)> { let font = match self.g.font.clone() { @@ -476,6 +586,15 @@ impl Interp<'_> { /// [`Self::set_type`] for the characters `text`. fn set_text(&mut self, text: &str, at: Point) -> Res<(TextObject, TextLayout, Vec2)> { + self.set_text_in(text, at, false) + } + + /// [`Self::set_text`], as vertical type when `vertical`: a column anchored at `at`, the top + /// center of its first em box, that moves the current point down the column by the layout's + /// advances. In vertical writing the current point is a glyph's origin 1, by default half its + /// width across and 880 units of 1000 above its origin 0 (PDF Reference 1.7, §5.6.3 "Glyph + /// Metrics in CIDFonts", `DW2`). + fn set_text_in(&mut self, text: &str, at: Point, vertical: bool) -> Res<(TextObject, TextLayout, Vec2)> { // Laying out type costs about as much as 300 operations, and 64 more a character // (measured), so `{ (a) stringwidth pop pop } loop` or `cshow` on a long string ends // within the budget like any other loop instead of running for minutes. @@ -487,17 +606,35 @@ impl Interp<'_> { if !(size.is_finite() && size > 1e-3 && size < 1e5) { return ps_err("undefinedresult", "a font size"); } - let (family, font_style) = family_style(&name); - // The available family's own spelling: `MicrosoftYaHei` is Microsoft YaHei, not "Microsoft Ya Hei". - let font_family = vectorcraft_text::FontDb::global().find_family(&family).unwrap_or(family); + // The installed face of that PostScript name, as type from a text document takes it; else + // the available family's own spelling: `MicrosoftYaHei` is Microsoft YaHei, not "Microsoft Ya Hei". + let (font_family, font_style, font_version) = document_font(&name, None); let fill = if self.g.paint.is_none() { Paint::solid(vectorcraft_color::Color::BLACK) } else { self.g.paint.clone() }; - let style = CharStyle { font_family, font_style, size, fill, stroke: Paint::None, ..CharStyle::default() }; + let style = CharStyle { font_family, font_style, font_version, size, fill, stroke: Paint::None, ..CharStyle::default() }; let mut t = TextObject::point(Point::ZERO, text, style); + t.vertical = vertical; let layout = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); t.xf = m * Affine::scale_non_uniform(1.0 / size, -1.0 / size); t.cached_bounds = Some(layout.bounds); let adv: f64 = layout.glyphs.iter().map(|g| g.advance).sum(); - Ok((t, layout, f1 * Point::new(adv / size, 0.0) - f1 * Point::ZERO)) + let moved = if vertical { Point::new(0.0, -adv / size) } else { Point::new(adv / size, 0.0) }; + Ok((t, layout, f1 * moved - f1 * Point::ZERO)) + } + + /// [`Self::set_text_in`] for characters the file places one by one: where the layout joins + /// characters in a ligature, the type is set without ligatures, so each character has its own + /// advance. + fn set_placed_text(&mut self, text: &str, at: Point, vertical: bool) -> Res<(TextObject, TextLayout)> { + let (mut t, mut layout, _) = self.set_text_in(text, at, vertical)?; + let glyph_starts: std::collections::HashSet = layout.glyphs.iter().map(|g| g.byte).collect(); + if text.char_indices().any(|(b, _)| !glyph_starts.contains(&b)) { + for run in &mut t.runs { + run.style.features.push("-liga".into()); + } + layout = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + t.cached_bounds = Some(layout.bounds); + } + Ok((t, layout)) } /// `show`: point type at the current point, which moves past it. @@ -527,27 +664,40 @@ impl Interp<'_> { return self.show_type42_outlines(data, glyphs, s, spacing, at, f1); } // Each code's character, if it has one that shows (control codes don't). - let chars: Vec> = match &plain { + let chars = match &plain { Some((_, glyphs)) => glyphs.iter().map(|g| g.ch).collect::>(), None => self.named_chars(s).into_iter().map(Some).collect(), + }; + let mut codes = Decoded::default(); + for (c, &code) in chars.into_iter().zip(s) { + codes.push(u32::from(code), c.filter(|c| !c.is_control())); } - .into_iter() - .map(|c| c.filter(|c| !c.is_control())) - .collect(); - let text: String = chars.iter().flatten().collect(); - let (mut t, mut layout, _) = self.set_text(&text, at)?; + let widths: Option> = plain.map(|(_, glyphs)| glyphs.iter().map(|g| g.width).collect()); + self.show_codes(&codes, widths.as_deref(), spacing, false, s, Draw::Fill) + } + + /// The codes `codes` (each standing for some of its characters, or none) shown in the current + /// font as [`Self::show_plain`] shows a string's, spaced as `spacing` says, each code `widths` + /// wide when given (in glyph space, one unit an em), else as wide as its characters' advances; + /// as vertical type when `vertical`, the codes moving the point down the column. `kern` holds + /// the codes `kshow` gives its procedure, one for each code. With `draw` [`Draw::Path`] the + /// type's glyph outlines are added to the current path, placed as the type would be + /// (`charpath`). + fn show_codes>( + &mut self, + codes: &Decoded, + widths: Option<&[f64]>, + spacing: &Spacing, + vertical: bool, + kern: &[C], + draw: Draw, + ) -> Res { + let at = self.user_point()?; + let (_, f1) = self.font()?; + let text = &codes.text; + let (mut t, layout) = self.set_placed_text(text, at, vertical)?; let size = t.runs.first().map_or(1.0, |r| r.style.size); let starts: Vec = text.char_indices().map(|(b, _)| b).collect(); - // The file places each character's glyph: where the layout joins characters in a - // ligature, the type is set without ligatures, so each character has its own advance. - let glyph_starts: std::collections::HashSet = layout.glyphs.iter().map(|g| g.byte).collect(); - if starts.iter().any(|b| !glyph_starts.contains(b)) { - for run in &mut t.runs { - run.style.features.push("-liga".into()); - } - layout = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); - t.cached_bounds = Some(layout.bounds); - } // Each character's advance in the layout (text space). let mut natural = vec![0.0; starts.len()]; for g in &layout.glyphs { @@ -555,48 +705,53 @@ impl Interp<'_> { *n += g.advance; } } - // Each code's move (user space) and that move in text space, along the baseline and across. - let em = |x: f64| f1 * Point::new(x, 0.0) - f1 * Point::ZERO; + // Each code's move (user space) and that move in text space, along the baseline (down the + // column) and across. + let em = |x: f64| f1 * if vertical { Point::new(0.0, -x) } else { Point::new(x, 0.0) } - f1 * Point::ZERO; let inv = f1.inverse(); - let mut moves = Vec::with_capacity(s.len()); + let mut moves = Vec::with_capacity(codes.codes.len()); let mut k = 0; // What `kshow`'s procedure draws goes after the type. let start = self.out.drawn.len(); let mut pen = at; - for (i, (&code, c)) in s.iter().zip(&chars).enumerate() { - let own = match &plain { - Some((_, glyphs)) => glyphs.get(i).map_or(0.0, |g| g.width), - None if c.is_some() => natural.get(k).copied().unwrap_or(0.0) / size, - None => 0.0, + for (i, &(code, n)) in codes.codes.iter().enumerate() { + let own = match widths { + Some(widths) => widths.get(i).copied().unwrap_or(0.0), + None => natural.get(k..k + n).map_or(0.0, |w| w.iter().sum::()) / size, }; - k += usize::from(c.is_some()); + k += n; let mut d = spacing.advance(i, i64::from(code), em(own)); - d += self.kern(spacing, s, i, pen + d)?; + d += self.kern(spacing, kern, i, pen + d)?; pen += d; let e = inv * Point::new(d.x, d.y) - inv * Point::ZERO; - if ![d.x, d.y, e.x * size, e.y * size].iter().all(|v| v.is_finite()) { + let (along, across) = if vertical { (-e.y * size, e.x * size) } else { (e.x * size, e.y * size) }; + if ![d.x, d.y, along, across].iter().all(|v| v.is_finite()) { return ps_err("undefinedresult", "a show"); } - moves.push((d, e.x * size, e.y * size)); + moves.push((d, along, across)); } let total: Vec2 = moves.iter().map(|m| m.0).sum(); if !(total.x.is_finite() && total.y.is_finite()) { return ps_err("undefinedresult", "a show"); } let across = moves.iter().any(|m| m.2.abs() > size * 1e-3); - // Nothing shows on the null device (`nulldevice`, a Type 3 glyph only measured). - let painted = !self.g.paint.is_none() && !self.g.null; + // Nothing shows on the null device (`nulldevice`, a Type 3 glyph only measured); + // `charpath` adds the outlines there too. + let painted = draw == Draw::Path || (!self.g.paint.is_none() && !self.g.null); if across { // Moves across the baseline (`yshow`, `xyshow`): each character where the file puts it. let mut pen = at; - for ((d, ..), c) in moves.iter().zip(&chars) { - if let Some(c) = c - && painted - && !c.is_whitespace() - { - let (t, ..) = self.set_text(c.encode_utf8(&mut [0; 4]), pen)?; - let clips = self.g.clips.clone(); - self.out.push(Node::new(NodeId(0), NodeKind::Text(Box::new(t))), &clips); + let mut chars = text.chars(); + for ((d, ..), &(_, n)) in moves.iter().zip(&codes.codes) { + let c: String = chars.by_ref().take(n).collect(); + if painted && !c.trim().is_empty() { + let (t, ..) = self.set_text_in(&c, pen, vertical)?; + if draw == Draw::Path { + self.type_path(&t)?; + } else { + let clips = self.g.clips.clone(); + self.out.push(Node::new(NodeId(0), NodeKind::Text(Box::new(t))), &clips); + } } pen += *d; } @@ -605,11 +760,17 @@ impl Interp<'_> { // a character, before the next, are that character's. let mut lead = Vec2::ZERO; let mut target: Vec = Vec::with_capacity(natural.len()); - for ((d, along, _), c) in moves.iter().zip(&chars) { - match (c, target.last_mut()) { - (Some(_), _) => target.push(*along), - (None, Some(last)) => *last += along, - (None, None) => lead += *d, + for ((d, along, _), &(_, n)) in moves.iter().zip(&codes.codes) { + if n > 0 { + // A code of several characters: those before its last keep their advances. + let before = natural.get(target.len()..target.len() + n - 1).unwrap_or_default().to_vec(); + let rest = *along - before.iter().sum::(); + target.extend(before); + target.push(rest); + } else if let Some(last) = target.last_mut() { + *last += along; + } else { + lead += *d; } } let tracking: Vec = target @@ -638,27 +799,62 @@ impl Interp<'_> { if lead != Vec2::ZERO { t.xf = Affine::translate(self.xf() * Point::new(lead.x, lead.y) - self.xf() * Point::ZERO) * t.xf; } - let clips = self.g.clips.clone(); - if self.out.push(Node::new(NodeId(0), NodeKind::Text(Box::new(t))), &clips).is_some() - && let Some(after) = self.out.drawn.get_mut(start..) - { - after.rotate_right(1); + if draw == Draw::Path { + self.type_path(&t)?; + } else { + let clips = self.g.clips.clone(); + if self.out.push(Node::new(NodeId(0), NodeKind::Text(Box::new(t))), &clips).is_some() + && let Some(after) = self.out.drawn.get_mut(start..) + { + after.rotate_right(1); + } } } self.g.cur = Some(self.xf() * (at + total)); Ok(()) } - /// `kshow` between character `i` of `s` and the next: its procedure run with the two codes - /// and the current point at user point `pen` (PLRM 3rd ed., `kshow`: the procedure may - /// change the current point, as kerning does) → how far it moved the point (user space). + /// The glyph outlines of point type `t` added to the current path (`charpath`). + fn type_path(&mut self, t: &TextObject) -> Res { + let layout = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + for g in &layout.glyphs { + let mut o = g.outline.clone(); + o.apply_affine(t.xf); + self.extend_path(o)?; + } + Ok(()) + } + + /// Glyph outline `o` added to the current path, unless the path would pass its most points. + fn extend_path(&mut self, o: vectorcraft_geom::BezPath) -> Res { + if self.g.path.elements().len().saturating_add(o.elements().len()) > super::graphics::MAX_PATH { + return Err(PsError::Limit("a path has too many points")); + } + self.g.path.extend(o); + Ok(()) + } + + /// `kshow` between character `i` of `s` (its codes) and the next: its procedure run with the + /// two codes and the current point at user point `pen` (PLRM 3rd ed., `kshow`: the procedure + /// may change the current point, as kerning does) → how far it moved the point (user space). /// Nothing for other show operators or after the last character. - fn kern(&mut self, spacing: &Spacing, s: &[u8], i: usize, pen: Point) -> Res { + fn kern>(&mut self, spacing: &Spacing, s: &[C], i: usize, pen: Point) -> Res { let (Spacing::Kern(p), Some(&code), Some(&next)) = (spacing, s.get(i), s.get(i + 1)) else { return Ok(Vec2::ZERO) }; self.g.cur = Some(self.xf() * pen); - self.push(Obj::Int(i64::from(code)))?; - self.push(Obj::Int(i64::from(next)))?; - self.call(p.clone())?; + self.push(Obj::Int(code.into()))?; + self.push(Obj::Int(next.into()))?; + // The procedure sees the font the file set, not the one type in a CIDFont only named is + // set in, and the current font is restored when it completes (PLRM 3rd ed., `kshow`). + // A `kshow` the procedure runs sees the font the procedure set. + let outer = self.kshow_font.take(); + let inner = match outer.clone() { + Some(outer) => self.g.font.replace(outer), + None => self.g.font.clone(), + }; + let r = self.call(p.clone()); + self.kshow_font = outer; + self.g.font = inner; + r?; Ok(self.user_point()? - pen) } @@ -709,15 +905,14 @@ impl Interp<'_> { if paint == Draw::Fill { return self.fill_path(outline, vectorcraft_geom::FillRule::NonZero); } - if self.g.path.elements().len().saturating_add(outline.elements().len()) > super::graphics::MAX_PATH { - return Err(PsError::Limit("a path has too many points")); - } - self.g.path.extend(outline); - Ok(()) + self.extend_path(outline) } /// `charpath`: the glyph outlines of `s` added to the path. fn char_path(&mut self, s: &[u8]) -> Res { + if let Some(named) = self.named_cid_type(s)? { + return self.show_named_cid(&named, &Spacing::Plain, Draw::Path); + } if let Some(glyphs) = self.composite_glyphs(s)? { for g in &glyphs { let at = self.user_point()?; @@ -743,10 +938,9 @@ impl Interp<'_> { let at = self.user_point()?; let (t, layout, adv) = self.set_type(s, at)?; for g in &layout.glyphs { - self.grow()?; let mut o = g.outline.clone(); o.apply_affine(t.xf); - self.g.path.extend(o); + self.extend_path(o)?; } self.g.cur = Some(self.xf() * (at + adv)); Ok(()) @@ -807,6 +1001,25 @@ struct Mapped { vertical: bool, } +/// Type in a CIDFont only named, over a predefined CMap ([`Interp::named_cid_type`]): its codes +/// with their characters, the font it is set in, whether it runs down a column, and whether each +/// code moves the point one em (down a column, or in a CMap VectorCraft can't read). +struct NamedCid { + codes: Decoded, + font: DictRef, + vertical: bool, + ems: bool, +} + +/// A `cshow` procedure running over type in a CIDFont only named ([`Interp::named_cshow`]): the +/// CIDFont it sees as current, the composite font `rootfont` gives while that CIDFont is current, +/// and the type of the code it was given. +pub(super) struct CShowFont { + selected: DictRef, + root: DictRef, + code: NamedCid, +} + /// What drawing a glyph does with it. #[derive(Clone, Copy, PartialEq)] enum Draw { @@ -931,23 +1144,85 @@ impl Interp<'_> { .collect()) } - /// The characters of `s` and the font to set them in when the current font is a CID-keyed - /// font over a predefined Unicode CMap the file doesn't define (`UniJIS-UCS2-H`), whose - /// mappings to CIDs aren't known: its codes say the characters, set as type in the font of - /// its CIDFont's name. - fn unicode_type(&mut self, s: &[u8]) -> Res> { - let Some((text, font, name)) = self.unicode_parts(s) else { return Ok(None) }; + /// The codes of `s` with the characters each stands for, the font to set them in and whether + /// they run down a column, when the current font is a CID-keyed font over a predefined CMap + /// the file doesn't define (`UniJIS-UCS2-H`, `90ms-RKSJ-H`), whose mappings to CIDs the file + /// doesn't give: a Unicode CMap's codes are the characters, another CMap's are read by the CMap + /// of that name and its character collection's CID → Unicode CMap (a code it doesn't map + /// stands for none), set as type in the font of its CIDFont's name, vertical over a vertical + /// CMap (`WMode` 1). Control codes stand for no character. Type in a CMap VectorCraft can't + /// read is left out, with a warning, each of its codes moving the point one em. + /// Inside a `cshow` procedure over such type, with the CIDFont current, the string must be the + /// one byte the procedure was given, else a `rangecheck` error, and it stands for the code + /// the procedure was given (PLRM 3rd ed., `cshow`: the glyph of the selected CID). + fn named_cid_type(&mut self, s: &[u8]) -> Res> { + if let Some(named) = self.cshow_code(true) { + let given = named.codes.codes.first().map(|&(code, _)| code & 0xff); + if s.len() != 1 || given != s.first().map(|&b| u32::from(b)) { + return ps_err("rangecheck", "a string shown in cshow"); + } + return Ok(Some(named)); + } + let Some(cmap) = self.named_cid_parts().map(|(cmap, ..)| cmap) else { return Ok(None) }; + // Each code is looked up in the CMap's mappings. + self.spend(s.len() as u64)?; + // The decoded codes and characters are held while the string is shown: checked against + // the memory budget first, so a huge string in the file stops the program with an error. + let held = s.len().saturating_mul(DECODED_BYTES); + self.alloc(held)?; + self.unalloc(held); + let (decoded, read) = match self.predefined_codes(&cmap) { + Some(codes) => (codes.codes(s), true), + None => { + self.out.warn(UNREAD_CMAP); + (super::predefined_cmap::unread_codes(&cmap, s), false) + } + }; + let Some(mut named) = self.named_cid_font()? else { return Ok(None) }; + let mut chars = decoded.text.chars(); + for &(code, n) in &decoded.codes { + named.codes.push(code, chars.by_ref().take(n).filter(|c| !c.is_control())); + } + named.ems |= !read; + Ok(Some(named)) + } + + /// The font [`Self::named_cid_type`] sets type in, with no codes yet, when the current font is + /// a CID-keyed font over a predefined CMap the file doesn't define. + fn named_cid_font(&mut self) -> Res> { + if let Some(named) = self.cshow_code(false) { + return Ok(Some(named)); + } + let Some((_, font, name, vertical)) = self.named_cid_parts() else { return Ok(None) }; // The composite font is copied under the CIDFont's name for every string: charged by // its size, so a huge font dictionary shown in a loop runs out of the budget. let entries = font.borrow().len(); self.spend(entries as u64)?; let mut named = font.borrow().clone(); named.insert(Key::name("FontName"), name); - Ok(Some((text, DictRef::new(named)))) + Ok(Some(NamedCid { codes: Decoded::default(), font: DictRef::new(named), vertical, ems: vertical })) } - /// The text, the composite font and the CIDFont's name of [`Self::unicode_type`]. - fn unicode_parts(&self, s: &[u8]) -> Option<(String, DictRef, Obj)> { + /// The type of the code a running `cshow` procedure was given ([`Self::named_cshow`]), with + /// that code when `code` and with none otherwise, while the CIDFont it selected is current. + fn cshow_code(&self, code: bool) -> Option { + let c = self.cshow.as_ref()?; + if !self.g.font.as_ref().is_some_and(|f| f.same(&c.selected)) { + return None; + } + let mut codes = Decoded::default(); + if code { + let mut chars = c.code.codes.text.chars(); + for &(value, n) in &c.code.codes.codes { + codes.push(value, chars.by_ref().take(n)); + } + } + Some(NamedCid { codes, font: c.code.font.clone(), vertical: c.code.vertical, ems: c.code.ems }) + } + + /// The CMap's name, the composite font, the CIDFont's name and the writing mode of + /// [`Self::named_cid_type`]. + fn named_cid_parts(&self) -> Option<(String, DictRef, Obj, bool)> { let font = self.g.font.clone()?; let f = font.borrow(); if font_type(&f) != Some(0.0) || f.get(&Key::name("FMapType")).and_then(Obj::as_num) != Some(9.0) { @@ -959,31 +1234,114 @@ impl Interp<'_> { if cmap.contains_key(&Key::name("CodeSpaceRange")) { return None; } - let (form, _) = super::cid::unicode_cmap(&cmap.get(&Key::name("CMapName")).and_then(Obj::text)?)?; + let cmap_name = cmap.get(&Key::name("CMapName")).and_then(Obj::text)?.to_string(); + if !super::predefined_cmap::known(&cmap_name) { + return None; + } + let wmode = f.get(&Key::name("WMode")).or_else(|| cmap.get(&Key::name("WMode"))).and_then(Obj::as_num); let Some(Obj::Dict(dep)) = f.get(&Key::name("FDepVector")).and_then(|v| v.items()?.get(0)) else { return None }; let name = { let d = dep.borrow(); d.get(&Key::name("CIDFontName")).or_else(|| d.get(&Key::name("FontName"))).cloned()? }; - Some((super::cid::unicode_text(s, form), font.clone(), name)) + Some((cmap_name, font.clone(), name, wmode == Some(1.0))) } - /// `text` set as point type at the current point in font `font` (see - /// [`Self::unicode_type`]), which moves past it. - fn show_unicode(&mut self, text: &str, font: &DictRef) -> Res { - let at = self.user_point()?; - let saved = self.g.font.replace(font.clone()); - let r = self.set_text(text, at); + /// How strings in predefined CMap `cmap` decode (a CMap other than a Unicode CMap read once a + /// file); `None` when VectorCraft can't read it. + fn predefined_codes(&mut self, cmap: &str) -> Option> { + if let Some(form) = super::predefined_cmap::unicode_cmap(cmap) { + return Some(Rc::new(super::predefined_cmap::CMapCodes::Unicode(form))); + } + if let Some((_, codes)) = self.predefined_cmaps.iter().find(|(n, _)| **n == *cmap) { + return codes.clone(); + } + let codes = super::predefined_cmap::codes(cmap).map(Rc::new); + // Only the names of the other predefined CMaps reach here (`named_cid_parts`), so the + // list stays short. + self.predefined_cmaps.push((Rc::from(cmap), codes.clone())); + codes + } + + /// Type `named` (see [`Self::named_cid_type`]) set as point type at the current point in its + /// font, running down a column when it is vertical, which moves past it, spaced as `spacing` + /// says, as [`Self::show_codes`] shows codes. `widthshow` and `awidthshow` match a code by its + /// value (font number 0 times 256 plus the code: PLRM 3rd ed., `widthshow` in chapter 8), and + /// `kshow`'s procedure gets the values of the two codes it runs between. Down a column, and in + /// a CMap VectorCraft can't read, each code moves the point one em, the default displacement + /// of a CIDFont whose metrics the file doesn't give (PDF Reference 1.7, §5.6.3, `DW` and + /// `DW2`). With `draw` [`Draw::Path`] the outlines go on the current path (`charpath`). + fn show_named_cid(&mut self, named: &NamedCid, spacing: &Spacing, draw: Draw) -> Res { + let widths = named.ems.then(|| vec![1.0; named.codes.codes.len()]); + let kern: Vec = match spacing { + Spacing::Kern(_) => named.codes.codes.iter().map(|&(code, _)| code).collect(), + _ => Vec::new(), + }; + let saved = self.g.font.replace(named.font.clone()); + let before = std::mem::replace(&mut self.kshow_font, saved.clone()); + let r = self.show_codes(&named.codes, widths.as_deref(), spacing, named.vertical, &kern, draw); + self.kshow_font = before; self.g.font = saved; - let (t, _, adv) = r?; - if !self.g.paint.is_none() && !self.g.null && !text.trim().is_empty() { - let clips = self.g.clips.clone(); - self.out.push(Node::new(NodeId(0), NodeKind::Text(Box::new(t))), &clips); + r + } + + /// `cshow`'s procedure `proc` run for each code of type `named` in composite font `root`, with + /// the code's last byte and its width (PLRM 3rd ed., `cshow`). While it runs the CIDFont is the + /// current font and `rootfont` gives `root`; a show operator in the CIDFont shows the code's + /// character, whatever its string (see [`Self::named_cid_type`]). The current font is restored + /// when the procedure completes. + fn named_cshow(&mut self, named: NamedCid, proc: &Obj, root: Option) -> Res { + let Some(composite) = root.clone() else { return Ok(()) }; + let dep = named.font.borrow().get(&Key::name("FDepVector")).and_then(|v| v.items()?.get(0)); + let selected = match dep { + Some(Obj::Dict(d)) => d, + _ => named.font.clone(), + }; + let mut chars = named.codes.text.chars(); + for &(code, n) in &named.codes.codes { + let mut one = NamedCid { codes: Decoded::default(), font: named.font.clone(), vertical: named.vertical, ems: named.ems }; + one.codes.push(code, chars.by_ref().take(n)); + let v = self.named_cid_width(&one, &one.codes)?; + self.push(Obj::Int(i64::from(code & 0xff)))?; + self.push_num(v.x)?; + self.push_num(v.y)?; + self.cshow = Some(CShowFont { selected: selected.clone(), root: composite.clone(), code: one }); + self.g.font = Some(selected.clone()); + let go = self.body(proc); + self.g.font = root.clone(); + if !go? { + break; + } } - self.g.cur = Some(self.xf() * (at + adv)); Ok(()) } + /// How far codes `codes` of type `named` move the current point (user space) when + /// [`Self::show_named_cid`] shows them with no extra spacing. + fn named_cid_width(&mut self, named: &NamedCid, codes: &Decoded) -> Res { + let saved = self.g.font.replace(named.font.clone()); + let r = self.named_cid_moved(codes, named.vertical, named.ems); + self.g.font = saved; + r + } + + /// [`Self::named_cid_width`] in the current font: codes `codes`, vertical when `vertical`, + /// each one em when `ems`. + fn named_cid_moved(&mut self, codes: &Decoded, vertical: bool, ems: bool) -> Res { + let (_, f1) = self.font()?; + let n = codes.codes.len() as f64; + let moved = match (vertical, ems) { + (true, _) => Point::new(0.0, -n), + (false, true) => Point::new(n, 0.0), + (false, false) => { + let (t, layout) = self.set_placed_text(&codes.text, Point::ZERO, false)?; + let size = t.runs.first().map_or(1.0, |r| r.style.size); + Point::new(layout.glyphs.iter().map(|g| g.advance).sum::() / size, 0.0) + } + }; + Ok(f1 * moved - f1 * Point::ZERO) + } + /// The characters of a composite font shown at the current point, spaced as `spacing` says. fn show_composite(&mut self, glyphs: &[Mapped], spacing: &Spacing) -> Res { let start = self.out.drawn.len(); @@ -1282,6 +1640,13 @@ const MAX_TYPE1: usize = 256; /// The warning for CID-keyed type in a CIDFont the file doesn't carry. const MISSING_CID_FONT: &str = "CID-keyed type in a font the file doesn't carry was left out"; +/// Most bytes [`Interp::named_cid_type`] holds for each byte of a string: two lists of codes (16 +/// bytes a code) and their characters (up to 4 bytes a character, a few characters a code). +const DECODED_BYTES: usize = 64; + +/// The warning for type in a predefined CMap whose mappings VectorCraft doesn't have. +pub(super) const UNREAD_CMAP: &str = "type in a CMap that couldn't be read was left out"; + /// Most Type 42 fonts whose TrueType data is kept between glyphs. const MAX_TYPE42: usize = 16; diff --git a/crates/eps/src/legacy_ai.rs b/crates/eps/src/legacy_ai.rs index 68c7610308..00bb29d12f 100644 --- a/crates/eps/src/legacy_ai.rs +++ b/crates/eps/src/legacy_ai.rs @@ -33,7 +33,10 @@ //! - Type (§15): point type, area type and type on a path as text objects, `type To`, `a b c d tx //! ty startPt Tp` (the text matrix; the frame or path in art space between it and `TP`), each //! run's paint style, `Tr` (fill, stroke, both or neither), `/_font size ascent descent Tf`, -//! `Ts Tz Tt TA Tl Ta Ti` and its characters `(…) Tx` (`\r` ends a paragraph), `TO`. Only the +//! `Ts Tz Tt TA Tl Ta Ti` and its characters `(…) Tx` (`\r` ends a paragraph), `TO`. Standard +//! Vertical Roman Alignment is written as `1 Tv` and `0 Tv`, and Tate-chu-yoko in horizontal +//! type as a Kumi block recorded for later use, `1 TY` … `0 TY` (§15.3.4); neither operator is +//! written for type that has neither mark. Only the //! revisable form is written: readers lay the type out again (§15.1). Fonts are named by their //! PostScript names in `%%DocumentFonts` and `%%IncludeFont` (§3.1) and re-encoded to //! Windows-1252 (`TE`, then `%AI3_BeginEncoding: _name name`, `TZ`, §3.3), the 8-bit encoding @@ -97,6 +100,7 @@ pub const SUBLAYERS: &str = "sublayers are written as groups in their top-level pub const TYPE: &str = "type a legacy .ai can't hold as text (characters outside Windows Latin-1, vertical type, ruby, inline graphics, gradient or pattern fills) is written as outlines"; pub const ROTATED_TYPE: &str = "type with rotated characters is written as outlines, which keep the rotation, and is no longer editable text (legacy .ai text can't rotate characters)"; pub const TYPE_ATTRIBUTES: &str = "type attributes legacy .ai files don't have (underline, strikethrough, manual kerning, optical kerning, small caps, superscript and subscript, OpenType features, Variable Font settings, optical margin alignment, System Layout, fractional widths off, area type options, type on a path's effect, alignment and spacing, an end bracket short of the path's end, subpaths after the first in an area type frame or a type path, space after paragraphs, tabs, bulleted and numbered lists) are left out"; +pub const DYNAMIC_TEXT: &str = "Dynamic Text is written as the sizes the type is drawn at (legacy .ai files don't have it)"; pub const HIDDEN: &str = "hidden objects are left out (hidden layers are kept, hidden)"; pub const HIDDEN_LAYER: &str = "hidden objects are moved to a hidden layer above their own (legacy .ai files can hide only layers)"; pub const HIDDEN_SHOWN: &str = "hidden objects are written visible (legacy .ai files can hide only layers)"; @@ -108,6 +112,10 @@ pub const NAMES: &str = "object names are left out (legacy .ai files name only l const PATTERNS: &str = "pattern fills are written as their tiles, clipped to the shape"; const FREEFORM: &str = "freeform gradients are written as their average colour"; const CONIC: &str = "conic gradients are written as solid wedges clipped to the shape (legacy .ai files have no conic gradient)"; +const DIAMOND: &str = "diamond gradients are written as four linear gradients clipped to the shape (legacy .ai files have no diamond gradient)"; +const SPREAD: &str = "gradients that repeat or reflect are written with their stops repeated across the shape (legacy .ai gradients only pad)"; +const SPREAD_CAPPED: &str = "gradients that repeat or reflect are written with at most 256 stops; they pad past those"; +const HUE_STOPS: &str = "gradients mixed around the hue wheel are written in process colors, with the colors between their stops as stops of their own (at most 256; legacy .ai gradients mix their stops' colors directly)"; /// Wedges a conic gradient is written as: one a degree. const CONIC_WEDGES: usize = 360; const STROKES: &str = @@ -151,6 +159,8 @@ pub enum HiddenObjects { pub struct LegacyAiOutput { pub bytes: Vec, pub warnings: Vec, + /// Notes on what the options asked for: hidden objects left out or written visible. + pub setting_notes: Vec, } /// Whether image node `n` of `doc` is written as a 1-bit image mask in its colorize color @@ -170,7 +180,7 @@ pub fn writes_image_mask(doc: &Document, n: &Node) -> bool { matches!(n.extras().colorize.as_deref(), Some(Paint::Solid { .. })) && !n.extras().mask.as_ref().is_some_and(|m| !m.disabled) && doc - .image_blob(im) + .image_blob(&doc.shown_image(n, im)) .is_some_and(|b| b.takes_colorize() && fits(&b.bytes) && b.coverage().is_some_and(|(_, _, c)| c.iter().all(|&v| v == 0 || v == 255))) } @@ -262,7 +272,7 @@ pub fn export_legacy_ai(doc: &Document, o: &LegacyAiOptions) -> Result f64 { pub(super) fn direct_fill(p: &Paint) -> bool { match p { Paint::Solid { .. } => true, - Paint::Gradient(g) => !matches!(g.gradient.kind, GradientKind::Freeform | GradientKind::Conic) && !g.gradient.stops.is_empty(), + Paint::Gradient(g) => { + !matches!(g.gradient.kind, GradientKind::Freeform | GradientKind::Conic | GradientKind::Diamond) && !g.gradient.stops.is_empty() + } _ => false, } } diff --git a/crates/eps/src/legacy_ai/prolog.rs b/crates/eps/src/legacy_ai/prolog.rs index b0d606bba9..5ee77f89cf 100644 --- a/crates/eps/src/legacy_ai/prolog.rs +++ b/crates/eps/src/legacy_ai/prolog.rs @@ -106,7 +106,7 @@ VCLegacy begin /TE {cleartomark} bd /TZ {cleartomark} bd /To {pop} bd /Tp {7 {pop} repeat} bd /TP {} bd /TO {} bd /Tr {pop} bd /Tf {pop pop pop pop} bd /Ts {pop} bd /Tz {pop pop} bd /Tt {pop} bd /TA {pop} bd -/Tl {pop pop} bd /Ta {pop} bd /Ti {pop pop pop} bd /Tx {pop} bd +/Tl {pop pop} bd /Ta {pop} bd /Ti {pop pop pop} bd /Tx {pop} bd /Tv {pop} bd /TY {pop} bd % The page trailer (3): annotatepage marks nothing. /annotatepage {} bd end diff --git a/crates/eps/src/legacy_ai/tests.rs b/crates/eps/src/legacy_ai/tests.rs index 8917c9aa73..6b2f8335b8 100644 --- a/crates/eps/src/legacy_ai/tests.rs +++ b/crates/eps/src/legacy_ai/tests.rs @@ -110,6 +110,214 @@ fn conic_gradients_are_written_as_wedges_clipped_to_the_shape() { } } +/// The format's gradients pad past their ends: a linear gradient that repeats or reflects is +/// written with its stops repeated across the shape (a definition of its own, not named after the +/// swatch), and a conic one as wedges that repeat with the stops (which print as the canvas +/// draws them), with a warning. +#[test] +fn spread_gradients_are_written_with_their_stops_repeated() { + use vectorcraft_color::{GradientGeom, GradientSpread}; + 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 linear = |spread| { + let mut g = GradientPaint::new(Gradient { spread, repeats: 3, ..Gradient::new(GradientKind::Linear, stops.clone()) }); + // Across the shape: three runs. + g.geom = Some(GradientGeom { + start: vectorcraft_geom::Point::new(20.0, 50.0), + end: vectorcraft_geom::Point::new(180.0, 50.0), + aspect: 1.0, + focal: None, + }); + g.swatch = Some("Bands".into()); + Paint::Gradient(Box::new(g)) + }; + for (spread, colors) in [ + (GradientSpread::Repeat, ["0 0 1", "1 0 0", "0 0 1", "1 0 0", "0 0 1", "1 0 0"]), + (GradientSpread::Reflect, ["0 0 1", "1 0 0", "1 0 0", "0 0 1", "0 0 1", "1 0 0"]), + ] { + let mut doc = Document::new(200.0, 100.0); + let n = shape(&mut doc, shapes::rectangle(Rect::new(20.0, 10.0, 180.0, 90.0)), linear(spread), Paint::None); + let l = doc.layers[0].id; + doc.insert(Some(l), 0, n).unwrap(); + let out = write(&doc); + assert!(out.warnings.iter().any(|w| w == SPREAD), "{:?}", out.warnings); + let text = String::from_utf8_lossy(&out.bytes); + assert!(text.contains("(Gradient) 0 6 Bd") && !text.contains("(Bands)"), "{text}"); + // A linear definition lists its stops from the last to the first, each RGB stop as + // `c m y k r g b 2 …`. + let def = text.split("(Gradient) 0 6 Bd\n[\n").nth(1).unwrap(); + for (line, rgb) in def.lines().take(6).zip(colors) { + assert!(line.contains(&format!(" {rgb} 2 ")), "{spread:?}: {line} lacks {rgb}\n{def}"); + } + } + let mut g = GradientPaint::new(Gradient { spread: GradientSpread::Reflect, repeats: 3, ..Gradient::new(GradientKind::Conic, stops) }); + g.geom = Some(GradientGeom { + start: vectorcraft_geom::Point::new(100.0, 50.0), + end: vectorcraft_geom::Point::new(140.0, 30.0), + aspect: 1.0, + focal: None, + }); + let mut doc = Document::new(200.0, 100.0); + let n = shape(&mut doc, shapes::ellipse(Rect::new(20.0, 10.0, 180.0, 90.0)), Paint::Gradient(Box::new(g)), Paint::None); + let l = doc.layers[0].id; + doc.insert(Some(l), 0, n).unwrap(); + let text = String::from_utf8_lossy(&write(&doc).bytes).into_owned(); + assert!(text.matches("\nf\n").count() >= 3 * CONIC_WEDGES, "a wedge a degree for each run"); +} + +/// A gradient repeated more times than the reader keeps stops for is written with no more stops +/// than it reads, with a warning, so it opens with every stop that was written. +#[test] +fn many_repeats_are_written_within_the_stops_the_reader_reads() { + use vectorcraft_color::{GradientGeom, GradientSpread}; + 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))]; + // A run of 0.4 pt across a shape 160 pt wide: 400 runs. + let mut g = GradientPaint::new(Gradient { spread: GradientSpread::Repeat, repeats: 100, ..Gradient::new(GradientKind::Linear, stops) }); + g.geom = Some(GradientGeom { + start: vectorcraft_geom::Point::new(20.0, 50.0), + end: vectorcraft_geom::Point::new(60.0, 50.0), + aspect: 1.0, + focal: None, + }); + let mut doc = Document::new(200.0, 100.0); + let n = shape(&mut doc, shapes::rectangle(Rect::new(20.0, 10.0, 180.0, 90.0)), Paint::Gradient(Box::new(g)), Paint::None); + let l = doc.layers[0].id; + doc.insert(Some(l), 0, n).unwrap(); + let out = write(&doc); + assert!(out.warnings.iter().any(|w| w == SPREAD_CAPPED), "{:?}", out.warnings); + let text = String::from_utf8_lossy(&out.bytes).into_owned(); + let def = text.split("%AI5_BeginGradient: (Gradient)\n").nth(1).and_then(|d| d.split("%AI5_EndGradient").next()).unwrap(); + let written = def.matches(" %_Bs\n").count(); + assert!((2..=crate::import::MAX_GRADIENT_STOPS).contains(&written), "{written} stops"); + let read = crate::import(&out.bytes).unwrap().document; + let mut stops = None; + read.walk(|n| { + if let (None, Paint::Gradient(g)) = (&stops, n.appearance.fill_paint()) { + stops = Some(g.gradient.stops.len()); + } + }); + assert_eq!(stops, Some(written), "every stop written is read"); +} + +/// The format's gradients mix their stops' colors directly: a gradient mixed around the hue wheel +/// is written with the colors on its way around the wheel as stops, no more than the reader +/// reads, with a warning, and opens with the colors it had. +#[test] +fn hue_wheel_gradients_are_written_with_the_stops_on_their_curve() { + use vectorcraft_color::GradientMethod; + for (method, middle) in [(GradientMethod::HueCounterclockwise, [0.0, 1.0, 0.0]), (GradientMethod::HueClockwise, [1.0, 0.0, 1.0])] { + 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 g = GradientPaint::new(Gradient { method, ..Gradient::new(GradientKind::Linear, stops) }); + let want = g.gradient.clone(); + let mut doc = Document::new(200.0, 100.0); + let n = shape(&mut doc, shapes::rectangle(Rect::new(20.0, 10.0, 180.0, 90.0)), Paint::Gradient(Box::new(g)), Paint::None); + let l = doc.layers[0].id; + doc.insert(Some(l), 0, n).unwrap(); + let out = write(&doc); + assert!(out.warnings.iter().any(|w| w == HUE_STOPS), "{method:?}: {:?}", out.warnings); + let text = String::from_utf8_lossy(&out.bytes).into_owned(); + let def = text.split("%AI5_BeginGradient: (Gradient)\n").nth(1).and_then(|d| d.split("%AI5_EndGradient").next()).unwrap(); + let written = def.matches(" %_Bs\n").count(); + // The two ends and each sixth of the wheel between them, where the way turns in RGB. + assert!((3..=crate::import::MAX_GRADIENT_STOPS).contains(&written), "{method:?}: {written} stops"); + let read = crate::import(&out.bytes).unwrap().document; + let mut back = None; + read.walk(|n| { + if let (None, Paint::Gradient(g)) = (&back, n.appearance.fill_paint()) { + back = Some(g.gradient.clone()); + } + }); + let back = back.unwrap(); + assert!(back.method.is_classic(), "{method:?}"); + let mid = back.sample(0.5).0.to_rgb(); + assert!(mid.iter().zip(middle).all(|(a, b)| (a - b).abs() < 0.03), "{method:?}: the middle is {mid:?}"); + for k in 0..=100 { + let t = k as f32 / 100.0; + let (a, b) = (want.sample(t).0.to_rgb(), back.sample(t).0.to_rgb()); + assert!(a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.03), "{method:?} at {t}: {a:?} vs {b:?}"); + } + } +} + +/// A radial gradient repeated out from a center far from the shape is written with its ramp points +/// (percent) to five decimals, so its runs keep their places hundreds of runs out. +#[test] +fn far_runs_keep_their_places() { + use vectorcraft_color::{GradientGeom, GradientSpread}; + 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 mut g = GradientPaint::new(Gradient { spread: GradientSpread::Repeat, ..Gradient::new(GradientKind::Radial, stops) }); + // Runs 0.25 pt apart, the shape 480 runs and more from the center. + let c = vectorcraft_geom::Point::new(-100.0, 50.0); + g.geom = Some(GradientGeom { start: c, end: c + vectorcraft_geom::Vec2::new(0.25, 0.0), aspect: 1.0, focal: None }); + let bounds = Rect::new(20.0, 10.0, 180.0, 90.0); + let padded = g.gradient.padded_within(&g.geom.unwrap(), bounds, crate::import::MAX_GRADIENT_STOPS).unwrap(); + let mut doc = Document::new(200.0, 100.0); + let n = shape(&mut doc, shapes::rectangle(bounds), Paint::Gradient(Box::new(g)), Paint::None); + let l = doc.layers[0].id; + doc.insert(Some(l), 0, n).unwrap(); + let text = String::from_utf8_lossy(&write(&doc).bytes).into_owned(); + let def = text.split("%AI5_BeginGradient: (Gradient)\n").nth(1).and_then(|d| d.split("%AI5_EndGradient").next()).unwrap(); + let ramps: Vec = def.lines().filter_map(|l| l.strip_suffix(" %_Bs")).map(|l| l.rsplit(' ').next().unwrap().parse().unwrap()).collect(); + assert_eq!(ramps.len(), padded.gradient.stops.len()); + for (ramp, stop) in ramps.iter().zip(&padded.gradient.stops) { + assert!((ramp / 100.0 - f64::from(stop.offset)).abs() < 2e-7, "{ramp} for {}", stop.offset); + } +} + +/// The format has no diamond gradient: a diamond fill, and a diamond stroke (written as its filled +/// outline), are four path objects clipped to the shape, each a linear gradient over a quadrant +/// of the diamond's frame, with a warning; the definition is not named after the swatch. +#[test] +fn diamond_gradients_are_written_as_four_linear_gradients_clipped_to_the_shape() { + 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 mut g = GradientPaint::new(Gradient::new(GradientKind::Diamond, stops)); + g.geom = Some(vectorcraft_color::GradientGeom { + start: vectorcraft_geom::Point::new(100.0, 50.0), + end: vectorcraft_geom::Point::new(140.0, 30.0), + aspect: 0.7, + focal: None, + }); + g.swatch = Some("Gem".into()); + let diamond = Paint::Gradient(Box::new(g)); + for (fill, stroke) in [(diamond.clone(), Paint::None), (Paint::None, diamond)] { + let mut doc = Document::new(200.0, 100.0); + let n = shape(&mut doc, shapes::ellipse(Rect::new(20.0, 10.0, 180.0, 90.0)), fill.clone(), stroke.clone()); + let l = doc.layers[0].id; + doc.insert(Some(l), 0, n).unwrap(); + let out = write(&doc); + assert!(out.warnings.iter().any(|w| w == DIAMOND), "{:?}", out.warnings); + let text = String::from_utf8_lossy(&out.bytes); + assert_eq!(text.matches("%AI5_BeginGradient: (Gradient)").count(), 1, "one linear definition: {text}"); + assert!(!text.contains("(Gem)"), "not named after the swatch"); + assert_eq!(text.matches(" Bg\n").count(), 4, "a gradient a quadrant"); + } +} + +/// A diamond gradient that repeats is four linear gradients over the quadrants of its frame, each +/// with its stops repeated out to the shape's edge, with a warning. +#[test] +fn a_spread_diamond_repeats_in_each_quadrant() { + use vectorcraft_color::GradientSpread; + 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 mut g = GradientPaint::new(Gradient { spread: GradientSpread::Repeat, repeats: 3, ..Gradient::new(GradientKind::Diamond, stops) }); + g.geom = Some(vectorcraft_color::GradientGeom { + start: vectorcraft_geom::Point::new(100.0, 50.0), + end: vectorcraft_geom::Point::new(140.0, 30.0), + aspect: 0.7, + focal: None, + }); + let mut doc = Document::new(200.0, 100.0); + let n = shape(&mut doc, shapes::ellipse(Rect::new(20.0, 10.0, 180.0, 90.0)), Paint::Gradient(Box::new(g)), Paint::None); + let l = doc.layers[0].id; + doc.insert(Some(l), 0, n).unwrap(); + let out = write(&doc); + assert!(out.warnings.iter().any(|w| w == DIAMOND) && out.warnings.iter().any(|w| w == SPREAD), "{:?}", out.warnings); + let text = String::from_utf8_lossy(&out.bytes).into_owned(); + assert_eq!(text.matches(" Bg\n").count(), 4, "a gradient a quadrant"); + let defs: Vec = + text.split("%AI5_BeginGradient: ").skip(1).map(|d| d.split("%AI5_EndGradient").next().unwrap_or("").matches(" %_Bs\n").count()).collect(); + assert!(!defs.is_empty() && defs.iter().all(|&n| n >= 6), "stops in each definition: {defs:?}"); +} + /// `doc` written with options `o`. Every file the tests write is also run as a PostScript program /// ([`prints_as`]) and must draw what `doc` draws. fn write_with(doc: &Document, o: LegacyAiOptions) -> LegacyAiOutput { @@ -587,6 +795,28 @@ fn a_gradient_fill_and_its_stroke_are_one_object() { assert_eq!(n.appearance.stroke_paint().color(), Some(Color::rgb(1.0, 0.0, 0.0))); } +/// An RGB gradient stop's CMYK equivalent is the one of its RGB values as written (to four +/// decimals), so the reopened file writes the same stops. +#[test] +fn rgb_stops_are_written_again_unchanged() { + let mut doc = Document::new(100.0, 100.0); + let rgb = |i: u16| { + let v = |s: f32| (f32::from(i) * s + 0.123_456_7).fract(); + Color::rgb(v(0.137_911_3), v(0.271_828_2), v(0.314_159_3)) + }; + let stops = (0..12u16).map(|i| GradientStop::new(f32::from(i) / 11.0, rgb(i))).collect(); + let paint = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))); + let n = shape(&mut doc, shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 50.0)), paint, Paint::None); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let stops = |bytes: Vec| String::from_utf8(bytes).unwrap().lines().filter(|l| l.ends_with("%_Bs")).map(String::from).collect::>(); + let first = write(&doc).bytes; + let again = write(&crate::import(&first).unwrap().document).bytes; + let (first, again) = (stops(first), stops(again)); + assert_eq!(first.len(), 12, "{first:?}"); + assert_eq!(again, first); +} + /// A gradient from white to #1b2a6b, the colors of #2687's circle, placed at `geom` (None: fitted /// to the object). fn white_to_navy(kind: GradientKind, geom: Option) -> Paint { @@ -1164,6 +1394,59 @@ fn variable_font_settings_are_warned_as_left_out() { assert!(String::from_utf8(out.bytes).unwrap().contains("(H\\351llo \\2005\\r) Tx\n"), "still written as text"); } +/// Standard Vertical Roman Alignment is written as `Tv` and Tate-chu-yoko in horizontal type as a +/// Kumi block recorded for later use, `TY` (§15.3.4), each where it changes: the marks read back +/// on the same characters, a block is closed before its text object ends, and type with neither +/// mark has neither operator. +#[test] +fn vertical_roman_and_tate_chu_yoko_are_written_and_read_back() { + use vectorcraft_doc::{TextObject, TextRun}; + let plain = style(12.0, Paint::solid(Color::BLACK)); + let roman = vectorcraft_doc::CharStyle { standard_vertical_roman: true, ..plain.clone() }; + let tcy = vectorcraft_doc::CharStyle { tate_chu_yoko: true, ..plain.clone() }; + let both = vectorcraft_doc::CharStyle { tate_chu_yoko: true, standard_vertical_roman: true, ..plain.clone() }; + let mut doc = Document::new(300.0, 200.0); + let layer = doc.layers[0].id; + let mut marked = TextObject::point(vectorcraft_geom::Point::new(20.0, 40.0), "A", plain.clone()); + for (text, st) in [("12", &tcy), ("b", &roman), ("c", &both), ("34", &tcy)] { + marked.runs.push(TextRun::new(text, st.clone())); + } + let next = TextObject::point(vectorcraft_geom::Point::new(20.0, 80.0), "D", plain.clone()); + for t in [marked, next] { + let n = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t))); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + let out = write(&doc); + assert!(!out.warnings.iter().any(|w| w == TYPE || w == TYPE_ATTRIBUTES), "{:?}", out.warnings); + let text = String::from_utf8(out.bytes.clone()).unwrap(); + assert_eq!((text.matches("1 TY\n").count(), text.matches("0 TY\n").count()), (2, 2), "{text}"); + assert_eq!((text.matches("1 Tv\n").count(), text.matches("0 Tv\n").count()), (1, 1), "{text}"); + // The last block ends before its text object does. + assert!(text.contains("(34) Tx\n0 TY\nTO\n"), "{text}"); + let read = texts(&crate::import(&out.bytes).unwrap().document); + let flags = |t: &TextObject| -> Vec<(String, bool, bool)> { + let mut out: Vec<(String, bool, bool)> = vec![]; + for r in &t.runs { + let key = (r.style.tate_chu_yoko, r.style.standard_vertical_roman); + match out.last_mut() { + Some(last) if (last.1, last.2) == key => last.0.push_str(&r.text), + _ => out.push((r.text.clone(), key.0, key.1)), + } + } + out + }; + let s = |x: &str| x.to_string(); + assert_eq!( + flags(&read[0].1), + [(s("A"), false, false), (s("12"), true, false), (s("b"), false, true), (s("c"), true, true), (s("34"), true, false)] + ); + assert_eq!(flags(&read[1].1), [(s("D"), false, false)]); + + // Type with neither mark has neither operator. + let text = String::from_utf8(write(&typed()).bytes).unwrap(); + assert!(!text.contains(" Tv\n") && !text.contains(" TY\n"), "{text}"); +} + /// A legacy `.ai` text path holds the path and where the type starts on it, and no Align to Path /// or end bracket: type on a path with either is written as text, with the warning that they are /// left out. An end bracket at the end of an open path, or once around a closed one, is kept. A @@ -1263,6 +1546,74 @@ fn a_font_height_reference_is_written_as_the_size_drawn() { assert!((size - 20.0).abs() < 1e-6, "{size}"); } +/// Type on a path with Dynamic Text is written at the sizes it is drawn at, with a warning that +/// the setting itself is not written; without Dynamic Text there is no warning. +#[test] +fn dynamic_text_is_written_at_its_drawn_sizes_with_a_warning() { + let mut doc = typed(); + assert!(!write(&doc).warnings.iter().any(|w| w == DYNAMIC_TEXT)); + let id = texts(&doc).into_iter().find(|(_, t)| matches!(t.kind, vectorcraft_doc::TextKind::OnPath { .. })).unwrap().0.id; + let mut drawn = 0.0; + if let Some(NodeKind::Text(t)) = doc.node_mut(id).map(|n| &mut n.kind) { + t.runs[0].style.size = 4.0; + t.dynamic_text = true; + drawn = 4.0 * vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).fit_scale; + } + assert!(drawn > 4.0, "{drawn}"); + let out = write(&doc); + assert!(out.warnings.iter().any(|w| w == DYNAMIC_TEXT), "{:?}", out.warnings); + let imported = crate::import(&out.bytes).unwrap(); + let (_, back) = texts(&imported.document).into_iter().find(|(_, t)| t.runs.iter().any(|r| r.text.contains("path"))).unwrap(); + assert!(!back.dynamic_text); + assert!((back.runs[0].style.size - drawn).abs() < 1e-3, "{} vs {drawn}", back.runs[0].style.size); + // Type written as outlines loses the setting too, and says so. + if let Some(NodeKind::Text(t)) = doc.node_mut(id).map(|n| &mut n.kind) { + t.runs[0].text.push('\u{2192}'); + } + let out = write(&doc); + assert!(out.warnings.iter().any(|w| w == TYPE) && out.warnings.iter().any(|w| w == DYNAMIC_TEXT), "{:?}", out.warnings); + let out = write_with(&doc, LegacyAiOptions { outline_text: true, ..LegacyAiOptions::default() }); + assert!(out.warnings.iter().any(|w| w == DYNAMIC_TEXT), "{:?}", out.warnings); +} + +/// Dynamic Text fits type whose size measures the cap height at the size the Character panel +/// shows: 1,000 pt measuring a 0.7 em cap height on a long path grows to the 1,296 pt limit and is +/// written at the em size drawn there, as text and as outlines. +#[test] +fn dynamic_text_with_a_font_height_reference_is_written_at_its_drawn_size() { + use vectorcraft_doc::{TextKind, TextObject}; + use vectorcraft_text::test_fonts::{HEIGHT_FAMILY, height_font}; + let db = vectorcraft_text::FontDb::global(); + db.add_font(height_font(true).unwrap()); + let mut t = TextObject::point(vectorcraft_geom::Point::ZERO, "HE", style(1000.0, red())); + let st = &mut t.runs[0].style; + st.font_family = HEIGHT_FAMILY.into(); + st.font_height_reference = vectorcraft_doc::FontHeightReference::CapHeight; + let mut line = PathData::new(vec![]); + line.subpaths.push(vectorcraft_geom::SubPath::polyline(&[(0.0, 2000.0).into(), (100_000.0, 2000.0).into()], false)); + t.kind = TextKind::OnPath { path: line, start: 0.0, end: None }; + t.xf = Affine::IDENTITY; + t.dynamic_text = true; + let lay = vectorcraft_text::layout(db, &t); + assert!((lay.fit_scale - 1.296).abs() < 1e-9, "{}", lay.fit_scale); + let em = 1296.0 / 0.7; + let mut glyphs = kurbo::BezPath::new(); + for g in &lay.glyphs { + glyphs.extend(g.outline.iter()); + } + let want = glyphs.bounding_box(); + let mut doc = Document::new(300.0, 200.0); + let layer = doc.layers[0].id; + let n = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t))); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let back = crate::import(&write(&doc).bytes).unwrap().document; + let size = texts(&back)[0].1.runs[0].style.size; + assert!((size - em).abs() < 1e-3, "{size} vs {em}"); + let back = crate::import(&write_with(&doc, LegacyAiOptions { outline_text: true, ..LegacyAiOptions::default() }).bytes).unwrap().document; + let b = children(&children(&back.layers[0])[0])[0].visual_bounds().unwrap(); + assert!((b.height() - want.height()).abs() < 0.05 && (b.width() - want.width()).abs() < 0.05, "{b:?}, laid out at {want:?}"); +} + /// Characters with Auto leading are written with their paragraph's Auto Leading share of the /// size: 18 pt type in paragraphs at 150% is written with 27 pt leading. #[test] @@ -1583,12 +1934,12 @@ fn hidden_objects_go_to_a_hidden_layer_above_their_own() { #[test] fn hidden_objects_can_be_left_out_or_shown() { let out = write_with(&with_hidden(), LegacyAiOptions { hidden: HiddenObjects::Omit, ..LegacyAiOptions::default() }); - assert!(out.warnings.iter().any(|w| w == HIDDEN), "{:?}", out.warnings); + assert!(out.setting_notes.iter().any(|w| w == HIDDEN), "{:?}", out.setting_notes); let doc = crate::import(&out.bytes).unwrap().document; assert_eq!(doc.layers.len(), 2); assert_eq!(children(&children(&doc.layers[0])[0]).len(), 1); let out = write_with(&with_hidden(), LegacyAiOptions { hidden: HiddenObjects::Visible, ..LegacyAiOptions::default() }); - assert!(out.warnings.iter().any(|w| w == HIDDEN_SHOWN), "{:?}", out.warnings); + assert!(out.setting_notes.iter().any(|w| w == HIDDEN_SHOWN), "{:?}", out.setting_notes); let doc = crate::import(&out.bytes).unwrap().document; assert_eq!(doc.layers.len(), 2); let pair = children(&children(&doc.layers[0])[0]); diff --git a/crates/eps/src/legacy_ai/writer.rs b/crates/eps/src/legacy_ai/writer.rs index 068f534868..20f8b32b96 100644 --- a/crates/eps/src/legacy_ai/writer.rs +++ b/crates/eps/src/legacy_ai/writer.rs @@ -3,13 +3,13 @@ use super::encoding::{ unit, writable, }; use super::{ - Affine, AppearanceItem, Arc, BezPath, BlendMode, CharStyle, Cms, Color, Document, ELLIPTICAL, FREEFORM, FillLayer, FillRule, Gradient, - GradientKind, GradientPaint, HEX_LINE, HIDDEN, HIDDEN_LAYER, HIDDEN_SHOWN, HiddenObjects, IMAGE_ALPHA, ImageBlob, Justify, LARGE_IMAGE, + Affine, AppearanceItem, Arc, BezPath, BlendMode, CharStyle, Cms, Color, DYNAMIC_TEXT, Document, ELLIPTICAL, FREEFORM, FillLayer, FillRule, + Gradient, GradientKind, GradientPaint, HEX_LINE, HIDDEN, HIDDEN_LAYER, HIDDEN_SHOWN, HiddenObjects, IMAGE_ALPHA, ImageBlob, Justify, LARGE_IMAGE, LAYER_NAME, LIVE, LegacyAiOptions, MAX_IMAGE_PIXELS, MAX_NEST, NAMES, Node, NodeKind, PATTERNS, Paint, ParaDirection, ParaStyle, PathData, ROTATED_TYPE, Rect, STROKES, SUBLAYERS, Shape, StrokeLayer, SubPath, TITLE_AND_COLOR_NAMES, TRANSPARENCY, TYPE, TYPE_ATTRIBUTES, TextKind, TextObject, UNDECODED, Vec2, Write, ai_ops, latin, ps, stroke, }; -use super::{CONIC, CONIC_WEDGES}; +use super::{CONIC, CONIC_WEDGES, DIAMOND, HUE_STOPS, SPREAD, SPREAD_CAPPED}; pub(super) struct Writer<'a> { doc: &'a Document, @@ -24,6 +24,8 @@ pub(super) struct Writer<'a> { /// The name each spot color (by its swatch's name) is written with ([`Self::spot`]). spot_names: Vec<(String, String)>, pub(super) warnings: Vec, + /// Notes on what the options asked for ([`crate::LegacyAiOutput::setting_notes`]). + pub(super) setting_notes: Vec, /// The lock state the last `A` set. locked: bool, /// Symbols and live objects being written inside one another. @@ -39,6 +41,10 @@ pub(super) struct Writer<'a> { in_hidden: bool, /// The fonts type is set in: PostScript name, and whether it's TrueType. pub(super) fonts: Vec<(String, bool)>, + /// The Standard Vertical Roman Alignment the last `Tv` set (it lasts into later text objects). + roman: bool, + /// Inside a Kumi block `1 TY` began (Tate-chu-yoko in horizontal type). + kumi: bool, } impl<'a> Writer<'a> { @@ -52,6 +58,7 @@ impl<'a> Writer<'a> { spots: vec![], spot_names: vec![], warnings: vec![], + setting_notes: vec![], locked: false, nest: 0, hidden: o.hidden, @@ -59,15 +66,26 @@ impl<'a> Writer<'a> { hidden_art: vec![], in_hidden: false, fonts: vec![], + roman: false, + kumi: false, } } + /// Note `w`, once, about something of the document that the file leaves out or that reaches + /// it changed. A note about an option goes to [`Self::note_setting`]. fn warn(&mut self, w: &str) { if !self.warnings.iter().any(|x| x == w) { self.warnings.push(w.to_string()); } } + /// Note `w`, once, about hidden objects left out or written visible as an option asks. + fn note_setting(&mut self, w: &str) { + if !self.setting_notes.iter().any(|x| x == w) { + self.setting_notes.push(w.to_string()); + } + } + fn line(&mut self, s: &str) { self.body.push_str(s); self.body.push('\n'); @@ -219,7 +237,7 @@ impl<'a> Writer<'a> { if !n.visible && !self.in_hidden { match self.hidden { HiddenObjects::Omit => { - self.warn(HIDDEN); + self.note_setting(HIDDEN); return; } HiddenObjects::Layer => { @@ -227,7 +245,7 @@ impl<'a> Writer<'a> { self.hidden_art.push((n.clone(), locked || n.locked)); return; } - HiddenObjects::Visible => self.warn(HIDDEN_SHOWN), + HiddenObjects::Visible => self.note_setting(HIDDEN_SHOWN), } } if n.opacity < 1.0 || n.blend != BlendMode::Normal || n.extras().mask.as_ref().is_some_and(|m| !m.disabled) { @@ -265,7 +283,8 @@ impl<'a> Writer<'a> { } NodeKind::Image(im) => { self.lock(locked); - let blob = self.doc.image_blob(im); + let shown = self.doc.shown_image(n, im); + let blob = self.doc.image_blob(&shown); // A colorize color the renderer draws the image in. let colorize = n.extras().colorize.as_deref().filter(|p| matches!(p, Paint::Solid { .. }) && blob.is_some_and(ImageBlob::takes_colorize)); @@ -429,6 +448,11 @@ impl<'a> Writer<'a> { { return self.conic_object(path, rule, f, g); } + if let Paint::Gradient(g) = &f.paint + && g.gradient.kind == GradientKind::Diamond + { + return self.diamond_object(path, rule, f, g); + } let Paint::Pattern { pattern, xf } = &f.paint else { // A freeform gradient: its average colour. self.warn(FREEFORM); @@ -476,7 +500,8 @@ impl<'a> Writer<'a> { self.warn(TRANSPARENCY); } let area = path.to_bezpath().bounding_box(); - let wedges = g.resolve(area).conic_wedges(area, CONIC_WEDGES, true); + let wedges = g.resolve(area).conic_wedges(area, g.gradient.conic_wedge_count(CONIC_WEDGES), true); + let spread = g.gradient.spreader(); self.line("q"); self.fill_rule(rule); let several = path.subpaths.len() > 1; @@ -490,13 +515,48 @@ impl<'a> Writer<'a> { self.line("*U"); } for (pts, t) in wedges { - let (color, _) = g.gradient.sample_keep_model(t as f32); + let (color, _) = g.gradient.sample_keep_model(spread(t) as f32); let wedge = FillLayer { paint: Paint::solid(color), ..f.clone() }; self.path_object(&PathData::single(SubPath::polyline(&pts, true)), FillRule::NonZero, Some(&wedge), None); } self.line("Q"); } + /// A diamond gradient fill (the format has no diamond gradient) as four linear gradients + /// clipped to `path` (filled by `rule`), one for each quadrant of its frame and equal to the + /// diamond there, each running on under the next + /// ([`vectorcraft_color::GradientGeom::diamond_quadrants`]). A diamond without an extent is its + /// last stop. + fn diamond_object(&mut self, path: &PathData, rule: FillRule, f: &FillLayer, g: &GradientPaint) { + let area = path.to_bezpath().bounding_box(); + let Some(quadrants) = g.resolve(area).diamond_quadrants(area) else { + let color = g.gradient.stops.last().map_or(Color::gray(0.5), |s| s.color); + let flat = FillLayer { paint: Paint::solid(color), ..f.clone() }; + return self.path_object(path, rule, Some(&flat), None); + }; + self.warn(DIAMOND); + self.line("q"); + self.fill_rule(rule); + let several = path.subpaths.len() > 1; + if several { + self.line("*u"); + } + for sp in path.subpaths.iter().filter(|sp| !sp.anchors.is_empty()) { + self.mask(sp); + } + if several { + self.line("*U"); + } + let gradient = Gradient { kind: GradientKind::Linear, ..g.gradient.clone() }; + for (pts, geom) in quadrants { + // Not named after the swatch: the definition is a linear gradient, not the swatch's. + let linear = GradientPaint { gradient: gradient.clone(), geom: Some(geom), swatch: None, ..g.clone() }; + let quadrant = FillLayer { paint: Paint::Gradient(Box::new(linear)), ..f.clone() }; + self.path_object(&PathData::single(SubPath::polyline(&pts, true)), FillRule::NonZero, Some(&quadrant), None); + } + self.line("Q"); + } + /// A path object painted with `fill` (a colour or a linear or radial gradient) and `stroke` /// (a plain line of a colour) over it; several subpaths make a compound path. fn path_object(&mut self, path: &PathData, rule: FillRule, fill: Option<&FillLayer>, stroke: Option<&StrokeLayer>) { @@ -586,7 +646,8 @@ impl<'a> Writer<'a> { // Grey is ink coverage; the format's grey is lightness. Color::Gray { k } => Ink::Gray(unit(1.0 - k)), Color::Cmyk { c, m, y, k } => Ink::Cmyk([c, m, y, k].map(unit)), - Color::Rgb { r, g, b } => Ink::Rgb(self.cms.to_cmyk(color, intent).map(unit), [r, g, b].map(unit)), + // The CMYK equivalent of the RGB values as written. + Color::Rgb { r, g, b } => Ink::Rgb(self.cms.to_cmyk(&ai_ops::as_written(*color), intent).map(unit), [r, g, b].map(unit)), Color::Lab { .. } => { let rgb = color.to_rgb().map(unit); Ink::Rgb(self.cms.to_cmyk(color, intent).map(unit), rgb) @@ -632,6 +693,32 @@ impl<'a> Writer<'a> { /// (its distance a fraction of the radius, at most 1, §3.5.5; `0 0 0 0 Bh` at the center, /// §3.5.6), `1 (name) x y angle length 1 0 0 1 0 0 Bg`. fn gradient(&mut self, g: &GradientPaint, bounds: Rect) -> String { + // A gradient mixed around the hue wheel (the format's gradients mix their stops' colors + // directly): the stops on its curve, no more than the reader reads, in a definition of + // its own. + if g.gradient.method.is_hue() { + self.warn(HUE_STOPS); + let curve = g.gradient.as_classic_curve(); + let gradient = if curve.is_spread() { curve } else { curve.fitted(crate::import::MAX_GRADIENT_STOPS).into_owned() }; + let p = GradientPaint { gradient, swatch: None, ..g.clone() }; + return self.gradient(&p, bounds); + } + // A gradient that repeats or reflects (the format's gradients pad past their ends): its + // stops repeated as many times as `bounds` needs, in a definition of its own, no more + // stops than the reader reads. + if let Some(padded) = g.gradient.padded_within(&g.resolve(bounds), bounds, crate::import::MAX_GRADIENT_STOPS) { + self.warn(if padded.capped { SPREAD_CAPPED } else { SPREAD }); + let geom = padded.geom; + let p = GradientPaint { gradient: padded.gradient, geom: Some(geom), angle: geom.angle_deg(), swatch: None, ..g.clone() }; + return self.gradient(&p, bounds); + } + // One whose levels over `bounds` are not finite (a vector of no length): its stops + // repeated along the vector, padding past it. + if g.gradient.is_spread() { + self.warn(SPREAD_CAPPED); + let p = GradientPaint { gradient: g.gradient.unrolled_within(crate::import::MAX_GRADIENT_STOPS).into_owned(), swatch: None, ..g.clone() }; + return self.gradient(&p, bounds); + } let name = self.define(&g.gradient, g.swatch.as_deref()); for stop in &g.gradient.stops { if stop.opacity < 1.0 { @@ -693,15 +780,15 @@ impl<'a> Writer<'a> { // ---------- type ---------- /// Type: a text object when the format can hold it as text, else its outlines (type with - /// rotated characters among them, which keeps their rotation). A run whose - /// font size measures a height other than the em box is written at the em size it is drawn - /// at ([`vectorcraft_text::FontDb::font_heights_resolved`]). + /// rotated characters among them, which keeps their rotation). fn text(&mut self, t: &TextObject) { if !invertible(t.xf) { return; } - let resolved = vectorcraft_text::FontDb::global().font_heights_resolved(t); - let t = &*resolved; + // Written as text or as outlines, the type keeps its drawn sizes but not the setting. + if t.dynamic_text && matches!(t.kind, TextKind::OnPath { .. }) { + self.warn(DYNAMIC_TEXT); + } if !self.outline_text { if writable(self.doc, t) { return self.text_object(t); @@ -719,14 +806,18 @@ impl<'a> Writer<'a> { /// A text object (§15): `type To`, the text path (`a b c d tx ty startPt Tp`, an area's frame /// or the path type runs along, `TP`), then each run's style and characters, `TO`. The matrix /// takes text space (y up, the first baseline's start for point type) to art space; the frame - /// and path are in art space, as the specification's examples have them (§15.5). + /// and path are in art space, as the specification's examples have them (§15.5). Type that + /// Shrink Text to Fit or Dynamic Text scales is written in the styles it draws in, fitted at + /// the sizes the Character panel shows; then a run whose font size measures a height other + /// than the em box is written at the em size it is drawn at + /// ([`vectorcraft_text::FontDb::font_heights_resolved`]). fn text_object(&mut self, t: &TextObject) { if lost_attributes(t) { self.warn(TYPE_ATTRIBUTES); } - // Type that Shrink Text to Fit or Dynamic Text scales is written in the styles it draws in. let fitted = vectorcraft_text::drawn(t); - let t = &*fitted; + let resolved = vectorcraft_text::FontDb::global().font_heights_resolved(&fitted); + let t = &*resolved; let m = self.to_art * t.xf * Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 0.0]); let (kind, path, start) = match &t.kind { TextKind::Point => (0, None, 0.0), @@ -775,6 +866,10 @@ impl<'a> Writer<'a> { self.line(" Tx"); } } + if self.kumi { + self.line("0 TY"); + self.kumi = false; + } self.line("TO"); } @@ -794,7 +889,8 @@ impl<'a> Writer<'a> { } /// A run's character attributes and paint style: `Tr`, its fill and stroke, `Tf`, `Ts`, `Tz`, - /// `Tt`, `TA`, and the leading with the space before its paragraph, `Tl`. + /// `Tt`, `TA`, and the leading with the space before its paragraph, `Tl`; then `Tv` and `TY` + /// where Standard Vertical Roman Alignment or Tate-chu-yoko changes. fn char_style(&mut self, st: &CharStyle, p: &ParaStyle) { let fill = !st.fill.is_none(); let stroke = st.has_stroke(); @@ -832,6 +928,14 @@ impl<'a> Writer<'a> { let leading = st.leading.unwrap_or_else(|| p.justification.auto_leading_for(st.size)); ps::push_nums(&mut self.body, &[finite(leading, size * 1.2), finite(p.space_before, 0.0)]); self.line("Tl"); + if st.standard_vertical_roman != self.roman { + self.roman = st.standard_vertical_roman; + self.line(if self.roman { "1 Tv" } else { "0 Tv" }); + } + if st.tate_chu_yoko != self.kumi { + self.kumi = st.tate_chu_yoko; + self.line(if self.kumi { "1 TY" } else { "0 TY" }); + } } /// Type as its glyphs' outlines: a group of a compound path for each run, with the run's fill diff --git a/crates/eps/src/lib.rs b/crates/eps/src/lib.rs index 586967234b..44ec49c190 100644 --- a/crates/eps/src/lib.rs +++ b/crates/eps/src/lib.rs @@ -31,9 +31,11 @@ //! - `ai_editing`: the editing copy of the art a PDF-compatible `.ai` file carries //! ([`export_ai_editing`], [`ai_private_data`]). //! - `ai_ops`: the path and line style operators those two write. +//! - [`dcs`]: DCS files, an EPS file with one program per printing plate, read for placing. mod ai_editing; mod ai_ops; +pub mod dcs; mod import; mod latin; mod legacy_ai; @@ -195,6 +197,8 @@ pub struct EpsOutput { pub bytes: Vec, /// What was approximated or left out. pub warnings: Vec, + /// Notes on the options: the preview or thumbnail asked for that was left out. + pub setting_notes: Vec, } /// The `%%BoundingBox` of `region` with PostScript's origin at document point `origin`: whole @@ -229,11 +233,11 @@ pub fn export(doc: &Document, opts: &EpsOptions, preview: Option<&Raster>, thumb let baked = vectorcraft_effects::bake_document(doc); let doc = baked.as_ref().unwrap_or(doc); let page = scene::Scene::new(doc, opts).run(); - let mut warnings = page.warnings; + let mut setting_notes = vec![]; let thumb = thumbnail.and_then(|t| match tiff::png(t) { Ok(png) => Some(png), Err(e) => { - warnings.push(format!("the thumbnail was left out: {e}")); + setting_notes.push(format!("the thumbnail was left out: {e}")); None } }); @@ -241,7 +245,7 @@ pub fn export(doc: &Document, opts: &EpsOptions, preview: Option<&Raster>, thumb let bytes = match (opts.preview, preview) { (Preview::None, _) => ps.into_bytes(), (_, None) => { - warnings.push("the preview was left out: nothing was rendered for it".into()); + setting_notes.push("the preview was left out: nothing was rendered for it".into()); ps.into_bytes() } (kind, Some(img)) => { @@ -249,7 +253,7 @@ pub fn export(doc: &Document, opts: &EpsOptions, preview: Option<&Raster>, thumb dos_eps(ps.as_bytes(), &tiff)? } }; - Ok(EpsOutput { bytes, warnings }) + Ok(EpsOutput { bytes, warnings: page.warnings, setting_notes }) } /// Comment lines that start a data section the file carries (`%VectorCraft_BeginData: `) diff --git a/crates/eps/src/print.rs b/crates/eps/src/print.rs index 99dffd8225..0ccd7a6331 100644 --- a/crates/eps/src/print.rs +++ b/crates/eps/src/print.rs @@ -181,7 +181,7 @@ pub fn print(pages: &[PrintPage], order: &[usize], job: &PrintJob) -> Result String { /// Append [`num`]`(v)` to `s`. pub(crate) fn push_num(s: &mut String, v: f64) { - // Beyond ~1.8e304 the scaling overflows; such values have no fractional digits to round. + push_num_places(s, v, 4); +} + +/// The value [`num`]`(v)` stands for, as a reader parses it back. +pub(crate) fn written(v: f64) -> f64 { + num(v).parse().unwrap_or(0.0) +} + +/// Append `v` to `s` with at most `places` decimals (up to 9), no trailing zeros (0 when not +/// finite). +pub(crate) fn push_num_places(s: &mut String, v: f64, places: u32) { + let places = places.min(9); + let scale = 10f64.powi(places as i32); + // Past where the scaling overflows, values have no fractional digits to round. let v = if !v.is_finite() { 0.0 - } else if (v * 10_000.0).is_finite() { - (v * 10_000.0).round() / 10_000.0 + } else if (v * scale).is_finite() { + (v * scale).round() / scale } else { v }; @@ -46,7 +59,7 @@ pub(crate) fn push_num(s: &mut String, v: f64) { return; } let start = s.len(); - let _ = write!(s, "{v:.4}"); + let _ = write!(s, "{v:.*}", places as usize); let keep = s[start..].trim_end_matches('0').trim_end_matches('.').len(); s.truncate(start + keep); } @@ -291,7 +304,7 @@ pub(crate) fn inflate(data: &[u8], max: u64) -> Option> { #[cfg(test)] mod tests { - use super::{ascii85, ascii85_decode, num}; + use super::{ascii85, ascii85_decode, num, push_num_places}; #[test] fn ascii85_first_line_never_starts_with_percent() { @@ -308,4 +321,18 @@ mod tests { assert!(!s.is_empty() && s.chars().all(|c| c.is_ascii_digit() || c == '-' || c == '.'), "{v}: got {s:?}"); } } + + #[test] + fn numbers_keep_the_decimals_asked_for() { + let places = |v: f64, n: u32| { + let mut s = String::new(); + push_num_places(&mut s, v, n); + s + }; + assert_eq!(num(0.123_456_78), "0.1235"); + assert_eq!(places(0.123_456_78, 7), "0.1234568"); + assert_eq!(places(f64::from(0.4f32), 7), "0.4"); + assert_eq!(places(2.5, 7), "2.5"); + assert_eq!(places(f64::NAN, 7), "0"); + } } diff --git a/crates/eps/src/scene.rs b/crates/eps/src/scene.rs index 3b2a91f0ff..c20c5847a2 100644 --- a/crates/eps/src/scene.rs +++ b/crates/eps/src/scene.rs @@ -42,16 +42,113 @@ const SPOT_GRADIENTS_L2: &str = "gradients mixing a spot color with other inks are written in process colors at PostScript Level 2 (Level 3 keeps the spot inks)"; const SPOT_GRADIENTS_SHARED: &str = "gradients whose spot inks can't share a DeviceN color space are written without the spot inks"; const SPOT_GRADIENTS_PERCEPTUAL: &str = "Perceptual gradients of spot colors are written in process colors"; +const SPOT_GRADIENTS_HUE: &str = "gradients of spot colors mixed around the hue wheel are written in process colors"; const CONIC_WEDGES: &str = "conic gradients are written as solid wedges (EPS has no conic shading)"; +const DIAMOND_QUADRANTS: &str = "diamond gradients are written as four linear gradients (EPS has no diamond shading)"; +const SPREAD_CAPPED: &str = + "gradients that repeat or reflect are written with at most 256 runs of their stops (at most 16384 stops); they pad past those"; /// Wedges a conic gradient is written as: one a degree. const CONIC_WEDGE_COUNT: usize = 360; +/// Decimals of a smooth shading's stitching function bounds (stop offsets, 0 to 1). +const BOUNDS_PLACES: u32 = 7; /// The most colorants a DeviceN color space may have (PostScript's limit). const MAX_DEVICE_N: usize = 32; const MISSING_PATTERN: &str = "missing patterns are written as mid-grey"; const TOO_LARGE: &str = "the artwork is too large for EPS: what follows 256 MB of PostScript was left out"; /// The most PostScript the page body may grow to: symbols and patterns that hold one another -/// expand into every instance, so nesting depth alone doesn't bound the output. +/// expand into every instance, so nesting depth alone doesn't bound the output. An image placed +/// more than once counts its data once. const MAX_BODY: usize = 256 << 20; +/// Most compressed bytes in one string of an image's samples at Level 2 (under PostScript's +/// 65,535-byte string limit). +const IMAGE_CHUNK: usize = 48 << 10; +/// The start of the procedure that reads an image's data from the lines after it. +const INLINE_SOURCE: &str = "{ /VCsrc currentfile /ASCII85Decode filter def\n"; + +/// An image as written: what sets up its color, its image dictionary and its compressed samples. +/// Placed once, it is written where it is drawn, its data following the operators that read it. +/// Placed more than once, its samples are written once in the setup as `VCim` (a reusable +/// stream at Level 3, an array of strings at Level 2) and each placement reads them from there. +struct ImageCode { + /// The color space or ink operators, each line ending in a line break. + prelude: String, + /// `<< /ImageType … /ImageMatrix […]` with its mask colors: the dictionary up to its data source. + dict: String, + /// The decoding filter of the samples: `/FlateDecode` or `/RunLengthDecode`. + filter: &'static str, + /// `image` or `imagemask`. + op: &'static str, + /// The compressed samples in ASCII85, as lines with the end marker. + ascii: String, + /// The compressed samples, kept at Level 2, where a reused image's samples are written as + /// strings of at most [`IMAGE_CHUNK`] bytes. + data: Vec, + /// How many placements in the page draw it. + uses: usize, + /// The length of [`ImageCode::push_inline`]'s text. + inline_len: usize, + /// The length of [`ImageCode::reference`]'s text. + ref_len: usize, +} + +impl ImageCode { + /// The operators and data that draw the image where it is placed. + fn push_inline(&self, s: &mut String) { + s.push_str(&self.prelude); + s.push_str(INLINE_SOURCE); + s.push_str(&self.dict); + s.push_str(&self.inline_read()); + s.push_str(&self.ascii); + } + + /// The end of the procedure [`ImageCode::push_inline`] writes. The procedure is read whole + /// before it runs: the image data follows it, and flushing the ASCII85 filter afterwards reads + /// past its end marker. + fn inline_read(&self) -> String { + format!("\n/DataSource VCsrc {} filter >> {}\nVCsrc flushfile }} exec\n", self.filter, self.op) + } + + /// The operators that draw the image `VCim` holds, for an image placed more than once. + fn reference(&self, i: usize, level: Level) -> String { + match level { + // The stream is read again from its start. + Level::Three => { + format!("{}VCim{i} resetfile\n{}\n/DataSource VCim{i} {} filter >> {}\n", self.prelude, self.dict, self.filter, self.op) + } + // A procedure gives the strings in turn, then an empty string: the end of the data. + Level::Two => format!( + "{}/VCi 0 def\n{}\n/DataSource {{VCi VCim{i} length lt {{VCim{i} VCi get /VCi VCi 1 add def}} {{()}} ifelse}} {} filter >> {}\n", + self.prelude, self.dict, self.filter, self.op + ), + } + } + + /// The setup's definition of `VCim`: the image's compressed samples, once. + fn resource(&self, i: usize, level: Level) -> String { + let mut s = String::with_capacity(self.ascii.len() + 200); + match level { + Level::Three => { + // The stream reads all of its data when it is made, so the data follows the + // procedure that makes it. + let intent = if self.op == "imagemask" { 1 } else { 0 }; + let _ = writeln!( + s, + "{{ /VCsrc currentfile /ASCII85Decode filter def\n/VCim{i} VCsrc << /Intent {intent} /AsyncRead false /CloseSource false >> /ReusableStreamDecode filter def\nVCsrc flushfile }} exec" + ); + s.push_str(&self.ascii); + } + Level::Two => { + let _ = writeln!(s, "/VCim{i} ["); + for chunk in self.data.chunks(IMAGE_CHUNK) { + s.push_str("<~"); + s.push_str(&ps::ascii85(chunk)); + } + s.push_str("] def\n"); + } + } + s + } +} /// What the walk wrote: definitions for the setup, the page, the spot colours it uses (name and /// CMYK equivalent) and the warnings. @@ -152,10 +249,18 @@ pub(crate) struct Scene<'a> { device_n: Vec, warnings: Vec, brushes: Option>, - /// Image keys → what draws them (`None`: left out). - images: HashMap>>, + /// Image keys → the index in `codes` of what draws them (`None`: left out). + images: HashMap>, /// The source key and solid paint together identify a colorized encoding. - colorized_images: HashMap<(String, String), Option>>, + colorized_images: HashMap<(String, String), Option>, + /// The encoded images. + codes: Vec, + /// Where in `body` each placement of an encoded image goes (in order) and the index of its code. + placements: Vec<(usize, usize)>, + /// What the placements in `placements` add to `body`'s length when the page is finished. + pending: usize, + /// The most the page body may grow to ([`MAX_BODY`]). + max_body: usize, /// Symbols and brush art being written inside one another. nest: u32, } @@ -176,10 +281,21 @@ impl<'a> Scene<'a> { brushes: None, images: HashMap::new(), colorized_images: HashMap::new(), + codes: vec![], + placements: vec![], + pending: 0, + max_body: MAX_BODY, nest: 0, } } + /// This scene with a page body of at most `max` bytes. + #[cfg(test)] + pub fn with_max_body(mut self, max: usize) -> Self { + self.max_body = max; + self + } + pub fn run(mut self) -> Page { let doc = self.doc; for l in &doc.layers { @@ -194,7 +310,27 @@ impl<'a> Scene<'a> { self.page() } - fn page(self) -> Page { + fn page(mut self) -> Page { + if !self.placements.is_empty() { + let level = self.o.level; + let mut body = String::with_capacity(self.body.len().saturating_add(self.pending)); + let mut at = 0; + for &(offset, i) in &self.placements { + body.push_str(self.body.get(at..offset).unwrap_or_default()); + at = offset; + let Some(code) = self.codes.get(i) else { continue }; + if code.uses > 1 { + body.push_str(&code.reference(i, level)); + } else { + code.push_inline(&mut body); + } + } + body.push_str(self.body.get(at..).unwrap_or_default()); + self.body = body; + for (i, code) in self.codes.iter().enumerate().filter(|(_, c)| c.uses > 1) { + self.setup.push_str(&code.resource(i, level)); + } + } let custom = self .spots .iter() @@ -332,7 +468,7 @@ impl<'a> Scene<'a> { if let NodeKind::Layer { template: true, .. } = n.kind { return; } - if self.body.len() >= MAX_BODY { + if self.size() >= self.max_body { self.warn(TOO_LARGE); return; } @@ -342,7 +478,7 @@ impl<'a> Scene<'a> { _ => {} } self.note_losses(n); - let was = self.body.len(); + let (was, placed) = (self.body.len(), self.placements.len()); match &n.kind { NodeKind::Layer { children, clip: false, .. } | NodeKind::Group { children, clip: false } => { children.iter().for_each(|c| self.node(c, false)); @@ -362,6 +498,8 @@ impl<'a> Scene<'a> { } NodeKind::Text(t) => self.text(n, t), NodeKind::Image(im) => { + let shown = self.doc.shown_image(n, im); + let im = &*shown; let blob = self.doc.image_blob(im); match n.extras().colorize.as_deref() { Some(p @ Paint::Solid { .. }) if blob.is_none_or(|b| b.gray_source().is_some()) => { @@ -395,12 +533,29 @@ impl<'a> Scene<'a> { // Ruler guides draw on screen only. NodeKind::RulerGuide { .. } => {} } - if self.body.len() > MAX_BODY { + if self.size() > self.max_body { self.body.truncate(was); + self.unplace(placed); self.warn(TOO_LARGE); } } + /// How long the page body will be: what is written and what its image placements add. + fn size(&self) -> usize { + self.body.len().saturating_add(self.pending) + } + + /// Take back the image placements after the first `n`, last first. + fn unplace(&mut self, n: usize) { + while self.placements.len() > n { + let Some((_, i)) = self.placements.pop() else { break }; + let Some(code) = self.codes.get_mut(i) else { continue }; + code.uses = code.uses.saturating_sub(1); + let cost = if code.uses == 0 { code.inline_len } else { code.ref_len }; + self.pending = self.pending.saturating_sub(cost); + } + } + /// A clipping group: the art inside its first child's outline. The clipping path's fills /// paint behind the art (clipped) and its strokes over it (not clipped). fn clip_group(&mut self, children: &[Arc]) { @@ -759,8 +914,8 @@ impl<'a> Scene<'a> { /// them. Paper white adds no ink, a gray stop is black ink, and a spot stop's process plates /// print with its ink. An off-center midpoint is a stop /// with the inks halfway between its two stops. `None` for a gradient without a spot ink, and, - /// with a warning, for one whose inks can't be kept or that is mixed by the Perceptual method; - /// it is then written in process colors. + /// with a warning, for one whose inks can't be kept or that is mixed by the Perceptual method + /// or around the hue wheel; it is then written in process colors. fn ink_stops(&mut self, g: &vectorcraft_color::Gradient) -> Option<(GradientSpace, RawStops)> { let doc = self.doc; let spot_of = |s: &vectorcraft_color::GradientStop| -> Option { @@ -782,7 +937,7 @@ impl<'a> Scene<'a> { return None; } if !g.method.is_classic() { - self.warn(SPOT_GRADIENTS_PERCEPTUAL); + self.warn(if g.method.is_hue() { SPOT_GRADIENTS_HUE } else { SPOT_GRADIENTS_PERCEPTUAL }); return None; } if names.len() > MAX_DEVICE_N { @@ -934,11 +1089,36 @@ impl<'a> Scene<'a> { (space, out) } - /// Paint all of `area` (inside the current clip) with linear, radial or conic gradient `g`, - /// placed on `bounds`: a smooth shading at Level 3, else stepped fills (a conic: wedges at - /// both levels). + /// Paint all of `area` (inside the current clip) with linear, radial, conic or diamond gradient + /// `g`, placed on `bounds`: a smooth shading at Level 3, else stepped fills (a conic: wedges at + /// both levels; a diamond: four linear gradients, [`Self::diamond_quadrants`]). fn gradient(&mut self, g: &GradientPaint, bounds: Rect, area: Rect) { let geom = g.resolve(bounds); + // One mixed around the hue wheel that reflects is repeated from its curve's stops, which + // keep no swatch links: the warning [`Self::ink_stops`] gives the others. + if g.gradient.method.is_hue() && g.gradient.is_spread() && g.gradient.spread == vectorcraft_color::GradientSpread::Reflect { + let doc = self.doc; + if g.gradient.stops.iter().any(|s| s.swatch.as_deref().is_some_and(|n| doc.swatch(n).is_some_and(|w| w.spot))) { + self.warn(SPOT_GRADIENTS_HUE); + } + } + // A linear, radial or diamond gradient that repeats or reflects: PostScript's shadings + // pad past their ends, so its stops are repeated as many times as the area needs. + if let Some(padded) = g.gradient.padded_over(&geom, area) { + if padded.capped { + self.warn(SPREAD_CAPPED); + } + let geom = padded.geom; + let paint = GradientPaint { gradient: padded.gradient, geom: Some(geom), angle: geom.angle_deg(), ..g.clone() }; + return self.gradient(&paint, bounds, area); + } + // One whose levels over the area are not finite (a vector of no length): its stops + // repeated along the vector, padding past it. + if g.gradient.is_spread() && g.gradient.kind != GradientKind::Conic { + self.warn(SPREAD_CAPPED); + let paint = GradientPaint { gradient: g.gradient.unrolled().into_owned(), ..g.clone() }; + return self.gradient(&paint, bounds, area); + } let (space, stops) = self.gradient_stops(&g.gradient); if !stops.windows(2).any(|w| w[1].0 > w[0].0) { if let Some((_, c)) = stops.first() { @@ -950,7 +1130,8 @@ impl<'a> Scene<'a> { let space = &space; let smooth = self.o.level == Level::Three && !self.o.compatible_gradients; match g.gradient.kind { - GradientKind::Conic => self.conic_steps(&geom, area, space, &stops), + GradientKind::Conic => self.conic_steps(&geom, area, space, &stops, &g.gradient), + GradientKind::Diamond => self.diamond_quadrants(&geom, area, space, &stops, smooth), GradientKind::Radial => { let r = geom.length().max(1e-6); let squash = geom.radial_squash(); @@ -982,15 +1163,24 @@ impl<'a> Scene<'a> { /// A conic gradient as [`CONIC_WEDGE_COUNT`] solid wedges about its center covering `area` /// (PostScript has no conic shading), each running on to the seam under the next, so no /// hairline shows between neighbors ([`vectorcraft_color::GradientGeom::conic_wedges`]). - fn conic_steps(&mut self, geom: &vectorcraft_color::GradientGeom, area: Rect, space: &GradientSpace, stops: &[(f64, Vec)]) { + /// Stops of `g` that repeat or reflect get that many wedges for each time they run around. + fn conic_steps( + &mut self, + geom: &vectorcraft_color::GradientGeom, + area: Rect, + space: &GradientSpace, + stops: &[(f64, Vec)], + g: &vectorcraft_color::Gradient, + ) { self.warn(CONIC_WEDGES); + let spread = g.spreader(); let at = |t: f64| match stops.windows(2).find(|w| t <= w[1].0) { Some(w) if w[1].0 > w[0].0 => mix(&w[0].1, &w[1].1, ((t - w[0].0) / (w[1].0 - w[0].0)).clamp(0.0, 1.0) as f32), Some(w) => w[1].1.clone(), None => stops.last().map_or_else(Vec::new, |s| s.1.clone()), }; - for (pts, t) in geom.conic_wedges(area, CONIC_WEDGE_COUNT, true) { - self.set_comps(space, &at(t)); + for (pts, t) in geom.conic_wedges(area, g.conic_wedge_count(CONIC_WEDGE_COUNT), true) { + self.set_comps(space, &at(spread(t))); for (i, p) in pts.iter().enumerate() { push_nums(&mut self.body, &[p.x, p.y]); self.line(if i == 0 { "newpath moveto" } else { "lineto" }); @@ -999,6 +1189,43 @@ impl<'a> Scene<'a> { } } + /// A diamond gradient over `area` as four linear gradients, each clipped to a quadrant of its + /// frame and equal to the diamond there (PostScript has no diamond shading; + /// [`vectorcraft_color::GradientGeom::diamond_quadrants`]): smooth axial shadings, else + /// stepped fills. Each quadrant but the last runs on under the next (stops are opaque here), + /// so no hairline shows between them. A diamond without an extent is its last stop. + fn diamond_quadrants( + &mut self, + geom: &vectorcraft_color::GradientGeom, + area: Rect, + space: &GradientSpace, + stops: &[(f64, Vec)], + smooth: bool, + ) { + let Some(quadrants) = geom.diamond_quadrants(area) else { + if let Some((_, c)) = stops.last() { + self.set_comps(space, c); + self.rect_fill(area); + } + return; + }; + self.warn(DIAMOND_QUADRANTS); + for (pts, q) in quadrants { + self.line("q"); + for (i, p) in pts.iter().enumerate() { + push_nums(&mut self.body, &[p.x, p.y]); + self.line(if i == 0 { "newpath moveto" } else { "lineto" }); + } + self.line("closepath clip newpath"); + if smooth { + self.shading(2, space, &[q.start.x, q.start.y, q.end.x, q.end.y], stops); + } else { + self.linear_steps(q.start, q.end, area, space, stops); + } + self.line("Q"); + } + } + /// A Level 3 smooth shading of `kind` (2 axial, 3 radial) at `coords`, extended both ways. fn shading(&mut self, kind: u8, space: &GradientSpace, coords: &[f64], stops: &[(f64, Vec)]) { let n = space.n(); @@ -1020,8 +1247,12 @@ impl<'a> Scene<'a> { f.push('\n'); } f.push_str("] /Bounds ["); - let bounds: Vec = many.iter().skip(1).map(|w| w[0].0).collect(); - push_nums(&mut f, &bounds); + // Seven decimals: a gradient's stops repeated hundreds or thousands of times + // (`Gradient::padded_over`) keep their places in each run. + for w in many.iter().skip(1) { + ps::push_num_places(&mut f, w[0].0, BOUNDS_PLACES); + f.push(' '); + } f.push_str("] /Encode ["); f.push_str(&"0 1 ".repeat(many.len())); f.push_str("] >>"); @@ -1154,7 +1385,7 @@ impl<'a> Scene<'a> { }; let place = Affine::translate(area.origin().to_vec2()) * Affine::scale_non_uniform(area.width(), area.height()); if let Some(image) = image { - self.place_image(&image, place); + self.place_inline(&image, place); } } @@ -1166,18 +1397,29 @@ impl<'a> Scene<'a> { return; } let encoded = match self.images.get(key) { - Some(e) => e.clone(), + Some(e) => *e, None => { - let e = self.decode_image(blob).and_then(|img| self.encode_image(img.as_raw(), img.width(), img.height())).map(Arc::new); - self.images.insert(key.to_string(), e.clone()); + let e = self.decode_image(blob).and_then(|img| self.encode_image(img.as_raw(), img.width(), img.height())).map(|c| self.add_code(c)); + self.images.insert(key.to_string(), e); e } }; - if let Some(e) = encoded { - self.place_image(&e, place); + if let Some(i) = encoded { + self.place_image(i, place); } } + /// Keep `code` for the placements that draw it: its index in `codes`. + fn add_code(&mut self, mut code: ImageCode) -> usize { + let i = self.codes.len(); + if self.o.level == Level::Three { + code.data = vec![]; + } + code.ref_len = code.reference(i, self.o.level).len(); + self.codes.push(code); + i + } + /// Gray coverage in the selected process or Separation ink. Binary coverage is a stencil; /// continuous coverage leaves zero pixels untouched at Level 3 and writes them as paper at Level 2. fn colorized_image(&mut self, key: &str, blob: Option<&ImageBlob>, width: u32, height: u32, xf: Affine, paint: &Paint) { @@ -1187,19 +1429,19 @@ impl<'a> Scene<'a> { } let cache = (key.to_string(), format!("{paint:?}")); let encoded = match self.colorized_images.get(&cache) { - Some(e) => e.clone(), + Some(e) => *e, None => { - let e = self.encode_colorized(blob, paint).map(Arc::new); - self.colorized_images.insert(cache, e.clone()); + let e = self.encode_colorized(blob, paint).map(|c| self.add_code(c)); + self.colorized_images.insert(cache, e); e } }; - if let Some(e) = encoded { - self.place_image(&e, place); + if let Some(i) = encoded { + self.place_image(i, place); } } - fn encode_colorized(&mut self, blob: Option<&ImageBlob>, paint: &Paint) -> Option { + fn encode_colorized(&mut self, blob: Option<&ImageBlob>, paint: &Paint) -> Option { let Some((w, h, coverage)) = blob.and_then(ImageBlob::coverage) else { self.warn(UNDECODED); return None; @@ -1280,17 +1522,17 @@ impl<'a> Scene<'a> { ("/RunLengthDecode", rl) } }; - let mut out = String::new(); + let mut prelude = String::new(); if binary { // imagemask takes its current ink from the graphics state. - out.push_str(&self.ink_code(ink)); + prelude.push_str(&self.ink_code(ink)); } else { match ink { Ink::Spot { space, .. } => { - let _ = writeln!(out, "VCsp{space} setcolorspace"); + let _ = writeln!(prelude, "VCsp{space} setcolorspace"); } Ink::Process(space, ..) => { - let _ = writeln!(out, "{} setcolorspace", space.name()); + let _ = writeln!(prelude, "{} setcolorspace", space.name()); } } } @@ -1299,19 +1541,16 @@ impl<'a> Scene<'a> { Ink::Process(space, ..) => space.n(), }; let decode = if binary { "1 0".to_string() } else { "0 1 ".repeat(n).trim_end().to_string() }; - let _ = write!( - out, - "{{ /VCsrc currentfile /ASCII85Decode filter def\n<< /ImageType {} /Width {w} /Height {h} /BitsPerComponent {} /Decode [{decode}] /ImageMatrix [{w} 0 0 {h} 0 0]", + let mut dict = format!( + "<< /ImageType {} /Width {w} /Height {h} /BitsPerComponent {} /Decode [{decode}] /ImageMatrix [{w} 0 0 {h} 0 0]", if keyed { 4 } else { 1 }, if binary { 1 } else { 8 }, ); if keyed { let mask: Vec = key.iter().take(n).map(|v| format!("{v} {v}")).collect(); - let _ = write!(out, " /MaskColor [{}]", mask.join(" ")); + let _ = write!(dict, " /MaskColor [{}]", mask.join(" ")); } - let _ = writeln!(out, "\n/DataSource VCsrc {filter} filter >> {}\nVCsrc flushfile }} exec", if binary { "imagemask" } else { "image" }); - out.push_str(&ps::ascii85(&encoded)); - Some(out) + Some(image_code(prelude, dict, filter, if binary { "imagemask" } else { "image" }, encoded)) } /// Ink-setting operators in the cached stencil body, built with the same path as solid fills. @@ -1334,18 +1573,40 @@ impl<'a> Scene<'a> { Some(img.to_rgba8()) } - /// Draw an image of [`Self::encode_image`] on the unit square mapped by `place`. - fn place_image(&mut self, encoded: &str, place: Affine) { + /// Draw the image of `codes[i]` on the unit square mapped by `place`. Its operators go in when + /// the page is finished ([`Self::page`]), once it is known how many placements draw it. + fn place_image(&mut self, i: usize, place: Affine) { if !invertible(place) { return; } - if self.body.len().saturating_add(encoded.len()).saturating_add(64) > MAX_BODY { + let Some(code) = self.codes.get(i) else { return }; + let cost = if code.uses == 0 { code.inline_len } else { code.ref_len }; + if self.size().saturating_add(cost).saturating_add(64) > self.max_body { self.warn(TOO_LARGE); return; } self.line("q"); let _ = writeln!(self.body, "{} cm", ps::matrix(place)); - self.body.push_str(encoded); + self.placements.push((self.body.len(), i)); + self.pending = self.pending.saturating_add(cost); + if let Some(code) = self.codes.get_mut(i) { + code.uses += 1; + } + self.line("Q"); + } + + /// Draw `code`, an image drawn nowhere else, on the unit square mapped by `place`. + fn place_inline(&mut self, code: &ImageCode, place: Affine) { + if !invertible(place) { + return; + } + if self.size().saturating_add(code.inline_len).saturating_add(64) > self.max_body { + self.warn(TOO_LARGE); + return; + } + self.line("q"); + let _ = writeln!(self.body, "{} cm", ps::matrix(place)); + code.push_inline(&mut self.body); self.line("Q"); } @@ -1353,7 +1614,7 @@ impl<'a> Scene<'a> { /// them on the unit square: in the process colour space, transparent pixels masked out at /// Level 3 (a key colour no opaque pixel has), white at Level 2; partly transparent ones over /// white. `None` for an empty image. - fn encode_image(&mut self, rgba: &[u8], w: u32, h: u32) -> Option { + fn encode_image(&mut self, rgba: &[u8], w: u32, h: u32) -> Option { let space = if self.cmyk { Space::Cmyk } else { Space::Rgb }; let mut cache: HashMap<[u8; 3], [u8; 4]> = HashMap::new(); let cms = self.cms.clone(); @@ -1372,7 +1633,7 @@ impl<'a> Scene<'a> { /// Straight CMYK pixels with opacity (five bytes a pixel, `w` × `h`, rows from the top), drawn /// as [`Self::encode_image`] draws its pixels and keeping their ink amounts: partly /// transparent pixels lay down that share of each ink. - fn encode_inks(&mut self, cmyka: &[u8], w: u32, h: u32) -> Option { + fn encode_inks(&mut self, cmyka: &[u8], w: u32, h: u32) -> Option { self.encode_samples(cmyka.as_chunks::<5>().0, w, h, Space::Cmyk, |p: &[u8; 5], al| { [0, 1, 2, 3].map(|i| ((u32::from(p[i]) * al + 127) / 255) as u8) }) @@ -1388,7 +1649,7 @@ impl<'a> Scene<'a> { h: u32, space: Space, mut sample: impl FnMut(&[u8; N], u32) -> [u8; 4], - ) -> Option { + ) -> Option { if w == 0 || h == 0 { return None; } @@ -1428,27 +1689,29 @@ impl<'a> Scene<'a> { ("/RunLengthDecode", rl) } }; - let mut out = String::with_capacity(encoded.len() * 5 / 4 + 400); - let _ = writeln!(out, "{} setcolorspace", space.name()); + let prelude = format!("{} setcolorspace\n", space.name()); let decode = "0 1 ".repeat(n); - let _ = write!( - out, - "{{ /VCsrc currentfile /ASCII85Decode filter def\n<< /ImageType {} /Width {w} /Height {h} /BitsPerComponent 8 /Decode [{}] /ImageMatrix [{w} 0 0 {h} 0 0]", + let mut dict = format!( + "<< /ImageType {} /Width {w} /Height {h} /BitsPerComponent 8 /Decode [{}] /ImageMatrix [{w} 0 0 {h} 0 0]", if keyed { 4 } else { 1 }, decode.trim_end() ); if keyed { let mask: Vec = key.iter().take(n).map(|v| format!("{v} {v}")).collect(); - let _ = write!(out, " /MaskColor [{}]", mask.join(" ")); + let _ = write!(dict, " /MaskColor [{}]", mask.join(" ")); } - // The procedure is read whole before it runs: the image data follows it, and flushing the - // ASCII85 filter afterwards reads past its end marker. - let _ = writeln!(out, "\n/DataSource VCsrc {filter} filter >> image\nVCsrc flushfile }} exec"); - out.push_str(&ps::ascii85(&encoded)); - Some(out) + Some(image_code(prelude, dict, filter, "image", encoded)) } } +/// An image of `prelude`, `dict`, `filter` and `op` (see [`ImageCode`]) with compressed samples +/// `data`, not yet placed. +fn image_code(prelude: String, dict: String, filter: &'static str, op: &'static str, data: Vec) -> ImageCode { + let mut code = ImageCode { prelude, dict, filter, op, ascii: ps::ascii85(&data), data, uses: 0, inline_len: 0, ref_len: 0 }; + code.inline_len = code.prelude.len() + INLINE_SOURCE.len() + code.dict.len() + code.inline_read().len() + code.ascii.len(); + code +} + /// `a` to `b` at `t`. fn mix(a: &[f32], b: &[f32], t: f32) -> Vec { a.iter().zip(b).map(|(x, y)| x + (y - x) * t).collect() diff --git a/crates/eps/src/tests.rs b/crates/eps/src/tests.rs index 96cf75c02a..c98cb9689a 100644 --- a/crates/eps/src/tests.rs +++ b/crates/eps/src/tests.rs @@ -82,6 +82,17 @@ fn checked_page(ps: &str) -> String { } } '{' | '[' => stack.push(c), + // An ASCII85 string: its digits are data. + '<' if chars.peek() == Some(&'~') => { + let mut last = ' '; + loop { + let c = chars.next().expect("ASCII85 string closes"); + if last == '~' && c == '>' { + break; + } + last = c; + } + } '<' if chars.peek() == Some(&'<') => { chars.next(); stack.push('<'); @@ -217,6 +228,109 @@ fn conic_gradients_are_solid_wedges_at_both_levels() { } } +/// PostScript has no diamond shading: a diamond is four axial shadings at Level 3 (stepped fills at +/// Level 2), each clipped to a quadrant of its frame, and read back from the PostScript it looks +/// as the canvas paints it, with no hairline between the quadrants. +#[test] +fn diamond_gradients_are_four_linear_gradients_clipped_to_quadrants() { + 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 mut g = GradientPaint::new(Gradient::new(GradientKind::Diamond, stops)); + g.geom = Some(vectorcraft_color::GradientGeom { start: Point::new(100.0, 70.0), end: Point::new(140.0, 40.0), aspect: 0.6, focal: None }); + let paint = Paint::Gradient(Box::new(g)); + let d = doc_with(|d| vec![path(d, shapes::rectangle(Rect::new(20.0, 20.0, 180.0, 120.0)), paint, Paint::None, 0.0)]); + for (o, shadings) in [(opts(&d), 4), (EpsOptions { level: Level::Two, ..opts(&d) }, 0)] { + let out = export(&d, &o, None, None).unwrap(); + assert!(out.warnings.iter().any(|w| w.contains("diamond gradients are written as four linear gradients")), "{:?}", out.warnings); + let page = page_of(&d, &o); + assert_eq!(page.matches("shfill").count(), shadings); + assert_eq!(page.matches("closepath clip newpath").count(), 4, "a clip a quadrant"); + } + let out = export(&d, &opts(&d), None, None).unwrap(); + let back = import_with(&out.bytes, false).unwrap().document; + vectorcraft_testkit::raster::assert_similar( + &vectorcraft_testkit::raster::render_artboard(&d), + &vectorcraft_testkit::raster::render_artboard(&back), + 6.0, + 0.01, + ); +} + +/// PostScript's shadings pad past their ends: a linear, radial or diamond gradient that repeats or +/// reflects is written with its stops repeated over the shape, a conic one as wedges that repeat +/// with the stops; read back from the PostScript, each looks as the canvas paints it, at Level 3 +/// and Level 2. +#[test] +fn spread_gradients_are_written_with_their_stops_repeated() { + use vectorcraft_color::{GradientGeom, GradientSpread}; + let c = Point::new(100.0, 100.0); + let around = GradientGeom { start: c, end: c + vectorcraft_geom::Vec2::new(60.0, -25.0), aspect: 0.7, focal: None }; + let cases = [ + (GradientKind::Linear, GradientGeom { start: Point::new(70.0, 80.0), end: Point::new(150.0, 110.0), aspect: 1.0, focal: None }), + (GradientKind::Radial, around), + (GradientKind::Radial, GradientGeom { focal: Some(c + vectorcraft_geom::Vec2::new(-15.0, 12.0)), ..around }), + (GradientKind::Conic, around), + (GradientKind::Diamond, around), + ]; + for (kind, geom) in cases { + for spread in [GradientSpread::Repeat, GradientSpread::Reflect] { + 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 mut g = GradientPaint::new(Gradient { spread, repeats: 3, ..Gradient::new(kind, stops) }); + g.geom = Some(geom); + let paint = Paint::Gradient(Box::new(g)); + let d = doc_with(|d| vec![path(d, shapes::rectangle(Rect::new(20.0, 20.0, 180.0, 180.0)), paint, Paint::None, 0.0)]); + for o in [opts(&d), EpsOptions { level: Level::Two, ..opts(&d) }] { + let out = export(&d, &o, None, None).unwrap(); + let back = import_with(&out.bytes, false).unwrap().document; + let (a, b) = (vectorcraft_testkit::raster::render_artboard(&d), vectorcraft_testkit::raster::render_artboard(&back)); + let st = vectorcraft_testkit::raster::perceptual_diff(&a, &b, 12.0); + assert!( + (st.bad_pixels as f64) < 0.03 * st.pixels as f64, + "{kind:?} {spread:?} level {:?}: {} of {} pixels differ", + o.level, + st.bad_pixels, + st.pixels + ); + } + } + } +} + +/// A gradient that repeats with no stops (a file can hold one) is written as one that pads, to +/// EPS, legacy `.ai` and the `.ai` editing data. +#[test] +fn a_spread_gradient_without_stops_is_written() { + use vectorcraft_color::GradientSpread; + for kind in [GradientKind::Linear, GradientKind::Radial, GradientKind::Conic, GradientKind::Diamond] { + let g = GradientPaint::new(Gradient { spread: GradientSpread::Repeat, repeats: 3, ..Gradient::new(kind, vec![]) }); + let paint = Paint::Gradient(Box::new(g)); + let d = doc_with(|d| vec![path(d, shapes::rectangle(Rect::new(20.0, 20.0, 180.0, 180.0)), paint.clone(), paint, 4.0)]); + export(&d, &opts(&d), None, None).unwrap(); + export_legacy_ai(&d, &LegacyAiOptions::default()).unwrap(); + crate::export_ai_editing(&d, &crate::AiEditingOptions::default()).unwrap(); + } +} + +/// A gradient repeated 256 times across the shape keeps each run's place: the smooth shading's +/// stitching bounds lie where the runs meet, to well under a run's thousandth. +#[test] +fn many_repeats_keep_their_places_in_a_smooth_shading() { + use vectorcraft_color::{GradientGeom, GradientSpread}; + 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))]; + // A run of 0.4 pt across a shape 160 pt wide: capped at 256 runs. + let mut g = GradientPaint::new(Gradient { spread: GradientSpread::Repeat, repeats: 100, ..Gradient::new(GradientKind::Linear, stops) }); + g.geom = Some(GradientGeom { start: Point::new(20.0, 100.0), end: Point::new(60.0, 100.0), aspect: 1.0, focal: None }); + let paint = Paint::Gradient(Box::new(g)); + let d = doc_with(|d| vec![path(d, shapes::rectangle(Rect::new(20.0, 20.0, 180.0, 180.0)), paint, Paint::None, 0.0)]); + let page = page_of(&d, &opts(&d)); + let bounds: Vec = + page.split("/Bounds [").nth(1).and_then(|s| s.split(']').next()).unwrap().split_whitespace().map(|v| v.parse().unwrap()).collect(); + let runs = (bounds.len() + 1) as f64; + assert_eq!(runs, 256.0, "{bounds:?}"); + for b in bounds { + assert!((b * runs - (b * runs).round()).abs() < 1e-3, "bound {b} is {} runs along", b * runs); + } +} + #[test] fn strokes_keep_their_caps_joins_and_dashes() { let d = doc_with(|d| { @@ -559,6 +673,53 @@ fn perceptual_gradients_of_spot_inks_are_written_in_process_colors() { assert!(text(&export(&d, &opts(&d), None, None).unwrap()).contains("/ColorSpace VCdn0")); } +/// The colors between two stops mixed around the hue wheel are not mixes of the stops' inks: a +/// gradient of spot inks mixed that way is written in process colors, with its own warning, as +/// the same gradient without spot inks is. +#[test] +fn hue_wheel_gradients_of_spot_inks_are_written_in_process_colors() { + for method in [GradientMethod::HueClockwise, GradientMethod::HueCounterclockwise] { + let stops = vec![spot_stop(0.0, "Gold Ink", GOLD, 1.0), spot_stop(1.0, "Leaf Ink", LEAF, 1.0)]; + let mut hue = Gradient::new(GradientKind::Linear, stops.clone()); + hue.method = method; + // Reflecting, it is written from the stops on its curve, and warns all the same. + let reflected = Gradient { spread: vectorcraft_color::GradientSpread::Reflect, repeats: 2, ..hue.clone() }; + let r = spot_gradient_doc_of(reflected); + let reflected_out = export(&r, &opts(&r), None, None).unwrap(); + let reflected_page = checked_page(&text(&reflected_out)); + assert!(!reflected_page.contains("VCdn") && !reflected_page.contains("VCsp"), "{method:?} reflected: {reflected_page}"); + assert!( + reflected_out.warnings.iter().any(|w| w.contains("mixed around the hue wheel are written in process colors")), + "{method:?} reflected: {:?}", + reflected_out.warnings + ); + let d = spot_gradient_doc_of(hue); + let out = export(&d, &opts(&d), None, None).unwrap(); + let page = checked_page(&text(&out)); + assert!(!page.contains("VCdn") && !page.contains("VCsp"), "{method:?}: {page}"); + assert!(page.contains("/ColorSpace /DeviceCMYK"), "{method:?}: {page}"); + assert!( + out.warnings.iter().any(|w| w.contains("gradients of spot colors mixed around the hue wheel are written in process colors")), + "{method:?}: {:?}", + out.warnings + ); + assert!(!out.warnings.iter().any(|w| w.contains("Perceptual")), "{method:?}: {:?}", out.warnings); + let process = |c: Color| GradientStop::new(0.0, c); + let mut plain = Gradient::new(GradientKind::Linear, vec![process(GOLD), GradientStop { offset: 1.0, ..process(LEAF) }]); + plain.method = method; + let p = spot_gradient_doc_of(plain); + let plain_out = export(&p, &opts(&p), None, None).unwrap(); + assert!(!plain_out.warnings.iter().any(|w| w.contains("hue wheel")), "{method:?}: {:?}", plain_out.warnings); + let plain_page = checked_page(&text(&plain_out)); + let shading = |s: &str| -> Option { + let i = s.find("/ShadingType")?; + Some(s[i..i + s[i..].find("shfill")?].to_string()) + }; + assert!(shading(&page).is_some_and(|s| s.contains("/Bounds")), "{method:?}: {page}"); + assert_eq!(shading(&page), shading(&plain_page), "{method:?}"); + } +} + #[test] fn rgb_is_written_as_cmyk_when_asked_and_in_cmyk_documents() { let d = doc_with(|d| vec![red_rect(d)]); @@ -576,15 +737,20 @@ fn png_doc() -> Document { for (x, _, p) in img.enumerate_pixels_mut() { *p = if x < 2 { image::Rgba([0, 200, 0, 255]) } else { image::Rgba([0, 0, 0, 0]) }; } + image_doc(&img, 10.0) +} + +/// A 200 × 200 pt document holding `img` as a PNG, its pixels `scale` points wide, at (10, 10). +fn image_doc(img: &image::RgbaImage, scale: f64) -> Document { let mut png = vec![]; img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); let mut d = Document::new(200.0, 200.0); d.images.insert("pic".into(), ImageBlob::new("image/png", png)); let im = ImageObject { key: "pic".into(), - width: 4, - height: 2, - xf: Affine::translate((10.0, 10.0)) * Affine::scale(10.0), + width: img.width(), + height: img.height(), + xf: Affine::translate((10.0, 10.0)) * Affine::scale(scale), link: None, placement: Default::default(), pixels: None, @@ -885,6 +1051,219 @@ fn uncolorized_image_stays_on_original_eps_path() { assert_eq!(page_of(&color, &opts(&color)), original); } +/// A copy of the first layer's object `i`, moved by `xf`, added on top. +fn place_again(d: &mut Document, i: usize, xf: Affine) { + let mut n = (*d.layers[0].children().unwrap()[i]).clone(); + n.id = d.alloc_id(); + if let NodeKind::Image(im) = &mut n.kind { + im.xf = xf * im.xf; + } + d.insert(d.default_layer(), usize::MAX, n).unwrap(); +} + +/// Pixels of noise, opaque. +fn noise(w: u32, h: u32) -> image::RgbaImage { + let mut seed = 1u32; + image::RgbaImage::from_fn(w, h, |_, _| { + let mut px = [255u8; 4]; + for v in &mut px[..3] { + seed = seed.wrapping_mul(1_103_515_245).wrapping_add(12_345); + *v = (seed >> 16) as u8; + } + image::Rgba(px) + }) +} + +/// The pixels of each image an EPS file's page draws, read back from the page. +fn imported_images(bytes: &[u8]) -> Vec> { + fn walk(n: &Node, d: &Document, out: &mut Vec>) { + if let NodeKind::Image(im) = &n.kind { + out.push(image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_rgba8().into_raw()); + } + for c in n.children().into_iter().flatten() { + walk(c, d, out); + } + } + let r = import_with(bytes, false).unwrap(); + assert!(!r.preview, "{:?}", r.warnings); + let mut out = vec![]; + for l in &r.document.layers { + walk(l, &r.document, &mut out); + } + out +} + +/// The samples of an image placed more than once, from the setup that defines them: inflated at +/// Level 3, each string run-length decoded in turn at Level 2. +fn reused_samples(ps: &str, level: Level) -> Vec { + let setup = &ps[ps.find("%%BeginSetup").unwrap()..ps.find("%%EndSetup").unwrap()]; + match level { + Level::Three => ps::inflate(&image_data(setup), 1 << 28).unwrap(), + Level::Two => { + let mut data = vec![]; + for s in setup.split("<~").skip(1) { + let chunk = ps::ascii85_decode(&s[..s.find("~>").unwrap() + 2]).unwrap(); + assert!(chunk.len() <= 65_535, "a string holds at most 65,535 bytes: {}", chunk.len()); + data.extend(chunk); + } + unpack(&data) + } + } +} + +/// The samples of a single image written where it is drawn. +fn inline_samples(ps: &str, level: Level) -> Vec { + match level { + Level::Three => ps::inflate(&image_data(ps), 1 << 28).unwrap(), + Level::Two => unpack(&image_data(ps)), + } +} + +/// How many placements draw the image the setup defines as `VCim`. +fn reuses(ps: &str, i: usize, level: Level) -> usize { + match level { + Level::Three => ps.matches(&format!("VCim{i} resetfile\n")).count(), + Level::Two => ps.matches(&format!("{{VCi VCim{i} length lt")).count(), + } +} + +#[test] +fn an_image_placed_twice_writes_its_samples_once_at_both_levels() { + let single = png_doc(); + let mut d = single.clone(); + place_again(&mut d, 0, Affine::translate((60.0, 80.0)) * Affine::rotate(0.5)); + for level in Level::ALL { + let one = export(&single, &EpsOptions { level, ..opts(&single) }, None, None).unwrap(); + let one_ps = text(&one); + assert!(!one_ps.contains("VCim"), "an image placed once is written where it is drawn: {one_ps}"); + let out = export(&d, &EpsOptions { level, ..opts(&d) }, None, None).unwrap(); + let ps = text(&out); + checked_page(&ps); + assert_eq!(reuses(&ps, 0, level), 2, "{ps}"); + assert!(!ps.contains("VCim1"), "{ps}"); + let body = &ps[ps.find("%%EndSetup").unwrap()..]; + assert!(!body.contains("currentfile") && !body.contains("~>"), "no samples in the page: {ps}"); + match level { + Level::Three => { + assert_eq!(ps.matches("/ReusableStreamDecode filter def").count(), 1, "{ps}"); + assert!(ps.contains("/Intent 0 /AsyncRead false /CloseSource false"), "{ps}"); + assert!(body.contains("/DataSource VCim0 /FlateDecode filter >> image\n"), "{ps}"); + } + Level::Two => { + assert!(ps.contains("/VCim0 [\n<~") && !ps.contains("ReusableStreamDecode"), "{ps}"); + assert!(body.contains("/VCi 0 def\n") && body.contains("/RunLengthDecode filter >> image\n"), "{ps}"); + } + } + assert_eq!(reused_samples(&ps, level), inline_samples(&one_ps, level)); + assert_eq!(out.warnings, one.warnings); + // Read back, each placement draws the image the single placement draws. + let once = imported_images(&one.bytes); + assert_eq!(once.len(), 1); + assert_eq!(imported_images(&out.bytes), vec![once[0].clone(); 2], "{level:?}"); + } +} + +/// An image in an envelope is drawn as clipped pieces, all from one copy of its samples, which the +/// image placed beside the envelope also draws. +#[test] +fn an_envelopes_image_pieces_draw_one_copy_of_its_samples() { + let mut d = png_doc(); + let mut content = (*d.layers[0].children().unwrap()[0]).clone(); + content.id = d.alloc_id(); + let kind = vectorcraft_doc::EnvelopeKind::Warp { style: "arc".into(), bend: 50.0, h: 0.0, v: 0.0, horizontal: true, version: 0 }; + let envelope = Node::new( + d.alloc_id(), + NodeKind::Envelope { + content: vec![Arc::new(content)], + kind: Box::new(kind), + fidelity: 50.0, + editing: false, + options: Default::default(), + frame: Box::new(Affine::IDENTITY), + }, + ); + d.insert(d.default_layer(), usize::MAX, envelope).unwrap(); + for level in Level::ALL { + let out = export(&d, &EpsOptions { level, ..opts(&d) }, None, None).unwrap(); + let ps = text(&out); + checked_page(&ps); + // The plain image and 200 pieces: 10 × 10 cells of two triangles. + assert_eq!(reuses(&ps, 0, level), 201, "{ps}"); + assert!(!ps.contains("VCim1"), "{ps}"); + assert_eq!(ps.matches(if level == Level::Three { "/ReusableStreamDecode" } else { "<~" }).count(), 1, "{ps}"); + assert!(!out.warnings.iter().any(|w| w.contains("too large")), "{:?}", out.warnings); + } +} + +#[test] +fn each_ink_of_a_colorized_image_placed_twice_is_written_once() { + let first = Paint::Solid { color: Color::rgb8(255, 0, 0), swatch: Some("Ink".into()), tint: 1.0 }; + let mut d = colorized_doc(vec![0, 255, 0], Some(first)); + let mut n = (*d.layers[0].children().unwrap()[0]).clone(); + n.id = d.alloc_id(); + n.extras_mut().colorize = Some(Box::new(Paint::Solid { color: Color::rgb8(255, 128, 128), swatch: Some("Ink".into()), tint: 0.5 })); + d.insert(d.default_layer(), usize::MAX, n).unwrap(); + place_again(&mut d, 0, Affine::translate((0.0, 50.0))); + place_again(&mut d, 1, Affine::translate((0.0, 100.0))); + for level in Level::ALL { + let ps = page_of(&d, &EpsOptions { level, ..opts(&d) }); + assert_eq!((reuses(&ps, 0, level), reuses(&ps, 1, level)), (2, 2), "{ps}"); + assert_eq!(ps.matches("VCsp0 setcolorspace 1 setcolor\n").count(), 2, "{ps}"); + assert_eq!(ps.matches("VCsp0 setcolorspace 0.5 setcolor\n").count(), 2, "{ps}"); + assert_eq!(ps.matches("imagemask").count(), 4, "{ps}"); + if level == Level::Three { + assert_eq!(ps.matches("/Intent 1 ").count(), 2, "image masks: {ps}"); + } + } +} + +/// Samples longer than PostScript's longest string: one stream at Level 3, several strings at +/// Level 2, each placement reading all of them. +#[test] +fn samples_longer_than_a_string_are_reused_at_both_levels() { + let single = image_doc(&noise(160, 160), 1.0); + let mut d = single.clone(); + place_again(&mut d, 0, Affine::translate((20.0, 0.0))); + for level in Level::ALL { + let one = export(&single, &EpsOptions { level, ..opts(&single) }, None, None).unwrap(); + let out = export(&d, &EpsOptions { level, ..opts(&d) }, None, None).unwrap(); + let ps = text(&out); + checked_page(&ps); + assert_eq!(reuses(&ps, 0, level), 2); + if level == Level::Two { + assert_eq!(ps.matches("<~").count(), 2, "160 × 160 × 3 run-length bytes take two strings"); + } + let samples = reused_samples(&ps, level); + assert_eq!(samples.len(), 160 * 160 * 3); + assert_eq!(samples, inline_samples(&text(&one), level)); + let once = imported_images(&one.bytes); + assert_eq!(imported_images(&out.bytes), vec![once[0].clone(); 2], "{level:?}"); + } +} + +/// The limit on the page body counts the samples of an image placed many times once. Art taken +/// back for passing the limit takes its image placements with it. +#[test] +fn the_page_limit_counts_a_repeated_images_samples_once() { + let single = image_doc(&noise(40, 40), 1.0); + let o = opts(&single); + let inline = crate::scene::Scene::new(&single, &o).run().body.len(); + let mut d = single.clone(); + for k in 1..20 { + place_again(&mut d, 0, Affine::translate((f64::from(k), 0.0))); + } + let page = crate::scene::Scene::new(&d, &o).with_max_body(inline * 3).run(); + assert!(page.warnings.is_empty(), "{:?}", page.warnings); + assert_eq!(reuses(&page.body, 0, Level::Three), 20); + assert!(page.setup.contains("/VCim0 VCsrc")); + // Past the limit, the placements that don't fit are left out with a warning. + let page = crate::scene::Scene::new(&d, &o).with_max_body(inline + 1000).run(); + assert!(page.warnings.iter().any(|w| w.contains("too large")), "{:?}", page.warnings); + let placed = reuses(&page.body, 0, Level::Three); + assert!((2..20).contains(&placed), "{placed}"); + assert!(page.body.len() + page.setup.len() <= inline + 1000 + 400, "{}", page.body.len()); +} + #[test] fn run_length_and_ascii85_round_trip() { let cycle: Vec = (0..=255u8).cycle().take(1000).collect(); @@ -949,7 +1328,7 @@ fn a_tiff_preview_sits_behind_the_binary_header() { } // Asked for but not rendered: the file has no preview, and says so. let out = export(&d, &EpsOptions { preview: Preview::TiffColor, ..opts(&d) }, None, None).unwrap(); - assert!(out.bytes.starts_with(b"%!PS") && out.warnings.iter().any(|w| w.contains("preview"))); + assert!(out.bytes.starts_with(b"%!PS") && out.setting_notes.iter().any(|w| w.contains("preview"))); } #[test] diff --git a/crates/eps/tests/envelope_ink.rs b/crates/eps/tests/envelope_ink.rs index eccbf8a8f0..3086043238 100644 --- a/crates/eps/tests/envelope_ink.rs +++ b/crates/eps/tests/envelope_ink.rs @@ -6,20 +6,38 @@ use std::sync::Arc; use vectorcraft_doc::{CharStyle, Node, NodeId, NodeKind, TextObject}; -use vectorcraft_geom::{Point, Rect}; +use vectorcraft_geom::{Point, Rect, Shape}; +use vectorcraft_text::test_fonts::{HEIGHT_FAMILY, height_font}; /// 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())) } +/// "Type" at 48 pt in a face the test adds, so its glyphs draw on a machine without craft-fonts or +/// system fonts. +fn type_in_test_face() -> TextObject { + assert!(vectorcraft_text::FontDb::global().add_font(height_font(true).unwrap()) > 0, "the test face loads"); + TextObject::point(Point::new(10.0, 60.0), "Type", CharStyle { font_family: HEIGHT_FAMILY.into(), size: 48.0, ..Default::default() }) +} + +/// The box of the outlines `t`'s glyphs draw, in document space, measured glyph by glyph. +fn outline_box(t: &TextObject) -> Rect { + let laid = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + let outlines: Vec = laid.glyphs.iter().filter(|g| !g.outline.elements().is_empty()).map(|g| (t.xf * &g.outline).bounding_box()).collect(); + assert_eq!(outlines.len(), 4, "every glyph of \"Type\" draws an outline"); + outlines.into_iter().reduce(|a, b| a.union(b)).unwrap() +} + #[test] fn reading_an_ai_file_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 t = type_in_test_face(); 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()); + let ink = outline_box(&t); assert!(laid.height() - ink.height() > 1.0, "the laid-out box {laid:?} reaches past the glyphs {ink:?}"); + let measured = vectorcraft_text::envelope_ink(&t, t.xf, None).unwrap(); + assert!(off(measured, ink) < 1e-6, "the envelope measure gives the glyphs' box: {measured:?} vs {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:?}"); diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rs index 863c6fdd34..8e7149cad2 100644 --- a/crates/format/src/atomic.rs +++ b/crates/format/src/atomic.rs @@ -18,6 +18,25 @@ use std::io::{self, Write as _}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering}; +/// Whether the returned write error refuses this location. Recovery errors must still be shown: +/// their message names copies the user may need, even when their kind is PermissionDenied. +pub fn read_only_location(error: &io::Error) -> bool { + matches!(error.kind(), io::ErrorKind::ReadOnlyFilesystem | io::ErrorKind::PermissionDenied) + && !error.get_ref().is_some_and(|e| e.is::()) +} + +/// Marks the existing recovery message without changing its text or the returned error kind. +#[derive(Debug)] +struct RecoveryError(String); + +impl std::fmt::Display for RecoveryError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl std::error::Error for RecoveryError {} + /// Write `bytes` to `path` atomically (see the module docs). pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> { write_atomic_with(path, |f| f.write_all(bytes)) @@ -102,7 +121,7 @@ fn write_over(tmp: &Path, target: &Path, refused: io::Error) -> io::Result<()> { let _ = std::fs::remove_file(old); let why = format!("{refused}, and the file can't be copied aside before it is overwritten ({e}); the new content is kept in {}", tmp.display()); - return Err(io::Error::new(refused.kind(), why)); + return Err(io::Error::new(refused.kind(), RecoveryError(why))); } let copied = to.set_len(0).and_then(|()| io::copy(&mut from, &mut to)).and_then(|_| sync_file(&to)); drop((from, to)); @@ -115,10 +134,11 @@ fn write_over(tmp: &Path, target: &Path, refused: io::Error) -> io::Result<()> { } Ok(()) } - (Err(e), Some(old)) => { - Err(io::Error::new(e.kind(), format!("{e} (the new content is kept in {}, the file as it was in {})", tmp.display(), old.display()))) - } - (Err(e), None) => Err(io::Error::new(e.kind(), format!("{e} (the new content is kept in {})", tmp.display()))), + (Err(e), Some(old)) => Err(io::Error::new( + e.kind(), + RecoveryError(format!("{e} (the new content is kept in {}, the file as it was in {})", tmp.display(), old.display())), + )), + (Err(e), None) => Err(io::Error::new(e.kind(), RecoveryError(format!("{e} (the new content is kept in {})", tmp.display())))), } } @@ -318,6 +338,24 @@ fn keep_permissions(_: &Path, _: &Path) -> io::Result<()> { mod tests { use super::*; + #[test] + fn readonly_classification_uses_the_terminal_kind_and_excludes_recovery() { + for (kind, expected) in [ + (io::ErrorKind::PermissionDenied, true), + (io::ErrorKind::ReadOnlyFilesystem, true), + (io::ErrorKind::StorageFull, false), + (io::ErrorKind::QuotaExceeded, false), + (io::ErrorKind::NotFound, false), + (io::ErrorKind::Other, false), + ] { + assert_eq!(read_only_location(&io::Error::new(kind, "injected")), expected, "{kind:?}"); + let recovery = io::Error::new(kind, RecoveryError("the new content is kept in a.tmp".into())); + assert!(!read_only_location(&recovery), "recovery: {kind:?}"); + assert_eq!(recovery.kind(), kind); + assert_eq!(recovery.to_string(), "the new content is kept in a.tmp"); + } + } + fn dir(name: &str) -> PathBuf { let d = std::env::temp_dir().join(format!("vc-atomic-{name}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 38545b8292..968cd720a0 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -55,7 +55,7 @@ use serde::{Deserializer, Serialize}; use vectorcraft_doc::{Document, ImageBlob}; #[cfg(not(target_arch = "wasm32"))] -pub use atomic::{sync_file, write_atomic, write_atomic_with, write_new_with}; +pub use atomic::{read_only_location, sync_file, write_atomic, write_atomic_with, write_new_with}; pub use craft_vectorcraft_format::base64::{decode as base64_decode, decoded_len as base64_decoded_len, encode as base64_encode}; pub use craft_vectorcraft_format::{ BLOB_MAGIC, COMPRESSED_SINCE, EXTENSION, ICC_MIME, INLINE_MAX, LEGACY_EXTENSION, MIN_VERSION, PREVIEW_MAX, VERSION, is_compressed, json_part, @@ -504,11 +504,23 @@ pub fn load_file(bytes: &[u8]) -> Result { load_file_within(bytes, vectorcraft_doc::node::MAX_READ_NODES, vectorcraft_doc::node::MAX_BUFFERED_VALUES) } +/// [`load_file`] with a compressed file refused when its JSON, or the data after it (images, +/// profiles, the preview), unpacks to more than `max` bytes (at most [`MAX_JSON`] and +/// [`MAX_BLOBS`]), or, when it lacks the marker after its JSON, when all of it does. +pub fn load_file_capped(bytes: &[u8], max: u64) -> Result { + let file = unpack::Unpacked::within_capped(bytes, max.min(MAX_JSON), max.min(MAX_UNPACKED), max.min(MAX_BLOBS))?; + load_unpacked(file, vectorcraft_doc::node::MAX_READ_NODES, vectorcraft_doc::node::MAX_BUFFERED_VALUES) +} + /// [`load_file`] reading at most `max_nodes` objects and buffering at most `max_values` values /// before objects' types, so a test can exercise the budgets without documents that large /// ([`vectorcraft_doc::node::MAX_READ_NODES`], [`vectorcraft_doc::node::MAX_BUFFERED_VALUES`]). fn load_file_within(bytes: &[u8], max_nodes: usize, max_values: usize) -> Result { - let file = unpack::Unpacked::new(bytes)?; + load_unpacked(unpack::Unpacked::new(bytes)?, max_nodes, max_values) +} + +/// The document of `file`, within the budgets of [`load_file_within`]. +fn load_unpacked(file: unpack::Unpacked<'_>, max_nodes: usize, max_values: usize) -> Result { // The JSON reader stops at 128 levels (a document's objects use three each), the paths read // at `MAX_READ_ANCHORS` anchors together, the document at `MAX_READ_NODES` objects, and the // fields read before an object's type at `MAX_BUFFERED_VALUES` values. The preview and the @@ -594,6 +606,10 @@ fn load_file_within(bytes: &[u8], max_nodes: usize, max_values: usize) -> Result doc.raster_effects.add_around = doc.raster_effects.add_around.clamp(0.0, vectorcraft_doc::rastersettings::MAX_ADD_AROUND); let mut depth_notes = vec![]; doc.limit_depth_noting(&mut depth_notes); + // Untrusted: ruler guide nodes only directly in layers, above their art (after the depth limit: + // the walk recurses; before the canvas check, which takes a layer's first member as its + // clipping path). + doc.tidy_ruler_guides(); // Untrusted: nothing beyond the canvas, where no edit may leave anything (after the depth // limit: the walk recurses). A file whose artboards all lie there has no page to show (#3575). let had_artboards = !doc.artboards.is_empty(); @@ -605,9 +621,6 @@ fn load_file_within(bytes: &[u8], max_nodes: usize, max_values: usize) -> Result ))); } depth_notes.extend(beyond.note()); - // Untrusted: ruler guide nodes only directly in layers, above their art (after the depth limit: - // the walk recurses). - doc.tidy_ruler_guides(); // The saved ruler guides become nodes on their layers (after the guides beyond the canvas are // dropped, and after `fix_next_id`: new ids start above the file's). doc.guides_into_nodes(); @@ -1185,6 +1198,30 @@ mod tests { assert_eq!(back.node(id).unwrap().path_data(), d.node(id).unwrap().path_data()); } + /// A capped read refuses a compressed file whose images unpack past the cap, before reading + /// them, and reads the same file under a cap it fits. + #[test] + fn a_capped_load_caps_the_data_after_the_json() { + use std::io::Write as _; + let mut d = Document::new(100.0, 100.0); + let l = d.layers[0].id; + d.images.insert("k".into(), ImageBlob::new("image/png", vec![7; 1 << 16])); + let img = d.alloc_id(); + let im = ImageObject { key: "k".into(), width: 1, height: 1, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None }; + d.insert(Some(l), 0, Node::new(img, NodeKind::Image(Box::new(im)))).unwrap(); + // The file gzipped whole, image and all, so the image unpacks from a few bytes. + let raw = save_with(&d, &SaveOptions::default()).unwrap(); + let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::best()); + gz.write_all(&raw).unwrap(); + let bytes = gz.finish().unwrap(); + assert!(is_compressed(&bytes) && bytes.len() < 1 << 12, "{}", bytes.len()); + let json = unpack::Unpacked::new(&bytes).unwrap().json().len(); + assert!(json < 1 << 15, "{json}"); + assert!(matches!(load_file_capped(&bytes, (1 << 16) - 1), Err(FormatError::TooBig))); + assert_eq!(load_file_capped(&bytes, 3 << 15).unwrap().doc.images["k"].bytes.len(), 1 << 16); + assert_eq!(load_file(&bytes).unwrap().doc.images["k"].bytes.len(), 1 << 16); + } + /// #3587: objects are read within a budget. A compressed file of many small objects stays /// small on disk while they take far more memory once read, so past the budget it is refused /// with a message naming it, before the rest of the document is read. @@ -1385,4 +1422,35 @@ mod tests { assert_eq!(base64_decode("QUI="), Some(vec![0x41, 0x42])); assert_eq!(base64_decode("QUJD"), Some(vec![0x41, 0x42, 0x43])); } + + /// A layer clipping by a path beyond the canvas is emptied on open and stops clipping, also + /// when the file puts a ruler guide before the clipping path: no other object becomes it. + #[test] + fn a_guide_before_a_clipping_path_beyond_the_canvas_does_not_change_the_clipping_path() { + let opened = |guide_first: bool| { + let mut d = Document::new(100.0, 100.0); + let rect = |d: &mut Document, y: f64| { + Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, y, 10.0, y + 10.0)), Appearance::default_art())) + }; + let (far, near) = (rect(&mut d, 1e17), rect(&mut d, 0.0)); + if let NodeKind::Layer { children, clip, .. } = &mut Arc::make_mut(&mut d.layers[0]).kind { + *children = vec![far, near]; + *clip = true; + } + // Saving writes ruler guides to the saved list: the guide node is put in the file. + let mut v: serde_json::Value = serde_json::from_slice(&save(&d, false)).unwrap(); + let guide = serde_json::json!({"id": 50, "kind": {"type": "rulerguide", "vertical": true, "pos": 5.0}}); + let kids = v["document"]["layers"][0]["kind"]["children"].as_array_mut().unwrap(); + if guide_first { + kids.insert(0, guide) + } else { + kids.push(guide) + } + let d = load(&serde_json::to_vec(&v).unwrap()).unwrap(); + let NodeKind::Layer { children, clip, .. } = &d.layers[0].kind else { panic!("a layer") }; + (*clip, children.iter().map(|c| c.is_ruler_guide()).collect::>()) + }; + assert_eq!(opened(false), (false, vec![true]), "the clipping path and what it clipped go; the guide stays"); + assert_eq!(opened(true), opened(false)); + } } diff --git a/crates/format/src/unpack.rs b/crates/format/src/unpack.rs index 1573fa0bc7..ec9623118c 100644 --- a/crates/format/src/unpack.rs +++ b/crates/format/src/unpack.rs @@ -28,6 +28,13 @@ pub(crate) type Entry = Option>>; pub(crate) struct Unpacked<'a> { json: Json<'a>, tail: Tail<'a>, + /// Most bytes the entries after the JSON may have together ([`MAX_BLOBS`] unless capped). + max_blobs: u64, + /// Most bytes unpacked to find them in a streamed file ([`MAX_WORK`] unless capped). + max_work: u64, + /// Must a streamed file's data after the JSON end within `max_blobs` bytes + /// ([`Self::within_capped`])? + capped: bool, } enum Json<'a> { @@ -68,9 +75,25 @@ impl<'a> Unpacked<'a> { /// a document several times its size, and the cap is what keeps that off the address space /// (#3587). fn within(bytes: &'a [u8], max_json: u64) -> Result { + let (json, tail) = Self::open(bytes, max_json, MAX_UNPACKED)?; + Ok(Self { json, tail, max_blobs: MAX_BLOBS, max_work: max_json.saturating_add(MAX_BLOBS).min(MAX_WORK), capped: false }) + } + + /// [`Self::within`], with a compressed file that lacks the marker after its JSON (unpacked + /// whole) capped at `max_whole` bytes instead of [`MAX_UNPACKED`], the entries after the JSON + /// at `max_blobs` bytes together instead of [`MAX_BLOBS`], and the bytes unpacked to find them + /// at `max_json` and `max_blobs` together instead of [`MAX_WORK`]. A streamed file whose data + /// after the JSON unpacks to more than `max_blobs` bytes is refused when its entries are read. + pub(crate) fn within_capped(bytes: &'a [u8], max_json: u64, max_whole: u64, max_blobs: u64) -> Result { + let (json, tail) = Self::open(bytes, max_json, max_whole)?; + Ok(Self { json, tail, max_blobs, max_work: max_json.saturating_add(max_blobs).min(MAX_WORK), capped: true }) + } + + /// The JSON of `bytes` and where the data after it is, within `max_json` and `max_whole`. + fn open(bytes: &'a [u8], max_json: u64, max_whole: u64) -> Result<(Json<'a>, Tail<'a>), FormatError> { if !is_compressed(bytes) { let (json, tail) = split_tail(bytes); - return Ok(Self { json: Json::Borrowed(json), tail: Tail::Slice(tail) }); + return Ok((Json::Borrowed(json), Tail::Slice(tail))); } let mut dec = GzDecoder::new(bytes); let mut buf = Vec::new(); @@ -93,7 +116,7 @@ impl<'a> Unpacked<'a> { if buf.len() as u64 > max_json { return Err(FormatError::TooBig); } - return Ok(Self { json: Json::Owned(buf), tail: Tail::None }); + return Ok((Json::Owned(buf), Tail::None)); } // The marker where the writer puts it, right after the JSON's last byte: what is unpacked // so far reaches past it. @@ -104,17 +127,17 @@ impl<'a> Unpacked<'a> { let read = buf.split_off(end + BLOB_MAGIC.len()); buf.truncate(end); let at = (end + BLOB_MAGIC.len()) as u64; - return Ok(Self { json: Json::Owned(buf), tail: Tail::Stream { file: bytes, at, read, rest: Box::new(dec) } }); + return Ok((Json::Owned(buf), Tail::Stream { file: bytes, at, read, rest: Box::new(dec) })); } // Anything else (hand-made or damaged files) is unpacked whole and split as an // uncompressed file is. - dec.take(MAX_UNPACKED + 1 - (buf.len() as u64).min(MAX_UNPACKED)).read_to_end(&mut buf).map_err(damaged)?; - if buf.len() as u64 > MAX_UNPACKED { + dec.take(max_whole + 1 - (buf.len() as u64).min(max_whole)).read_to_end(&mut buf).map_err(damaged)?; + if buf.len() as u64 > max_whole { return Err(FormatError::TooBig); } let (json, tail) = split_tail(&buf); let (json, tail) = (json.len(), buf.len() - tail.len()); - Ok(Self { json: Json::Whole { buf, json }, tail: Tail::Whole(tail) }) + Ok((Json::Whole { buf, json }, Tail::Whole(tail))) } /// The JSON text. @@ -133,13 +156,16 @@ impl<'a> Unpacked<'a> { /// of an uncompressed file larger together than both [`MAX_BLOBS`] and the data, or the /// distinct entries found larger together than the data they are in (overlapping entries /// would copy the same bytes once each, #3574). Entries are read in the order of their - /// offsets, each straight into its own buffer. + /// offsets, each straight into its own buffer. A capped file ([`Self::within_capped`]) takes + /// its own totals in place of [`MAX_BLOBS`] and [`MAX_WORK`]. pub(crate) fn entries(self, wanted: &[[u64; 2]]) -> Result, FormatError> { - self.entries_within(wanted, MAX_WORK) + let work = self.max_work; + self.entries_within(wanted, work) } /// [`Self::entries`], unpacking at most `work` bytes of a streamed file to find them. fn entries_within(self, wanted: &[[u64; 2]], work: u64) -> Result, FormatError> { + let (max_blobs, capped) = (self.max_blobs, self.capped); let mut out: Vec = vec![None; wanted.len()]; // Data in memory is read through the crate's `Entries`: entries naming the same bytes // share them, and the bytes copied stay within the data. @@ -155,11 +181,11 @@ impl<'a> Unpacked<'a> { }; match self.tail { Tail::Slice(tail) => { - within(wanted, u64::MAX, MAX_BLOBS.max(tail.len() as u64))?; + within(wanted, u64::MAX, max_blobs.max(tail.len() as u64))?; in_memory(tail, &mut out)?; } Tail::Whole(at) => { - within(wanted, MAX_BLOB, MAX_BLOBS)?; + within(wanted, MAX_BLOB, max_blobs)?; let buf = match &self.json { Json::Whole { buf, .. } => buf.as_slice(), _ => &[], @@ -168,7 +194,7 @@ impl<'a> Unpacked<'a> { } Tail::None => in_memory(&[], &mut out)?, Tail::Stream { file, at, read, rest } => { - within(wanted, MAX_BLOB, MAX_BLOBS)?; + within(wanted, MAX_BLOB, max_blobs)?; drop(self.json); // The entries read so far, by `[offset, length]`, and the bytes copied for them. let mut done: HashMap<[u64; 2], Entry> = HashMap::new(); @@ -193,9 +219,10 @@ impl<'a> Unpacked<'a> { } done.insert(w, slot.clone()); } - // To the end, so the stream's checksum is verified as before. - s.left = MAX_BLOBS; - s.skip(MAX_BLOBS)?; + // To the end, so the stream's checksum is verified as before. A capped file's data + // must end within its cap from its start: one byte more is over the budget. + s.left = if capped { max_blobs.checked_sub(s.pos).ok_or(FormatError::TooBig)? } else { max_blobs }; + s.skip(if capped { s.left.saturating_add(1) } else { max_blobs })?; } } Ok(out) @@ -317,6 +344,16 @@ mod tests { // An offset past the data is still just missing, and the default budget reads all of it. assert_eq!(read(&[[1 << 40, 1]], 1 << 20).unwrap(), vec![None]); assert_eq!(Unpacked::new(&file).unwrap().entries(&[[0, 4096]]).unwrap(), vec![Some(Arc::new(tail.clone()))]); + // A capped file finds its entries within its own caps: a small entry far into the data, + // entries larger than the cap together, or data that goes on past the cap after the + // entries, are refused. + let capped = |cap: u64| Unpacked::within_capped(&file, 64, MAX_UNPACKED, cap).unwrap(); + assert_eq!(capped(4096).entries(&[[0, 16]]).unwrap(), vec![Some(Arc::new(tail[..16].to_vec()))]); + assert!(matches!(capped(4095).entries(&[[0, 16]]), Err(FormatError::TooBig))); + assert!(matches!(capped(4095).entries(&[[4095, 1]]), Err(FormatError::TooBig))); + assert!(matches!(capped(16).entries(&[[4000, 1]]), Err(FormatError::TooBig))); + assert!(matches!(capped(16).entries(&[[0, 17]]), Err(FormatError::TooBig))); + assert_eq!(Unpacked::new(&file).unwrap().entries(&[[4000, 1]]).unwrap(), vec![Some(Arc::new(vec![tail[4000]]))]); } /// #3587: a compressed file's JSON is capped wherever the cap runs, so a small gzip that diff --git a/crates/geom/src/arc.rs b/crates/geom/src/arc.rs index c4fe640ae2..644dc44f6a 100644 --- a/crates/geom/src/arc.rs +++ b/crates/geom/src/arc.rs @@ -2,7 +2,7 @@ //! distance along it of the point nearest another (type on a path lays its glyphs out and the //! selection tools drag its brackets by distance along the path). -use kurbo::{ParamCurve, ParamCurveArclen, ParamCurveNearest, PathSeg, Point, Vec2}; +use kurbo::{Affine, ParamCurve, ParamCurveArclen, ParamCurveExtrema, ParamCurveNearest, PathSeg, Point, Vec2}; use crate::PathData; @@ -76,6 +76,78 @@ impl ArcPath { pub fn fraction_at(&self, p: Point) -> Option { (self.len > 0.0).then(|| self.nearest(p)).flatten().map(|s| (s / self.len).clamp(0.0, 1.0)) } + + /// The distance along the path of the middle of its topmost points (the least y) where `xf` + /// draws it: the topmost point when there is one, the middle of a level stretch (a + /// rectangle's top edge), and when several points or stretches are topmost, the middle of the + /// shortest part of the path that holds them all. None for a path with no length, or a closed + /// path whose every point is topmost. + pub fn topmost(&self, xf: Affine) -> Option { + let drawn: Vec<(PathSeg, PathSeg, f64, f64)> = self.segs.iter().map(|&(s, c, l)| (s, xf * s, c, l)).collect(); + // The candidates for the least y in each segment: its ends and where it turns. + let turns = |d: &PathSeg| [0.0, 1.0].into_iter().chain(d.extrema()).collect::>(); + let mut bounds: Option = None; + let mut top = f64::INFINITY; + for (_, d, _, _) in &drawn { + let b = d.bounding_box(); + bounds = Some(bounds.map_or(b, |a| a.union(b))); + top = turns(d).into_iter().map(|t| d.eval(t).y).fold(top, f64::min); + } + let b = bounds?; + if !(top.is_finite() && b.width().is_finite() && b.height().is_finite()) { + return None; + } + // Points this close to the top count as topmost: a part of the drawn size, and no less than + // the rounding error of coordinates this far from the origin. + let tol = (1e-9 * (b.width() + b.height())).max(64.0 * f64::EPSILON * b.y0.abs().max(b.y1.abs())); + // Stretches this close along the path meet. + let near = 1e-9 * self.len; + // The topmost points as stretches of distance along the path, in order. + let mut runs: Vec<(f64, f64)> = vec![]; + for (s, d, c, l) in &drawn { + let db = d.bounding_box(); + if db.y1 - db.y0 <= tol && db.y0 <= top + tol { + runs.push((*c, c + l)); + continue; + } + for t in turns(d) { + if d.eval(t).y <= top + tol { + let at = c + s.subsegment(0.0..t).arclen(ACCURACY).min(*l); + runs.push((at, at)); + } + } + } + runs.sort_by(|a, b| a.0.total_cmp(&b.0)); + // Stretches that meet or overlap are one. + let mut merged: Vec<(f64, f64)> = vec![]; + for (a, z) in runs { + match merged.last_mut() { + Some(last) if a <= last.1 + near => last.1 = last.1.max(z), + _ => merged.push((a, z)), + } + } + let (first, last) = (*merged.first()?, *merged.last()?); + if !self.closed { + return Some((first.0 + last.1) * 0.5); + } + let len = self.len; + // Round a closed path, the shortest part holding every stretch leaves out the longest + // gap between two of them (the gap from the last round to the first included). + let wrap = first.0 + len - last.1; + let (mut gap, mut from, mut to) = (wrap, first.0, last.1); + for w in merged.windows(2) { + if let [a, b] = w + && b.0 - a.1 > gap + { + (gap, from, to) = (b.0 - a.1, b.0, a.1); + } + } + if gap <= near { + return None; + } + let run = (to - from).rem_euclid(len); + Some((from + run * 0.5).rem_euclid(len)) + } } #[cfg(test)] @@ -99,4 +171,64 @@ mod tests { assert!(sq.at(45.0).0.distance(sq.at(5.0).0) < 1e-6); assert!(ArcPath::new(&PathData::default()).is_empty()); } + + fn polyline(points: &[Point], closed: bool) -> PathData { + PathData::single(crate::SubPath::polyline(points, closed)) + } + + /// Where `topmost` puts the middle, drawn by `xf`. + fn top_point(a: &ArcPath, xf: Affine) -> Point { + xf * a.at(a.topmost(xf).unwrap()).0 + } + + #[test] + fn topmost_points_as_drawn() { + // A circle starts at 9 o'clock and runs clockwise (y down): its top is a quarter of the way round, its + // bottom three quarters. + let circle = ArcPath::new(&shapes::ellipse(Rect::new(0.0, 0.0, 100.0, 100.0))); + assert!((circle.topmost(Affine::IDENTITY).unwrap() - circle.len() * 0.25).abs() < 1e-6); + assert!((circle.topmost(Affine::FLIP_Y).unwrap() - circle.len() * 0.75).abs() < 1e-6); + // As the transform draws it: turned a quarter turn the other way, 3 o'clock is at the top. + let turned = Affine::rotate_about(-std::f64::consts::FRAC_PI_2, Point::new(50.0, 50.0)); + assert!((circle.topmost(turned).unwrap() - circle.len() * 0.5).abs() < 1e-6); + // Turned part way, the top lies inside a segment. + let tilted = Affine::rotate_about(0.4, Point::new(50.0, 50.0)); + assert!(top_point(&circle, tilted).distance(Point::new(50.0, 0.0)) < 0.05, "{:?}", top_point(&circle, tilted)); + // An ellipse squashed and skewed by its transform. + let skewed = Affine::skew(0.5, 0.0) * Affine::scale_non_uniform(2.0, 0.5); + let p = top_point(&circle, skewed); + let lowest = (0..3600).map(|i| (skewed * circle.at(circle.len() * i as f64 / 3600.0).0).y).fold(f64::INFINITY, f64::min); + assert!((p.y - lowest).abs() < 1e-3, "{p:?} {lowest}"); + // A level top: the middle of the top edge, for a rectangle and a rounded rectangle. + for path in [shapes::rectangle(Rect::new(10.0, 20.0, 110.0, 70.0)), shapes::rounded_rectangle(Rect::new(10.0, 20.0, 110.0, 70.0), 8.0)] { + let a = ArcPath::new(&path); + assert!(top_point(&a, Affine::IDENTITY).distance(Point::new(60.0, 20.0)) < 1e-6, "{:?}", top_point(&a, Affine::IDENTITY)); + assert!(top_point(&a, Affine::FLIP_Y).distance(Point::new(60.0, -70.0)) < 1e-6); + } + // Far from the origin the top is still the top edge's middle. + let square = ArcPath::new(&shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0))); + let far = Affine::translate((1e12, 1e12)); + assert!(top_point(&square, far).distance(Point::new(1e12 + 50.0, 1e12)) < 1e-3, "{:?}", top_point(&square, far)); + // A level top across the path's start: the start in the middle of the top edge. + let across = ArcPath::new(&polyline( + &[Point::new(50.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 50.0), Point::new(0.0, 50.0), Point::new(0.0, 0.0)], + true, + )); + assert!(top_point(&across, Affine::IDENTITY).distance(Point::new(50.0, 0.0)) < 1e-6); + // Two peaks: the middle of the shortest part that holds both, the dip between them. + let peaks = ArcPath::new(&polyline( + &[Point::new(0.0, 10.0), Point::new(2.0, 0.0), Point::new(4.0, 5.0), Point::new(6.0, 0.0), Point::new(8.0, 10.0)], + true, + )); + assert!(top_point(&peaks, Affine::IDENTITY).distance(Point::new(4.0, 5.0)) < 1e-6, "{:?}", top_point(&peaks, Affine::IDENTITY)); + // An open path: the middle of its topmost points too. + let open = ArcPath::new(&polyline(&[Point::new(0.0, 10.0), Point::new(5.0, 0.0), Point::new(10.0, 10.0)], false)); + assert!(top_point(&open, Affine::IDENTITY).distance(Point::new(5.0, 0.0)) < 1e-6); + // No top: a closed path that is level all round, and a path with no length. + let flat = ArcPath::new(&shapes::ellipse(Rect::new(0.0, 10.0, 100.0, 10.0))); + assert!(!flat.is_empty() && flat.topmost(Affine::IDENTITY).is_none()); + assert!(ArcPath::new(&PathData::default()).topmost(Affine::IDENTITY).is_none()); + let point = ArcPath::new(&polyline(&[Point::new(5.0, 5.0), Point::new(5.0, 5.0)], true)); + assert!(point.topmost(Affine::IDENTITY).is_none()); + } } diff --git a/crates/geom/src/path.rs b/crates/geom/src/path.rs index 59a8f30660..ac7dc63add 100644 --- a/crates/geom/src/path.rs +++ b/crates/geom/src/path.rs @@ -165,6 +165,26 @@ impl Anchor { pub fn reversed(&self) -> Self { Self { p: self.p, h_in: self.h_out, h_out: self.h_in, kind: self.kind } } + /// Make the anchor smooth between the points `prev` and `next` (its own point for a missing + /// one): handles in line with them, each a third of the way to that side's point. A smooth + /// anchor with both handles keeps them. False, with no change, when the two points give no + /// direction. [`SubPath::smooth_anchor`] calls it with the anchor's neighbors. + pub fn smooth_between(&mut self, prev: Option, next: Option) -> bool { + if self.kind == AnchorKind::Smooth && self.has_in() && self.has_out() { + return true; + } + let (pp, nn) = (prev.unwrap_or(self.p), next.unwrap_or(self.p)); + let dir = nn - pp; + let l = dir.hypot(); + if l <= 1e-9 { + return false; + } + let u = dir / l; + self.h_in = self.p - u * (self.p.distance(pp) / 3.0); + self.h_out = self.p + u * (self.p.distance(nn) / 3.0); + self.kind = AnchorKind::Smooth; + true + } /// Remove both handles (convert to a sharp corner). pub fn retract(&mut self) { self.h_in = self.p; @@ -398,21 +418,7 @@ impl SubPath { }; let at = |j: Option| j.and_then(|j| self.anchors.get(j)).map(|a| a.p); let (prev, next) = (at(prev), at(next)); - let Some(a) = self.anchors.get_mut(i) else { return false }; - if a.kind == AnchorKind::Smooth && a.has_in() && a.has_out() { - return true; - } - let (pp, nn) = (prev.unwrap_or(a.p), next.unwrap_or(a.p)); - let dir = nn - pp; - let l = dir.hypot(); - if l <= 1e-9 { - return false; - } - let u = dir / l; - a.h_in = a.p - u * (a.p.distance(pp) / 3.0); - a.h_out = a.p + u * (a.p.distance(nn) / 3.0); - a.kind = AnchorKind::Smooth; - true + self.anchors.get_mut(i).is_some_and(|a| a.smooth_between(prev, next)) } /// Cut at the anchors `at`: each becomes the end of one open piece and the start of the next, /// its handle off each piece retracted (the shape doesn't change). A closed subpath opens at @@ -688,7 +694,8 @@ fn box_gap(c: &CubicBez, p: Point) -> Option { const MEASURE_LIMIT: f64 = 1e9; /// The length of `seg` to `accuracy`; 0 for a segment whose control points are not finite or past -/// [`MEASURE_LIMIT`]. +/// [`MEASURE_LIMIT`], and 0 when the measurement is not finite (kurbo gives NaN for a quadratic +/// segment whose three points coincide). pub fn measured_arclen(seg: &PathSeg, accuracy: f64) -> f64 { let ok = |p: Point| p.x.is_finite() && p.y.is_finite() && p.x.abs() <= MEASURE_LIMIT && p.y.abs() <= MEASURE_LIMIT; let fits = match seg { @@ -696,7 +703,11 @@ pub fn measured_arclen(seg: &PathSeg, accuracy: f64) -> f64 { PathSeg::Quad(q) => ok(q.p0) && ok(q.p1) && ok(q.p2), PathSeg::Cubic(c) => ok(c.p0) && ok(c.p1) && ok(c.p2) && ok(c.p3), }; - if fits { kurbo::ParamCurveArclen::arclen(seg, accuracy) } else { 0.0 } + if !fits { + return 0.0; + } + let len = kurbo::ParamCurveArclen::arclen(seg, accuracy); + if len.is_finite() { len } else { 0.0 } } /// The largest x or y, in size, of a segment's control points for which [`segment_bounds`] @@ -1056,6 +1067,19 @@ mod tests { assert!((square().length() - 40.0).abs() < 1e-6); } + /// A quadratic segment whose three points coincide measures 0, not NaN; quadratic segments + /// with only two points together, and an ordinary one, keep kurbo's length. + #[test] + fn measured_arclen_of_a_quad_whose_points_coincide_is_zero() { + let quad = |a: (f64, f64), b: (f64, f64), c: (f64, f64)| PathSeg::Quad(kurbo::QuadBez::new(a, b, c)); + assert_eq!(measured_arclen(&quad((5.0, 5.0), (5.0, 5.0), (5.0, 5.0)), 1e-6), 0.0); + assert_eq!(measured_arclen(&quad((0.0, 0.0), (0.0, 0.0), (0.0, 0.0)), 1e-3), 0.0); + assert!((measured_arclen(&quad((0.0, 0.0), (0.0, 0.0), (10.0, 0.0)), 1e-6) - 10.0).abs() < 1e-6); + assert!((measured_arclen(&quad((0.0, 0.0), (10.0, 0.0), (0.0, 0.0)), 1e-6) - 10.0).abs() < 1e-6); + let ordinary = quad((0.0, 0.0), (10.0, 0.0), (10.0, 10.0)); + assert_eq!(measured_arclen(&ordinary, 1e-6), kurbo::ParamCurveArclen::arclen(&ordinary, 1e-6)); + } + #[test] fn serde_roundtrip() { let p = square(); diff --git a/crates/js/Cargo.toml b/crates/js/Cargo.toml index 610c8f9bd6..c12871583a 100644 --- a/crates/js/Cargo.toml +++ b/crates/js/Cargo.toml @@ -11,7 +11,9 @@ workspace = true [dependencies] chrono = { workspace = true } -unicode-general-category = "1" +# Unicode 17.0 general categories for identifiers (chars.rs). 0.1.5 adds the Unicode-3.0 license, +# which is not on the license allowlist, so the version is exact. +unicode-properties = { version = "=0.1.4", default-features = false, features = ["general-category"] } # The seed of Math.random (interp.rs). getrandom = "0.4" diff --git a/crates/js/src/ast.rs b/crates/js/src/ast.rs index 5a4363108a..8d9ffc06c0 100644 --- a/crates/js/src/ast.rs +++ b/crates/js/src/ast.rs @@ -187,7 +187,8 @@ pub enum Expr { qualifier: Option, name: XmlNamePart, }, - /// An E4X name standing alone (`@a` in a filter): looked up on the nearest XML value in scope. + /// An E4X name standing alone (`@a` in a filter): looked up on the nearest XML value in scope + /// that holds it, and also an assignment, update or `delete` target. XmlScopeName(ExprId), /// `object..name`. XmlDescendants { diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index f7c21a8d8e..301b1235a4 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -466,6 +466,7 @@ fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe .chain([parts.len().saturating_sub(1), HEAD.len() + MID.len() + TAIL.len(), body.len()]) .fold(0usize, usize::saturating_add); interp.check_source_units(total).map_err(|e| interp.compile_error_to_abrupt(e))?; + interp.prepare_source(total)?; let mut units = Vec::with_capacity(total); units.extend(HEAD.encode_utf16()); for (i, p) in parts.iter().enumerate() { @@ -554,6 +555,7 @@ fn eval(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult JsResult<()> { @@ -278,17 +279,20 @@ fn join_with(interp: &mut Interp, o: ObjId, separator: &Value, item: fn(&mut Int if len == 0 { return Ok(Value::str("")); } - let flat = sep.flat(); - let sep = &flat[..]; - // A result that cannot fit is refused before any element is read. - let least = (sep.len() as u64).saturating_mul(u64::from(len - 1)); - if least > (interp.limits.heap_bytes / 4) as u64 { - return Err(Abrupt::Limit(crate::LimitKind::Heap)); - } - interp.join_stack.push(o); - let r = join_elements(interp, o, len, sep, item); - interp.join_stack.pop(); - r + // The separator stays rooted for the whole join, so its flattened copy stays counted. + interp.rooted(&[Value::String(sep.clone())], |interp| { + let flat = flat_charged(interp, &sep)?; + let sep = &flat[..]; + // A result that cannot fit is refused before any element is read. + let least = (sep.len() as u64).saturating_mul(u64::from(len - 1)); + if least > (interp.limits.heap_bytes / 4) as u64 { + return Err(Abrupt::Limit(crate::LimitKind::Heap)); + } + interp.join_stack.push(o); + let r = join_elements(interp, o, len, sep, item); + interp.join_stack.pop(); + r + }) } fn join_elements(interp: &mut Interp, o: ObjId, len: u32, sep: &[u16], item: fn(&mut Interp, Value) -> JsResult>) -> JsResult { @@ -301,7 +305,10 @@ fn join_elements(interp: &mut Interp, o: ObjId, len: u32, sep: &[u16], item: fn( let Some(s) = item(interp, v)? else { continue }; out.push_repeated(interp, sep, k.saturating_sub(seps))?; seps = k; - out.push_units(interp, &s.flat())?; + interp.rooted(&[Value::String(s.clone())], |interp| { + let units = flat_charged(interp, &s)?; + out.push_units(interp, &units) + })?; } out.push_repeated(interp, sep, u64::from(len - 1).saturating_sub(seps))?; Ok(out.finish(interp)) @@ -472,7 +479,7 @@ fn unshift(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResul with_this(interp, &this, |interp, o| { let len = u64::from(length_of(interp, o)?); let count = args.len() as u64; - // With no arguments each element is still read and written back in place (steps 6 and 7). + // With no arguments each element is still read and written back in place (step 6). let maps = vec![Map::Shift(-1), Map::Shift(count as i64 - 1)]; let mut it = Indices::new(interp, o, 1, len + 1, false, maps)?; while let Some(k) = it.next(interp)? { diff --git a/crates/js/src/builtins/extensions.rs b/crates/js/src/builtins/extensions.rs index 15ebbe734f..94ee226d57 100644 --- a/crates/js/src/builtins/extensions.rs +++ b/crates/js/src/builtins/extensions.rs @@ -9,14 +9,18 @@ //! a script's own method: a getter, a function, a date, a regular expression, an error, a boxed //! primitive, an array with properties besides its elements, an object whose prototype is not //! `Object.prototype`, a property that is not enumerable or any other object that is not plain -//! data throws a `TypeError`, and so does an object that contains itself. A value nested deeper, with more entries or longer text than the +//! data throws a `TypeError`, and so does an object that contains itself. A literal makes an +//! extensible object whose properties are writable and configurable and an array whose `length` +//! is writable, so a property that is not writable or not configurable, an object or array that is +//! not extensible (after `Object.preventExtensions`, `Object.seal` or `Object.freeze`) and an +//! array with a read-only `length` throw a `TypeError` too. A value nested deeper, with more entries or longer text than the //! realm's [`crate::DataLimits`] allow throws a `RangeError`. Every value written takes fuel. use std::cell::{Cell, RefCell}; use std::rc::Rc; use super::{Builder, arg, method}; -use crate::heap::{Class, NativeFn, ObjId, Prop, key}; +use crate::heap::{CONFIGURABLE, Class, NativeFn, ObjId, Object, Prop, WRITABLE, key}; use crate::interp::{ErrorType, Interp, JsResult}; use crate::value::{Value, array_index, index_key, number_to_str}; use crate::{ScriptItem, bytecode::Code}; @@ -289,10 +293,14 @@ impl Source { Class::Ordinary => return Err(interp.type_error(NOT_PLAIN_OBJECT)), _ => None, }; + let fixed = shape.as_ref().and(fixed_state(o)); let Some(shape) = shape else { let what = format!("toSource: a {} cannot be written as source", interp.object(id)?.class.name()); return Err(interp.type_error(&what)); }; + if let Some(what) = fixed { + return Err(interp.type_error(what)); + } self.ancestors.push(id); let r = match shape { Err(length) => self.array(interp, id, length), @@ -347,6 +355,23 @@ const NOT_PLAIN_ARRAY: &str = "toSource: an array with properties besides its elements, a property that is not enumerable or another prototype cannot be written as source"; const NOT_PLAIN_OBJECT: &str = "toSource: an object with a property that is not enumerable, or whose prototype is not Object.prototype, cannot be written as source"; +const NOT_EXTENSIBLE: &str = "toSource: a non-extensible object cannot be written as source"; +const READ_ONLY_LENGTH: &str = "toSource: an array with a read-only length cannot be written as source"; +const FIXED_PROPERTY: &str = "toSource: a property that is not writable or configurable cannot be written as source"; + +/// Why the literal for the array or plain object `o` would not make it again: `o` is not +/// extensible, its `length` is read-only, or one of its data properties is not writable or not +/// configurable. A literal makes each of these open. +fn fixed_state(o: &Object) -> Option<&'static str> { + if !o.extensible { + return Some(NOT_EXTENSIBLE); + } + if matches!(o.class, Class::Array { length_writable: false, .. }) { + return Some(READ_ONLY_LENGTH); + } + let open = WRITABLE | CONFIGURABLE; + o.props.iter().any(|(_, p)| matches!(p, Prop::Data { flags, .. } if flags & open != open)).then_some(FIXED_PROPERTY) +} /// The getter behind `item`; [`ScriptItem::Global`] is a value and has none. pub(crate) fn getter(item: ScriptItem) -> Option<(&'static str, NativeFn)> { @@ -363,18 +388,33 @@ fn last_error(interp: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult JsResult { - let line = interp.script_frames().last().map_or(0, |(code, pc, _)| code.line_column(pc.saturating_sub(1)).0); + let line = interp.script_frames().last().map_or(0, |(code, pc, _)| place(interp.locator.as_ref(), code, pc).1); Ok(Value::Number(f64::from(line))) } +/// Where the instruction before `pc` in `code` came from: the file the realm's locator names +/// (`None` without one) and the line there, or the line in the compiled source without a locator. +fn place(locator: Option<&crate::realm::SourceLocator>, code: &Code, pc: usize) -> (Option, u32) { + let line = code.line_column(pc.saturating_sub(1)).0; + match locator { + Some(locate) => { + let (file, line) = locate(code.source.tag, line); + (Some(file), line) + } + None => (None, line), + } +} + /// The most frames `$.stack` lists, and the most characters of a function's name it shows. const STACK_FRAMES: usize = 64; const STACK_NAME_UNITS: usize = 64; -/// The script's frames, outermost first, one a line: the function's name and the line it is at. +/// The script's frames, outermost first, one a line: the function's name and the line it is at, +/// as `name:line`, or as `name@file:line` with the file the realm's locator names. fn stack(interp: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { let frames: Vec<(Rc, usize, bool)> = interp.script_frames().map(|(c, pc, f)| (c.clone(), pc, f)).collect(); let skip = frames.len().saturating_sub(STACK_FRAMES); + let locator = interp.locator.clone(); let mut text = String::new(); if skip > 0 { text.push_str("…\n"); @@ -382,8 +422,10 @@ fn stack(interp: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult for (code, pc, function) in frames.iter().skip(skip) { interp.use_fuel()?; let name = if *function { function_name(code) } else { "[global]".to_string() }; - let line = code.line_column(pc.saturating_sub(1)).0; - text.push_str(&format!("{name}:{line}\n")); + match place(locator.as_ref(), code, *pc) { + (Some(file), line) => text.push_str(&format!("{name}@{file}:{line}\n")), + (None, line) => text.push_str(&format!("{name}:{line}\n")), + } } let mut out = Builder::new(); out.push_str(interp, &text)?; diff --git a/crates/js/src/builtins/json.rs b/crates/js/src/builtins/json.rs index 4375303fe0..364ec99696 100644 --- a/crates/js/src/builtins/json.rs +++ b/crates/js/src/builtins/json.rs @@ -13,6 +13,7 @@ use std::collections::HashSet; use super::{Builder, ELEMENT_BYTES, arg, data, key_of, length_of, method, new_array, new_string, to_integer}; use crate::heap::{Class, Key, OBJECT_BYTES, OPEN, ObjId, Object, Prop, key, string_bytes}; use crate::interp::{Desc, ErrorType, Hint, Interp, JsResult}; +use crate::string_builtins::flat_charged; use crate::value::{Str, Value, number_to_str}; pub(super) fn install(interp: &mut Interp) -> JsResult<()> { @@ -473,7 +474,7 @@ fn settings(interp: &mut Interp, replacer: &Value, space: &Value) -> JsResult s.gap = t.flat().iter().take(10).copied().collect(), + Value::String(t) => s.gap = flat_charged(interp, &t)?.iter().take(10).copied().collect(), _ => {} } Ok(s) @@ -632,7 +633,10 @@ fn write_primitive(interp: &mut Interp, out: &mut Builder, v: &Value) -> JsResul Value::Bool(b) => out.push_str(interp, if *b { "true" } else { "false" }), Value::Number(n) if n.is_finite() => out.push_units(interp, &number_to_str(*n).flat()), Value::Number(_) => out.push_str(interp, "null"), - Value::String(s) => write_quoted(interp, out, &s.flat()), + Value::String(s) => interp.rooted(std::slice::from_ref(v), |i| { + let units = flat_charged(i, s)?; + write_quoted(i, out, &units) + }), Value::Undefined | Value::Object(_) => Ok(()), } } diff --git a/crates/js/src/bytecode.rs b/crates/js/src/bytecode.rs index 3092530d46..6992fd5606 100644 --- a/crates/js/src/bytecode.rs +++ b/crates/js/src/bytecode.rs @@ -160,8 +160,11 @@ pub(crate) enum Op { parts: u32, list: bool, }, - /// `name` → the value of the name on the nearest XML value in scope. + /// `name` → the value of the name on the nearest XML value in scope that holds it. XmlScopeGet, + /// `name` → `object name`: the nearest XML value in scope that holds the name, for an + /// assignment, update or `delete`. + XmlScopeRef, /// `object` → the filter's state. XmlFilterStart, /// `state` → `state item`, or jumps with `state` when the items are used up. @@ -170,8 +173,9 @@ pub(crate) enum Op { XmlFilterTest, /// `state` → the XMLList of the items kept. XmlFilterEnd, - /// `iterator name` → `iterator value`: the value under the name a `for each` got. - ForEachValue, + /// `iterator name x₁…xₙ` → `iterator name x₁…xₙ value`: the value under the name a `for each` + /// got, read after the `n` values its target pushed. + ForEachValue(u32), /// `value` → nothing: sets the default XML namespace of the running code. SetDefaultNamespace, } @@ -308,7 +312,8 @@ fn effect(op: Op, finally_tables: &[Vec]) -> Result { Op::XmlDescendants | Op::XmlFilterTest => e(2, 1), Op::XmlEscape(_) | Op::XmlScopeGet | Op::XmlFilterStart | Op::XmlFilterEnd => e(1, 1), Op::XmlLiteral { parts, .. } => e(parts, 1), - Op::ForEachValue => e(2, 2), + Op::XmlScopeRef => e(1, 2), + Op::ForEachValue(n) => e(n + 2, n + 3), Op::SetDefaultNamespace => e(1, 0), }) } diff --git a/crates/js/src/chars.rs b/crates/js/src/chars.rs index a7b2c1374c..61b9a7f318 100644 --- a/crates/js/src/chars.rs +++ b/crates/js/src/chars.rs @@ -4,7 +4,7 @@ use std::cmp::Ordering; -use unicode_general_category::{GeneralCategory as G, get_general_category}; +use unicode_properties::{GeneralCategory as G, UnicodeGeneralCategory}; /// A line terminator: LF, CR, U+2028 or U+2029 (section 7.3). pub fn is_line_terminator(c: u32) -> bool { @@ -20,7 +20,7 @@ pub fn is_whitespace(c: u32) -> bool { /// A character an identifier may start with: a Unicode `ID_Start` character, `$` or `_` /// (the Names and Keywords clause of current ECMA-262 editions). `ID_Start` is the letters (categories Lu, Ll, Lt, Lm, Lo and Nl) /// and `Other_ID_Start`, less `Pattern_Syntax` and `Pattern_White_Space` (Unicode Standard Annex -/// #31). The categories come from Unicode 16.0. `\u` escapes are decoded before this check. +/// #31). The categories come from Unicode 17.0. `\u` escapes are decoded before this check. pub fn is_id_start(c: u32) -> bool { match c { 0x24 | 0x5F => true, @@ -58,7 +58,7 @@ fn is_other_id_start(c: u32) -> bool { matches!(c, 0x1885 | 0x1886 | 0x2118 | 0x212E | 0x309B | 0x309C) } -/// `Other_ID_Continue` (Unicode PropList 16.0): characters kept in `ID_Continue` though their +/// `Other_ID_Continue` (Unicode PropList 17.0): characters kept in `ID_Continue` though their /// category is not a letter, mark, digit or connector. fn is_other_id_continue(c: u32) -> bool { matches!(c, 0xB7 | 0x387 | 0x1369..=0x1371 | 0x19DA | 0x200C | 0x200D | 0x30FB | 0xFF65) @@ -110,7 +110,7 @@ fn is_pattern_syntax(c: u32) -> bool { /// The Unicode general category of a code point; `None` for a lone surrogate. fn category(c: u32) -> Option { - char::from_u32(c).map(get_general_category) + char::from_u32(c).map(char::general_category) } /// The value of a hexadecimal digit. diff --git a/crates/js/src/compiler.rs b/crates/js/src/compiler.rs index 071e99a60e..3023e3b127 100644 --- a/crates/js/src/compiler.rs +++ b/crates/js/src/compiler.rs @@ -497,16 +497,21 @@ impl<'a> FnCompiler<'a> { let brk = self.new_label(); self.bind(head); self.jump(Op::ForInNext, brk); - if each { - self.emit(Op::ForEachValue); - } match target { ForInTarget::Var(d) => { let n = self.var_name(&d.name.name); + if each { + self.emit(Op::ForEachValue(0)); + } self.emit(Op::SetVar(n)); } + ForInTarget::Expr(e) if each => self.store_value_to(*e)?, ForInTarget::Expr(e) => self.store_key_to(*e)?, } + if each { + // The value; the name under it goes next. + self.emit(Op::Pop); + } self.emit(Op::Pop); self.loop_body(body, labels, brk, head)?; self.jump(Op::Jump, head); @@ -538,6 +543,11 @@ impl<'a> FnCompiler<'a> { self.emit(Op::Rot3); self.emit(Op::SetIndex); } + Some(Expr::XmlScopeName(name)) => { + self.xml_scope_ref(target, *name)?; + self.emit(Op::Rot3); + self.emit(Op::SetIndex); + } _ => { self.expr(target)?; self.emit(Op::Pop); @@ -547,6 +557,46 @@ impl<'a> FnCompiler<'a> { Ok(()) } + /// Assigns the value under the name on top of the stack to a `for each` target expression, + /// leaving the name and then the value on top. The target is evaluated before the value is + /// read (ECMA-357 section 12.3). + fn store_value_to(&mut self, target: ExprId) -> CResult<()> { + let target = self.ast.unparenthesized(target); + self.at(self.ast.expr_span(target).start); + match self.ast.expr(target) { + Some(Expr::Ident(name)) => { + let n = self.var_name(name); + self.emit(Op::ForEachValue(0)); + self.emit(Op::SetVar(n)); + } + Some(Expr::Member { object, property }) => { + self.expr(*object)?; + self.emit(Op::ForEachValue(1)); + let n = self.name_key(key_of(&property.name)); + self.emit(Op::SetMember(n)); + } + Some(Expr::Index { object, index }) => { + self.expr(*object)?; + self.expr(*index)?; + self.emit(Op::ToKey); + self.emit(Op::ForEachValue(2)); + self.emit(Op::SetIndex); + } + Some(Expr::XmlScopeName(name)) => { + self.xml_scope_ref(target, *name)?; + self.emit(Op::ForEachValue(2)); + self.emit(Op::SetIndex); + } + _ => { + self.expr(target)?; + self.emit(Op::Pop); + self.emit(Op::ForEachValue(0)); + self.throw_invalid_target(); + } + } + Ok(()) + } + fn throw_invalid_target(&mut self) { let s = self.string(&"invalid assignment target".encode_utf16().collect::>()); let depth = self.depth; @@ -854,6 +904,15 @@ impl<'a> FnCompiler<'a> { Ok(()) } + /// Pushes the nearest XML value in scope that holds the E4X name `name` of the expression + /// `id`, then the name, as an assignment, update or `delete` uses them. + fn xml_scope_ref(&mut self, id: ExprId, name: ExprId) -> CResult<()> { + self.expr(name)?; + self.at(self.ast.expr_span(id).start); + self.emit(Op::XmlScopeRef); + Ok(()) + } + fn xml_literal(&mut self, parts: &[XmlPart], list: bool) -> CResult<()> { for part in parts { match part { @@ -1096,6 +1155,10 @@ impl<'a> FnCompiler<'a> { self.expr(*index)?; self.emit(Op::DeleteIndex); } + Some(Expr::XmlScopeName(name)) => { + self.xml_scope_ref(arg, *name)?; + self.emit(Op::DeleteIndex); + } _ => { self.expr(arg)?; self.emit(Op::Pop); @@ -1202,6 +1265,13 @@ impl<'a> FnCompiler<'a> { self.emit(Op::GetIndex); } } + Some(Expr::XmlScopeName(name)) => { + self.xml_scope_ref(target, *name)?; + if op.is_some() { + self.emit(Op::Dup2); + self.emit(Op::GetIndex); + } + } _ => { self.expr(target)?; if op.is_none() { @@ -1222,7 +1292,7 @@ impl<'a> FnCompiler<'a> { let n = self.name_key(key_of(&property.name)); self.emit(Op::SetMember(n)); } - Some(Expr::Index { .. }) => self.emit(Op::SetIndex), + Some(Expr::Index { .. } | Expr::XmlScopeName(_)) => self.emit(Op::SetIndex), _ => self.throw_invalid_target(), } Ok(()) @@ -1246,6 +1316,10 @@ impl<'a> FnCompiler<'a> { self.expr(*index)?; self.emit(Op::IncIndex { prefix, dec }); } + Some(Expr::XmlScopeName(name)) => { + self.xml_scope_ref(target, *name)?; + self.emit(Op::IncIndex { prefix, dec }); + } _ => { self.expr(target)?; self.emit(Op::ToNumber); diff --git a/crates/js/src/extension_tests.rs b/crates/js/src/extension_tests.rs index 19a20ab5b8..4807856bf5 100644 --- a/crates/js/src/extension_tests.rs +++ b/crates/js/src/extension_tests.rs @@ -126,6 +126,45 @@ fn to_source_refuses_what_is_not_plain_data() { assert!(thrown(&mut r, "toSource({get g() { throw 'ran'; }})").starts_with("TypeError"), "the getter does not run"); } +#[test] +fn to_source_refuses_flags_and_extensibility_a_literal_does_not_make() { + let mut r = realm(); + let property = "TypeError: toSource: a property that is not writable or configurable cannot be written as source"; + let extensible = "TypeError: toSource: a non-extensible object cannot be written as source"; + let length = "TypeError: toSource: an array with a read-only length cannot be written as source"; + for (source, want) in [ + ("var o = {}; Object.defineProperty(o, 'a', {value: 1, enumerable: true, configurable: true}); toSource(o)", property), + ("var o = {}; Object.defineProperty(o, 'a', {value: 1, enumerable: true, writable: true}); toSource(o)", property), + ("var a = [1, 2]; Object.defineProperty(a, '1', {writable: false}); toSource(a)", property), + ("var a = [1, 2]; Object.defineProperty(a, '0', {configurable: false}); a.toSource()", property), + ("var o = {}; Object.defineProperty(o, 'a', {value: 1, enumerable: true}); toSource({x: [{b: o}]})", property), + ("toSource(Object.preventExtensions({}))", extensible), + ("toSource(Object.preventExtensions([]))", extensible), + ("toSource(Object.seal({a: 1}))", extensible), + ("toSource(Object.freeze({a: 1}))", extensible), + ("toSource(Object.seal([1]))", extensible), + ("toSource(Object.freeze([1]))", extensible), + ("toSource([1, {b: Object.freeze({})}])", extensible), + ("var a = []; Object.defineProperty(a, 'length', {writable: false}); toSource(a)", length), + ("var a = [1, , 3]; Object.defineProperty(a, 'length', {writable: false}); toSource({a: a})", length), + ] { + assert_eq!(thrown(&mut r, source), want, "{source}"); + } + // The refused states are ones the literal would lose: evaluated, it is open again. + let lost = "var o = Object.freeze({a: 1}); var w = eval('({\"a\":1})'); + [Object.isExtensible(o), Object.isExtensible(w), Object.getOwnPropertyDescriptor(w, 'a').writable].join()"; + assert_eq!(text(&mut r, lost), "false,true,true"); +} + +#[test] +fn to_source_writes_properties_defined_with_every_flag_on() { + let mut r = realm(); + let source = "var o = {}; Object.defineProperty(o, 'a', {value: 1, writable: true, enumerable: true, configurable: true}); + var a = [0]; Object.defineProperty(a, '0', {value: 2, writable: true, enumerable: true, configurable: true}); + toSource({o: o, a: a, e: {}, f: [], s: [1, , 3]})"; + assert_eq!(text(&mut r, source), r#"({"o":({"a":1}), "a":[2], "e":({}), "f":[], "s":[1, , 3]})"#); +} + #[test] fn to_source_of_a_string_with_many_escapes_throws_a_range_error_before_the_heap_limit() { let mut r = realm(); @@ -180,6 +219,32 @@ fn script_items_read_the_global_object_the_last_error_the_line_and_the_stack() { assert!(thrown(&mut r, "'use strict'; h.line = 1").starts_with("TypeError"), "the items cannot be assigned"); } +#[test] +fn the_line_and_the_stack_give_the_place_the_source_locator_maps_each_frame_to() { + let mut r = realm(); + let items = [("line", ScriptItem::Line), ("stack", ScriptItem::Stack)].into_iter().map(|(n, i)| (n.to_string(), HostItem::Script(i))).collect(); + r.define_host_object("h", items).unwrap(); + let asked: Rc>> = Rc::default(); + let seen = asked.clone(); + r.set_source_locator(Rc::new(move |tag, line| { + seen.borrow_mut().push((tag, line)); + let file = if tag == UNKNOWN_SOURCE { "[eval]".to_string() } else { format!("f{tag}") }; + (file, line + 100) + })); + let source = "function inner() {\n return h.stack;\n}\n\ninner()"; + let stack = text(&mut r, source); + let tag = r.script_tag(); + assert_eq!(stack, format!("[global]@f{tag}:105\ninner@f{tag}:102\n")); + assert_eq!(*asked.borrow(), [(tag, 5), (tag, 2)], "each frame's tag and its line in the compiled source"); + assert_eq!(r.run("\n\n h.line").unwrap(), JsValue::Number(103.0)); + let tag = r.script_tag(); + let stack = text(&mut r, "\neval('\\n\\nh.stack')"); + assert_eq!(stack, format!("[global]@f{}:102\n[global]@[eval]:103\n", tag + 1), "code eval compiles has no tag of its own"); + let deep = "function d(n) { return n ? d(n - 1) : h.stack; } var s = d(100).split('\\n'); s.length + ',' + s[0] + ',' + s[1]"; + let tag = r.script_tag() + 1; + assert_eq!(text(&mut r, deep), format!("66,…,d@f{tag}:101"), "the frames past 64 are still left out"); +} + #[test] fn a_host_property_reads_its_getter_and_gives_assignments_to_its_setter() { let mut r = Realm::new(); diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index cc22f1834d..cabf7c84aa 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -31,6 +31,8 @@ pub(crate) struct Classes { folder_proto: ObjId, host: ObjId, current: Value, + /// The count of [`reset_current`] calls: a file is open only in the run that opened it. + run: f64, } impl Classes { @@ -43,6 +45,7 @@ impl Classes { const PATH: &str = "__vcPath"; const ERROR: &str = "__vcError"; const HANDLE: &str = "__vcHandle"; +const RUN: &str = "__vcRun"; const ENCODING: &str = "__vcEncoding"; const LINE_FEED: &str = "__vcLineFeed"; @@ -67,8 +70,13 @@ fn message(i: &mut Interp, name: &str) -> JsResult { i.get_value(&text, &key(name)) } +/// The field `name` of a record the host gave: its own data property, `undefined` when it has none, +/// so that a property a script put on `Object.prototype` is not read as part of it. fn field(i: &mut Interp, v: &Value, name: &str) -> JsResult { - i.get_value(v, &key(name)) + match v.as_object() { + Some(o) => slot(i, o, name), + None => Ok(Value::Undefined), + } } /// The value of the own data property `name` of `o`, `undefined` when it has none. @@ -132,12 +140,13 @@ fn parsed(i: &mut Interp, this: &Value, what: &str, name: &str) -> JsResult JsResult { let line_feed = host_value(i, "lineFeed")?; i.rooted(&[fs.clone(), line_feed.clone()], |i| { - i.reserve_heap(OBJECT_BYTES + 5 * PROP_BYTES)?; + i.reserve_heap(OBJECT_BYTES + 6 * PROP_BYTES)?; let o = i.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))); i.rooted(&[Value::Object(o)], |i| { set_slot(i, o, PATH, fs.clone())?; set_slot(i, o, ERROR, Value::str(""))?; set_slot(i, o, HANDLE, Value::Number(-1.0))?; + set_slot(i, o, RUN, Value::Number(-1.0))?; set_slot(i, o, ENCODING, Value::str(""))?; set_slot(i, o, LINE_FEED, line_feed.clone())?; Ok(Value::Object(o)) @@ -189,8 +198,7 @@ fn text_result(i: &mut Interp, o: ObjId, r: Value, failed: Value) -> JsResult JsResult> { - let h = slot(i, o, HANDLE)?; - if matches!(h, Value::Number(n) if n >= 0.0) { + if let Some(h) = is_open(i, o)? { return Ok(Some(h)); } let m = message(i, "notOpen")?; @@ -198,9 +206,11 @@ fn opened(i: &mut Interp, o: ObjId) -> JsResult> { Ok(None) } +/// The id of the object's open file, when this run opened it. fn is_open(i: &Interp, o: ObjId) -> JsResult> { let h = slot(i, o, HANDLE)?; - Ok(matches!(h, Value::Number(n) if n >= 0.0).then_some(h)) + let this_run = matches!(slot(i, o, RUN)?, Value::Number(n) if n == classes(i)?.run); + Ok((this_run && matches!(h, Value::Number(n) if n >= 0.0)).then_some(h)) } /// Closes the object's open file, if it has one. @@ -305,8 +315,19 @@ fn parent(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult instance(i, proto, up) } +/// `exists`: whether the path names something of the object's own kind, a folder for a `Folder` +/// and anything else for a `File`. fn exists(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { - Ok(Value::Bool(stat_field(i, &this, "exists", "exists", Value::Bool(false))?.truthy())) + let folder = classes(i)?.folder_proto; + let want_dir = match this.as_object() { + Some(o) => i.object(o)?.proto == Some(folder), + None => false, + }; + let Some(r) = stat(i, &this, "exists")? else { return Ok(Value::Bool(false)) }; + i.rooted(std::slice::from_ref(&r), |i| { + let dir = field(i, &r, "dir")?.truthy(); + Ok(Value::Bool(field(i, &r, "exists")?.truthy() && dir == want_dir)) + }) } fn created(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { @@ -528,6 +549,8 @@ fn open(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult return Ok(Value::Bool(false)); } set_slot(i, o, HANDLE, id)?; + let run = classes(i)?.run; + set_slot(i, o, RUN, Value::Number(run))?; Ok(Value::Bool(true)) } @@ -600,7 +623,7 @@ fn get_files(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult JsResult<()> { Ok(()) } +/// Sets `Folder.current` back to the host's `current`, when the realm has `File` and `Folder`, and +/// begins a new run, in which the files earlier runs opened are not open. +pub(crate) fn reset_current(i: &mut Interp) -> JsResult<()> { + let Some(c) = i.files.as_mut() else { return Ok(()) }; + c.run += 1.0; + let start = host(i, "current", &[])?; + if let Some(c) = i.files.as_mut() { + c.current = start; + } + Ok(()) +} + /// Adds `File` and `Folder` to the global object, their work done by the host functions in /// `items` ([`crate::Realm::define_file_classes`]). pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResult<()> { @@ -768,7 +803,7 @@ pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResul i.reserve_heap(2 * OBJECT_BYTES)?; let file_proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); let folder_proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); - i.files = Some(Classes { file_proto, folder_proto, host: host_obj, current: Value::str("") }); + i.files = Some(Classes { file_proto, folder_proto, host: host_obj, current: Value::str(""), run: 0.0 }); let start = host(i, "current", &[])?; if let Some(c) = i.files.as_mut() { c.current = start; diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index 4e0ef7e789..fb980843e8 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -74,6 +74,21 @@ pub enum HostError { /// A function the host gives a script, with its arguments converted. pub type HostFunction = Rc) -> Result>; +/// The place in the script's code that reads a [`HostItem::SiteGetter`] property: the source tag +/// of that code, as [`crate::Realm::error_tag`] gives one, and the line and column there, counted +/// from 1. A function an earlier script defined keeps its script's tag; code that `eval` or +/// `Function` compiled has [`crate::UNKNOWN_SOURCE`]. A read with none of the script's code +/// running has [`crate::UNKNOWN_SOURCE`] and line and column 0. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct CallSite { + pub source: u32, + pub line: u32, + pub column: u32, +} + +/// A getter the host gives a script that is told where the code reading it is. +pub type SiteFunction = Rc Result>; + /// How one argument of a [`HostItem::Converted`] function is read. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Arg { @@ -85,15 +100,19 @@ pub enum Arg { Bool, } -/// How the arguments of a host function are read. +/// How the arguments of a host function are read, and its result given. #[derive(Clone)] pub(crate) enum ArgRead { /// Each as [`Data`]. Data, + /// Each as [`Data`], with the result given frozen, as [`HostItem::Value`] gives its value. + Frozen, /// Each as the string `String(value)` gives. Text, /// One by one as the list says; those past its end are not read. Each(Rc<[Arg]>), + /// None: the function is given the [`CallSite`] of the code that calls it, as three numbers. + Site, } /// A member of an object the host adds to the global environment. @@ -109,6 +128,12 @@ pub enum HostItem { Converted(Vec, HostFunction), /// A property whose value the function gives each time it is read. Getter(HostFunction), + /// A property whose value the function gives each time it is read, frozen as + /// [`HostItem::Value`] gives its value. + FrozenGetter(HostFunction), + /// A property whose value the function gives each time it is read, given the [`CallSite`] of + /// the code that reads it. + SiteGetter(SiteFunction), /// A property whose value `get` gives each time it is read, and that `set` is given each value /// assigned to it, as its one argument; an error from `set` is thrown to the script. Property { @@ -352,14 +377,17 @@ impl Interp { /// Calls host function `f`: reads its arguments as `how` says, runs it, and gives its result to /// the script. pub(crate) fn call_data(&mut self, f: &crate::heap::DataFn, name: &Rc, args: &[Value], how: &ArgRead) -> JsResult { - let data = self.read_args(name, args, how)?; + let data = match how { + ArgRead::Site => site_data(self.call_site()), + _ => self.read_args(name, args, how)?, + }; // Only the script's own code, in a run that can pause, can wait for a result. let can_wait = self.in_slice && self.reentry == 0; self.can_wait.set(can_wait); let result = f(data); self.can_wait.set(false); match result { - Ok(d) => self.write_data(d, 0, false), + Ok(d) => self.write_data(d, 0, matches!(how, ArgRead::Frozen)), Err(HostError::Wait) if can_wait => { self.waiting = true; self.pause.set(true); @@ -370,6 +398,18 @@ impl Interp { } } + /// Where the innermost frame of the script's code is: its source's tag and the line and column + /// of the instruction it is running. + fn call_site(&self) -> CallSite { + match self.script_frames().last() { + Some((code, pc, _)) => { + let (line, column) = code.line_column(pc.saturating_sub(1)); + CallSite { source: code.source.tag, line, column } + } + None => CallSite { source: crate::UNKNOWN_SOURCE, line: 0, column: 0 }, + } + } + /// Calls evaluator `f` ([`HostItem::Evaluator`]): reads its arguments, runs it, and runs the /// source it gives as global code, as an indirect `eval` does, giving that code's completion /// value. A result that is not a string is given to the script as it is. `end` is called once @@ -390,13 +430,31 @@ impl Interp { Err(e) => return Err(self.host_error(e)?), }; let writes = strict_writes().unwrap_or_else(|| self.writes_mode()); - self.evaluated = self.evaluated.saturating_add(1); + self.evaluated = crate::realm::next_tag(self.evaluated); let tag = std::mem::replace(&mut self.source_tag, self.evaluated); - let code = self.encode_source(&source).and_then(|units| self.compile_source_writes(&units, false, writes, crate::bytecode::CodeKind::Eval)); + // UTF-8 takes at most 3 bytes for each UTF-16 code unit, so the fuel for a third of the + // bytes is taken before the source is encoded, and the rest after. A source within the + // source limit must fit in the heap whole before it is encoded; a longer one is refused as + // a syntax error when it is encoded. + let floor = source.len().div_ceil(3); + let fits = |interp: &mut Self| { + let units = source.encode_utf16().count(); + if interp.check_source_units(units).is_ok() { interp.reserve_heap(string_bytes(units)) } else { Ok(()) } + }; + let code = self.prepare_source(floor).and_then(|()| fits(self)).map(|()| { + let units = self.encode_source(&source); + let rest = match &units { + Ok(units) => self.prepare_source(units.len().saturating_sub(floor)), + Err(_) => Ok(()), + }; + rest.map(|()| units.and_then(|units| self.compile_source_writes(&units, false, writes, crate::bytecode::CodeKind::Eval))) + }); + let code = code.and_then(|c| c); self.source_tag = tag; let r = match code { - Ok(code) => self.run_global(code, true), - Err(e) => Err(self.compile_error_to_abrupt(e)), + Ok(Ok(code)) => self.run_global(code, true), + Ok(Err(e)) => Err(self.compile_error_to_abrupt(e)), + Err(limit) => Err(limit), }; end(); r @@ -412,14 +470,14 @@ impl Interp { let mut data = Vec::with_capacity(args.len()); // A conversion can run the script's own `toString`, which may collect garbage. let mark = self.temp_roots.len(); - if !matches!(how, ArgRead::Data) { + if !matches!(how, ArgRead::Data | ArgRead::Frozen) { self.temp_roots.extend(args.iter().cloned()); } let mut read = Ok(()); for (i, a) in args.iter().enumerate() { reading.path.push(Step::Index(u32::try_from(i).unwrap_or(u32::MAX))); let d = match how { - ArgRead::Data => self.read_data(a, &mut reading), + ArgRead::Data | ArgRead::Frozen | ArgRead::Site => self.read_data(a, &mut reading), ArgRead::Text => self.read_text(a, &mut reading), ArgRead::Each(list) => match list.get(i) { Some(Arg::TextOrUndefined) if matches!(a, Value::Undefined) => Ok(Data::Undefined), @@ -507,6 +565,11 @@ impl Interp { let prop = match item { HostItem::Value(d) => Prop::Data { value: self.write_data(d, 0, true)?, flags: ENUMERABLE }, HostItem::Getter(f) => Prop::Accessor { get: Some(self.host_function(f, &full, ArgRead::Data)), set: None, flags: ENUMERABLE }, + HostItem::FrozenGetter(f) => Prop::Accessor { get: Some(self.host_function(f, &full, ArgRead::Frozen)), set: None, flags: ENUMERABLE }, + HostItem::SiteGetter(f) => { + let get: HostFunction = Rc::new(move |data| f(read_site(&data))); + Prop::Accessor { get: Some(self.host_function(get, &full, ArgRead::Site)), set: None, flags: ENUMERABLE } + } HostItem::Property { get, set } => Prop::Accessor { get: Some(self.host_function(get, &full, ArgRead::Data)), set: Some(self.host_function(set, &full, ArgRead::Data)), @@ -553,3 +616,18 @@ enum Slot { Index(usize), Name(String), } + +/// `site` as the three numbers [`ArgRead::Site`] gives its function. +fn site_data(site: CallSite) -> Vec { + vec![Data::Number(f64::from(site.source)), Data::Number(f64::from(site.line)), Data::Number(f64::from(site.column))] +} + +/// The [`CallSite`] that [`site_data`] gave as `data`. +fn read_site(data: &[Data]) -> CallSite { + let at = |i: usize, missing: u32| match data.get(i) { + // Each number is a `u32` that `site_data` gave, so the conversion is exact. + Some(Data::Number(n)) => *n as u32, + _ => missing, + }; + CallSite { source: at(0, crate::UNKNOWN_SOURCE), line: at(1, 0), column: at(2, 0) } +} diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index c699ea285e..700efddfb2 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -58,6 +58,42 @@ fn state_survives_a_pause_and_a_collection_between_slices() { assert_eq!(finish(&mut r, 50).0.unwrap(), JsValue::Number(1500.0)); } +/// A paused run that is ended leaves no frames behind: the realm starts the next run with its +/// globals, as many times as it is ended. +#[test] +fn an_ended_run_leaves_the_realm_ready_for_the_next() { + let mut r = realm(u64::MAX); + for _ in 0..3 { + r.start("var kept = 'yes'; function deep(n) { return n ? deep(n - 1) : (function () { while (true) {} })(); } deep(50);").unwrap(); + assert_eq!(r.advance(500).unwrap(), Progress::Paused); + r.end(); + assert!(!r.is_running()); + } + assert!(r.interp().frames.is_empty() && r.interp().stack.is_empty()); + r.start("kept").unwrap(); + assert_eq!(finish(&mut r, 1_000).0.unwrap(), JsValue::String("yes".into())); + r.end(); +} + +/// Setting `Folder.current` back for the next run drops what only the last run's uncaught +/// exception held, so a full heap from that exception does not stop the next run. +#[test] +fn resetting_folder_current_drops_the_last_uncaught_exception() { + let mut r = realm(10_000_000); + let len = Rc::new(Cell::new(4)); + let n = len.clone(); + let current: HostFunction = Rc::new(move |_| Ok(Data::String("d".repeat(n.get())))); + r.define_file_classes(vec![("current".into(), HostItem::Function(current))]).unwrap(); + assert!(r.run("throw (function () { var a = []; for (var i = 0; i < 2000; i++) a.push('item ' + i); return a; })();").is_err()); + let interp = r.interp(); + interp.collect_garbage(); + interp.limits.heap_bytes = interp.heap.bytes; + len.set(200); + assert_eq!(r.reset_folder_current(), Ok(())); + r.set_limits(Limits::default()); + assert_eq!(r.run("typeof Folder"), Ok(JsValue::String("function".into()))); +} + #[test] fn the_fuel_limit_covers_every_slice_together() { let mut r = realm(5_000); @@ -223,6 +259,53 @@ fn a_getter_is_read_each_time() { assert_eq!(r.run("host.n + host.n").unwrap(), JsValue::Number(3.0)); } +/// A frozen getter gives a new value each time it is read, frozen to its leaves. +#[test] +fn a_frozen_getter_gives_a_frozen_value_each_time() { + let mut r = realm(1_000_000); + let f: HostFunction = Rc::new(|_| Ok(Data::Object(vec![("a".into(), Data::Array(vec![Data::Number(1.0)]))]))); + let g = f.clone(); + r.define_host_object("host", vec![("v".into(), HostItem::FrozenGetter(f)), ("open".into(), HostItem::Getter(g))]).unwrap(); + let source = "var v = host.v; v.b = 2; try { v.a.push(2); } catch (e) {} \ + [Object.isFrozen(v), Object.isFrozen(v.a), v.b === undefined, v.a.length, host.v === host.v, Object.isFrozen(host.open)].join()"; + assert_eq!(r.run(source).unwrap(), JsValue::String("true,true,true,1,false,false".into())); +} + +/// A site getter is told the source tag, line and column of the code that reads it: a function an +/// earlier script or an evaluator's source defined keeps that source's tag, and code that `eval` +/// compiled has none. +#[test] +fn a_site_getter_is_told_where_the_code_that_reads_it_is() { + let mut r = realm(10_000_000); + let seen: Rc>> = Rc::default(); + let log = seen.clone(); + let site: SiteFunction = Rc::new(move |s| { + log.borrow_mut().push(s); + Ok(Data::Number(f64::from(s.line))) + }); + let source: HostFunction = Rc::new(|_| Ok(Data::String("\n\nfunction inEval() { return host.site; }".into()))); + let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) }; + r.define_host_object("host", vec![("site".into(), HostItem::SiteGetter(site)), ("load".into(), load)]).unwrap(); + r.run("function early() {\n return host.site;\n}\nhost.load();").unwrap(); + let first = r.script_tag(); + assert_eq!(r.run("\n\n\n\nhost.site + early() + inEval() + eval('host.site')").unwrap(), JsValue::Number(5.0 + 2.0 + 3.0 + 1.0)); + let second = r.script_tag(); + let sites = seen.borrow().clone(); + assert_eq!( + sites, + vec![ + CallSite { source: second, line: 5, column: 1 }, + CallSite { source: first, line: 2, column: 11 }, + CallSite { source: first + 1, line: 3, column: 28 }, + CallSite { source: UNKNOWN_SOURCE, line: 1, column: 1 }, + ] + ); + seen.borrow_mut().clear(); + // A getter a built-in calls is at the place of the code that called the built-in. + assert_eq!(r.run("\nObject.getOwnPropertyDescriptor(host, 'site').get.call(host)").unwrap(), JsValue::Number(2.0)); + assert_eq!(seen.borrow().first().map(|s| s.source), Some(r.script_tag())); +} + #[test] fn a_text_function_takes_each_argument_as_string_gives_it() { let mut r = realm(1_000_000); @@ -388,6 +471,104 @@ fn a_marked_host_error_that_passes_through_a_finally_block_says_where_it_was_rai assert_eq!(r.error_mark(), Some(7)); } +/// A realm with a 1 MiB heap, the size that the `finally` blocks of these tests collect garbage in. +fn small_heap_realm() -> Realm { + let mut r = Realm::new(); + r.set_limits(Limits { fuel: 200_000_000, heap_bytes: 1 << 20, ..Limits::default() }); + r +} + +/// Begins a run of `source` and advances it one instruction at a time until a `finally` block runs +/// for an exception whose throw site is saved. +fn start_until_a_throw_site_is_saved(r: &mut Realm, source: &str) { + r.start(source).unwrap(); + while r.interp().finally_sites.is_empty() { + assert_eq!(r.advance(1), Ok(Progress::Paused), "{source}"); + } +} + +/// The collections that a `finally` block's allocations cause under a small heap limit keep the +/// site its exception was raised at, and the run's end leaves no saved site behind. +#[test] +fn an_error_that_passes_through_a_finally_block_that_collects_garbage_says_where_it_was_raised() { + let mut r = small_heap_realm(); + let source = "try {\n throw new Error('original');\n} finally {\n for (var i = 0; i < 20000; i++) { var waste = [i, i + 1, i + 2]; }\n}"; + start_until_a_throw_site_is_saved(&mut r, source); + r.collect_garbage(); + let collections = r.interp().heap.collections; + let e = loop { + match r.advance(1_000) { + Ok(Progress::Paused) => assert_eq!(r.interp().finally_sites.len(), 1, "the site stays saved while the block runs"), + Ok(Progress::Done(v)) => panic!("the run ended with {v:?}"), + Err(e) => break e, + } + }; + assert!(r.interp().heap.collections > collections, "the block's allocations collect garbage"); + assert_eq!((e.kind, e.line, e.column, e.message.as_str()), (RunErrorKind::Thrown, 2, 3, "Error: original")); + assert!(r.interp().finally_sites.is_empty()); +} + +/// The code of a saved throw site stays live through a collection: direct `eval` code that +/// threw is not part of the code of any frame still running. +#[test] +fn a_saved_throw_site_keeps_its_code_live() { + let mut r = small_heap_realm(); + let source = "try {\n eval(\"var unused = 'padding padding padding padding';\\nthrow new Error('original');\");\n} finally {\n for (var i = 0; i < 2000; i++) { var waste = [i]; }\n}"; + start_until_a_throw_site_is_saved(&mut r, source); + let with_site = r.collect_garbage(); + let sites = std::mem::take(&mut r.interp().finally_sites); + let without_site = r.collect_garbage(); + r.interp().finally_sites = sites; + assert_eq!(r.collect_garbage(), with_site, "the saved site's code is counted again"); + assert!(with_site > without_site, "{with_site} <= {without_site}"); + let e = finish(&mut r, 1_000).0.unwrap_err(); + assert_eq!((e.kind, e.line, e.message.as_str()), (RunErrorKind::Thrown, 2, "Error: original")); + assert!(r.interp().finally_sites.is_empty()); +} + +/// A run that a host function stops inside a `finally` block leaves no saved throw site behind. +#[test] +fn a_run_stopped_in_a_finally_block_leaves_no_saved_throw_site() { + let mut r = realm(1_000_000); + let f: HostFunction = Rc::new(|_| Err(HostError::Abort("stopped".into()))); + r.define_host_object("host", vec![("abort".into(), HostItem::Function(f))]).unwrap(); + let e = r.run("try { throw new Error('original'); } finally { host.abort(); }").unwrap_err(); + assert_eq!((e.kind, e.message.as_str()), (RunErrorKind::Limit(LimitKind::Host), "stopped")); + assert!(r.interp().finally_sites.is_empty()); + assert_eq!(r.run("1").unwrap(), JsValue::Number(1.0)); + assert!(r.interp().finally_sites.is_empty()); +} + +/// A `finally` block that `break`, `continue` or `return` leaves drops the saved site of the +/// exception it ran for as it leaves, before the stack grows back over that site's slot. +#[test] +fn leaving_a_finally_block_early_drops_its_saved_throw_site() { + let mut r = realm(1_000_000); + let marked = Rc::new(Cell::new(false)); + let seen = marked.clone(); + let f: HostFunction = Rc::new(move |_| { + seen.set(true); + Ok(Data::Undefined) + }); + r.define_host_object("host", vec![("mark".into(), HostItem::Function(f))]).unwrap(); + for source in [ + "do { try { throw new Error('x'); } finally { break; } } while (false);\nhost.mark(); var a = [1, 2, 3];", + "for (var i = 0; i < 1; i++) { try { throw new Error('x'); } finally { continue; } }\nhost.mark(); var a = [1, 2, 3];", + "function f() { try { throw new Error('x'); } finally { return 1; } }\nf(); host.mark(); var a = [f, f, f];", + ] { + marked.set(false); + let mut saved = false; + r.start(source).unwrap(); + while r.advance(1).unwrap() == Progress::Paused { + saved |= !r.interp().finally_sites.is_empty(); + if marked.get() { + assert!(r.interp().finally_sites.is_empty(), "{source}"); + } + } + assert!(saved && marked.get(), "{source}"); + } +} + #[test] fn advancing_without_a_run_is_an_error() { let mut r = realm(1_000); @@ -473,6 +654,95 @@ fn a_converted_function_reads_each_argument_as_its_list_says() { assert_eq!(out, JsValue::String("function 1".into()), "a script may replace the function"); } +#[test] +fn error_sources_count_from_the_last_script_and_code_from_an_earlier_one_is_unknown() { + let mut r = realm(10_000_000); + let source: HostFunction = Rc::new(|_| Ok(Data::String("\nthrow new Error('in eval')".into()))); + let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) }; + r.define_host_object("host", vec![("load".into(), load)]).unwrap(); + r.run("function late() { throw new Error('late'); }").unwrap(); + assert!(r.run("host.load()").is_err()); + assert_eq!(r.error_source(), 1, "the first source the evaluator gave in this run"); + assert!(r.run("\nlate()").is_err()); + assert_eq!(r.error_source(), UNKNOWN_SOURCE, "an earlier script defined late"); + assert!(r.run("\nthrow 1").is_err()); + assert_eq!(r.error_source(), 0); + assert!(r.run("host.load()").is_err()); + assert_eq!(r.error_source(), 1, "counted again from this run's script"); + assert!(r.run("var = 1").is_err()); + assert_eq!(r.error_source(), 0, "a syntax error is in the script"); +} + +#[test] +fn error_tags_stay_the_same_from_run_to_run_and_are_never_shared() { + let mut r = realm(10_000_000); + let source: HostFunction = Rc::new(|_| Ok(Data::String("function inEval() { throw new Error('in eval'); }".into()))); + let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) }; + r.define_host_object("host", vec![("load".into(), load)]).unwrap(); + assert_eq!(r.script_tag(), UNKNOWN_SOURCE, "no script yet"); + r.run("function late() { throw new Error('late'); }\nhost.load(); host.load();").unwrap(); + let first = r.script_tag(); + assert_ne!(first, UNKNOWN_SOURCE); + assert!(r.run("\nlate()").is_err()); + let second = r.script_tag(); + assert!(second > first + 2, "the evaluator's two sources took the tags after the first script"); + assert_eq!((r.error_source(), r.error_tag()), (UNKNOWN_SOURCE, first), "late keeps its script's tag"); + assert!(r.run("inEval()").is_err()); + assert_eq!(r.error_tag(), first + 2, "the second source the evaluator gave in the first run"); + assert!(r.run("\nthrow 1").is_err()); + assert_eq!((r.error_source(), r.error_tag()), (0, r.script_tag())); + // Once the tags are used up, a source gets no tag rather than one an earlier source has. + r.set_last_tag(UNKNOWN_SOURCE - 3); + r.run("function nearEnd() { throw 1; }\nhost.load(); host.load(); host.load();").unwrap(); + assert_eq!(r.script_tag(), UNKNOWN_SOURCE - 2); + assert!(r.run("nearEnd()").is_err()); + assert_eq!(r.script_tag(), UNKNOWN_SOURCE, "a script after the last tag"); + assert_eq!(r.error_tag(), UNKNOWN_SOURCE - 2); + assert!(r.run("inEval()").is_err()); + assert_eq!(r.error_tag(), UNKNOWN_SOURCE, "the third source came after the last tag"); + assert!(r.run("\nthrow 1").is_err()); + assert_eq!((r.error_source(), r.error_tag()), (UNKNOWN_SOURCE, UNKNOWN_SOURCE)); +} + +#[test] +fn an_evaluators_source_takes_fuel_before_it_is_parsed() { + // The evaluator gives 131,072 spaces and a number: far more code units than the fuel left. + let ends = Rc::new(Cell::new(0)); + let ended = ends.clone(); + let source: HostFunction = Rc::new(|_| Ok(Data::String(format!("{}7", " ".repeat(1 << 17))))); + let item = HostItem::Evaluator { source, end: Rc::new(move || ended.set(ended.get() + 1)), strict_writes: Rc::new(|| None) }; + let mut r = realm(10_000); + r.define_host_object("host", vec![("evaluate".into(), item)]).unwrap(); + let e = r.run("host.evaluate()").unwrap_err(); + assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Fuel)); + assert_eq!(ends.get(), 1, "the evaluator's end runs once"); + // This fuel covers a third of the source's bytes but not all of its code units. + r.set_limits(Limits { fuel: 60_000, ..Limits::default() }); + assert_eq!(r.run("host.evaluate()").unwrap_err().kind, RunErrorKind::Limit(LimitKind::Fuel)); + assert_eq!(ends.get(), 2); + r.set_limits(Limits { fuel: 1_000_000, ..Limits::default() }); + assert_eq!(r.run("host.evaluate()"), Ok(JsValue::Number(7.0))); + assert_eq!(ends.get(), 3); +} + +#[test] +fn an_evaluators_whole_source_must_fit_in_the_heap_before_it_is_parsed() { + // A third of the source and the other two thirds each fit in the heap; the whole does not. + // The source does not parse, so a parse would throw a syntax error instead. + let n = (1 << 17) + 1; + let source: HostFunction = Rc::new(move |_| Ok(Data::String(format!("{}(", " ".repeat(n - 1))))); + let item = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) }; + let mut r = realm(1_000_000); + r.define_host_object("host", vec![("evaluate".into(), item)]).unwrap(); + r.interp().collect_for_room(); + let heap_bytes = r.interp().heap.bytes + crate::heap::string_bytes(n * 5 / 6); + r.set_limits(Limits { fuel: 1_000_000, heap_bytes, ..Limits::default() }); + assert_eq!(r.run("host.evaluate()").unwrap_err().kind, RunErrorKind::Limit(LimitKind::Heap)); + // With room for the whole source, it is parsed. + r.set_limits(Limits { fuel: 1_000_000, ..Limits::default() }); + assert_eq!(r.run("host.evaluate()").unwrap_err().kind, RunErrorKind::Thrown); +} + proptest::proptest! { /// A slice size does not change what a script computes. #[test] diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 458d68f40c..edc5282fe5 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -9,7 +9,8 @@ //! Before each instruction the interpreter takes one unit of fuel, checks the interrupt flag and, //! when the heap has grown past its threshold, collects garbage. Running out of fuel, the heap //! limit, the frame limit, the re-entry limit and the interrupt flag each end the run with an -//! [`Abrupt::Limit`] that unwinds every frame without running catch or finally blocks. +//! [`Abrupt::Limit`] that unwinds every frame without running catch or finally blocks. Source +//! compiled during a run takes a unit of fuel for each code unit before it is parsed. //! //! Collection runs only between instructions. An operation that may run JavaScript in the middle //! keeps its operands on the operand stack until it is done, so everything it holds is reachable @@ -26,6 +27,7 @@ use crate::heap::{ ArgMap, Binding, CONFIGURABLE, Class, ENUMERABLE, ENV_BYTES, Env, EnvId, ForIn, Func, HIDDEN, Heap, Key, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, PropMap, ROPE_BYTES, Roots, WRITABLE, code_bytes, key, string_bytes, }; +use crate::string_builtins::flat_charged; use crate::value::{Str, Value, array_index, index_key, number_to_str, string_to_number, to_int32, to_uint32}; use crate::{LimitKind, Limits, Options}; @@ -204,6 +206,12 @@ pub(crate) struct Interp { pub(crate) date_host: crate::date_builtins::DateHost, /// The bytes native code holds outside the heap's cells through [`HeldBytes`]. pub(crate) held: Rc, + /// Bytes of the copies [`Self::get_own_property`] made flattening the rope of a String + /// object, which the heap's total adds before the next limit check. + flattened: std::cell::Cell, + /// Fuel for the units those copies took and the rope nodes it read in place, which the next + /// step takes. + pub(crate) flattened_fuel: std::cell::Cell, /// The global code's default XML namespace URI (ECMA-357 section 12.1). pub(crate) xml_default_uri: Key, /// Set by the host to end the current slice of a resumable run at the next safe point. @@ -224,6 +232,8 @@ pub(crate) struct Interp { pub(crate) evaluated: u32, /// The tag of the source the last run's error was raised in. pub(crate) error_tag: u32, + /// Where `$.line` and `$.stack` find the file and line of a compiled line. + pub(crate) locator: Option, /// The mark of the host error ([`crate::HostError::Marked`]) whose exception or limit is /// propagating. pub(crate) thrown_mark: Option, @@ -235,9 +245,9 @@ pub(crate) struct Interp { /// Where the exceptions `finally` blocks are running for were raised, innermost last, each with /// the stack slot that holds the exception while the block runs. The block's end throws the /// exception on from that site. An entry whose slot is at or above the stack's length belongs to - /// a block that was left, and [`Self::drop_left_finally_sites`] removes it. [`Self::unwind`] - /// removes the entries at or above a handler's slot before it adds one, so the slots rise and - /// the list is never longer than the stack. + /// a block that was left, and [`Self::drop_left_finally_sites`] removes it at each `Jump`, each + /// return and each collection. [`Self::unwind`] removes the entries at or above a handler's slot + /// before it adds one, so the slots rise and the list is never longer than the stack. pub(crate) finally_sites: Vec<(ThrowSite, usize)>, /// The mark of the host error the last run ended with. pub(crate) error_mark: Option, @@ -300,6 +310,12 @@ pub(crate) const MAX_APPLY_ARGS: usize = 1 << 16; /// The estimated bytes of a name's entries in the list and the set `for-in` builds. const KEY_ENTRY_BYTES: usize = 32; +#[cfg(test)] +thread_local! { + /// Tests: the [`Interp::finally_sites`] entries that leaving a block or a frame has looked at. + pub(crate) static SITE_CHECKS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// The estimated bytes of the index names `0` to `len - 1` while `for-in` lists them. fn index_keys_bytes(len: usize) -> usize { let mut total = 0usize; @@ -443,6 +459,8 @@ impl Interp { files: None, date_host: crate::date_builtins::DateHost::default(), held: Rc::default(), + flattened: std::cell::Cell::new(0), + flattened_fuel: std::cell::Cell::new(0), xml_default_uri: Rc::from(Vec::new()), pause: Rc::default(), in_slice: false, @@ -453,6 +471,7 @@ impl Interp { source_tag: crate::realm::UNKNOWN_SOURCE, evaluated: 0, error_tag: crate::realm::UNKNOWN_SOURCE, + locator: None, thrown_mark: None, finally_marks: Vec::new(), finally_sites: Vec::new(), @@ -562,6 +581,7 @@ impl Interp { fn tick(&mut self) -> JsResult<()> { self.use_fuel()?; + crate::regexp_vm::use_fuel_n(self, self.flattened_fuel.replace(0))?; self.settle_held(); if self.heap.bytes > self.gc_threshold { self.collect_garbage(); @@ -588,10 +608,12 @@ impl Interp { Ok(()) } - /// Takes the bytes that dropped [`HeldBytes`] released off the heap's total. + /// Takes the bytes that dropped [`HeldBytes`] released off the heap's total, and adds the + /// bytes of the ropes [`Self::get_own_property`] flattened. fn settle_held(&mut self) { let released = self.held.released.replace(0); - self.heap.bytes = self.heap.bytes.saturating_sub(released); + let flattened = self.flattened.replace(0); + self.heap.bytes = self.heap.bytes.saturating_sub(released).saturating_add(flattened); } /// Collects garbage now and sets when the next collection runs. @@ -611,6 +633,22 @@ impl Interp { Ok(()) } + /// Prepares for parsing `units` code units of source at run time: takes a unit of fuel for + /// each code unit and checks that the source text fits in the heap, before any of it is + /// flattened, parsed or compiled. Running out of fuel uses up what was left. + pub(crate) fn prepare_source(&mut self, units: usize) -> JsResult<()> { + let fuel = u64::try_from(units).unwrap_or(u64::MAX); + if fuel > self.fuel { + self.fuel = 0; + return Err(Abrupt::Limit(LimitKind::Fuel)); + } + self.fuel -= fuel; + if self.interrupt.load(Ordering::Relaxed) { + return Err(Abrupt::Limit(LimitKind::Interrupted)); + } + self.reserve_heap(string_bytes(units)) + } + /// Removes the [`Self::finally_marks`] entries of `finally` blocks that `break`, `continue` or /// `return` left: those whose stack slot no longer holds their exception. fn drop_left_finally_marks(&mut self) { @@ -619,9 +657,16 @@ impl Interp { } /// Removes the [`Self::finally_sites`] entries whose stack slot is at or above `len`: those of - /// `finally` blocks that were left. + /// `finally` blocks that were left. The slots rise along the list, so only its end is looked at. fn drop_left_finally_sites(&mut self, len: usize) { - self.finally_sites.retain(|&(_, slot)| slot < len); + while let Some(&(_, slot)) = self.finally_sites.last() { + #[cfg(test)] + SITE_CHECKS.with(|c| c.set(c.get() + 1)); + if slot < len { + break; + } + self.finally_sites.pop(); + } } pub(crate) fn collect_garbage(&mut self) { @@ -650,6 +695,7 @@ impl Interp { self.heap.collect(&roots); // The collection counts the live total again, so bytes already released are not in it. self.held.released.set(0); + self.flattened.set(0); self.heap.bytes = self.heap.bytes.saturating_add(self.held_bytes).saturating_add(self.held.now.get()); } @@ -784,6 +830,8 @@ impl Interp { fn return_value(&mut self, v: Value) -> JsResult> { let Some(frame) = self.frames.pop() else { return internal("return without a frame") }; self.stack.truncate(frame.base); + // A `return` in a finally block leaves the block, and the value takes its exception's slot. + self.drop_left_finally_sites(frame.base); let v = match frame.construct { Some(o) if !matches!(v, Value::Object(_)) => Value::Object(o), _ => v, @@ -870,7 +918,11 @@ impl Interp { Op::New(n) => self.op_new(n), Op::Binary(b) => self.op_binary(b), Op::Neg | Op::Plus | Op::BitNot | Op::Not | Op::Typeof | Op::ToNumber => self.op_unary(op), - Op::Jump(t) => self.jump_to(t), + Op::Jump(t) => { + // `break` and `continue` leave a `finally` block by popping its exception and jumping. + self.drop_left_finally_sites(self.stack.len()); + self.jump_to(t) + } Op::JumpIfFalse(t) | Op::JumpIfTrue(t) => self.op_branch(t, matches!(op, Op::JumpIfTrue(_)), false), Op::JumpIfFalseKeep(t) | Op::JumpIfTrueKeep(t) => self.op_branch(t, matches!(op, Op::JumpIfTrueKeep(_)), true), Op::Throw => { @@ -907,11 +959,12 @@ impl Interp { Op::XmlEscape(kind) => self.op_xml_escape(kind), Op::XmlLiteral { parts, list } => self.op_xml_literal(parts, list), Op::XmlScopeGet => self.op_xml_scope_get(), + Op::XmlScopeRef => self.op_xml_scope_ref(), Op::XmlFilterStart => self.op_xml_filter_start(), Op::XmlFilterNext(t) => self.op_xml_filter_next(t), Op::XmlFilterTest => self.op_xml_filter_test(), Op::XmlFilterEnd => self.op_xml_filter_end(), - Op::ForEachValue => self.op_for_each_value(), + Op::ForEachValue(n) => self.op_for_each_value(n as usize), Op::SetDefaultNamespace => self.op_set_default_namespace(), Op::Return | Op::ReturnCompletion => internal("return reached the dispatcher"), } @@ -1198,7 +1251,33 @@ impl Interp { if let Some(i) = array_index(k) && (i as usize) < s.len() { - let unit = s.flat().get(i as usize).copied().unwrap_or(0); + let unit = if s.is_rope() { + let owed = self.flattened_fuel.get(); + let flattened = self.flattened.get().saturating_add(string_bytes(s.len())); + if self.heap.bytes.saturating_add(flattened) > self.limits.heap_bytes { + // The copy does not fit without a collection, which needs `&mut self`: + // the unit is read along the rope instead, a unit of fuel per node. + let Some((unit, visited)) = s.unit_at(i as usize, self.fuel.saturating_sub(owed)) else { + return Err(Abrupt::Limit(LimitKind::Fuel)); + }; + self.flattened_fuel.set(owed.saturating_add(visited)); + unit + } else { + // Flattening copies the units. The run ends here when the fuel for + // the copy is not left; otherwise the next step takes it, and the + // next limit check adds the copy's bytes. + let fuel = owed.saturating_add((s.len() / crate::string_builtins::UNITS_PER_FUEL) as u64 + 1); + if fuel > self.fuel { + return Err(Abrupt::Limit(LimitKind::Fuel)); + } + self.flattened_fuel.set(fuel); + self.flattened.set(flattened); + s.flat().get(i as usize).copied() + } + } else { + s.flat().get(i as usize).copied() + } + .unwrap_or(0); return Ok(Some(Prop::Data { value: Value::String(Str::from_units(vec![unit])), flags: ENUMERABLE })); } } @@ -1275,7 +1354,7 @@ impl Interp { if let Some(i) = array_index(k) && (i as usize) < s.len() { - let unit = s.flat().get(i as usize).copied().unwrap_or(0); + let unit = flat_charged(self, s)?.get(i as usize).copied().unwrap_or(0); return Ok(Value::String(Str::from_units(vec![unit]))); } } @@ -2382,7 +2461,8 @@ impl Interp { }; let strict = self.strict(); self.check_source_units(s.len()).map_err(|e| self.compile_error_to_abrupt(e))?; - let units = s.flat(); + self.prepare_source(s.len())?; + let units = self.flat_reserved(s)?; let code = self.compile_source(&units, strict, CodeKind::Eval).map_err(|e| self.compile_error_to_abrupt(e))?; self.charge_code(&code, declaration_bytes(&code).saturating_add(ENV_BYTES))?; let frame = self.frame()?; @@ -2547,7 +2627,7 @@ impl Interp { Value::Null => 0.0, Value::Bool(b) => f64::from(u8::from(*b)), Value::Number(n) => *n, - Value::String(s) => string_to_number(&s.flat()), + Value::String(s) => string_to_number(&flat_charged(self, s)?), Value::Object(_) => { let p = self.to_primitive(v, Hint::Number)?; return self.to_number(&p); @@ -2581,19 +2661,28 @@ impl Interp { #[allow(clippy::wrong_self_convention)] pub(crate) fn to_key(&mut self, v: &Value) -> JsResult { match v { - Value::String(s) => { - let rope = s.is_rope(); - let flat = s.flat(); - if rope { - self.heap.bytes += string_bytes(flat.len()); - } - Ok(flat) - } + Value::String(s) => self.flat_reserved(s), Value::Number(n) if *n >= 0.0 && *n < 4_294_967_295.0 && n.fract() == 0.0 => Ok(index_key(*n as u32)), - _ => Ok(self.to_str(v)?.flat()), + _ => { + let s = self.to_str(v)?; + self.flat_reserved(&s) + } } } + /// The code units of `s`. Flattening a rope makes a copy of its units, so for a rope that + /// copy's bytes are reserved and added to the heap first, without taking fuel. The rope stays + /// rooted while the copy is reserved; everything else the caller still needs must be + /// reachable from the roots. + fn flat_reserved(&mut self, s: &Str) -> JsResult { + if s.is_rope() { + let bytes = string_bytes(s.len()); + self.rooted(&[Value::String(s.clone())], |i| i.reserve_heap(bytes))?; + self.heap.bytes = self.heap.bytes.saturating_add(bytes); + } + Ok(s.flat()) + } + /// ToObject (section 9.9). #[allow(clippy::wrong_self_convention)] pub(crate) fn to_object(&mut self, v: &Value) -> JsResult { @@ -2716,7 +2805,11 @@ impl Interp { (self.to_primitive(x, Hint::Number)?, py) }; if let (Value::String(a), Value::String(b)) = (&px, &py) { - return Ok(Some(*a.flat() < *b.flat())); + // Both stay rooted, so the first copy is still counted while the second is made. + return self.rooted(&[px.clone(), py.clone()], |i| { + let (a, b) = (flat_charged(i, a)?, flat_charged(i, b)?); + Ok(Some(*a < *b)) + }); } let nx = self.to_number(&px)?; let ny = self.to_number(&py)?; @@ -2741,7 +2834,9 @@ impl Interp { | (Value::String(_), Value::String(_)) | (Value::Bool(_), Value::Bool(_)) | (Value::Object(_), Value::Object(_)) => return Ok(strict_eq(&x, &y)), - (Value::Number(n), Value::String(s)) | (Value::String(s), Value::Number(n)) => return Ok(*n == string_to_number(&s.flat())), + (Value::Number(n), Value::String(s)) | (Value::String(s), Value::Number(n)) => { + return Ok(*n == string_to_number(&flat_charged(self, s)?)); + } (Value::Bool(v), _) => x = Value::Number(f64::from(u8::from(*v))), (_, Value::Bool(v)) => y = Value::Number(f64::from(u8::from(*v))), (Value::Number(_) | Value::String(_), Value::Object(_)) => y = self.to_primitive(&y, Hint::Default)?, diff --git a/crates/js/src/interp_tests.rs b/crates/js/src/interp_tests.rs index d2a12b5fb0..93c487b378 100644 --- a/crates/js/src/interp_tests.rs +++ b/crates/js/src/interp_tests.rs @@ -3,7 +3,7 @@ use std::rc::Rc; use proptest::prelude::*; use crate::bytecode::{Code, Handler, Op, Source, verify}; -use crate::{JsValue, LimitKind, Limits, Options, Realm, RunError, RunErrorKind}; +use crate::{JsValue, LimitKind, Limits, Options, Progress, Realm, RunError, RunErrorKind}; fn run(src: &str) -> JsValue { match Realm::new().run(src) { @@ -357,6 +357,58 @@ fn function_source_text_counts_toward_the_heap() { assert_eq!(realm.run("(function f(a) { return a; }).toString()"), Ok(JsValue::String("function f(a) { return a; }".into()))); } +#[test] +fn a_function_that_returns_from_a_finally_block_does_not_keep_its_code() { + // The function's source holds a 256 Ki-unit comment. Its result stays on the stack while the + // second call runs, after the function was dropped. A collection then leaves its code out of + // the live total, as it does for a function whose finally block ran without an exception. + let live = |body: &str| { + let mut r = small(Limits::default()); + let src = format!( + "var s = 'x'; for (var i = 0; i < 18; i++) s += s;\n\ + var f = Function('/*' + s + '*/ try {{ {body} }} finally {{ return 0; }}'); s = null;\n\ + f() + (f = null, (function () {{ var a = 0; for (var i = 0; i < 50; i++) a += i; return a; }})())" + ); + if let Err(e) = r.start(&src) { + panic!("{e:?}"); + } + let mut bytes = None; + loop { + match r.advance(1) { + Ok(Progress::Paused) => { + let i = r.interp(); + if i.frames.len() == 2 && i.stack.len() > 1 { + i.collect_garbage(); + bytes = Some(i.heap.bytes); + } + } + Ok(Progress::Done(v)) => { + assert_eq!(v, JsValue::Number(1225.0)); + break; + } + Err(e) => panic!("{e:?}"), + } + } + let Some(bytes) = bytes else { panic!("the second call never paused") }; + bytes + }; + let (plain, thrown) = (live(""), live("throw 1;")); + assert!(thrown < plain + 4096, "{thrown} > {plain}"); +} + +#[test] +fn a_return_looks_only_at_the_finally_sites_of_its_own_frame() { + // 200 finally blocks run at once, each for its own exception, and the innermost calls a + // function 1,000 times. Each return looks at the last saved site only, not at all 200. + let src = "function g() { return 1; }\n\ + function f(n) { try { throw n; } finally { if (n) { f(n - 1); } else { for (var i = 0; i < 1000; i++) g(); } } }\n\ + try { f(199); } catch (e) { e; }"; + crate::interp::SITE_CHECKS.with(|c| c.set(0)); + assert_eq!(small(Limits::default()).run(src), Ok(JsValue::Number(0.0))); + let checks = crate::interp::SITE_CHECKS.with(std::cell::Cell::get); + assert!(checks < 10_000, "{checks} saved sites looked at"); +} + #[test] fn for_in_names_take_fuel_and_heap_under_later_limits() { // The first run, under the default limits, builds an object with many properties. Later runs @@ -448,6 +500,19 @@ fn declarations_take_fuel() { assert_eq!(limit(&mut realm, &format!("Function('var {vars};')();")), LimitKind::Fuel); } +#[test] +fn source_compiled_during_a_run_takes_fuel_before_it_is_parsed() { + // Doubling a string 17 times makes 131,072 spaces in about a hundred instructions, so only + // the compiled source can use up the fuel. + let build = "var s = ' '; for (var i = 0; i < 17; i++) s += s;"; + let mut realm = small(Limits { fuel: 10_000, ..Limits::default() }); + for call in ["eval(s)", "(0, eval)(s)", "Function(s)", "new Function('a', s)"] { + assert_eq!(limit(&mut realm, &format!("{build} {call};")), LimitKind::Fuel, "{call}"); + } + let mut realm = small(Limits { fuel: 1_000_000, ..Limits::default() }); + assert_eq!(realm.run(&format!("{build} eval(s + '1') + (0, eval)(s + '2') + Function(s + 'return 3')()")), Ok(JsValue::Number(6.0))); +} + #[test] fn a_lower_heap_limit_applies_to_what_is_already_live() { // A heap already past the new limit ends the next run. @@ -771,13 +836,14 @@ fn long_property_names_count_toward_the_heap_after_their_strings_are_collected() // Each name is a 16,385-unit buffer that only the object's key or the function's binding // holds once the string that made it is garbage, so about 32 of them fill the heap well before // the fuel runs out. In the second script the property lookup flattens a long string each - // time, so collections run. + // time, so collections run. Each eval there also takes fuel for its source, so that run has + // more fuel. let mut realm = small(Limits { heap_bytes: 1 << 20, fuel: 20_000, ..Limits::default() }); let src = "var s = 'x'; while (s.length < 10000) s += s; var o = {}; for (var i = 0; ; i++) o[s + i] = 1;"; assert_eq!(limit(&mut realm, src), LimitKind::Heap); let src = "var s = 'x'; while (s.length < 10000) s += s; \ (function () { for (var i = 0; ; i++) { eval('var ' + s + i + ' = 1'); ({})[s + i]; } })();"; - let mut realm = small(Limits { heap_bytes: 1 << 20, fuel: 20_000, ..Limits::default() }); + let mut realm = small(Limits { heap_bytes: 1 << 20, fuel: 5_000_000, ..Limits::default() }); assert_eq!(limit(&mut realm, src), LimitKind::Heap); } diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 7df9953a67..1561d71dfe 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -41,9 +41,11 @@ //! With [`Options::e4x`], the parser also reads E4X (ECMA-357, second edition, December 2005): //! XML and XMLList literals, the `.@`, `..`, `::` and `.( )` operators, `for each … in` and //! `default xml namespace`; the realm then provides `XML`, `XMLList`, `Namespace`, `QName`, -//! `isXMLName` and `setDefaultXMLNamespace`. Without the option, the language and the built-ins are +//! `isXMLName` and `setDefaultXMLNamespace`, and XML and XMLList values have an `xpath` method that +//! evaluates an XPath 1.0 expression. Without the option, the language and the built-ins are //! those of ECMAScript 5.1 above. XML trees live in the heap, and parsing, copying, comparing and -//! serializing them use no native recursion and take fuel for each node. +//! serializing them, and evaluating XPath on them, use no native recursion and take fuel for each +//! node. #![forbid(unsafe_code)] pub mod ast; @@ -70,6 +72,7 @@ mod token; mod value; mod xml; mod xml_builtins; +mod xpath; pub use ast::{ AssignOp, Ast, BinaryOp, CatchClause, Expr, ExprId, ForInTarget, ForInit, Function, FunctionId, FunctionKind, LogicalOp, Name, Program, Property, @@ -77,10 +80,10 @@ pub use ast::{ }; pub use builtins::extensions::Localization; pub use error::{SyntaxError, TOO_DEEP, TOO_LONG}; -pub use host::{Arg, Data, DataLimits, HostError, HostFunction, HostItem, ScriptItem}; +pub use host::{Arg, CallSite, Data, DataLimits, HostError, HostFunction, HostItem, ScriptItem, SiteFunction}; pub use lexer::{Goal, Lexer}; pub use number::to_string as number_to_string; -pub use realm::{Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, RunError, RunErrorKind, UNKNOWN_SOURCE}; +pub use realm::{Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, RunError, RunErrorKind, SourceLocator, UNKNOWN_SOURCE}; pub use token::{Directive, DirectiveName, Keyword, Punct, Span, Token, TokenKind}; /// How a script is read. diff --git a/crates/js/src/parser.rs b/crates/js/src/parser.rs index 3c2ab3ed30..fa201c58ff 100644 --- a/crates/js/src/parser.rs +++ b/crates/js/src/parser.rs @@ -873,8 +873,9 @@ impl<'s> Parser<'s> { } /// An assignment's, `++`'s, `--`'s or `for-in`'s target: an identifier (in strict code - /// neither `eval` nor `arguments`), a property, or outside strict mode code a call (assigning - /// to its result fails at run time, as ECMA-262 2015 Annex B and web browsers have it). + /// neither `eval` nor `arguments`), a property, an E4X name standing alone (`@a`, `ns::a`; + /// ECMA-357 section 11.1), or outside strict mode code a call (assigning to its result fails + /// at run time, as ECMA-262 2015 Annex B and web browsers have it). fn check_target(&self, expr: ExprId, message: &str) -> Result<()> { let inner = self.ast.unparenthesized(expr); match self.ast.expr(inner) { @@ -884,7 +885,7 @@ impl<'s> Parser<'s> { } Ok(()) } - Some(Expr::Member { .. } | Expr::Index { .. }) => Ok(()), + Some(Expr::Member { .. } | Expr::Index { .. } | Expr::XmlScopeName(_)) => Ok(()), Some(Expr::Call { .. }) if !self.ctx.strict => Ok(()), _ => Err(self.error_at_offset(self.ast.expr_span(expr).start, message)), } diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 255f5b4551..4146ae891b 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -14,7 +14,8 @@ use crate::{Options, SyntaxError}; /// cannot catch it, and their `finally` blocks do not run. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Limits { - /// Instructions a run may execute. + /// Instructions a run may execute. Source that `eval`, `Function` or a host evaluator + /// compiles during the run also takes one unit for each UTF-16 code unit, before it is parsed. pub fuel: u64, /// Estimated bytes the heap (objects, environments and the strings they hold) may reach /// after a collection. A string longer than a quarter of this many code units cannot be @@ -62,6 +63,16 @@ pub enum LimitKind { /// evaluator's: code that `eval` or `Function` compiled, or an error with no place. pub const UNKNOWN_SOURCE: u32 = u32::MAX; +/// The file and line that line `line` of the source with tag `tag` ([`Realm::error_tag`]) came +/// from, as `$.line` and `$.stack` give them ([`Realm::set_source_locator`]). +pub type SourceLocator = std::rc::Rc (String, u32)>; + +/// The source tag after `tag`. Once the tags are used up, every later source gets +/// [`UNKNOWN_SOURCE`], so no two sources share a tag. +pub(crate) fn next_tag(tag: u32) -> u32 { + if tag >= UNKNOWN_SOURCE - 1 { UNKNOWN_SOURCE } else { tag + 1 } +} + /// The fuel [`Realm::advance`] lets a slice spend, past the slice it was asked for, in a nested run /// it cannot pause. pub const MAX_UNBROKEN_FUEL: u64 = 200_000_000; @@ -148,6 +159,12 @@ impl From for RunError { pub struct Realm { interp: Interp, unbroken_fuel: u64, + /// The source tag of the script the last [`Realm::run`] or [`Realm::start`] compiled. Each + /// script gets a new one, and the sources an evaluator gives during its run get the ones after + /// it, so code that an earlier script defined keeps a tag of its own. [`UNKNOWN_SOURCE`] + /// before the first script, for a script the realm did not compile, and once the tags are used + /// up. + script_tag: u32, } impl Default for Realm { @@ -165,7 +182,7 @@ impl Realm { /// `options`; [`Options::max_source_units`] caps the source parsed in one run, all of it /// counted together. pub fn with_options(options: Options, limits: Limits) -> Self { - Self { interp: Interp::new(options, limits), unbroken_fuel: MAX_UNBROKEN_FUEL } + Self { interp: Interp::new(options, limits), unbroken_fuel: MAX_UNBROKEN_FUEL, script_tag: UNKNOWN_SOURCE } } /// Sets the fuel [`Realm::advance`] lets a nested run spend past its slice (by default @@ -221,11 +238,13 @@ impl Realm { /// Compiles `source` and readies the realm for a run. fn compile(&mut self, source: &str) -> Result, RunError> { + self.script_tag = UNKNOWN_SOURCE; let interp = &mut self.interp; if let Some(message) = &interp.install_error { return Err(RunError { kind: RunErrorKind::Internal, message: message.clone(), line: 0, column: 0 }); } interp.fuel = interp.limits.fuel; + interp.flattened_fuel.set(0); interp.source_units = 0; interp.throw_site = None; interp.last_thrown = Value::Undefined; @@ -238,13 +257,15 @@ impl Realm { interp.finally_sites.clear(); interp.error_mark = None; let strict = interp.options.strict; - interp.source_tag = 0; + interp.evaluated = next_tag(interp.evaluated); + self.script_tag = interp.evaluated; + interp.source_tag = self.script_tag; let code = interp.encode_source(source).and_then(|units| interp.compile_source(&units, strict, CodeKind::Global)); interp.source_tag = UNKNOWN_SOURCE; match code { Ok(code) => Ok(code), Err(CompileError::Syntax(e)) => { - interp.error_tag = 0; + interp.error_tag = self.script_tag; Err(e.into()) } Err(CompileError::Internal(m)) => Err(RunError { kind: RunErrorKind::Internal, message: m, line: 0, column: 0 }), @@ -327,6 +348,15 @@ impl Realm { !self.interp.frames.is_empty() } + /// Ends a run begun with [`Realm::start`] where it is, paused or waiting for a host function's + /// result, as an interrupt would: its stacks are emptied, so the realm can start another run. + /// The globals the run set stay. + pub fn end(&mut self) { + if self.is_running() || self.interp.waiting { + let _ = self.outcome(Err(Abrupt::Limit(LimitKind::Interrupted))); + } + } + /// The flag a host function sets to end the current slice at the next point it can pause. pub fn pause_flag(&self) -> std::rc::Rc> { self.interp.pause.clone() @@ -369,13 +399,46 @@ impl Realm { self.interp.interrupt = interrupt.0.clone(); } - /// Which source the last error's `line` and `column` are in: 0 for the script given to + /// Has `$.line` give the line `locate` maps the running line to, and `$.stack` give each + /// frame's line that way, after the file `locate` names: `function@file:line`. Without a + /// locator they give the line of the compiled source, and `$.stack` names no file. + pub fn set_source_locator(&mut self, locate: SourceLocator) { + self.interp.locator = Some(locate); + } + + /// Which source the last error's `line` and `column` are in: 0 for the script last given to /// [`Realm::run`] or [`Realm::start`], `n` for the `n`th source a - /// [`crate::HostItem::Evaluator`] gave in this realm, and [`UNKNOWN_SOURCE`] otherwise. + /// [`crate::HostItem::Evaluator`] gave since then, and [`UNKNOWN_SOURCE`] otherwise, which + /// includes code from an earlier script and from the sources given during its run. pub fn error_source(&self) -> u32 { + match self.interp.error_tag { + UNKNOWN_SOURCE => UNKNOWN_SOURCE, + tag => tag.checked_sub(self.script_tag).unwrap_or(UNKNOWN_SOURCE), + } + } + + /// The source tag of the code the last error's `line` and `column` are in, which stays the same + /// from run to run: each script given to [`Realm::run`] or [`Realm::start`] and each source a + /// [`crate::HostItem::Evaluator`] gives gets the next tag, so a function an earlier script + /// defined has its script's tag. [`UNKNOWN_SOURCE`] for code that `eval` or `Function` + /// compiled, an error with no place, and sources given once the tags are used up. + pub fn error_tag(&self) -> u32 { self.interp.error_tag } + /// The source tag ([`Realm::error_tag`]) of the script the last [`Realm::run`] or + /// [`Realm::start`] compiled; the `n`th source an evaluator gave during that run has this tag + /// plus `n`. [`UNKNOWN_SOURCE`] when that call compiled nothing. + pub fn script_tag(&self) -> u32 { + self.script_tag + } + + /// Tests: makes `tag` the last source tag given out. + #[cfg(test)] + pub(crate) fn set_last_tag(&mut self, tag: u32) { + self.interp.evaluated = tag; + } + /// The mark of the host error ([`crate::HostError::Marked`]) the last run ended with, when no /// `catch` clause took that error's exception on its way out; `None` otherwise. pub fn error_mark(&self) -> Option { @@ -416,6 +479,20 @@ impl Realm { } } + /// Sets `Folder.current` back to the host's `current`, for the next run of a realm that has + /// `File` and `Folder` ([`Realm::define_file_classes`]); a realm without them keeps its + /// `Folder.current`. The files an earlier run opened are no longer open. The last run's uncaught + /// exception and `$.error` are dropped first, as [`Realm::start`] drops them, so memory that only + /// they held is free for the reset. + pub fn reset_folder_current(&mut self) -> Result<(), RunError> { + self.interp.last_thrown = Value::Undefined; + self.interp.last_error = Value::Null; + match crate::file_classes::reset_current(&mut self.interp) { + Ok(()) => Ok(()), + Err(e) => self.outcome(Err(e)).map(drop), + } + } + /// Adds the script extensions: the global `localize(object, ...values)`, which gives a /// localization object's text for the locale of [`Realm::localization`], the global /// `toSource(value)` and `Object.prototype.toSource()`, which write plain data as source text, diff --git a/crates/js/src/string_builtins.rs b/crates/js/src/string_builtins.rs index b3758bdf54..eed08f96bd 100644 --- a/crates/js/src/string_builtins.rs +++ b/crates/js/src/string_builtins.rs @@ -98,7 +98,7 @@ fn check_string_room(interp: &mut Interp, len: usize) -> JsResult<()> { /// Pushes `item` onto `list`, first holding the bytes of the list's new capacity when it must /// grow. -fn push_held(interp: &mut Interp, held: &mut HeldBytes, list: &mut Vec, item: T) -> JsResult<()> { +pub(crate) fn push_held(interp: &mut Interp, held: &mut HeldBytes, list: &mut Vec, item: T) -> JsResult<()> { if list.len() == list.capacity() { let more = list.capacity().max(4); held.add(interp, more.saturating_mul(size_of::()))?; @@ -109,10 +109,11 @@ fn push_held(interp: &mut Interp, held: &mut HeldBytes, list: &mut Vec, it } /// The code units of `s`. Flattening a rope makes a copy of its units, so for a rope that copy's -/// bytes are reserved and added to the heap, and its units charged as fuel, first. +/// bytes are reserved and added to the heap, and its units charged as fuel, first. The rope stays +/// rooted while the copy is reserved, so what it holds is still counted. pub(crate) fn flat_charged(interp: &mut Interp, s: &Str) -> JsResult> { if s.is_rope() { - reserve_units(interp, s.len())?; + interp.rooted(&[Value::String(s.clone())], |interp| reserve_units(interp, s.len()))?; } Ok(s.flat()) } @@ -179,7 +180,7 @@ fn clamp(n: f64, len: usize) -> usize { /// The first index at `from` or after where `needle` occurs in `hay`. Every position tried takes /// fuel. -fn find(interp: &mut Interp, hay: &[u16], needle: &[u16], from: usize) -> JsResult> { +pub(crate) fn find(interp: &mut Interp, hay: &[u16], needle: &[u16], from: usize) -> JsResult> { if needle.len() > hay.len() { return Ok(None); } diff --git a/crates/js/src/tests.rs b/crates/js/src/tests.rs index 8c24b5d0bb..d2d4537439 100644 --- a/crates/js/src/tests.rs +++ b/crates/js/src/tests.rs @@ -424,6 +424,27 @@ fn identifiers_take_the_other_id_start_and_continue_characters() { } } +#[test] +fn identifiers_take_the_characters_unicode_17_assigned() { + // U+088F (a letter, Lo) starts a name; U+1ACF (a combining mark, Mn) may follow the first + // character but cannot start a name. Unicode 17.0 assigned both. + for (src, name) in [ + ("var \u{88F} = 1;", "\u{88F}"), + ("var \\u088F = 1;", "\u{88F}"), + (r"var \u{88F} = 1;", "\u{88F}"), + ("var _\u{1ACF} = 1;", "_\u{1ACF}"), + ("var _\\u1ACF = 1;", "_\u{1ACF}"), + (r"var _\u{1ACF} = 1;", "_\u{1ACF}"), + ] { + let p = ok(src); + let Stmt::Var(decls) = stmt(&p, p.body[0]) else { panic!("{src:?}") }; + assert_eq!(decls[0].name.name, name, "{src:?}"); + } + assert!(err("var \u{1ACF} = 1;").message.contains("unexpected character")); + assert!(err("var \\u1ACF = 1;").message.contains("identifier escape")); + assert!(err(r"var \u{1ACF} = 1;").message.contains("identifier escape")); +} + #[test] fn identifiers_refuse_pattern_syntax_surrogates_and_bad_escapes() { // U+2E2F is a letter by category but Pattern_Syntax; U+2010, U+00B6 and U+2190 are @@ -480,12 +501,12 @@ fn no_pattern_syntax_or_white_space_character_is_an_identifier_character() { } #[test] -fn identifier_characters_are_unicode_16_id_start_and_id_continue() { +fn identifier_characters_are_unicode_17_id_start_and_id_continue() { use crate::chars::{is_id_part, is_id_start}; - use unicode_general_category::{GeneralCategory as G, get_general_category}; + use unicode_properties::{GeneralCategory as G, UnicodeGeneralCategory}; // Unicode Standard Annex #31: ID_Start is the categories Lu, Ll, Lt, Lm, Lo and Nl plus // Other_ID_Start; ID_Continue adds Mn, Mc, Nd, Pc and Other_ID_Continue; both leave out - // Pattern_Syntax and Pattern_White_Space. Other_ID_Start and Other_ID_Continue as PropList 16.0 + // Pattern_Syntax and Pattern_White_Space. Other_ID_Start and Other_ID_Continue as PropList 17.0 // lists them. let other_start = [0x1885..=0x1886, 0x2118..=0x2118, 0x212E..=0x212E, 0x309B..=0x309C]; let other_continue = [0xB7..=0xB7, 0x387..=0x387, 0x1369..=0x1371, 0x19DA..=0x19DA, 0x200C..=0x200D, 0x30FB..=0x30FB, 0xFF65..=0xFF65]; @@ -498,7 +519,7 @@ fn identifier_characters_are_unicode_16_id_start_and_id_continue() { let (mut id_starts, mut id_continues) = (0, 0); for c in (0..=0x10_FFFF_u32).filter(|c| !(0xD800..=0xDFFF).contains(c)) { let Some(ch) = char::from_u32(c) else { panic!("U+{c:04X}") }; - let g = get_general_category(ch); + let g = ch.general_category(); let letter = matches!(g, G::UppercaseLetter | G::LowercaseLetter | G::TitlecaseLetter | G::ModifierLetter | G::OtherLetter | G::LetterNumber); let id_start = (letter || other_start.iter().any(|r| r.contains(&c))) && !excluded[c as usize]; let continuing = matches!(g, G::NonspacingMark | G::SpacingMark | G::DecimalNumber | G::ConnectorPunctuation); @@ -509,8 +530,8 @@ fn identifier_characters_are_unicode_16_id_start_and_id_continue() { assert_eq!(is_id_start(c), id_start || c == 0x24 || c == 0x5F, "start U+{c:04X}"); assert_eq!(is_id_part(c), id_continue || c == 0x24, "part U+{c:04X}"); } - // The totals of ID_Start and ID_Continue in DerivedCoreProperties 16.0. - assert_eq!((id_starts, id_continues), (141_269, 144_541)); + // The totals of ID_Start and ID_Continue in DerivedCoreProperties 17.0. + assert_eq!((id_starts, id_continues), (145_916, 149_240)); } #[test] diff --git a/crates/js/src/text_tests.rs b/crates/js/src/text_tests.rs index c873bdaf59..01fc613cc3 100644 --- a/crates/js/src/text_tests.rs +++ b/crates/js/src/text_tests.rs @@ -309,6 +309,131 @@ fn flattening_a_rope_counts_against_the_heap() { } } +#[test] +fn operators_and_builtins_count_a_flattened_rope_against_the_heap() { + // Three ropes of about 524,288 units, each 1 MiB once flat, with a 3 MiB heap. + let build = "var s = 'x'; for (var i = 0; i < 19; i++) s = s + s; var t = s + 'y', u = s + 'z';"; + let limits = Limits { heap_bytes: 3 << 20, ..Limits::default() }; + let not_stopped: Vec<_> = + ["X < 'a'", "X == 1", "+X", "X[0]", "({})[{ toString: function () { return X; } }]", "JSON.stringify(0, null, X)", "[1].join(X)"] + .into_iter() + .filter(|read| { + let src = format!("{build} {}; {}; {}; 0", read.replace('X', "s"), read.replace('X', "t"), read.replace('X', "u")); + let result = Realm::with_options(Options::default(), limits.clone()).run(&src); + !matches!(result, Err(ref e) if e.kind == RunErrorKind::Limit(LimitKind::Heap)) + }) + .collect(); + assert!(not_stopped.is_empty(), "not stopped by the heap limit: {not_stopped:?}"); +} + +#[test] +fn a_flattened_temporary_stays_counted_while_the_next_copy_is_made() { + // Ropes of 262,145 units, each about half the heap once flat: one fits, two don't. Each is + // made by a function, so nothing but the native code holds it while it is flattened. + let build = "var s = 'x'; for (var i = 0; i < 18; i++) s = s + s; function f(c) { return s + c; }"; + let limits = Limits { heap_bytes: 4 * 262_146, ..Limits::default() }; + let run = |read: &str| Realm::with_options(Options::default(), limits.clone()).run(&format!("{build} {read}; 0")); + assert!(run("f('a')[0]").is_ok(), "one flattened copy fits"); + let not_stopped: Vec<_> = [ + "({ valueOf: function () { return f('a'); } }) < ({ valueOf: function () { return f('b'); } })", + "JSON.stringify({ toJSON: function () { return f('a'); } })", + "[1, 2].join({ toString: function () { return f('a'); } })", + "[{ toString: function () { return f('a'); } }].join('')", + ] + .into_iter() + .filter(|read| !matches!(run(read), Err(ref e) if e.kind == RunErrorKind::Limit(LimitKind::Heap))) + .collect(); + assert!(not_stopped.is_empty(), "not stopped by the heap limit: {not_stopped:?}"); +} + +#[test] +fn a_converted_rope_counts_what_it_holds_while_its_copy_is_made() { + // `mk` returns a rope whose left half is a flat string of about half the heap, held by + // nothing else. Its flattened copy is the other half, so the two don't fit together. + let build = "var s = 'x'; for (var i = 0; i < 18; i++) s = s + s; function f(c) { return s + c; } \ + function mk() { var a = f('a'); a[0]; return a + 'b'; }"; + let limits = Limits { heap_bytes: 4 * 262_146, ..Limits::default() }; + let not_stopped: Vec<_> = [ + "+({ valueOf: mk })", + "({})[{ toString: mk }]", + "({ valueOf: mk }) == 1", + "++({ get x() { return mk(); } }).x", + "JSON.stringify(0, null, (function () { var o = new String(''); o.toString = mk; return o; })())", + ] + .into_iter() + .filter(|read| { + let result = Realm::with_options(Options::default(), limits.clone()).run(&format!("{build} {read}; 0")); + !matches!(result, Err(ref e) if e.kind == RunErrorKind::Limit(LimitKind::Heap)) + }) + .collect(); + assert!(not_stopped.is_empty(), "not stopped by the heap limit: {not_stopped:?}"); +} + +#[test] +fn a_string_object_counts_its_flattened_rope_against_the_heap() { + // The same three ropes, each wrapped in a String object and read by index. + let build = "var s = 'x'; for (var i = 0; i < 19; i++) s = s + s; var t = s + 'y', u = s + 'z'; \ + String.prototype.first = function () { return this[0]; };"; + let limits = Limits { heap_bytes: 3 << 20, ..Limits::default() }; + // Wrapping alone reads no units, so it makes no copy. + let lengths = + Realm::with_options(Options::default(), limits.clone()).run(&format!("{build} Object(s).length + new String(t).length + Object(u).length")); + assert_eq!(lengths, Ok(JsValue::Number(1_572_866.0))); + // Two copies fit. The third read finds no room for its copy and reads the unit along the + // rope, so the live heap stays within the limit. + for (read, expected) in [ + ("Object(X)[0]", "xxx"), + ("new String(X)[0]", "xxx"), + ("0 in Object(X)", "truetruetrue"), + ("Object(X).hasOwnProperty(0)", "truetruetrue"), + ("X.first()", "xxx"), + ("Object(X)[524288]", "undefinedyz"), + ] { + let src = format!("{build} '' + ({}) + ({}) + ({})", read.replace('X', "s"), read.replace('X', "t"), read.replace('X', "u")); + let mut realm = Realm::with_options(Options::default(), limits.clone()); + assert_eq!(realm.run(&src), Ok(JsValue::String(expected.into())), "{read}"); + let interp = realm.interp(); + interp.collect_garbage(); + assert!(interp.heap.bytes <= limits.heap_bytes, "{read}: {} bytes live", interp.heap.bytes); + } + let wrapped = + Realm::with_options(Options::default(), Limits::default()).run(&format!("{build} Object(t)[524288] + new String(u)[524288] + t.first()")); + assert_eq!(wrapped, Ok(JsValue::String("yzx".into()))); +} + +#[test] +fn a_string_object_takes_fuel_for_the_rope_it_flattens() { + let limits = Limits { fuel: 40_000, ..Limits::default() }; + let build = "var s = ' '; for (var i = 0; i < 20; i++) s = s + s; Object(s).length"; + assert!(Realm::with_options(Options::default(), limits.clone()).run(build).is_ok()); + for read in ["Object(s)[0]", "0 in new String(s)"] { + let e = fail_with(Realm::with_options(Options::default(), limits.clone()), &format!("{build}; {read}")); + assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Fuel), "{read}: {e:?}"); + } + // A run that ends with an error right after the read leaves the next run its whole fuel. + let mut realm = Realm::with_options(Options::default(), Limits { fuel: 100_000, ..Limits::default() }); + let defined = realm.run("var s = ' '; for (var i = 0; i < 20; i++) s = s + s; Object.defineProperty(new String(s), 0, { value: 'a' })"); + assert!(matches!(defined, Err(ref e) if e.kind == RunErrorKind::Thrown), "{defined:?}"); + assert!(realm.run("for (var j = 0; j < 5000; j++) {} j").is_ok()); +} + +#[test] +fn a_call_keeps_its_operands_while_a_string_receiver_is_boxed() { + // `g` leaves a garbage string, so the heap is close to its limit when the rope receiver of a + // non-strict function is boxed. The callee and the argument object are off the stack by + // then, and must survive anything boxing the receiver does. + let build = "var s = 'x'; for (var i = 0; i < 17; i++) s = s + s; function f(c) { return s + c; } \ + function mk() { var a = f('a'); a[0]; return a + 'b'; } 0"; + let mut realm = Realm::with_options(Options::default(), Limits::default()); + assert_eq!(realm.run(build), Ok(JsValue::Number(0.0))); + let interp = realm.interp(); + interp.collect_garbage(); + interp.limits.heap_bytes = interp.heap.bytes + 2 * crate::heap::string_bytes(131_073) + (64 << 10); + interp.reset_gc_threshold(); + let src = "(function () { var g = f('g'); g[0]; })(); (function (o) { return o.x; }).call(mk(), { x: 1 })"; + assert_eq!(realm.run(src), Ok(JsValue::Number(1.0))); +} + #[test] fn compiling_a_pattern_counts_against_the_heap() { let src = "var s = '[\\\\s\\\\S]a*'; for (var i = 0; i < 14; i++) s = s + s; new RegExp(s).source.length"; diff --git a/crates/js/src/value.rs b/crates/js/src/value.rs index e164001ad9..a0fbcd4a53 100644 --- a/crates/js/src/value.rs +++ b/crates/js/src/value.rs @@ -163,6 +163,34 @@ impl Str { flat } + /// The code unit at `i` read along the rope without flattening it, visiting at most + /// `max_nodes` nodes: `None` when that is not enough, otherwise the unit (when `i` is in + /// range) and the number of nodes visited. + pub(crate) fn unit_at(&self, mut i: usize, max_nodes: u64) -> Option<(Option, u64)> { + let mut node = self.clone(); + let mut visited = 0u64; + loop { + visited += 1; + if visited > max_nodes { + return None; + } + let next = match &*node.0.borrow() { + Node::Flat(f) => return Some((f.get(i).copied(), visited)), + Node::Concat { left, right, .. } => { + let left_len = left.len(); + if i < left_len { + left.clone() + } else { + i -= left_len; + right.clone() + } + } + Node::Taken => return Some((None, visited)), + }; + node = next; + } + } + pub(crate) fn to_rust_string(&self) -> String { String::from_utf16_lossy(&self.flat()) } diff --git a/crates/js/src/xml.rs b/crates/js/src/xml.rs index 9dc6d71f85..f49c94eb46 100644 --- a/crates/js/src/xml.rs +++ b/crates/js/src/xml.rs @@ -7,6 +7,7 @@ //! each new node, name, reference or output unit is charged to the heap before it is made. use std::collections::{HashMap, HashSet}; +use std::hash::Hash; use std::rc::Rc; use crate::LimitKind; @@ -18,7 +19,7 @@ use crate::heap::{ XmlListData, XmlName, XmlNode, XmlNs, key, string_bytes, }; use crate::interp::{Abrupt, ErrorType, HeldBytes, Interp, JsResult}; -use crate::string_builtins::{UNITS_PER_FUEL, flat_charged}; +use crate::string_builtins::{UNITS_PER_FUEL, flat_charged, push_held, reserve_units}; use crate::value::{Str, Value, index_key}; fn parser_units(s: &str) -> Vec { @@ -175,6 +176,52 @@ fn is_attribute_run(units: &[u16]) -> bool { true } +/// Reads one pseudo-attribute of an XML declaration at `at`: white space, `name`, `=` with +/// optional white space around it, and a quoted value. Returns the offset after the closing +/// quote and the value. +fn decl_attribute<'a>(body: &'a [u16], at: usize, name: &str) -> Option<(usize, &'a [u16])> { + let start = skip_xml_space(body, at); + let name = parser_units(name); + if start == at || !body.get(start..)?.starts_with(&name) { + return None; + } + let eq = skip_xml_space(body, start + name.len()); + if body.get(eq) != Some(&EQ) { + return None; + } + let open = skip_xml_space(body, eq + 1); + let quote = body.get(open).copied().filter(|&q| q == DQUOTE || q == SQUOTE)?; + let len = body.get(open + 1..)?.iter().position(|&c| c == quote)?; + Some((open + len + 2, body.get(open + 1..open + 1 + len)?)) +} + +/// Whether `body`, the text between ``, is an XML declaration's version, optional +/// encoding, optional standalone flag and optional trailing white space (XML 1.0 productions 23 +/// to 26, 32, 80 and 81). +fn is_xml_decl_body(body: &[u16]) -> bool { + let is_digit = |c: &u16| (u16::from(b'0')..=u16::from(b'9')).contains(c); + let is_letter = |c: &u16| (u16::from(b'A')..=u16::from(b'Z')).contains(c) || (u16::from(b'a')..=u16::from(b'z')).contains(c); + let Some((mut at, version)) = decl_attribute(body, 0, "version") else { return false }; + let digits = version.strip_prefix(parser_units("1.").as_slice()).unwrap_or_default(); + if digits.is_empty() || !digits.iter().all(is_digit) { + return false; + } + if let Some((next, encoding)) = decl_attribute(body, at, "encoding") { + let Some((first, rest)) = encoding.split_first() else { return false }; + if !is_letter(first) || !rest.iter().all(|c| is_letter(c) || is_digit(c) || matches!(*c, 0x2D | 0x2E | 0x5F)) { + return false; + } + at = next; + } + if let Some((next, standalone)) = decl_attribute(body, at, "standalone") { + if standalone != parser_units("yes").as_slice() && standalone != parser_units("no").as_slice() { + return false; + } + at = next; + } + skip_xml_space(body, at) == body.len() +} + /// An XML name without a prefix (ECMA-357 section 13.1.2.1). pub(crate) fn is_ncname(units: &[u16]) -> bool { let Some((&first, rest)) = units.split_first() else { return false }; @@ -249,26 +296,40 @@ fn name_bytes(n: &XmlName) -> usize { string_bytes(n.local.len()) + n.uri.as_ref().map_or(0, |u| string_bytes(u.len())) + n.prefix.as_ref().map_or(0, |p| string_bytes(p.len())) } -/// The namespace `stack` declares for `uri`, nearest first, skipping prefixes redeclared nearer. -/// `prefer` picks that prefix when several match; `need_prefix` rejects the default namespace. -fn ns_lookup(stack: &[XmlNs], uri: &Key, prefer: Option<&Key>, need_prefix: bool) -> Option { - let mut seen: HashSet<&[u16]> = HashSet::new(); - let mut best = None; - for ns in stack.iter().rev() { - let Some(p) = &ns.prefix else { continue }; - if !seen.insert(p) { - continue; - } - if ns.uri == *uri && !(need_prefix && p.is_empty()) { - if prefer == Some(p) { - return Some(ns.clone()); - } - if best.is_none() { - best = Some(ns.clone()); - } - } +/// Inserts `item` into `set`, first holding an upper estimate of the bytes of the set's new table +/// when it must grow. Returns whether `item` was new. +fn insert_held(interp: &mut Interp, held: &mut HeldBytes, set: &mut HashSet, item: T) -> JsResult { + if set.len() == set.capacity() && !set.contains(&item) { + let more = set.capacity().max(4); + held.add(interp, more.saturating_mul(size_of::() + 1).saturating_mul(16) / 7)?; + set.reserve(more); } - best + Ok(set.insert(item)) +} + +/// Makes room in `list` for `more` items, first holding the bytes of its new capacity when it must +/// grow. The capacity at least doubles, as a push's would. +fn reserve_held(interp: &mut Interp, held: &mut HeldBytes, list: &mut Vec, more: usize) -> JsResult<()> { + if list.capacity() - list.len() < more { + let cap = list.len().saturating_add(more).max(list.capacity().saturating_mul(2)); + held.add(interp, (cap - list.capacity()).saturating_mul(size_of::()))?; + list.reserve_exact(cap - list.len()); + } + Ok(()) +} + +/// The number `n` of a prefix written `ns` in decimal without leading zeros, as +/// [`Interp::fresh_prefix`] makes them. +fn prefix_number(prefix: &[u16]) -> Option { + let digits = prefix.strip_prefix(&[u16::from(b'n'), u16::from(b's')])?; + let (&first, _) = digits.split_first()?; + if digits.len() > 9 || (first == u16::from(b'0') && digits.len() > 1) { + return None; + } + digits.iter().try_fold(0usize, |n, &c| { + let d = c.checked_sub(u16::from(b'0')).filter(|d| *d < 10)?; + Some(n * 10 + usize::from(d)) + }) } fn prefix_in_scope<'a>(stack: &'a [XmlNs], prefix: &[u16]) -> Option<&'a XmlNs> { @@ -299,18 +360,6 @@ fn units_are(units: &[u16], text: &str) -> bool { units.iter().copied().eq(text.encode_utf16()) } -/// A prefix no entry of `stack` uses. -fn fresh_prefix(stack: &[XmlNs]) -> Key { - let mut n = 0u32; - loop { - let candidate = key(&format!("ns{n}")); - if prefix_in_scope(stack, &candidate).is_none() { - return candidate; - } - n += 1; - } -} - /// One open element while serializing. struct OutFrame { node: ObjId, @@ -533,13 +582,16 @@ impl Interp { // ---- names ---- - fn name_from_string(&mut self, s: &[u16]) -> JsResult { + /// The name `s` gives: an attribute name after `@`, which is copied after its units are + /// reserved, and otherwise an element name that shares `s`. + fn name_from_string(&mut self, s: &Key) -> JsResult { if let Some((&0x40, rest)) = s.split_first() { let uri = if rest == STAR { None } else { Some(Rc::from(Vec::new())) }; + reserve_units(self, rest.len())?; return Ok(NameRef { uri, local: Rc::from(rest), attribute: true }); } - let uri = if s == STAR { None } else { Some(self.xml_default_uri()?) }; - Ok(NameRef { uri, local: Rc::from(s), attribute: false }) + let uri = if **s == *STAR { None } else { Some(self.xml_default_uri()?) }; + Ok(NameRef { uri, local: s.clone(), attribute: false }) } /// ToXMLName, with a canonical array index read as a position (ECMA-357 section 10.6). @@ -547,7 +599,7 @@ impl Interp { match k { Value::Number(n) if *n >= 0.0 && n.fract() == 0.0 && *n < 4_294_967_295.0 => Ok(Access::Index(*n as u32)), Value::String(s) => { - let flat = s.flat(); + let flat = flat_charged(self, s)?; if let Some(i) = canonical_index(&flat) { return Ok(Access::Index(i)); } @@ -557,7 +609,8 @@ impl Interp { if let Some(Class::QName { name, attribute, .. }) = self.heap.object(*o).map(|ob| &ob.class) { return Ok(Access::Name(NameRef { uri: name.uri.clone(), local: name.local.clone(), attribute: *attribute })); } - let s = self.to_str(k)?.flat(); + let s = self.to_str(k)?; + let s = flat_charged(self, &s)?; if let Some(i) = canonical_index(&s) { return Ok(Access::Index(i)); } @@ -741,31 +794,33 @@ impl Interp { if n.attribute { let count = self.xml_node(x)?.attrs.len(); self.xml_take_fuel(count)?; - let attrs = std::mem::take(&mut self.xml_node_mut(x)?.attrs); - let mut kept = Vec::with_capacity(attrs.len()); - for a in attrs { + let mut kept = 0; + for k in 0..count { + let Some(a) = self.xml_node(x)?.attrs.get(k).copied() else { break }; let hit = self.xml_node(a)?.name.as_ref().is_some_and(|q| n.matches(q)); if hit { self.xml_node_mut(a)?.parent = None; } else { - kept.push(a); + self.xml_node_mut(x)?.attrs.swap(kept, k); + kept += 1; } } - self.xml_node_mut(x)?.attrs = kept; + self.xml_node_mut(x)?.attrs.truncate(kept); return Ok(()); } let count = self.children_len(x)?; self.xml_take_fuel(count)?; - let children = std::mem::take(&mut self.xml_node_mut(x)?.children); - let mut kept = Vec::with_capacity(children.len()); - for c in children { + let mut kept = 0; + for k in 0..count { + let Some(c) = self.child_at(x, k)? else { break }; if n.matches_child(self.xml_node(c)?) { self.xml_node_mut(c)?.parent = None; } else { - kept.push(c); + self.xml_node_mut(x)?.children.swap(kept, k); + kept += 1; } } - self.xml_node_mut(x)?.children = kept; + self.xml_node_mut(x)?.children.truncate(kept); Ok(()) } @@ -893,7 +948,7 @@ impl Interp { self.use_fuel()?; cur = self.xml_node(a)?.parent; } - let height = self.node_height(v)?; + let height = self.rooted(&[Value::Object(x), Value::Object(v)], |i| i.node_height(v))?; if depth.saturating_add(height) > self.options.max_depth { return Err(Abrupt::Limit(LimitKind::Heap)); } @@ -925,7 +980,9 @@ impl Interp { /// The levels of the tree at `root`, counting it. fn node_height(&mut self, root: ObjId) -> JsResult { - let mut stack = vec![(root, 0usize)]; + let mut held = HeldBytes::new(self); + let mut stack = Vec::new(); + push_held(self, &mut held, &mut stack, (root, 0usize))?; let mut height = 1; while let Some(&(node, next)) = stack.last() { self.use_fuel()?; @@ -934,7 +991,7 @@ impl Interp { if let Some(top) = stack.last_mut() { top.1 += 1; } - stack.push((c, 0)); + push_held(self, &mut held, &mut stack, (c, 0))?; height = height.max(stack.len()); } None => { @@ -1003,19 +1060,22 @@ impl Interp { } /// Takes the fuel and heap to put every item of `l` under `x` and returns the nodes to place, - /// from [`Self::child_for_item`]. The tree does not change here, so a limit leaves it as it - /// was. - fn reserve_list_insert(&mut self, x: ObjId, l: ObjId) -> JsResult> { + /// from [`Self::child_for_item`], with the hold on the list of them, which the caller keeps + /// until they are placed. The tree does not change here, so a limit leaves it as it was. + fn reserve_list_insert(&mut self, x: ObjId, l: ObjId) -> JsResult<(Vec, HeldBytes)> { + let count = self.list_len(l)?; + let roots = [Value::Object(x), Value::Object(l)]; + let mut held = HeldBytes::new(self); + self.rooted(&roots, |i| held.add(i, size_of::().saturating_mul(count)))?; let mut items = self.xml_list(l)?.items.clone(); let bytes = XML_REF_BYTES.saturating_mul(items.len()); - let roots = [Value::Object(x), Value::Object(l)]; self.rooted(&roots, |i| i.xml_charge(bytes))?; let len = self.children_len(x)?; for (j, item) in items.iter_mut().enumerate() { *item = self.child_for_item(*item, &roots)?; self.place_fuel(len + j, *item)?; } - Ok(items) + Ok((items, held)) } /// Puts `items` at `at` in order, after [`Self::reserve_list_insert`]. @@ -1054,7 +1114,7 @@ impl Interp { self.insert_node(x, at, *v)?; } Content::List(l) => { - let items = self.reserve_list_insert(x, *l)?; + let (items, _held) = self.reserve_list_insert(x, *l)?; self.place_children(x, at, &items)?; } } @@ -1106,7 +1166,7 @@ impl Interp { } Content::List(l) => { self.check_attach(x, c)?; - let items = self.reserve_list_insert(x, *l)?; + let (items, _held) = self.reserve_list_insert(x, *l)?; let len = self.children_len(x)?; self.xml_text_fuel(len)?; if at < len { @@ -1183,7 +1243,8 @@ impl Interp { s.push_units(self, &[SPACE])?; } let Some(item) = self.list_at(*l, i)? else { break }; - let text = self.node_to_str(item)?.flat(); + let text = self.node_to_str(item)?; + let text = flat_charged(self, &text)?; s.push_units(self, &text)?; } let Value::String(s) = s.finish(self) else { return Err(Abrupt::Internal("not a string".into())) }; @@ -1194,9 +1255,9 @@ impl Interp { let mut found = None; let count = self.xml_node(x)?.attrs.len(); self.xml_take_fuel(count)?; - let attrs = std::mem::take(&mut self.xml_node_mut(x)?.attrs); - let mut kept = Vec::with_capacity(attrs.len()); - for a in attrs { + let mut kept = 0; + for k in 0..count { + let Some(a) = self.xml_node(x)?.attrs.get(k).copied() else { break }; let hit = self.xml_node(a)?.name.as_ref().is_some_and(|q| n.matches(q)); if hit && found.is_some() { self.xml_node_mut(a)?.parent = None; @@ -1204,10 +1265,11 @@ impl Interp { if hit { found = Some(a); } - kept.push(a); + self.xml_node_mut(x)?.attrs.swap(kept, k); + kept += 1; } } - self.xml_node_mut(x)?.attrs = kept; + self.xml_node_mut(x)?.attrs.truncate(kept); if let Some(a) = found { self.xml_node_mut(a)?.value = value; return Ok(()); @@ -1234,11 +1296,13 @@ impl Interp { } let len = self.children_len(x)?; self.xml_take_fuel(len)?; + self.xml_keep(x); + let mut held = HeldBytes::new(self); let mut matches = Vec::new(); for k in 0..len { let Some(child) = self.child_at(x, k)? else { break }; if n.matches_child(self.xml_node(child)?) { - matches.push(child); + push_held(self, &mut held, &mut matches, child)?; } } match c { @@ -1332,6 +1396,8 @@ impl Interp { /// The steps of [`Self::resolve_value`], setting `created` to the first element they add. fn resolve_value_adding(&mut self, x: ObjId, created: &mut Option) -> JsResult> { + self.xml_keep(x); + let mut held = HeldBytes::new(self); let mut chain = Vec::new(); let mut cur = x; let base = loop { @@ -1345,7 +1411,7 @@ impl Interp { if *name.local == *STAR { return Ok(None); } - chain.push(l); + push_held(self, &mut held, &mut chain, l)?; cur = target; }; let mut base = base; @@ -1569,6 +1635,9 @@ impl Interp { Some(parent) => self.index_in_parent(parent, item)?.map(|q| (parent, q)), None => None, }; + let count = self.list_len(c)?; + let mut held = HeldBytes::new(self); + self.rooted(&[Value::Object(x), Value::Object(c)], |i| held.add(i, size_of::().saturating_mul(count)))?; let mut items = self.xml_list(c)?.items.clone(); if place.is_some() { let roots = [Value::Object(x), Value::Object(c)]; @@ -1636,6 +1705,8 @@ impl Interp { // ---- copies ---- fn copy_shallow(&mut self, src: ObjId, parent: Option) -> JsResult { + let declared = self.xml_node(src)?.ns.len(); + self.xml_charge(XML_NS_BYTES.saturating_mul(declared))?; let node = self.xml_node(src)?; let copy = XmlNode { kind: node.kind, @@ -1646,11 +1717,11 @@ impl Interp { children: Vec::new(), ns: node.ns.clone(), }; - let attrs = node.attrs.clone(); - self.xml_charge(XML_NS_BYTES.saturating_mul(copy.ns.len()))?; let c = self.new_xml_node(copy)?; self.xml_keep(c); - for a in attrs { + let mut k = 0; + while let Some(a) = self.xml_node(src)?.attrs.get(k).copied() { + k += 1; self.use_fuel()?; let n = self.xml_node(a)?; let attr = XmlNode { @@ -1675,7 +1746,9 @@ impl Interp { let top = i.copy_shallow(root, None)?; i.xml_keep(top); let mark = i.temp_roots.len(); - let mut stack = vec![(root, top, 0usize)]; + let mut held = HeldBytes::new(i); + let mut stack = Vec::new(); + push_held(i, &mut held, &mut stack, (root, top, 0usize))?; while let Some(&(src, dst, next)) = stack.last() { i.use_fuel()?; i.temp_roots.truncate(mark); @@ -1687,7 +1760,7 @@ impl Interp { let c = i.copy_shallow(child, Some(dst))?; i.xml_charge_link(c)?; i.xml_node_mut(dst)?.children.push(c); - stack.push((child, c, 0)); + push_held(i, &mut held, &mut stack, (child, c, 0))?; } None => { stack.pop(); @@ -1732,9 +1805,18 @@ impl Interp { // ---- comparison ---- + /// The namespace, local name and value of the attribute `id`, flattening a value that is a + /// rope with [`flat_charged`]. + fn attr_key(&mut self, id: ObjId) -> JsResult<(Option, Key, Key)> { + let n = self.xml_node(id)?; + let name = n.name.as_ref().ok_or_else(|| Abrupt::Internal("attribute without a name".into()))?; + let (uri, local, value) = (name.uri.clone(), name.local.clone(), n.value.clone()); + Ok((uri, local, flat_charged(self, &value)?)) + } + fn same_shallow(&mut self, a: ObjId, b: ObjId) -> JsResult { let (x, y) = (self.xml_node(a)?, self.xml_node(b)?); - if x.kind != y.kind || x.attrs.len() != y.attrs.len() || x.children.len() != y.children.len() || x.value.flat() != y.value.flat() { + if x.kind != y.kind || x.attrs.len() != y.attrs.len() || x.children.len() != y.children.len() || x.value.len() != y.value.len() { return Ok(false); } match (&x.name, &y.name) { @@ -1742,26 +1824,25 @@ impl Interp { (Some(p), Some(q)) if p.local == q.local && p.uri == q.uri => {} _ => return Ok(false), } - if x.attrs.is_empty() { + let (xv, yv) = (x.value.clone(), y.value.clone()); + if flat_charged(self, &xv)? != flat_charged(self, &yv)? { + return Ok(false); + } + let count = self.xml_node(a)?.attrs.len(); + if count == 0 { return Ok(true); } - let count = x.attrs.len(); self.xml_take_fuel(count)?; let mut held = HeldBytes::new(self); held.add(self, ATTR_COUNT_BYTES.saturating_mul(count))?; - let (x, y) = (self.xml_node(a)?, self.xml_node(b)?); - let (xa, ya) = (x.attrs.clone(), y.attrs.clone()); let mut counts: HashMap<(Option, Key, Key), usize> = HashMap::new(); - let attr_key = |i: &Self, id: ObjId| -> JsResult<(Option, Key, Key)> { - let n = i.xml_node(id)?; - let name = n.name.as_ref().ok_or_else(|| Abrupt::Internal("attribute without a name".into()))?; - Ok((name.uri.clone(), name.local.clone(), n.value.flat())) - }; - for a in xa { - *counts.entry(attr_key(self, a)?).or_default() += 1; + for k in 0..count { + let Some(id) = self.xml_node(a)?.attrs.get(k).copied() else { break }; + *counts.entry(self.attr_key(id)?).or_default() += 1; } - for b in ya { - match counts.get_mut(&attr_key(self, b)?) { + for k in 0..count { + let Some(id) = self.xml_node(b)?.attrs.get(k).copied() else { break }; + match counts.get_mut(&self.attr_key(id)?) { Some(n) if *n > 0 => *n -= 1, _ => return Ok(false), } @@ -1838,7 +1919,8 @@ impl Interp { let (xk, yk) = (self.xml_kind(x)?, self.xml_kind(y)?); let textual = |k| matches!(k, XmlKind::Text | XmlKind::Attribute); if (textual(xk) && self.node_simple(y)?) || (textual(yk) && self.node_simple(x)?) { - return Ok(Some(self.node_to_str(x)?.flat() == self.node_to_str(y)?.flat())); + let (s, other) = (self.node_to_str(x)?, self.node_to_str(y)?); + return Ok(Some(flat_charged(self, &s)? == flat_charged(self, &other)?)); } return self.node_equals(x, y).map(Some); } @@ -1854,9 +1936,9 @@ impl Interp { if let Xv::Node(n) = self.classify(x) && self.node_simple(n)? { - let s = self.node_to_str(n)?.flat(); - let other = self.to_str(y)?.flat(); - return Ok(Some(s == other)); + let s = self.node_to_str(n)?; + let other = self.to_str(y)?; + return Ok(Some(flat_charged(self, &s)? == flat_charged(self, &other)?)); } } Ok(None) @@ -1905,7 +1987,9 @@ impl Interp { /// The nodes under `x` matching `n`, in document order ([[Descendants]], section 9.1.1.8). pub(crate) fn node_descendants(&mut self, x: ObjId, n: &NameRef, out: ObjId) -> JsResult<()> { - let mut stack = vec![(x, 0usize)]; + let mut held = HeldBytes::new(self); + let mut stack = Vec::new(); + push_held(self, &mut held, &mut stack, (x, 0usize))?; if n.attribute { self.collect_matching(x, n, out)?; } @@ -1923,14 +2007,16 @@ impl Interp { } else if n.matches_child(self.xml_node(child)?) { self.list_push(out, child)?; } - stack.push((child, 0)); + push_held(self, &mut held, &mut stack, (child, 0))?; } Ok(()) } /// Merges adjacent text and removes empty text under `root` (ECMA-357 section 13.4.4.26). pub(crate) fn node_normalize(&mut self, root: ObjId) -> JsResult<()> { - let mut stack = vec![(root, 0usize)]; + let mut held = HeldBytes::new(self); + let mut stack = Vec::new(); + push_held(self, &mut held, &mut stack, (root, 0usize))?; while let Some(&(x, mut i)) = stack.last() { self.use_fuel()?; let Some(child) = self.child_at(x, i)? else { @@ -1964,7 +2050,7 @@ impl Interp { frame.1 = i + 1; } if kind == XmlKind::Element { - stack.push((child, 0)); + push_held(self, &mut held, &mut stack, (child, 0))?; } } Ok(()) @@ -1986,7 +2072,8 @@ impl Interp { let Some(c) = self.child_at(x, i)? else { break }; let node = self.xml_node(c)?; if !matches!(node.kind, XmlKind::Comment | XmlKind::Pi) { - let text = node.value.flat(); + let text = node.value.clone(); + let text = flat_charged(self, &text)?; out.push_units(self, &text)?; } } @@ -2023,7 +2110,8 @@ impl Interp { self.use_fuel()?; let Some(item) = self.list_at(l, i)? else { break }; if !matches!(self.xml_kind(item)?, XmlKind::Comment | XmlKind::Pi) { - let text = self.node_to_str(item)?.flat(); + let text = self.node_to_str(item)?; + let text = flat_charged(self, &text)?; out.push_units(self, &text)?; } } @@ -2061,6 +2149,46 @@ impl Interp { out.push_units(self, text.get(from..).unwrap_or_default()) } + /// The namespace `stack` declares for `uri`, nearest first, skipping prefixes redeclared nearer. + /// `prefer` picks that prefix when several match; `need_prefix` rejects the default namespace. + /// The set of prefixes it has passed is held against the heap limit. + fn ns_lookup(&mut self, stack: &[XmlNs], uri: &Key, prefer: Option<&Key>, need_prefix: bool) -> JsResult> { + let mut held = HeldBytes::new(self); + let mut seen: HashSet<&[u16]> = HashSet::new(); + let mut best = None; + for ns in stack.iter().rev() { + let Some(p) = &ns.prefix else { continue }; + if !insert_held(self, &mut held, &mut seen, &p[..])? { + continue; + } + if ns.uri == *uri && !(need_prefix && p.is_empty()) { + if prefer == Some(p) { + return Ok(Some(ns.clone())); + } + if best.is_none() { + best = Some(ns.clone()); + } + } + } + Ok(best) + } + + /// The first of `ns0`, `ns1`, ... that no entry of `stack` uses. One of the first + /// `stack.len() + 1` is free, so one pass over `stack` marks the used ones. + fn fresh_prefix(&mut self, stack: &[XmlNs]) -> JsResult { + self.xml_take_fuel(stack.len() + 1)?; + let mut held = HeldBytes::new(self); + held.add(self, stack.len() + 1)?; + let mut used = vec![false; stack.len() + 1]; + for ns in stack { + if let Some(slot) = ns.prefix.as_deref().and_then(prefix_number).and_then(|n| used.get_mut(n)) { + *slot = true; + } + } + let n = used.iter().position(|u| !u).unwrap_or(stack.len()); + Ok(key(&format!("ns{n}"))) + } + /// Picks the prefix of a name in `scope`, adding a declaration to `scope` when none is there. fn out_prefix(&mut self, name: &XmlName, scope: &mut Vec, attribute: bool) -> JsResult { self.xml_take_fuel(scope.len() + 1)?; @@ -2076,13 +2204,13 @@ impl Interp { if *uri == *key(XML_URI) { return Ok(key("xml")); } - if let Some(ns) = ns_lookup(scope, &uri, name.prefix.as_ref(), attribute) { + if let Some(ns) = self.ns_lookup(scope, &uri, name.prefix.as_ref(), attribute)? { return Ok(ns.prefix.unwrap_or(empty)); } let prefix = match &name.prefix { Some(p) if !(attribute && p.is_empty()) && prefix_in_scope(scope, p).is_none() => p.clone(), _ if !attribute && prefix_in_scope(scope, &empty).is_none() => empty, - _ => fresh_prefix(scope), + _ => self.fresh_prefix(scope)?, }; self.xml_charge(XML_NS_BYTES)?; scope.push(XmlNs { prefix: Some(prefix.clone()), uri }); @@ -2097,8 +2225,7 @@ impl Interp { out.push_units(self, local) } - /// Writes `x`; an element with children is left open on `stack`. - #[allow(clippy::too_many_arguments)] + /// Writes `x`, and returns the frame of an element with children, which is left open. fn write_enter( &mut self, out: &mut Builder, @@ -2107,11 +2234,11 @@ impl Interp { settings: &Settings, pretty: bool, scope: &mut Vec, - stack: &mut Vec, - ) -> JsResult<()> { + ) -> JsResult> { self.use_fuel()?; let node = self.xml_node(x)?; - let (kind, value) = (node.kind, node.value.flat()); + let (kind, value) = (node.kind, node.value.clone()); + let value = flat_charged(self, &value)?; self.xml_text_fuel(value.len())?; if pretty { out.push_repeated(self, &[SPACE], indent)?; @@ -2119,13 +2246,18 @@ impl Interp { match kind { XmlKind::Text => { let trimmed: &[u16] = if pretty { trim_xml_space(&value) } else { &value }; - return self.write_escaped(out, trimmed, false); + self.write_escaped(out, trimmed, false)?; + return Ok(None); + } + XmlKind::Attribute => { + self.write_escaped(out, &value, true)?; + return Ok(None); } - XmlKind::Attribute => return self.write_escaped(out, &value, true), XmlKind::Comment => { out.push_str(self, ""); + out.push_str(self, "-->")?; + return Ok(None); } XmlKind::Pi => { let target = self.xml_node(x)?.name.as_ref().map(|n| n.local.clone()).unwrap_or_else(|| Rc::from(Vec::new())); @@ -2133,47 +2265,46 @@ impl Interp { out.push_units(self, &target)?; out.push_units(self, &[SPACE])?; out.push_units(self, &value)?; - return out.push_str(self, "?>"); + out.push_str(self, "?>")?; + return Ok(None); } XmlKind::Element => {} } let ns_mark = scope.len(); let node = self.xml_node(x)?; - let declared = node.ns.clone(); - let attrs = node.attrs.clone(); + let declared = node.ns.len(); let name = node.name.clone().ok_or_else(|| Abrupt::Internal("element without a name".into()))?; - self.xml_take_fuel(declared.len().saturating_mul(scope.len() + 1))?; - let mut unnamed = Vec::new(); - for ns in declared { - if ns.prefix.is_none() { - unnamed.push(ns); - } else if !scope.iter().any(|a| a.uri == ns.uri && a.prefix == ns.prefix) { - self.xml_charge(XML_NS_BYTES)?; - scope.push(ns); - } - } - for ns in unnamed { - if !scope.iter().any(|a| a.uri == ns.uri) { - let prefix = fresh_prefix(scope); - self.xml_charge(XML_NS_BYTES)?; - scope.push(XmlNs { prefix: Some(prefix), uri: ns.uri }); + self.xml_take_fuel(declared.saturating_mul(scope.len() + 1))?; + for unnamed in [false, true] { + let mut k = 0; + while let Some(ns) = self.xml_node(x)?.ns.get(k).cloned() { + k += 1; + if ns.prefix.is_none() != unnamed { + continue; + } + if !unnamed && !scope.iter().any(|a| a.uri == ns.uri && a.prefix == ns.prefix) { + self.xml_charge(XML_NS_BYTES)?; + scope.push(ns); + } else if unnamed && !scope.iter().any(|a| a.uri == ns.uri) { + let prefix = self.fresh_prefix(scope)?; + self.xml_charge(XML_NS_BYTES)?; + scope.push(XmlNs { prefix: Some(prefix), uri: ns.uri }); + } } } let prefix = self.out_prefix(&name, scope, false)?; - let mut attr_prefixes = Vec::new(); - for &a in &attrs { - self.use_fuel()?; - let an = self.xml_node(a)?.name.clone().ok_or_else(|| Abrupt::Internal("attribute without a name".into()))?; - attr_prefixes.push(self.out_prefix(&an, scope, true)?); - } out.push_units(self, &[LT])?; self.write_name(out, &prefix, &name.local)?; - for (&a, attr_prefix) in attrs.iter().zip(&attr_prefixes) { - let an = self.xml_node(a)?; - let local = an.name.as_ref().map(|q| q.local.clone()).unwrap_or_else(|| Rc::from(Vec::new())); - let value = an.value.flat(); + let mut k = 0; + while let Some(a) = self.xml_node(x)?.attrs.get(k).copied() { + k += 1; + self.use_fuel()?; + let an = self.xml_node(a)?.name.clone().ok_or_else(|| Abrupt::Internal("attribute without a name".into()))?; + let attr_prefix = self.out_prefix(&an, scope, true)?; + let value = self.xml_node(a)?.value.clone(); + let value = flat_charged(self, &value)?; out.push_units(self, &[SPACE])?; - self.write_name(out, attr_prefix, &local)?; + self.write_name(out, &attr_prefix, &an.local)?; out.push_units(self, &[EQ, DQUOTE])?; self.write_escaped(out, &value, true)?; out.push_units(self, &[DQUOTE])?; @@ -2193,7 +2324,8 @@ impl Interp { let count = self.children_len(x)?; if count == 0 { scope.truncate(ns_mark); - return out.push_str(self, "/>"); + out.push_str(self, "/>")?; + return Ok(None); } out.push_units(self, &[GT])?; let first_is_text = match self.child_at(x, 0)? { @@ -2202,14 +2334,17 @@ impl Interp { }; let pretty_children = pretty && (count > 1 || !first_is_text); let child_indent = if pretty_children { indent.saturating_add(u64::from(settings.indent)) } else { 0 }; - stack.push(OutFrame { node: x, next: 0, indent, child_indent, pretty_children, ns_mark, prefix, local: name.local }); - Ok(()) + Ok(Some(OutFrame { node: x, next: 0, indent, child_indent, pretty_children, ns_mark, prefix, local: name.local })) } + /// Writes the tree at `root`. Its open elements are held against the heap limit. fn write_node(&mut self, out: &mut Builder, root: ObjId, indent: u64, settings: &Settings, pretty: bool) -> JsResult<()> { let mut scope: Vec = Vec::new(); + let mut held = HeldBytes::new(self); let mut stack: Vec = Vec::new(); - self.write_enter(out, root, indent, settings, pretty, &mut scope, &mut stack)?; + if let Some(frame) = self.write_enter(out, root, indent, settings, pretty, &mut scope)? { + push_held(self, &mut held, &mut stack, frame)?; + } while let Some(frame) = stack.last_mut() { let (node, next, child_indent, pretty_children) = (frame.node, frame.next, frame.child_indent, frame.pretty_children); frame.next += 1; @@ -2218,7 +2353,9 @@ impl Interp { if pretty_children { out.push_units(self, &[LF])?; } - self.write_enter(out, child, child_indent, settings, pretty && pretty_children, &mut scope, &mut stack)?; + if let Some(frame) = self.write_enter(out, child, child_indent, settings, pretty && pretty_children, &mut scope)? { + push_held(self, &mut held, &mut stack, frame)?; + } } None => { let Some(frame) = stack.pop() else { break }; @@ -2265,8 +2402,11 @@ impl Interp { self.throw(ErrorType::Syntax, message) } - fn decode_into(&mut self, src: &[u16], from: usize, to: usize, out: &mut Vec, attribute: bool) -> JsResult<()> { + /// Decodes `src[from..to]` onto `out`, holding the room it takes in `out` with `held` first. The + /// decoded text is never longer than the source. + fn decode_into(&mut self, src: &[u16], from: usize, to: usize, out: &mut Vec, attribute: bool, held: &mut HeldBytes) -> JsResult<()> { self.xml_text_fuel(to.saturating_sub(from))?; + reserve_held(self, held, out, to.saturating_sub(from))?; let mut pos = from; while pos < to { let Some(&c) = src.get(pos) else { break }; @@ -2305,8 +2445,30 @@ impl Interp { src.get(from..)?.windows(needle.len()).position(|w| w == needle).map(|i| from + i) } + /// Takes fuel for `units` code units that the parser scanned, on top of the fuel of the step + /// that scanned them, so a short run costs nothing extra. + fn xml_scan_fuel(&mut self, units: usize) -> JsResult<()> { + self.xml_take_fuel(units / UNITS_PER_FUEL) + } + + /// The offset after the white space at `src[pos]`, taking fuel for its length. + fn skip_space(&mut self, src: &[u16], pos: usize) -> JsResult { + let end = skip_xml_space(src, pos); + self.xml_scan_fuel(end - pos)?; + Ok(end) + } + + /// The offset after the XML name at `src[pos]`, taking fuel for the units it scanned. fn read_name(&mut self, src: &[u16], pos: usize) -> JsResult { - scan_name(src, pos).ok_or_else(|| self.syntax("invalid XML name")) + if let Some(end) = scan_name(src, pos) { + self.xml_scan_fuel(end - pos)?; + return Ok(end); + } + if src.get(pos).copied().is_some_and(is_name_start) { + let scanned = src.get(pos..).unwrap_or_default().iter().skip(1).take_while(|&&c| is_name_part(c)).count(); + self.xml_scan_fuel(scanned + 1)?; + } + Err(self.syntax("invalid XML name")) } fn check_units(&mut self, src: &[u16], from: usize, to: usize) -> JsResult<()> { @@ -2359,7 +2521,16 @@ impl Interp { Ok(()) } - fn flush_text(&mut self, text: &mut Vec, ignore_whitespace: bool, open: &[ObjId], roots: &mut Vec) -> JsResult<()> { + /// Makes a text node of `text`, unless it is empty or ignored white space. Taking the buffer + /// releases `text_held`, its hold. + fn flush_text( + &mut self, + text: &mut Vec, + text_held: &mut HeldBytes, + ignore_whitespace: bool, + open: &[ObjId], + roots: &mut Vec, + ) -> JsResult<()> { if text.is_empty() { return Ok(()); } @@ -2367,16 +2538,22 @@ impl Interp { text.clear(); return Ok(()); } - let t = self.new_text_node(Str::from_units(std::mem::take(text)), None)?; + let value = Str::from_units(std::mem::take(text)); + *text_held = HeldBytes::new(self); + let t = self.new_text_node(value, None)?; self.place_parsed(t, open, roots) } + /// Parses the open tag at `src[pos]` and returns the offset after it. An element left open is + /// pushed onto `open` and its name onto `names`, both held with `stack_held`. The attributes, + /// sets and copies it works with are held until it returns. fn parse_open_tag( &mut self, src: &[u16], pos: usize, open: &mut Vec, names: &mut Vec<(usize, usize)>, + stack_held: &mut HeldBytes, roots: &mut Vec, ) -> JsResult { if open.len() >= self.options.max_depth { @@ -2387,12 +2564,11 @@ impl Interp { let raw_name = src.get(name_start..name_end).unwrap_or_default(); let (elem_prefix, elem_local) = self.split_name(raw_name)?; let mut at = name_end; + let mut held = HeldBytes::new(self); let mut raw_attrs: Vec<(usize, usize, Vec)> = Vec::new(); let closes = loop { let before = at; - while src.get(at).copied().is_some_and(is_xml_space) { - at += 1; - } + at = self.skip_space(src, at)?; match src.get(at).copied() { None => return Err(self.syntax("unterminated XML tag")), Some(SLASH) if src.get(at + 1) == Some(>) => { @@ -2407,50 +2583,50 @@ impl Interp { Some(_) => { self.use_fuel()?; let end = self.read_name(src, at)?; - let mut p = end; - while src.get(p).copied().is_some_and(is_xml_space) { - p += 1; - } + let p = self.skip_space(src, end)?; if src.get(p) != Some(&EQ) { return Err(self.syntax("expected '=' after an attribute name")); } - p += 1; - while src.get(p).copied().is_some_and(is_xml_space) { - p += 1; - } + let p = self.skip_space(src, p + 1)?; let quote = match src.get(p).copied() { Some(q @ (DQUOTE | SQUOTE)) => q, _ => return Err(self.syntax("expected a quoted attribute value")), }; let value_start = p + 1; let Some(value_end) = Self::find_from(src, value_start, &[quote]) else { + self.xml_text_fuel(src.len().saturating_sub(value_start))?; return Err(self.syntax("unterminated attribute value")); }; if src.get(value_start..value_end).is_some_and(|v| v.contains(<)) { + self.xml_text_fuel(value_end - value_start)?; return Err(self.syntax("'<' cannot appear in an attribute value")); } let mut value = Vec::new(); - self.decode_into(src, value_start, value_end, &mut value, true)?; - raw_attrs.push((at, end, value)); + self.decode_into(src, value_start, value_end, &mut value, true, &mut held)?; + push_held(self, &mut held, &mut raw_attrs, (at, end, value))?; at = value_end + 1; } } }; self.xml_charge(XML_NS_BYTES.saturating_mul(raw_attrs.len()))?; - let mut ns: Vec = Vec::new(); - let mut seen_decl: HashSet> = HashSet::new(); + let xmlns = key("xmlns"); + let declares = |raw: &[u16]| raw == &xmlns[..] || raw.strip_prefix(&xmlns[..]).is_some_and(|rest| rest.first() == Some(&COLON)); + let decls = raw_attrs.iter().filter(|(start, end, _)| declares(src.get(*start..*end).unwrap_or_default())).count(); + let mut ns: Vec = Vec::with_capacity(decls); + let mut seen_decl: HashSet<&[u16]> = HashSet::new(); for (start, end, value) in &raw_attrs { let raw = src.get(*start..*end).unwrap_or_default(); - if raw == key("xmlns").as_ref() { + if raw == &xmlns[..] { if !ns_binding_allowed(&[], value) { return Err(self.syntax(RESERVED_NS_BINDING)); } - if !seen_decl.insert(Vec::new()) { + if !insert_held(self, &mut held, &mut seen_decl, &[] as &[u16])? { return Err(self.syntax("a namespace is declared twice")); } + self.xml_charge(string_bytes(0).saturating_add(string_bytes(value.len())))?; ns.push(XmlNs { prefix: Some(Rc::from(Vec::new())), uri: Rc::from(value.as_slice()) }); } else if let (Some(p), local) = self.split_name(raw)? - && p == key("xmlns").as_ref() + && p == &xmlns[..] { if value.is_empty() { return Err(self.syntax("a namespace prefix cannot be declared with an empty URI")); @@ -2458,9 +2634,10 @@ impl Interp { if !ns_binding_allowed(local, value) { return Err(self.syntax(RESERVED_NS_BINDING)); } - if !seen_decl.insert(local.to_vec()) { + if !insert_held(self, &mut held, &mut seen_decl, local)? { return Err(self.syntax("a namespace is declared twice")); } + self.xml_charge(string_bytes(local.len()).saturating_add(string_bytes(value.len())))?; ns.push(XmlNs { prefix: Some(Rc::from(local)), uri: Rc::from(value.as_slice()) }); } } @@ -2485,7 +2662,8 @@ impl Interp { ns, })?; self.place_parsed(element, open, roots)?; - let mut unique: HashSet<(Key, Vec)> = HashSet::new(); + let mut unique: HashSet<(Key, &[u16])> = HashSet::new(); + let mut own: Option> = None; for (start, end, value) in raw_attrs { self.use_fuel()?; let raw = src.get(start..end).unwrap_or_default(); @@ -2495,15 +2673,19 @@ impl Interp { } let (auri, stored_prefix): (Key, Key) = match prefix { Some(p) => { - let own = self.xml_node(element)?.ns.clone(); - match self.resolve_prefix(p, &own, open)? { + if own.is_none() { + let count = self.xml_node(element)?.ns.len(); + held.add(self, size_of::().saturating_mul(count))?; + own = Some(self.xml_node(element)?.ns.clone()); + } + match self.resolve_prefix(p, own.as_deref().unwrap_or_default(), open)? { Some(u) => (u, Rc::from(p)), None => return Err(self.syntax("an XML name uses an undeclared namespace prefix")), } } None => (Rc::from(Vec::new()), Rc::from(Vec::new())), }; - if !unique.insert((auri.clone(), local.to_vec())) { + if !insert_held(self, &mut held, &mut unique, (auri.clone(), local))? { return Err(self.type_error("an XML element has two attributes with the same name")); } let a = self.new_xml_node(XmlNode { @@ -2519,8 +2701,8 @@ impl Interp { self.xml_node_mut(element)?.attrs.push(a); } if !closes { - open.push(element); - names.push((name_start, name_end)); + push_held(self, stack_held, open, element)?; + push_held(self, stack_held, names, (name_start, name_end))?; } Ok(at) } @@ -2528,10 +2710,7 @@ impl Interp { fn parse_close_tag(&mut self, src: &[u16], pos: usize, open: &mut Vec, names: &mut Vec<(usize, usize)>) -> JsResult { let name_start = pos + 2; let name_end = self.read_name(src, name_start)?; - let mut at = name_end; - while src.get(at).copied().is_some_and(is_xml_space) { - at += 1; - } + let at = self.skip_space(src, name_end)?; if src.get(at) != Some(>) { return Err(self.syntax("expected '>' at the end of a closing tag")); } @@ -2546,20 +2725,27 @@ impl Interp { } /// Parses XML text into nodes, kept reachable through the temporary roots until the caller's - /// scope ends. + /// scope ends. The open elements and their names, the text being gathered and each tag's + /// attributes are held as they grow. The allowance held from the source's length covers the + /// copy a value's units take as it becomes a string, before the node that holds it is charged. pub(crate) fn xml_parse(&mut self, source: &[u16]) -> JsResult> { let mut held = HeldBytes::new(self); held.add(self, string_bytes(source.len()).saturating_mul(2))?; + let mut stack_held = HeldBytes::new(self); + let mut text_held = HeldBytes::new(self); let settings = self.xml_settings()?; let mut src = source; - let mut offset_start = 0; - while src.get(offset_start).copied().is_some_and(is_xml_space) { - offset_start += 1; - } + let offset_start = skip_xml_space(src, 0); if src.get(offset_start..).is_some_and(|r| r.starts_with(&parser_units("")) else { + self.xml_text_fuel(src.len())?; return Err(self.syntax("unterminated XML declaration")); }; + self.xml_text_fuel(end + 2)?; + self.check_units(src, offset_start, end)?; + if !is_xml_decl_body(src.get(offset_start + 5..end).unwrap_or_default()) { + return Err(self.syntax("invalid XML declaration")); + } src = src.get(end + 2..).unwrap_or_default(); } let mut pos = 0; @@ -2573,35 +2759,40 @@ impl Interp { let end = Self::find_from(src, pos, &[LT]).unwrap_or(src.len()); let section_end = parser_units("]]>"); if src.get(pos..end).is_some_and(|run| run.windows(3).any(|w| w == section_end)) { + self.xml_text_fuel(end - pos)?; return Err(self.syntax("']]>' cannot appear in XML text")); } - self.decode_into(src, pos, end, &mut text, false)?; + self.decode_into(src, pos, end, &mut text, false, &mut text_held)?; pos = end; continue; } let rest = src.get(pos..).unwrap_or_default(); if rest.starts_with(&parser_units("")) else { + self.xml_text_fuel(src.len() - pos)?; return Err(self.syntax("unterminated CDATA section")); }; self.xml_text_fuel(end - pos)?; self.check_units(src, pos + 9, end)?; - text.extend_from_slice(src.get(pos + 9..end).unwrap_or_default()); + let section = src.get(pos + 9..end).unwrap_or_default(); + reserve_held(self, &mut text_held, &mut text, section.len())?; + text.extend_from_slice(section); pos = end + 3; continue; } - self.flush_text(&mut text, settings.ignore_whitespace, &open, &mut roots)?; + self.flush_text(&mut text, &mut text_held, settings.ignore_whitespace, &open, &mut roots)?; if rest.starts_with(&parser_units("'; \ + var g = ''; isXMLName(g);"; + for ctor in ["XML", "XMLList"] { + let rope = least_spare(text, &format!("new {ctor}(s); 1")); + let flat = least_spare(text, &format!("new {ctor}(g); 1")); + if rope < flat + 32768 { + wrong.push(format!("new {ctor} needs {rope} spare for a rope and {flat} for flat text")); + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); +} + #[test] fn an_interrupt_stops_serialization() { let mut r = realm(); @@ -1080,6 +1662,471 @@ fn an_interrupt_stops_serialization() { assert_eq!(r.run("stop(); x.toXMLString()").map_err(|e| e.kind), Err(RunErrorKind::Limit(LimitKind::Interrupted))); } +// ---- xpath ---- + +/// A script function that joins the local names of a list's items. +const NAMES: &str = "function names(l) { var s = ''; for each (var n in l) s += n.localName(); return s; }"; + +#[test] +fn xpath_selects_child_attribute_and_text_nodes() { + for check in [ + "xml.xpath('book').length() === 4", + "xml.xpath('book[2]/title') == 'Oz'", + "xml.xpath('book[last()]/title') == 'Opera'", + "xml.xpath('book[position() < 3]').length() === 2", + "xml.xpath('book[year > 1890]/title').length() === 3", + "xml.xpath('book[count(author) > 1]/title') == 'Alice'", + "xml.xpath('book[@category = \"CHILDREN\"]/title').length() === 2", + "xml.xpath('//author').length() === 6", + "xml.xpath('book/@category').length() === 4 && xml.xpath('book/@category')[0].nodeKind() === 'attribute'", + "xml.xpath('book[1]/title/text()')[0].nodeKind() === 'text' && xml.xpath('book[1]/title/text()') == 'Cookbook'", + "xml.xpath('book[1]/title/@lang') == 'en'", + "xml.xpath('nothing').length() === 0", + "xml.xpath('child::book[3]/child::author[2]') == 'B'", + "xml.xpath('*').length() === 4 && xml.xpath('book/node()').length() === 14", + ] { + truth(&format!("{BOOKS} {check}")); + } +} + +#[test] +fn xpath_returns_the_nodes_of_the_tree() { + truth(&format!("{BOOKS} xml.book[1].title[0].xpath('..')[0] === xml.book[1]")); + truth(&format!("{BOOKS} xml.xpath('book[2]')[0] === xml.book[1] && xml.xpath('.')[0] === xml")); + truth(&format!("{BOOKS} xml.xpath('book[1]/year')[0].setChildren('2000'); xml.book[0].year == '2000'")); + truth(&format!("{BOOKS} xml.xpath('book/@category')[1].setName('kind'); xml.book[1].@kind == 'CHILDREN'")); + truth("var x = t; x.a.text()[0].xpath('..')[0] === x.a[0]"); +} + +#[test] +fn xpath_absolute_paths_start_above_the_topmost_element() { + truth(&format!("{BOOKS} xml.book[0].title[0].xpath('/bookstore/book').length() === 4")); + truth(&format!("{BOOKS} xml.book[0].title[0].xpath('/*')[0] === xml")); + truth(&format!("{BOOKS} xml.book[0].title[0].xpath('//title').length() === 4")); + truth(&format!("{BOOKS} xml.book[0].title[0].xpath('/title').length() === 0")); + truth("var d = ; d.e[0].xpath('/d')[0] === d"); + for src in ["().xpath('/')", "().xpath('..')", "().xpath('ancestor-or-self::node()')"] { + assert_eq!(thrown_name(src), "TypeError", "{src}"); + } +} + +#[test] +fn xpath_walks_every_axis() { + let tree = "var x = ;"; + for (expr, want) in [ + ("x.a[0].xpath('following-sibling::*')", "df"), + ("x.f[0].xpath('preceding-sibling::*')", "ad"), + ("x.f[0].xpath('preceding-sibling::*[1]')", "d"), + ("x.d.e[0].xpath('ancestor::*')", "rd"), + ("x.d.e[0].xpath('ancestor::*[1]')", "d"), + ("x.d.e[0].xpath('ancestor-or-self::*')", "rde"), + ("x.a.b[0].xpath('following::*')", "cdef"), + ("x.d.e[0].xpath('preceding::*')", "abc"), + ("x.d.e[0].xpath('preceding::*[1]')", "c"), + ("x.xpath('descendant::*')", "abcdef"), + ("x.xpath('descendant-or-self::*')", "rabcdef"), + ("x.a[0].xpath('self::a')", "a"), + ("x.a[0].xpath('self::b')", ""), + ("x.a.b[0].xpath('parent::*')", "a"), + ("x.xpath('//*[2]')", "cd"), + ("x.xpath('(//*)[2]')", "a"), + ("x.xpath('d/e/../preceding-sibling::*/c')", "c"), + ] { + assert_eq!(string(&format!("{NAMES} {tree} names({expr})")), want, "{expr}"); + } + let attr = "var x = ;"; + assert_eq!(string(&format!("{NAMES} {attr} names(x.a.@p[0].xpath('following::*'))")), "bc"); + assert_eq!(string(&format!("{NAMES} {attr} names(x.a.@p[0].xpath('ancestor::*'))")), "ra"); + truth(&format!("{attr} x.a.@p[0].xpath('following-sibling::node()').length() === 0 && x.a.@p[0].xpath('preceding::*').length() === 0")); +} + +#[test] +fn xpath_results_are_in_document_order_without_repeats() { + let tree = "var x = ;"; + for (expr, want) in [ + ("x.xpath('c | a | //b')", "abbc"), + ("x.xpath('a | a')", "a"), + ("x.xpath('//b/..')", "ra"), + ("x.xpath('//*/ancestor::*')", "ra"), + ("x.c[0].xpath('preceding::*[position() < 3]')", "bb"), + ] { + assert_eq!(string(&format!("{NAMES} {tree} names({expr})")), want, "{expr}"); + } + truth(&format!("{tree} x.xpath('c | @p')[0].nodeKind() === 'attribute' && x.xpath('c | @p').length() === 2")); +} + +#[test] +fn xpath_names_match_by_namespace_uri() { + let tree = "var x = ;"; + for check in [ + "x.xpath('p:a').length() === 2", + "x.xpath('a').length() === 1 && x.xpath('a')[0].name().uri === ''", + "x.xpath('p:*').length() === 2", + "x.xpath('*').length() === 4", + "x.xpath('*[local-name() = \"a\"]').length() === 4", + "x.xpath('*[namespace-uri() = \"urn:s\"]').length() === 1", + "x.xpath('*[name() = \"p:a\"]').length() === 1", + ] { + truth(&format!("{tree} {check}")); + } + truth("var x = ; x.xpath('a').length() === 0 && x.xpath('*').length() === 1"); + truth("var x = ; default xml namespace = 'urn:d'; x.xpath('a').length() === 1"); + truth("var x = ; x.xpath('a/@xml:lang') == 'en'"); + let rebound = "var x = ;"; + truth(&format!("{rebound} x.xpath('//p:a').length() === 1 && x.xpath('//p:a')[0].parent() === x")); + truth(&format!("{rebound} x.b[0].xpath('p:a').length() === 1 && x.b[0].xpath('/r/p:a').length() === 0")); + assert_eq!(thrown_name("().xpath('z:a')"), "TypeError"); +} + +#[test] +fn xpath_namespace_nodes_can_be_tested_but_not_returned() { + let tree = "var x = ;"; + truth(&format!("{tree} x.xpath('self::*[namespace::xml]').length() === 1")); + truth(&format!("{tree} x.xpath('a[count(namespace::*) = 3]').length() === 1")); + truth(&format!("{tree} x.xpath('a[namespace::q = \"urn:q\"]').length() === 1 && x.xpath('self::*[namespace::q]').length() === 0")); + truth(&format!("{tree} x.xpath('a[namespace::*[name() = \"p\"]/.. = .]').length() === 1")); + assert_eq!(thrown_name(&format!("{tree} x.xpath('namespace::*')")), "TypeError"); +} + +#[test] +fn xpath_variables_come_from_the_object_properties() { + truth(&format!("{BOOKS} xml.xpath('book[title = $t]/author', {{ t: 'Oz' }}) == 'Baum'")); + truth(&format!("{BOOKS} xml.xpath('book[$n]/title', {{ n: 3 }}) == 'Alice'")); + truth(&format!("{BOOKS} xml.xpath('book[$yes]', {{ yes: true }}).length() === 4 && xml.xpath('book[$no]', {{ no: false }}).length() === 0")); + truth(&format!("{BOOKS} xml.xpath('$b/title', {{ b: xml.book[1] }}) == 'Oz'")); + truth(&format!("{BOOKS} xml.xpath('$l/year', {{ l: xml.book.(@category == 'CHILDREN') }}).length() === 2")); + truth(&format!("{BOOKS} xml.xpath('book[year = $y]/title', {{ y: {{ toString: function () {{ return '1922'; }} }} }}) == 'Opera'")); + truth(&format!( + "{BOOKS} var o = {{}}; Object.defineProperty(o, 'v', {{ get: function () {{ return 'Alice'; }} }}); xml.xpath('book[title = $v]', o).length() === 1" + )); + for src in + ["().xpath('$v')", "().xpath('$v', {})", "().xpath('$v', { v: undefined })", "().xpath('a', 5)", "().xpath('a', null)"] + { + assert_eq!(thrown_name(src), "TypeError", "{src}"); + } +} + +#[test] +fn xpath_keeps_the_items_of_a_list_variable_that_a_later_getter_empties() { + let setup = "var l = <>;"; + let action = "var o = { get v() { return l; }, get w() { delete l[0]; l = null; squeeze(100000000); return 1; } }; + var r = ().xpath('$v/b | $v[$w]', o); r.length() === 2 && r[0].localName() === 'a' && r[1].localName() === 'b'"; + assert_eq!(after_setup(setup, action), Ok(JsValue::Bool(true))); +} + +#[test] +fn xpath_functions_and_operators_follow_xpath_1() { + let tree = "var x = 12x y12.5;"; + let checks = [ + "last() = 1 and position() = 1", + "count(a) = 2", + "count(id('a')) = 0", + "local-name() = 'r' and name(a) = 'a' and namespace-uri() = ''", + "local-name(nothing) = '' and name(@xml:lang) = 'xml:lang'", + "string(a) = '1' and string() = '12x y12.5' and string(nothing) = ''", + "concat('a', 'b', 'c') = 'abc'", + "starts-with('abc', 'ab') and not(starts-with('abc', 'b'))", + "contains('abc', 'bc') and contains('abc', '') and not(contains('abc', 'd'))", + "substring-before('1999/04/01', '/') = '1999' and substring-before('abc', 'd') = ''", + "substring-after('1999/04/01', '/') = '04/01' and substring-after('abc', '') = 'abc'", + "substring('12345', 2, 3) = '234' and substring('12345', 2) = '2345'", + "substring('12345', 1.5, 2.6) = '234' and substring('12345', 0, 3) = '12'", + "substring('12345', 0 div 0, 3) = '' and substring('12345', 1, 0 div 0) = ''", + "substring('12345', -42, 1 div 0) = '12345' and substring('12345', -1 div 0, 1 div 0) = ''", + "string-length('abc') = 3 and string-length(b) = 4 and string-length() = 10", + "normalize-space(b) = 'x y' and normalize-space(' x \t y ') = 'x y' and normalize-space(' ') = ''", + "translate('bar', 'abc', 'ABC') = 'BAr' and translate('--aaa--', 'abc-', 'ABC') = 'AAA'", + "boolean(a) and not(boolean(nothing)) and boolean('x') and not(boolean('')) and not(boolean(0)) and not(boolean(0 div 0))", + "true() and not(false())", + "lang('en') and lang('EN-us') and not(lang('fr')) and a[lang('en')]", + "number(n) = 12.5 and number(' -3 ') = -3 and string(number('1e3')) = 'NaN' and string(number('+1')) = 'NaN'", + "sum(a) = 3 and sum(nothing) = 0", + "floor(2.5) = 2 and ceiling(2.1) = 3 and floor(-2.5) = -3", + "round(2.5) = 3 and round(-2.5) = -2 and round(2.4) = 2 and string(round(-0.4)) = '0'", + "string(1 div 0) = 'Infinity' and string(-1 div 0) = '-Infinity' and string(0 div 0) = 'NaN'", + "string(1.5) = '1.5' and string(2) = '2' and string(-0.25) = '-0.25' and string(1 div 3) = '0.3333333333333333'", + "string(1000000 * 1000000 * 1000000 * 1000) = '1000000000000000000000'", + "7 mod 3 = 1 and -7 mod 3 = -1 and 5 div 2 = 2.5 and 2 - 3 = -1 and --1 = 1 and -(1 + 1) = -2", + "1 + 2 * 3 = 7 and (1 + 2) * 3 = 9 and 3 > 2 > 1 = false()", + "a = 2 and a = '1' and a != 1 and a > 1 and not(a > 2) and a < 2 and 1 < a and 2 >= a", + "a = a and a != a and not(a[1] != a[1]) and not(nothing = nothing) and not(nothing != a) and a < a", + "true() = a and false() = nothing and '1' = 1 and true() = 'x' and 1 = true() and not(0 = true())", + "a > false() and not(a > true()) and nothing < true() and not(nothing >= true())", + "1 < 2 and 2 > 1 or false()", + "false() and 1 div 0 or true()", + "'a' < 'b' = false() and '1' < '2'", + "*[2] = 2 and *[last()] = 12.5", + "(a | b)[2] = 2", + ]; + for check in checks { + let expr = format!("self::*[{check}]"); + truth(&format!("{tree} x.xpath({expr:?}).length() === 1")); + } +} + +#[test] +fn xpath_throws_a_type_error_for_a_value_that_is_not_a_node_set() { + for expr in ["count(book)", "string(book)", "1", "'a'", "true()", "book = 1", "-book"] { + let src = format!("{BOOKS} try {{ xml.xpath({expr:?}); 'no error' }} catch (e) {{ e.name + ': ' + e.message }}"); + assert_eq!(string(&src), "TypeError: the XPath expression does not evaluate to a node-set", "{expr}"); + } +} + +#[test] +fn xpath_errors_name_their_cause() { + for expr in [ + "", + " ", + "/[1]", + "book[", + "book]", + "(", + ")", + "1 +", + "book/", + "@", + "foo::bar", + ".[1]", + "..[1]", + "'abc", + "$", + "book book", + "!", + "a//", + ",", + "count(", + "count(1,", + "a::", + "::a", + "a:", + "1..2", + "book[1]]", + "count(book))", + "//", + "/ /a", + "(1)(2)", + "processing-instruction(1)", + "node(1)", + "*:a", + "a:b:c", + ] { + assert_eq!(thrown_name(&format!("{BOOKS} xml.xpath({expr:?})")), "SyntaxError", "{expr:?}"); + } + for expr in + ["foo()", "count()", "count(1)", "p:count(book)", "sum('1')", "1 | book", "'a'/b", "'a'[1]", "concat('a')", "name(1)", "substring('a')"] + { + assert_eq!(thrown_name(&format!("{BOOKS} xml.xpath({expr:?})")), "TypeError", "{expr:?}"); + } + for src in ["().xpath()", "().xpath(5)", "().xpath(new String('a'))", "XML.prototype.xpath.call({}, 'a')"] { + assert_eq!(thrown_name(src), "TypeError", "{src}"); + } +} + +#[test] +fn xpath_on_an_xml_list_runs_on_each_element_in_turn() { + truth( + "var l = <>123; l.xpath('b').length() === 3 && l.xpath('b').toXMLString() === '1\\n2\\n3'", + ); + truth("var l = <>123; l.xpath('b[1]').length() === 2"); + truth("var x = ; var l = x.*; var p = l.xpath('..'); p.length() === 2 && p[0] === x && p[1] === x"); + truth("var x = t; var l = x.a.text() + x.a; l.xpath('.').length() === 1 && l.xpath('.')[0] === x.a[0]"); + truth("var x = ; (x.@p + x.comments()).xpath('.').length() === 0"); + truth("new XMLList().xpath('a').length() === 0 && new XMLList().xpath('z:a').length() === 0"); + truth("var l = <>; l.xpath('p:b').length() === 2"); + assert_eq!(thrown_name("var l = <>; l.xpath('p:b')"), "TypeError"); +} + +#[test] +fn xpath_expressions_of_any_depth_use_no_native_stack() { + let deep = format!("{}1{}", "(".repeat(100_000), ")".repeat(100_000)); + assert_eq!(thrown_name(&format!("().xpath('{deep}')")), "SyntaxError"); + let predicates = format!("{}{}", "a[".repeat(100_000), "]".repeat(100_000)); + assert_eq!(thrown_name(&format!("().xpath('{predicates}')")), "SyntaxError"); + let sum = format!("1{}", " + 1".repeat(100_000)); + truth(&format!("().xpath('self::*[{sum} = 100001]').length() === 1")); + let negated = format!("{}1", "-".repeat(100_001)); + truth(&format!("().xpath('self::*[{negated} = -1]').length() === 1")); + let union = format!("a{}", " | a".repeat(50_000)); + truth(&format!("().xpath('{union}').length() === 1")); + let mut shallow = Realm::with_options(Options { max_depth: 8, ..e4x() }, Limits::default()); + let seven = format!("{}1{}", "(".repeat(6), ")".repeat(6)); + assert_eq!(shallow.run(&format!("().xpath('self::*[{seven}]').length()")), Ok(JsValue::Number(1.0))); + let eight = format!("{}1{}", "(".repeat(8), ")".repeat(8)); + assert_eq!(shallow.run(&format!("try {{ ().xpath('{eight}') }} catch (e) {{ e.message }}")), Ok(JsValue::String("nesting too deep".into()))); +} + +#[test] +fn xpath_stops_at_the_fuel_and_heap_limits_leaving_the_tree() { + let setup = "var x = ; for (var i = 0; i < 6; i++) x.appendChild({i});"; + let check = "x.a.length() === 6 && x.a[5].b == '5' && x.*.length() === 6"; + assert!(fuel_stops(setup, "x.xpath('//b[. > 2]/preceding::*')", check) > 0); + assert!(heap_stops(setup, "x.xpath((SPARE, '//b[contains(concat(., ., .), \"3\")] | //a'))", check) > 0); + let mut r = realm(); + r.run("var x = ; for (var i = 0; i < 500; i++) x.appendChild();").unwrap(); + let interrupt = r.interrupt(); + r.define_function("stop", move |_| { + interrupt.set(); + Ok(JsValue::Undefined) + }); + assert_eq!(r.run("stop(); x.xpath('//a/following::a')").map_err(|e| e.kind), Err(RunErrorKind::Limit(LimitKind::Interrupted))); +} + +#[test] +fn xpath_walks_of_deep_trees_and_long_lists_count_against_the_heap_limit() { + let deep = "var s = ''; for (var i = 0; i < 5000; i++) s += ''; s += ''; for (var i = 0; i < 5000; i++) s += ''; var x = new XML(s);"; + for (action, room) in [ + ("x.xpath('descendant::c').length()", JsValue::Number(0.0)), + ("x.xpath('self::*[string() = \"q\"]').length()", JsValue::Number(0.0)), + ("x.xpath('descendant::b | self::a').length()", JsValue::Number(2.0)), + ] { + for (spare, want) in [(20_000, Err(RunErrorKind::Limit(LimitKind::Heap))), (50_000_000, Ok(room.clone()))] { + let mut r = Realm::with_options(Options { max_depth: 1_000_000, ..e4x() }, Limits::default()); + let interp = r.interp(); + let global = interp.global; + assert!(crate::builtins::method(interp, global, "squeeze", squeeze, 1).is_ok()); + r.run(deep).unwrap(); + assert_eq!(r.run(&format!("squeeze({spare}); {action}")).map_err(|e| e.kind), want, "{action} {spare}"); + } + } + let long = "var s = ''; for (var i = 0; i < 20000; i++) s += ''; var l = new XML(s + '').a;"; + assert_eq!(after_setup(long, "squeeze(50000); l.xpath('self::c').length()"), Err(RunErrorKind::Limit(LimitKind::Heap))); + assert_eq!(after_setup(long, "squeeze(50000000); l.xpath('self::c').length()"), Ok(JsValue::Number(0.0))); +} + +#[test] +fn xpath_reading_a_long_string_takes_fuel_for_its_length() { + let setup = "var s = 'x'; for (var i = 0; i < 20; i++) s += s; var x = ; for (var i = 0; i < 200; i++) x.appendChild(y);"; + for expr in ["a[string-length($s) = 1]", "a[starts-with($s, $s) = false()]", "a[$s = concat('', 'x')]", "a[number($s) = 1]", "a[. = $s]"] { + let mut r = realm(); + r.run(setup).unwrap(); + let src = format!("x.xpath({expr:?}, {{ s: s }}).length()"); + assert_eq!(r.run(&src), Ok(JsValue::Number(0.0)), "{expr}"); + r.set_limits(Limits { fuel: 2_000_000, ..Limits::default() }); + assert_eq!(r.run(&src).map_err(|e| e.kind), Err(RunErrorKind::Limit(LimitKind::Fuel)), "{expr}"); + } +} + +#[test] +fn xpath_string_functions_hold_the_bytes_they_build() { + let setup = "var s = 'x'; for (var i = 0; i < 20; i++) s += s; var d = '1'; for (var i = 0; i < 20; i++) d += d; var o = { s: s, d: d };"; + for (expr, spare) in [("translate('a', 'b', $s) = 'a'", 1_000_000), ("number($d) > 1", 500_000), ("substring($s, 1) != 'z'", 4_000_000)] { + let action = |spare: u32| format!("squeeze({spare}); ().xpath(\"self::*[{expr}]\", o).length()"); + assert_eq!(after_setup(setup, &action(spare)), Err(RunErrorKind::Limit(LimitKind::Heap)), "{expr}"); + assert_eq!(after_setup(setup, &action(100_000_000)), Ok(JsValue::Number(1.0)), "{expr}"); + } +} + +#[test] +fn xpath_string_variables_hold_the_bytes_of_their_flat_copy() { + // The setup ends with `0` so that its completion value does not flatten `s`. + let setup = "var s = 'x'; for (var i = 0; i < 20; i++) s += s; var o = { s: s }; 0;"; + let action = |spare: u32| format!("squeeze({spare}); ().xpath('self::*[$s]', o).length()"); + assert_eq!(after_setup(setup, &action(1_000_000)), Err(RunErrorKind::Limit(LimitKind::Heap))); + assert_eq!(after_setup(setup, &action(100_000_000)), Ok(JsValue::Number(1.0))); +} + +#[test] +fn xpath_substring_searches_take_fuel_for_every_position_tried() { + let setup = "var h = 'a'; for (var i = 0; i < 16; i++) h += h; var n = h.substring(0, 4095) + 'b'; var o = { h: h, n: n };"; + for expr in ["contains($h, $n)", "substring-before($h, $n) = ''", "substring-after($h, $n) = ''"] { + let mut r = realm(); + r.run(setup).unwrap(); + let src = format!("().xpath(\"self::*[{expr}]\", o).length()"); + let want = if expr.starts_with("contains") { 0.0 } else { 1.0 }; + assert_eq!(r.run(&src), Ok(JsValue::Number(want)), "{expr}"); + r.set_limits(Limits { fuel: 5_000_000, ..Limits::default() }); + assert_eq!(r.run(&src).map_err(|e| e.kind), Err(RunErrorKind::Limit(LimitKind::Fuel)), "{expr}"); + } +} + +#[test] +fn xpath_lang_takes_fuel_for_every_attribute_it_reads() { + let setup = "var s = '');"; + let mut r = realm(); + r.run(setup).unwrap(); + let src = "x.xpath('a[lang(\"en\")]').length()"; + assert_eq!(r.run(src), Ok(JsValue::Number(0.0))); + r.set_limits(Limits { fuel: 2_000_000, ..Limits::default() }); + assert_eq!(r.run(src).map_err(|e| e.kind), Err(RunErrorKind::Limit(LimitKind::Fuel))); +} + +#[test] +fn xpath_on_a_large_tree_ends_within_the_default_limits() { + let setup = "var x = ; for (var i = 0; i < 3000; i++) x.appendChild();"; + truth(&format!("{setup} x.xpath('//a[@n = 2999]/b').length() === 1 && x.xpath('//b/..').length() === 3000")); + let mut r = realm(); + r.run("var x = ; for (var i = 0; i < 2000; i++) x.appendChild();").unwrap(); + r.set_limits(Limits { fuel: 2_000_000, ..Limits::default() }); + assert_eq!(r.run("x.xpath('//a/following::a')").map_err(|e| e.kind), Err(RunErrorKind::Limit(LimitKind::Fuel))); +} + +const XPATH_PIECES: &[&str] = &[ + "/", + "//", + "a", + "b", + "*", + "@", + "@*", + ".", + "..", + "[", + "]", + "(", + ")", + "1", + "'x'", + "$v", + "|", + "+", + "-", + "=", + "!=", + "<", + ">=", + " and ", + " or ", + " div ", + " mod ", + "child::", + "following::", + "preceding::", + "ancestor::", + "namespace::", + "node()", + "text()", + "count(", + "last()", + "position()", + "concat(", + "substring(", + ",", + "p:", + "p:*", + "xml:lang", + "::", + ":", + "'", + " ", +]; + +proptest! { + #![proptest_config(ProptestConfig::with_cases(256))] + + #[test] + fn random_xpath_expressions_select_nodes_or_throw(parts in proptest::collection::vec(0..XPATH_PIECES.len(), 0..30)) { + let expr: String = parts.iter().map(|&i| XPATH_PIECES[i]).collect(); + let quoted = format!("{expr:?}"); + let src = format!("var x = 23t; typeof XML.prototype.xpath === 'function' && x.a[0].xpath({quoted}, {{ v: 1 }}).length() >= 0"); + let mut r = limited(Limits { fuel: 200_000, heap_bytes: 4 << 20, frames: 200, reentry: 8 }); + match r.run(&src) { + Ok(v) => prop_assert_eq!(v, JsValue::Bool(true), "{}", expr), + Err(e) => prop_assert!(matches!(e.kind, RunErrorKind::Thrown | RunErrorKind::Limit(_)), "{expr:?}: {e:?}"), + } + } +} + // ---- generated input ---- const PIECES: &[&str] = &[ diff --git a/crates/js/src/xpath.rs b/crates/js/src/xpath.rs new file mode 100644 index 0000000000..6ff84f1508 --- /dev/null +++ b/crates/js/src/xpath.rs @@ -0,0 +1,2381 @@ +//! `xpath` on XML and XMLList values: XPath 1.0 expressions +//! () evaluated on E4X trees. +//! +//! An expression is read into tokens, then into a syntax tree whose nodes live in one arena, and is +//! evaluated with an explicit task stack, so neither step uses native recursion. Brackets nest at +//! most [`crate::Options::max_depth`] deep. Every token, task and visited node takes fuel, and the +//! token, tree, node-set and string buffers are held against the heap limit while they live. +//! +//! `/` is a root node above the topmost node of the context node's tree. A node-set result is +//! returned as an XMLList of the selected nodes themselves, in document order with attributes +//! before children. The root node and namespace nodes can be selected and tested inside an +//! expression, but a result that holds one throws a `TypeError`, since E4X has no such value. The +//! tree keeps no DTD, so `id()` selects nothing. Prefixes in the expression are read from the +//! namespaces in scope on the context element, and `xml` is always bound. + +use std::collections::{HashMap, HashSet}; +use std::mem::replace; +use std::rc::Rc; + +use crate::builtins::arg; +use crate::error::TOO_DEEP; +use crate::heap::{Key, ObjId, XmlKind, XmlName, XmlNs, key}; +use crate::interp::{Abrupt, ErrorType, HeldBytes, Interp, JsResult}; +use crate::regexp_vm::use_fuel_n; +use crate::string_builtins::{self, charge_units, flat_charged, push_held}; +use crate::value::Value; +use crate::xml::{Xv, is_name_part, is_name_start, is_xml_space, valid_xml_units}; +use crate::xml_builtins::scope_of; + +const XML_URI: &str = "http://www.w3.org/XML/1998/namespace"; +const COLON: u16 = b':' as u16; +const STAR: u16 = b'*' as u16; +const SLASH: u16 = b'/' as u16; +const DOT: u16 = b'.' as u16; +const EQUALS: u16 = b'=' as u16; +const DASH: u16 = b'-' as u16; +/// The estimated bytes of a syntax tree node's own lists, beyond its slot in the arena. +const EXPR_BYTES: usize = 64; +/// The estimated bytes of one entry of a hash map or set the evaluator keeps. +const ENTRY_BYTES: usize = 64; + +fn empty() -> Key { + Rc::from(Vec::new()) +} + +fn syntax(interp: &mut Interp, message: &str) -> Abrupt { + interp.throw(ErrorType::Syntax, message) +} + +fn internal() -> Abrupt { + Abrupt::Internal("XPath evaluation state".into()) +} + +fn is_digit(c: u16) -> bool { + (0x30..=0x39).contains(&c) +} + +// ---- tokens ---- + +#[derive(Clone, Copy, PartialEq)] +enum Punct { + LParen, + RParen, + LBracket, + RBracket, + Dot, + DotDot, + At, + Comma, + ColonColon, + Slash, + SlashSlash, + Pipe, + Plus, + Minus, + Eq, + Ne, + Lt, + Le, + Gt, + Ge, +} + +/// A token as the lexer reads it, before names and `*` are told apart by their position. +enum Raw { + Punct(Punct), + Star, + Name(Option, Key), + PrefixStar(Key), + Literal(Key), + Number(f64), + Var(Key), +} + +#[derive(Clone, Copy, PartialEq)] +enum Axis { + Ancestor, + AncestorOrSelf, + Attribute, + Child, + Descendant, + DescendantOrSelf, + Following, + FollowingSibling, + Namespace, + Parent, + Preceding, + PrecedingSibling, + Itself, +} + +const AXES: [(&str, Axis); 13] = [ + ("ancestor", Axis::Ancestor), + ("ancestor-or-self", Axis::AncestorOrSelf), + ("attribute", Axis::Attribute), + ("child", Axis::Child), + ("descendant", Axis::Descendant), + ("descendant-or-self", Axis::DescendantOrSelf), + ("following", Axis::Following), + ("following-sibling", Axis::FollowingSibling), + ("namespace", Axis::Namespace), + ("parent", Axis::Parent), + ("preceding", Axis::Preceding), + ("preceding-sibling", Axis::PrecedingSibling), + ("self", Axis::Itself), +]; + +impl Axis { + /// Whether the axis lists its nodes in reverse document order. + fn reverse(self) -> bool { + matches!(self, Axis::Ancestor | Axis::AncestorOrSelf | Axis::Preceding | Axis::PrecedingSibling) + } +} + +/// A node test. A prefix is resolved when the expression runs. +#[derive(Clone)] +enum Test { + Any, + Prefix(Key), + Name(Option, Key), + Node, + Text, + Comment, + Pi(Option), +} + +#[derive(Clone, Copy, PartialEq)] +enum Bin { + Or, + And, + Eq, + Ne, + Lt, + Le, + Gt, + Ge, + Add, + Sub, + Mul, + Div, + Mod, + Union, +} + +impl Bin { + fn precedence(self) -> u8 { + match self { + Bin::Or => 1, + Bin::And => 2, + Bin::Eq | Bin::Ne => 3, + Bin::Lt | Bin::Le | Bin::Gt | Bin::Ge => 4, + Bin::Add | Bin::Sub => 5, + Bin::Mul | Bin::Div | Bin::Mod => 6, + Bin::Union => 8, + } + } +} + +/// The precedence of unary minus: tighter than `*`, looser than `|`. +const NEG_PRECEDENCE: u8 = 7; + +#[derive(Clone, Copy, PartialEq)] +enum Func { + Last, + Position, + Count, + Id, + LocalName, + NamespaceUri, + Name, + String, + Concat, + StartsWith, + Contains, + SubstringBefore, + SubstringAfter, + Substring, + StringLength, + NormalizeSpace, + Translate, + Boolean, + Not, + True, + False, + Lang, + Number, + Sum, + Floor, + Ceiling, + Round, +} + +/// The core function library (XPath 1.0 section 4): each name, and its least and most arguments. +const FUNCS: [(&str, Func, usize, usize); 27] = [ + ("last", Func::Last, 0, 0), + ("position", Func::Position, 0, 0), + ("count", Func::Count, 1, 1), + ("id", Func::Id, 1, 1), + ("local-name", Func::LocalName, 0, 1), + ("namespace-uri", Func::NamespaceUri, 0, 1), + ("name", Func::Name, 0, 1), + ("string", Func::String, 0, 1), + ("concat", Func::Concat, 2, usize::MAX), + ("starts-with", Func::StartsWith, 2, 2), + ("contains", Func::Contains, 2, 2), + ("substring-before", Func::SubstringBefore, 2, 2), + ("substring-after", Func::SubstringAfter, 2, 2), + ("substring", Func::Substring, 2, 3), + ("string-length", Func::StringLength, 0, 1), + ("normalize-space", Func::NormalizeSpace, 0, 1), + ("translate", Func::Translate, 3, 3), + ("boolean", Func::Boolean, 1, 1), + ("not", Func::Not, 1, 1), + ("true", Func::True, 0, 0), + ("false", Func::False, 0, 0), + ("lang", Func::Lang, 1, 1), + ("number", Func::Number, 0, 1), + ("sum", Func::Sum, 1, 1), + ("floor", Func::Floor, 1, 1), + ("ceiling", Func::Ceiling, 1, 1), + ("round", Func::Round, 1, 1), +]; + +/// A token the parser reads: names and `*` with their roles decided (XPath 1.0 section 3.7). +enum Tok { + Punct(Punct), + Op(Bin), + Test(Test), + Axis(Axis), + Func(Func, &'static str), + Literal(Key), + Number(f64), + Var(Key), +} + +fn ncname_end(src: &[u16], at: usize) -> Option { + let first = *src.get(at)?; + if first == COLON || !is_name_start(first) { + return None; + } + let mut end = at + 1; + while src.get(end).is_some_and(|&c| c != COLON && is_name_part(c)) { + end += 1; + } + valid_xml_units(src.get(at..end)?).then_some(end) +} + +fn lex_name(src: &[u16], at: usize) -> Option<(Raw, usize)> { + let end = ncname_end(src, at)?; + let first: Key = Rc::from(src.get(at..end)?); + if src.get(end) != Some(&COLON) || src.get(end + 1) == Some(&COLON) { + return Some((Raw::Name(None, first), end)); + } + if src.get(end + 1) == Some(&STAR) { + return Some((Raw::PrefixStar(first), end + 2)); + } + let local_end = ncname_end(src, end + 1)?; + Some((Raw::Name(Some(first), Rc::from(src.get(end + 1..local_end)?)), local_end)) +} + +fn lex_number(src: &[u16], at: usize) -> Option<(Raw, usize)> { + let mut end = at; + while src.get(end).copied().is_some_and(is_digit) { + end += 1; + } + if src.get(end) == Some(&DOT) { + end += 1; + while src.get(end).copied().is_some_and(is_digit) { + end += 1; + } + } + let text = String::from_utf16(src.get(at..end)?).ok()?; + Some((Raw::Number(text.parse().ok()?), end)) +} + +fn lex_literal(src: &[u16], at: usize, quote: u16) -> Option<(Raw, usize)> { + let rest = src.get(at + 1..)?; + let len = rest.iter().position(|&c| c == quote)?; + Some((Raw::Literal(Rc::from(rest.get(..len)?)), at + len + 2)) +} + +fn lex_var(src: &[u16], at: usize) -> Option<(Raw, usize)> { + let (Raw::Name(..), end) = lex_name(src, at + 1)? else { return None }; + Some((Raw::Var(Rc::from(src.get(at + 1..end)?)), end)) +} + +/// The token that starts at `src[at]`, and the offset after it. +fn lex_one(src: &[u16], at: usize, c: u16) -> Option<(Raw, usize)> { + if c != COLON && is_name_start(c) { + return lex_name(src, at); + } + let next = src.get(at + 1).copied(); + let p = |p: Punct, n: usize| Some((Raw::Punct(p), at + n)); + match char::from_u32(u32::from(c))? { + '(' => p(Punct::LParen, 1), + ')' => p(Punct::RParen, 1), + '[' => p(Punct::LBracket, 1), + ']' => p(Punct::RBracket, 1), + '@' => p(Punct::At, 1), + ',' => p(Punct::Comma, 1), + '|' => p(Punct::Pipe, 1), + '+' => p(Punct::Plus, 1), + '-' => p(Punct::Minus, 1), + '=' => p(Punct::Eq, 1), + '*' => Some((Raw::Star, at + 1)), + '/' if next == Some(SLASH) => p(Punct::SlashSlash, 2), + '/' => p(Punct::Slash, 1), + ':' if next == Some(COLON) => p(Punct::ColonColon, 2), + '!' if next == Some(EQUALS) => p(Punct::Ne, 2), + '<' if next == Some(EQUALS) => p(Punct::Le, 2), + '<' => p(Punct::Lt, 1), + '>' if next == Some(EQUALS) => p(Punct::Ge, 2), + '>' => p(Punct::Gt, 1), + '.' if next == Some(DOT) => p(Punct::DotDot, 2), + '.' if next.is_some_and(is_digit) => lex_number(src, at), + '.' => p(Punct::Dot, 1), + '"' | '\'' => lex_literal(src, at, c), + '$' => lex_var(src, at), + _ if is_digit(c) => lex_number(src, at), + _ => None, + } +} + +fn lex(interp: &mut Interp, held: &mut HeldBytes, src: &[u16]) -> JsResult> { + let mut out = Vec::new(); + let mut at = 0; + loop { + while src.get(at).copied().is_some_and(is_xml_space) { + at += 1; + } + let Some(&c) = src.get(at) else { return Ok(out) }; + let Some((raw, end)) = lex_one(src, at, c) else { + return Err(syntax(interp, &format!("the XPath expression cannot be read at offset {at}"))); + }; + charge_units(interp, end - at)?; + push_held(interp, held, &mut out, raw)?; + at = end; + } +} + +fn units_are(units: &[u16], text: &str) -> bool { + units.iter().copied().eq(text.encode_utf16()) +} + +fn operator_name(name: &[u16]) -> Option { + [("and", Bin::And), ("or", Bin::Or), ("mod", Bin::Mod), ("div", Bin::Div)].into_iter().find(|(n, _)| units_are(name, n)).map(|(_, b)| b) +} + +fn punct_token(p: Punct) -> Tok { + match p { + Punct::Pipe => Tok::Op(Bin::Union), + Punct::Plus => Tok::Op(Bin::Add), + Punct::Minus => Tok::Op(Bin::Sub), + Punct::Eq => Tok::Op(Bin::Eq), + Punct::Ne => Tok::Op(Bin::Ne), + Punct::Lt => Tok::Op(Bin::Lt), + Punct::Le => Tok::Op(Bin::Le), + Punct::Gt => Tok::Op(Bin::Gt), + Punct::Ge => Tok::Op(Bin::Ge), + other => Tok::Punct(other), + } +} + +/// Whether a token at this point is an operator: there is a token before it, and it is not `@`, +/// `::`, `(`, `[`, `,` or an operator (XPath 1.0 section 3.7). +fn operator_position(last: Option<&Tok>) -> bool { + last.is_some_and(|t| { + !matches!( + t, + Tok::Punct(Punct::LParen | Punct::LBracket | Punct::At | Punct::Comma | Punct::Slash | Punct::SlashSlash) + | Tok::Op(_) + | Tok::Axis(_) + | Tok::Func(..) + ) + }) +} + +/// A name followed by `(`: a node type test, which also takes its `)`, or a function call. +/// Returns the token and how many raw tokens it takes. +fn call_or_node_type(interp: &mut Interp, prefix: Option<&Key>, name: &Key, after: &[Raw]) -> JsResult<(Tok, usize)> { + if prefix.is_none() { + let plain = [("node", Test::Node), ("text", Test::Text), ("comment", Test::Comment)].into_iter().find(|(n, _)| units_are(name, n)); + if let Some((_, test)) = plain { + return match after.first() { + Some(Raw::Punct(Punct::RParen)) => Ok((Tok::Test(test), 3)), + _ => Err(syntax(interp, "an XPath node type test takes no argument")), + }; + } + if units_are(name, "processing-instruction") { + return match after { + [Raw::Punct(Punct::RParen), ..] => Ok((Tok::Test(Test::Pi(None)), 3)), + [Raw::Literal(target), Raw::Punct(Punct::RParen), ..] => Ok((Tok::Test(Test::Pi(Some(target.clone()))), 4)), + _ => Err(syntax(interp, "processing-instruction() takes one string literal or none")), + }; + } + } + let found = FUNCS.iter().find(|(n, ..)| prefix.is_none() && units_are(name, n)); + match found { + Some(&(n, f, ..)) => Ok((Tok::Func(f, n), 2)), + None => { + let shown = String::from_utf16_lossy(name); + Err(interp.type_error(&format!("{shown} is not an XPath 1.0 function"))) + } + } +} + +fn classify(interp: &mut Interp, held: &mut HeldBytes, raw: &[Raw]) -> JsResult> { + let mut out: Vec = Vec::new(); + let mut at = 0; + while let Some(r) = raw.get(at) { + interp.use_fuel()?; + let operator = operator_position(out.last()); + let next = raw.get(at + 1); + let (tok, used) = match r { + Raw::Star if operator => (Tok::Op(Bin::Mul), 1), + Raw::Star => (Tok::Test(Test::Any), 1), + Raw::Name(None, n) if operator => match operator_name(n) { + Some(op) => (Tok::Op(op), 1), + None => return Err(syntax(interp, "an XPath operator is missing")), + }, + Raw::Name(p, n) if matches!(next, Some(Raw::Punct(Punct::LParen))) => { + call_or_node_type(interp, p.as_ref(), n, raw.get(at + 2..).unwrap_or_default())? + } + Raw::Name(p, n) if matches!(next, Some(Raw::Punct(Punct::ColonColon))) => { + let axis = AXES.iter().find(|(a, _)| p.is_none() && units_are(n, a)).map(|&(_, a)| a); + match axis { + Some(a) => (Tok::Axis(a), 2), + None => return Err(syntax(interp, &format!("{} is not an XPath axis", String::from_utf16_lossy(n)))), + } + } + Raw::Name(p, n) => (Tok::Test(Test::Name(p.clone(), n.clone())), 1), + Raw::PrefixStar(p) => (Tok::Test(Test::Prefix(p.clone())), 1), + Raw::Punct(Punct::ColonColon) => return Err(syntax(interp, "an XPath axis name is missing before ::")), + Raw::Punct(p) => (punct_token(*p), 1), + Raw::Literal(s) => (Tok::Literal(s.clone()), 1), + Raw::Number(n) => (Tok::Number(*n), 1), + Raw::Var(v) => (Tok::Var(v.clone()), 1), + }; + push_held(interp, held, &mut out, tok)?; + at += used; + } + Ok(out) +} + +// ---- the syntax tree ---- + +struct Step { + axis: Axis, + test: Test, + preds: Vec, +} + +enum Expr { + Bin(Bin, usize, usize), + Neg(usize), + Num(f64), + Lit(Key), + Var(usize), + Call(Func, Vec), + /// A location path, or a filter expression with its predicates, followed by steps. + Path { + filter: Option<(usize, Vec)>, + absolute: bool, + steps: Vec, + }, +} + +/// A parsed expression: the tree in its arena, its root, and the variables and prefixes it names. +struct Parsed { + exprs: Vec, + root: usize, + vars: Vec, + prefixes: Vec, + _held: HeldBytes, +} + +#[derive(Clone, Copy)] +enum Op { + Bin(Bin), + Neg, +} + +impl Op { + fn precedence(self) -> u8 { + match self { + Op::Bin(b) => b.precedence(), + Op::Neg => NEG_PRECEDENCE, + } + } +} + +/// A path expression being read. +#[derive(Default)] +struct Operand { + filter: Option<(usize, Vec)>, + absolute: bool, + steps: Vec, + /// The last step is `.` or `..`, which take no predicate. + abbreviated: bool, +} + +impl Operand { + fn bare_root(&self) -> bool { + self.absolute && self.steps.is_empty() && self.filter.is_none() + } +} + +enum FrameKind { + Top, + Group, + Pred, + Args(Func, &'static str, Vec), +} + +/// One bracket level: its operators and operands, read by operator precedence. +struct Frame { + kind: FrameKind, + ops: Vec, + vals: Vec, + operand: Option, +} + +impl Frame { + fn new(kind: FrameKind) -> Self { + Frame { kind, ops: Vec::new(), vals: Vec::new(), operand: None } + } +} + +#[derive(Clone, Copy, PartialEq)] +enum Want { + Operand, + Step, + Test(Axis), + After, +} + +struct Parser<'i> { + interp: &'i mut Interp, + held: HeldBytes, + exprs: Vec, + vars: Vec, + var_index: HashMap, + prefixes: HashSet, + frames: Vec, + want: Want, +} + +impl Parser<'_> { + fn error(&mut self, message: &str) -> Abrupt { + syntax(self.interp, message) + } + + fn push_expr(&mut self, e: Expr) -> JsResult { + self.held.add(self.interp, EXPR_BYTES)?; + push_held(self.interp, &mut self.held, &mut self.exprs, e)?; + Ok(self.exprs.len() - 1) + } + + fn top(&mut self) -> JsResult<&mut Frame> { + self.frames.last_mut().ok_or_else(internal) + } + + fn operand(&mut self) -> JsResult<&mut Operand> { + self.top()?.operand.as_mut().ok_or_else(internal) + } + + fn open(&mut self, kind: FrameKind) -> JsResult<()> { + if self.frames.len() >= self.interp.options.max_depth { + return Err(self.error(TOO_DEEP)); + } + self.held.add(self.interp, size_of::())?; + self.frames.push(Frame::new(kind)); + self.want = Want::Operand; + Ok(()) + } + + fn token(&mut self, tok: Tok) -> JsResult<()> { + match self.want { + Want::Operand => self.operand_token(tok), + Want::Step => self.step_token(tok), + Want::Test(axis) => match tok { + Tok::Test(test) => self.push_step(axis, test, false), + _ => Err(self.error("an XPath node test is missing")), + }, + Want::After => self.after_token(tok), + } + } + + fn primary(&mut self, e: Expr) -> JsResult<()> { + let id = self.push_expr(e)?; + self.top()?.operand = Some(Operand { filter: Some((id, Vec::new())), ..Operand::default() }); + self.want = Want::After; + Ok(()) + } + + fn operand_token(&mut self, tok: Tok) -> JsResult<()> { + match tok { + Tok::Op(Bin::Sub) => { + self.top()?.ops.push(Op::Neg); + Ok(()) + } + Tok::Punct(Punct::Slash) => { + self.top()?.operand = Some(Operand { absolute: true, ..Operand::default() }); + self.want = Want::Step; + Ok(()) + } + Tok::Punct(Punct::SlashSlash) => { + self.top()?.operand = Some(Operand { absolute: true, ..Operand::default() }); + self.descendants_step() + } + Tok::Literal(s) => self.primary(Expr::Lit(s)), + Tok::Number(n) => self.primary(Expr::Num(n)), + Tok::Var(name) => { + let next = self.vars.len(); + let at = *self.var_index.entry(name.clone()).or_insert(next); + if at == next { + push_held(self.interp, &mut self.held, &mut self.vars, name)?; + } + self.primary(Expr::Var(at)) + } + Tok::Func(f, n) => self.open(FrameKind::Args(f, n, Vec::new())), + Tok::Punct(Punct::LParen) => self.open(FrameKind::Group), + Tok::Punct(Punct::RParen) if self.empty_call()? => self.close_paren(), + tok @ (Tok::Test(_) | Tok::Axis(_) | Tok::Punct(Punct::At | Punct::Dot | Punct::DotDot)) => { + self.top()?.operand = Some(Operand::default()); + self.step_token(tok) + } + _ => Err(self.error("an XPath operand is missing")), + } + } + + /// Whether the open bracket is a function call's, with nothing in it yet. + fn empty_call(&mut self) -> JsResult { + let f = self.top()?; + Ok(matches!(&f.kind, FrameKind::Args(_, _, args) if args.is_empty()) && f.ops.is_empty() && f.vals.is_empty() && f.operand.is_none()) + } + + fn descendants_step(&mut self) -> JsResult<()> { + self.operand()?.steps.push(Step { axis: Axis::DescendantOrSelf, test: Test::Node, preds: Vec::new() }); + self.want = Want::Step; + Ok(()) + } + + fn push_step(&mut self, axis: Axis, test: Test, abbreviated: bool) -> JsResult<()> { + if let Test::Prefix(p) | Test::Name(Some(p), _) = &test + && !self.prefixes.contains(p) + { + self.held.add(self.interp, ENTRY_BYTES)?; + self.prefixes.insert(p.clone()); + } + self.held.add(self.interp, size_of::())?; + let operand = self.operand()?; + operand.steps.push(Step { axis, test, preds: Vec::new() }); + operand.abbreviated = abbreviated; + self.want = Want::After; + Ok(()) + } + + fn step_token(&mut self, tok: Tok) -> JsResult<()> { + match tok { + Tok::Punct(Punct::Dot) => self.push_step(Axis::Itself, Test::Node, true), + Tok::Punct(Punct::DotDot) => self.push_step(Axis::Parent, Test::Node, true), + Tok::Punct(Punct::At) => { + self.want = Want::Test(Axis::Attribute); + Ok(()) + } + Tok::Axis(a) => { + self.want = Want::Test(a); + Ok(()) + } + Tok::Test(t) => self.push_step(Axis::Child, t, false), + tok if self.operand()?.bare_root() => { + self.want = Want::After; + self.after_token(tok) + } + _ => Err(self.error("an XPath step is missing")), + } + } + + fn after_token(&mut self, tok: Tok) -> JsResult<()> { + match tok { + Tok::Punct(p @ (Punct::LBracket | Punct::Slash | Punct::SlashSlash)) => { + let operand = self.operand()?; + let (bare, abbreviated) = (operand.bare_root(), operand.abbreviated); + if bare || (p == Punct::LBracket && abbreviated) { + return Err(self.error("an XPath predicate or step cannot follow here")); + } + match p { + Punct::LBracket => self.open(FrameKind::Pred), + Punct::Slash => { + self.want = Want::Step; + Ok(()) + } + _ => self.descendants_step(), + } + } + Tok::Op(b) => self.binary(b), + Tok::Punct(Punct::RParen) => self.close_paren(), + Tok::Punct(Punct::RBracket) => self.close_bracket(), + Tok::Punct(Punct::Comma) => self.next_argument(), + _ => Err(self.error("an XPath operator is missing")), + } + } + + fn finish_operand(&mut self, operand: Operand) -> JsResult { + match operand { + Operand { filter: Some((e, preds)), steps, .. } if preds.is_empty() && steps.is_empty() => Ok(e), + Operand { filter, absolute, steps, .. } => self.push_expr(Expr::Path { filter, absolute, steps }), + } + } + + fn reduce_one(&mut self, frame: &mut Frame) -> JsResult<()> { + let op = frame.ops.pop().ok_or_else(internal)?; + let rhs = frame.vals.pop().ok_or_else(internal)?; + let e = match op { + Op::Neg => Expr::Neg(rhs), + Op::Bin(b) => Expr::Bin(b, frame.vals.pop().ok_or_else(internal)?, rhs), + }; + let id = self.push_expr(e)?; + frame.vals.push(id); + Ok(()) + } + + fn binary(&mut self, b: Bin) -> JsResult<()> { + let mut frame = self.frames.pop().ok_or_else(internal)?; + let result = self.binary_in(&mut frame, b); + self.frames.push(frame); + result?; + self.want = Want::Operand; + Ok(()) + } + + fn binary_in(&mut self, frame: &mut Frame, b: Bin) -> JsResult<()> { + let operand = frame.operand.take().ok_or_else(internal)?; + let e = self.finish_operand(operand)?; + frame.vals.push(e); + while frame.ops.last().is_some_and(|op| op.precedence() >= b.precedence()) { + self.interp.use_fuel()?; + self.reduce_one(frame)?; + } + self.held.add(self.interp, 2 * size_of::())?; + frame.ops.push(Op::Bin(b)); + Ok(()) + } + + /// Ends the innermost bracket and returns its kind and expression. + fn close(&mut self) -> JsResult<(FrameKind, usize)> { + if self.frames.len() < 2 { + return Err(self.error("the XPath expression has an unmatched closing bracket")); + } + let mut frame = self.frames.pop().ok_or_else(internal)?; + let e = self.reduce(&mut frame)?; + Ok((frame.kind, e)) + } + + fn reduce(&mut self, frame: &mut Frame) -> JsResult { + let operand = frame.operand.take().ok_or_else(|| syntax(self.interp, "an XPath operand is missing"))?; + let e = self.finish_operand(operand)?; + frame.vals.push(e); + while !frame.ops.is_empty() { + self.interp.use_fuel()?; + self.reduce_one(frame)?; + } + match frame.vals.as_slice() { + [e] => Ok(*e), + _ => Err(internal()), + } + } + + fn close_paren(&mut self) -> JsResult<()> { + let (kind, e) = if self.top()?.operand.is_none() { + (self.frames.pop().ok_or_else(internal)?.kind, None) + } else { + let (kind, e) = self.close()?; + (kind, Some(e)) + }; + match kind { + FrameKind::Group => self.primary_id(e.ok_or_else(internal)?), + FrameKind::Args(f, name, mut args) => { + args.extend(e); + let (_, _, least, most) = FUNCS.iter().find(|(_, g, ..)| *g == f).copied().ok_or_else(internal)?; + if args.len() < least || args.len() > most { + return Err(self.interp.type_error(&format!("the XPath function {name} takes the wrong number of arguments"))); + } + let call = self.push_expr(Expr::Call(f, args))?; + self.primary_id(call) + } + _ => Err(self.error("the XPath expression has an unmatched )")), + } + } + + fn primary_id(&mut self, id: usize) -> JsResult<()> { + if self.frames.is_empty() { + return Err(self.error("the XPath expression has an unmatched )")); + } + self.top()?.operand = Some(Operand { filter: Some((id, Vec::new())), ..Operand::default() }); + self.want = Want::After; + Ok(()) + } + + fn close_bracket(&mut self) -> JsResult<()> { + let (kind, e) = self.close()?; + if !matches!(kind, FrameKind::Pred) { + return Err(self.error("the XPath expression has an unmatched ]")); + } + let operand = self.operand()?; + match (operand.steps.last_mut(), operand.filter.as_mut()) { + (Some(step), _) => step.preds.push(e), + (None, Some((_, preds))) => preds.push(e), + (None, None) => return Err(internal()), + } + self.want = Want::After; + Ok(()) + } + + fn next_argument(&mut self) -> JsResult<()> { + if !matches!(self.top()?.kind, FrameKind::Args(..)) || self.frames.len() < 2 { + return Err(self.error("a comma in an XPath expression must separate function arguments")); + } + let mut frame = self.frames.pop().ok_or_else(internal)?; + let e = self.reduce(&mut frame); + if let (Ok(e), FrameKind::Args(_, _, args)) = (&e, &mut frame.kind) { + args.push(*e); + } + frame.ops.clear(); + frame.vals.clear(); + self.frames.push(frame); + e?; + self.want = Want::Operand; + Ok(()) + } + + fn finish(mut self) -> JsResult { + let complete = self.want == Want::After || (self.want == Want::Step && self.operand()?.bare_root()); + if !complete || self.frames.len() != 1 { + return Err(self.error("the XPath expression ends early")); + } + let mut frame = self.frames.pop().ok_or_else(internal)?; + let root = self.reduce(&mut frame)?; + Ok(Parsed { exprs: self.exprs, root, vars: self.vars, prefixes: self.prefixes.into_iter().collect(), _held: self.held }) + } +} + +fn parse(interp: &mut Interp, src: &[u16]) -> JsResult { + let mut held = HeldBytes::new(interp); + let raw = lex(interp, &mut held, src)?; + let toks = classify(interp, &mut held, &raw)?; + drop(raw); + let mut p = Parser { + interp, + held, + exprs: Vec::new(), + vars: Vec::new(), + var_index: HashMap::new(), + prefixes: HashSet::new(), + frames: vec![Frame::new(FrameKind::Top)], + want: Want::Operand, + }; + for tok in toks { + p.interp.use_fuel()?; + p.token(tok)?; + } + p.finish() +} + +// ---- values ---- + +/// A node of the XPath data model. `Root` is the root above the topmost node it names, and `Ns` +/// is a namespace node of `owner`, at position `at` among its namespaces. +#[derive(Clone, PartialEq, Eq, Hash)] +enum XNode { + Root(ObjId), + Node(ObjId), + Ns { owner: ObjId, at: u32, prefix: Key, uri: Key }, +} + +#[derive(Clone, Copy, PartialEq)] +enum NodeKind { + Root, + Ns, + Xml(XmlKind), +} + +/// A list of nodes whose buffer is held against the heap limit. +struct Nodes { + list: Vec, + held: HeldBytes, +} + +impl Nodes { + fn new(interp: &Interp) -> Self { + Nodes { list: Vec::new(), held: HeldBytes::new(interp) } + } + + fn push(&mut self, interp: &mut Interp, n: XNode) -> JsResult<()> { + push_held(interp, &mut self.held, &mut self.list, n) + } +} + +/// A string value whose units are held against the heap limit when the evaluator built them. +struct Text { + units: Key, + _held: HeldBytes, +} + +impl Text { + fn plain(interp: &Interp, units: Key) -> Self { + Text { units, _held: HeldBytes::new(interp) } + } +} + +struct TextBuf { + units: Vec, + held: HeldBytes, +} + +impl TextBuf { + fn new(interp: &Interp) -> Self { + TextBuf { units: Vec::new(), held: HeldBytes::new(interp) } + } + + fn push(&mut self, interp: &mut Interp, more: &[u16]) -> JsResult<()> { + charge_units(interp, more.len())?; + let want = self.units.len().saturating_add(more.len()); + let cap = self.units.capacity(); + if want > cap { + let grown = want.max(cap.saturating_mul(2)).max(16); + self.held.add(interp, (grown - cap).saturating_mul(2))?; + self.units.reserve_exact(grown - self.units.len()); + } + self.units.extend_from_slice(more); + Ok(()) + } + + fn finish(self) -> Text { + Text { units: Rc::from(self.units), _held: self.held } + } +} + +enum Val { + Set(Nodes), + Bool(bool), + Num(f64), + Str(Text), +} + +/// A variable's value, read from the variables object before evaluation starts. +enum Bound { + Set(Vec), + Bool(bool), + Num(f64), + Str(Key), +} + +#[derive(Clone)] +struct Ctx { + node: XNode, + pos: usize, + size: usize, +} + +/// A location path being evaluated. Stage 0 applies the filter expression's predicates to the +/// filter's nodes; stage `s` applies step `s - 1` to each node of `inputs` in turn. +struct PathRun { + path: usize, + stage: usize, + inputs: Nodes, + ci: usize, + cur: Nodes, + pred: usize, + at: usize, + kept: Nodes, + waiting: bool, + out: Nodes, + seen: HashSet, + seen_held: HeldBytes, +} + +enum Task { + Eval(usize, Ctx), + Bin(Bin), + Neg, + Logic { and: bool, rhs: usize, ctx: Ctx }, + Bool, + Call(Func, usize, Ctx), + PathStart(usize), + Path(Box), +} + +fn to_bool(v: &Val) -> bool { + match v { + Val::Set(s) => !s.list.is_empty(), + Val::Bool(b) => *b, + Val::Num(n) => *n != 0.0 && !n.is_nan(), + Val::Str(t) => !t.units.is_empty(), + } +} + +/// The number a string stands for (XPath 1.0 section 4.4): optional white space, an optional +/// minus, digits with an optional fraction, optional white space; anything else is NaN. +fn str_num(interp: &mut Interp, units: &[u16]) -> JsResult { + let start = units.iter().position(|&c| !is_xml_space(c)).unwrap_or(units.len()); + let end = units.iter().rposition(|&c| !is_xml_space(c)).map_or(start, |e| e + 1); + let body = units.get(start..end).unwrap_or_default(); + let (negative, digits) = match body.split_first() { + Some((&DASH, rest)) => (true, rest), + _ => (false, body), + }; + let dots = digits.iter().filter(|&&c| c == DOT).count(); + if dots > 1 || !digits.iter().all(|&c| c == DOT || is_digit(c)) || !digits.iter().any(|&c| is_digit(c)) { + return Ok(f64::NAN); + } + let mut held = HeldBytes::new(interp); + held.add(interp, digits.len())?; + let text: String = digits.iter().map(|&c| char::from(c as u8)).collect(); + let n: f64 = text.parse().unwrap_or(f64::NAN); + Ok(if negative { -n } else { n }) +} + +/// A number as a string (XPath 1.0 section 4.2): integers without a decimal point, and no +/// exponent. +fn num_text(n: f64) -> String { + if n.is_nan() { + "NaN".into() + } else if n.is_infinite() { + if n > 0.0 { "Infinity".into() } else { "-Infinity".into() } + } else if n == 0.0 { + "0".into() + } else { + format!("{n}") + } +} + +/// `round` (XPath 1.0 section 4.4): the nearest integer, halves toward positive infinity, with +/// negative zero for values from -0.5 up to zero. +fn round(n: f64) -> f64 { + if !n.is_finite() || n == 0.0 { + return n; + } + let floor = n.floor(); + let r = if n - floor >= 0.5 { floor + 1.0 } else { floor }; + if r == 0.0 && n < 0.0 { -0.0 } else { r } +} + +fn compare_numbers(op: Bin, a: f64, b: f64) -> bool { + match op { + Bin::Eq => a == b, + Bin::Ne => a != b, + Bin::Lt => a < b, + Bin::Le => a <= b, + Bin::Gt => a > b, + _ => a >= b, + } +} + +fn flip(op: Bin) -> Bin { + match op { + Bin::Lt => Bin::Gt, + Bin::Le => Bin::Ge, + Bin::Gt => Bin::Lt, + Bin::Ge => Bin::Le, + other => other, + } +} + +fn code_points(units: &[u16]) -> Vec { + char::decode_utf16(units.iter().copied()).map(|r| r.map_or_else(|e| u32::from(e.unpaired_surrogate()), u32::from)).collect() +} + +fn push_point(out: &mut Vec, p: u32) { + match char::from_u32(p) { + Some(c) => { + let mut buf = [0u16; 2]; + out.extend_from_slice(c.encode_utf16(&mut buf)); + } + None => out.extend(u16::try_from(p).ok()), + } +} + +fn lower(c: u16) -> u16 { + if (0x41..=0x5A).contains(&c) { c + 0x20 } else { c } +} + +fn same_ignoring_case(a: &[u16], b: &[u16]) -> bool { + a.len() == b.len() && a.iter().zip(b).all(|(&x, &y)| lower(x) == lower(y)) +} + +fn name_uri(name: &XmlName) -> &[u16] { + name.uri.as_deref().unwrap_or_default() +} + +fn kind_of(interp: &Interp, n: &XNode) -> JsResult { + Ok(match n { + XNode::Root(_) => NodeKind::Root, + XNode::Ns { .. } => NodeKind::Ns, + XNode::Node(x) => NodeKind::Xml(interp.xml_kind(*x)?), + }) +} + +fn parent_of(interp: &Interp, n: &XNode) -> JsResult> { + Ok(match n { + XNode::Root(_) => None, + XNode::Node(x) => Some(interp.xml_node(*x)?.parent.map_or(XNode::Root(*x), XNode::Node)), + XNode::Ns { owner, .. } => Some(XNode::Node(*owner)), + }) +} + +/// The parent of `x` and the position of `x` among its children, when `x` is a child. +fn child_position(interp: &mut Interp, x: ObjId) -> JsResult> { + let node = interp.xml_node(x)?; + let Some(p) = node.parent.filter(|_| node.kind != XmlKind::Attribute) else { return Ok(None) }; + let len = interp.xml_node(p)?.children.len(); + for i in 0..len { + interp.use_fuel()?; + if interp.xml_node(p)?.children.get(i) == Some(&x) { + return Ok(Some((p, i))); + } + } + Ok(None) +} + +fn top_of(interp: &mut Interp, mut x: ObjId) -> JsResult { + while let Some(p) = interp.xml_node(x)?.parent { + interp.use_fuel()?; + x = p; + } + Ok(x) +} + +/// The XPath expression evaluator for one call: the parsed expression, the variables, the +/// prefixes resolved for the current context element, and the document order of the trees met. +struct Ev<'p> { + parsed: &'p Parsed, + bound: Vec, + uris: HashMap, + order: HashMap, + root_order: HashMap, + next: u64, + held: HeldBytes, + tasks: Vec, + vals: Vec, +} + +impl<'p> Ev<'p> { + fn new(interp: &mut Interp, parsed: &'p Parsed, bound: Vec) -> JsResult { + let mut ev = Ev { + parsed, + bound: Vec::new(), + uris: HashMap::new(), + order: HashMap::new(), + root_order: HashMap::new(), + next: 0, + held: HeldBytes::new(interp), + tasks: Vec::new(), + vals: Vec::new(), + }; + for b in bound { + let b = match b { + Bound::Set(list) => { + let mut nodes = Nodes::new(interp); + for n in list { + nodes.push(interp, n)?; + } + let sorted = ev.sort(interp, nodes)?; + ev.held.add(interp, sorted.list.len().saturating_mul(size_of::()))?; + Bound::Set(sorted.list) + } + other => other, + }; + ev.bound.push(b); + } + Ok(ev) + } + + // ---- document order ---- + + fn put_order(&mut self, interp: &mut Interp, x: ObjId) -> JsResult<()> { + self.held.add(interp, ENTRY_BYTES)?; + self.order.insert(x, self.next); + self.next += 1; + Ok(()) + } + + /// Numbers the tree under `top` in document order: the root, then each node followed by its + /// attributes and then its children. + fn number_tree(&mut self, interp: &mut Interp, top: ObjId) -> JsResult<()> { + if self.root_order.contains_key(&top) { + return Ok(()); + } + self.held.add(interp, ENTRY_BYTES)?; + self.root_order.insert(top, self.next); + self.next += 1; + self.number_node(interp, top)?; + let mut held = HeldBytes::new(interp); + let mut stack = Vec::new(); + push_held(interp, &mut held, &mut stack, (top, 0usize))?; + while let Some(&(x, at)) = stack.last() { + interp.use_fuel()?; + let Some(c) = interp.xml_node(x)?.children.get(at).copied() else { + stack.pop(); + continue; + }; + if let Some(frame) = stack.last_mut() { + frame.1 += 1; + } + self.number_node(interp, c)?; + push_held(interp, &mut held, &mut stack, (c, 0))?; + } + Ok(()) + } + + fn number_node(&mut self, interp: &mut Interp, x: ObjId) -> JsResult<()> { + self.put_order(interp, x)?; + let count = interp.xml_node(x)?.attrs.len(); + for i in 0..count { + interp.use_fuel()?; + if let Some(a) = interp.xml_node(x)?.attrs.get(i).copied() { + self.put_order(interp, a)?; + } + } + Ok(()) + } + + fn order_of(&mut self, interp: &mut Interp, n: &XNode) -> JsResult<(u64, u32)> { + match n { + XNode::Root(t) => { + self.number_tree(interp, *t)?; + Ok((self.root_order.get(t).copied().ok_or_else(internal)?, 0)) + } + XNode::Node(x) => { + if !self.order.contains_key(x) { + let top = top_of(interp, *x)?; + self.number_tree(interp, top)?; + } + Ok((self.order.get(x).copied().ok_or_else(internal)?, 0)) + } + XNode::Ns { owner, at, .. } => { + let (o, _) = self.order_of(interp, &XNode::Node(*owner))?; + Ok((o, at.saturating_add(1))) + } + } + } + + /// The nodes in document order, without repeats. + fn sort(&mut self, interp: &mut Interp, set: Nodes) -> JsResult { + if set.list.len() < 2 { + return Ok(set); + } + let n = set.list.len() as u64; + let mut held = HeldBytes::new(interp); + let mut keyed = Vec::new(); + for x in set.list { + let k = self.order_of(interp, &x)?; + push_held(interp, &mut held, &mut keyed, (k, x))?; + } + use_fuel_n(interp, n.saturating_mul(u64::from(n.ilog2()) + 1) / 8 + 1)?; + keyed.sort_by_key(|(k, _)| *k); + keyed.dedup_by_key(|(k, _)| *k); + let mut out = Nodes::new(interp); + for (_, x) in keyed { + out.push(interp, x)?; + } + Ok(out) + } + + // ---- axes and node tests ---- + + fn prefix_uri(&self, p: &Key) -> JsResult<&Key> { + self.uris.get(p).ok_or_else(internal) + } + + fn matches(&self, interp: &Interp, axis: Axis, test: &Test, n: &XNode) -> JsResult { + let kind = kind_of(interp, n)?; + let principal = match axis { + Axis::Attribute => NodeKind::Xml(XmlKind::Attribute), + Axis::Namespace => NodeKind::Ns, + _ => NodeKind::Xml(XmlKind::Element), + }; + let name = match n { + XNode::Node(x) => interp.xml_node(*x)?.name.as_ref(), + _ => None, + }; + Ok(match test { + Test::Node => true, + Test::Text => kind == NodeKind::Xml(XmlKind::Text), + Test::Comment => kind == NodeKind::Xml(XmlKind::Comment), + Test::Pi(target) => kind == NodeKind::Xml(XmlKind::Pi) && target.as_ref().is_none_or(|t| name.is_some_and(|q| q.local == *t)), + Test::Any => kind == principal, + Test::Prefix(p) => { + let uri = self.prefix_uri(p)?; + kind == principal && name.is_some_and(|q| name_uri(q) == &**uri) + } + Test::Name(p, local) => kind == principal && self.name_matches(n, name, p.as_ref(), local)?, + }) + } + + fn name_matches(&self, n: &XNode, name: Option<&XmlName>, prefix: Option<&Key>, local: &Key) -> JsResult { + if let XNode::Ns { prefix: ns_prefix, .. } = n { + return Ok(prefix.is_none() && ns_prefix == local); + } + let Some(q) = name else { return Ok(false) }; + let uri: &[u16] = match prefix { + Some(p) => self.prefix_uri(p)?, + None => &[], + }; + Ok(q.local == *local && name_uri(q) == uri) + } + + fn add(&self, interp: &mut Interp, out: &mut Nodes, axis: Axis, test: &Test, n: XNode) -> JsResult<()> { + interp.use_fuel()?; + if self.matches(interp, axis, test, &n)? { + out.push(interp, n)?; + } + Ok(()) + } + + /// Adds `x` and the nodes under it, in document order. + fn subtree(&self, interp: &mut Interp, out: &mut Nodes, axis: Axis, test: &Test, x: ObjId) -> JsResult<()> { + self.add(interp, out, axis, test, XNode::Node(x))?; + self.under(interp, out, axis, test, x) + } + + /// Adds the nodes under `x`, in document order. + fn under(&self, interp: &mut Interp, out: &mut Nodes, axis: Axis, test: &Test, x: ObjId) -> JsResult<()> { + let mut held = HeldBytes::new(interp); + let mut stack = Vec::new(); + push_held(interp, &mut held, &mut stack, (x, 0usize))?; + while let Some(&(p, at)) = stack.last() { + let Some(c) = interp.xml_node(p)?.children.get(at).copied() else { + stack.pop(); + continue; + }; + if let Some(frame) = stack.last_mut() { + frame.1 += 1; + } + self.add(interp, out, axis, test, XNode::Node(c))?; + push_held(interp, &mut held, &mut stack, (c, 0))?; + } + Ok(()) + } + + fn descendants(&self, interp: &mut Interp, out: &mut Nodes, axis: Axis, test: &Test, n: &XNode) -> JsResult<()> { + match n { + XNode::Root(t) => self.subtree(interp, out, axis, test, *t), + XNode::Node(x) => self.under(interp, out, axis, test, *x), + XNode::Ns { .. } => Ok(()), + } + } + + fn children(&self, interp: &mut Interp, out: &mut Nodes, axis: Axis, test: &Test, n: &XNode) -> JsResult<()> { + let x = match n { + XNode::Root(t) => return self.add(interp, out, axis, test, XNode::Node(*t)), + XNode::Node(x) => *x, + XNode::Ns { .. } => return Ok(()), + }; + let count = interp.xml_node(x)?.children.len(); + for i in 0..count { + if let Some(c) = interp.xml_node(x)?.children.get(i).copied() { + self.add(interp, out, axis, test, XNode::Node(c))?; + } + } + Ok(()) + } + + fn ancestors(&self, interp: &mut Interp, out: &mut Nodes, axis: Axis, test: &Test, n: &XNode) -> JsResult<()> { + let mut cur = parent_of(interp, n)?; + while let Some(p) = cur { + cur = parent_of(interp, &p)?; + self.add(interp, out, axis, test, p)?; + } + Ok(()) + } + + fn siblings(&self, interp: &mut Interp, out: &mut Nodes, axis: Axis, test: &Test, n: &XNode) -> JsResult<()> { + let XNode::Node(x) = n else { return Ok(()) }; + let Some((p, at)) = child_position(interp, *x)? else { return Ok(()) }; + let count = interp.xml_node(p)?.children.len(); + let range: Box> = if axis == Axis::FollowingSibling { Box::new(at + 1..count) } else { Box::new((0..at).rev()) }; + for i in range { + if let Some(c) = interp.xml_node(p)?.children.get(i).copied() { + self.add(interp, out, axis, test, XNode::Node(c))?; + } + } + Ok(()) + } + + /// The node the following and preceding axes start from: an attribute's or a namespace + /// node's element, or the node itself. The flag is true for the first two. + fn start_of(interp: &Interp, n: &XNode) -> JsResult> { + Ok(match n { + XNode::Root(_) => None, + XNode::Ns { owner, .. } => Some((*owner, true)), + XNode::Node(x) => match interp.xml_node(*x)?.parent { + Some(p) if interp.xml_kind(*x)? == XmlKind::Attribute => Some((p, true)), + _ => Some((*x, false)), + }, + }) + } + + fn following(&self, interp: &mut Interp, out: &mut Nodes, axis: Axis, test: &Test, n: &XNode) -> JsResult<()> { + let Some((mut cur, owned)) = Self::start_of(interp, n)? else { return Ok(()) }; + if owned { + self.under(interp, out, axis, test, cur)?; + } + while let Some((p, at)) = child_position(interp, cur)? { + let count = interp.xml_node(p)?.children.len(); + for i in at + 1..count { + if let Some(s) = interp.xml_node(p)?.children.get(i).copied() { + self.subtree(interp, out, axis, test, s)?; + } + } + cur = p; + } + Ok(()) + } + + fn preceding(&self, interp: &mut Interp, out: &mut Nodes, axis: Axis, test: &Test, n: &XNode) -> JsResult<()> { + let Some((mut cur, _)) = Self::start_of(interp, n)? else { return Ok(()) }; + while let Some((p, at)) = child_position(interp, cur)? { + for i in (0..at).rev() { + let Some(s) = interp.xml_node(p)?.children.get(i).copied() else { continue }; + let mut part = Nodes::new(interp); + self.subtree(interp, &mut part, axis, test, s)?; + for x in part.list.into_iter().rev() { + out.push(interp, x)?; + } + } + cur = p; + } + Ok(()) + } + + fn attributes(&self, interp: &mut Interp, out: &mut Nodes, axis: Axis, test: &Test, n: &XNode) -> JsResult<()> { + let XNode::Node(x) = n else { return Ok(()) }; + if interp.xml_kind(*x)? != XmlKind::Element { + return Ok(()); + } + let count = interp.xml_node(*x)?.attrs.len(); + for i in 0..count { + if let Some(a) = interp.xml_node(*x)?.attrs.get(i).copied() { + self.add(interp, out, axis, test, XNode::Node(a))?; + } + } + Ok(()) + } + + fn namespaces(&self, interp: &mut Interp, out: &mut Nodes, axis: Axis, test: &Test, n: &XNode) -> JsResult<()> { + let XNode::Node(x) = n else { return Ok(()) }; + if interp.xml_kind(*x)? != XmlKind::Element { + return Ok(()); + } + let xml = key("xml"); + let mut at = 0u32; + let mut has_xml = false; + let scope = scope_of(interp, Some(*x))?; + for ns in &scope.list { + let Some(prefix) = ns.prefix.clone() else { continue }; + if prefix.is_empty() && ns.uri.is_empty() { + continue; + } + has_xml |= prefix == xml; + self.add(interp, out, axis, test, XNode::Ns { owner: *x, at, prefix, uri: ns.uri.clone() })?; + at += 1; + } + if !has_xml { + self.add(interp, out, axis, test, XNode::Ns { owner: *x, at, prefix: xml, uri: key(XML_URI) })?; + } + Ok(()) + } + + /// The nodes `axis` reaches from `n` that pass `test`, nearest first. + fn axis(&self, interp: &mut Interp, axis: Axis, test: &Test, n: &XNode) -> JsResult { + let mut out = Nodes::new(interp); + match axis { + Axis::Itself => self.add(interp, &mut out, axis, test, n.clone())?, + Axis::Child => self.children(interp, &mut out, axis, test, n)?, + Axis::Descendant => self.descendants(interp, &mut out, axis, test, n)?, + Axis::DescendantOrSelf => { + self.add(interp, &mut out, axis, test, n.clone())?; + self.descendants(interp, &mut out, axis, test, n)?; + } + Axis::Parent => { + if let Some(p) = parent_of(interp, n)? { + self.add(interp, &mut out, axis, test, p)?; + } + } + Axis::Ancestor => self.ancestors(interp, &mut out, axis, test, n)?, + Axis::AncestorOrSelf => { + self.add(interp, &mut out, axis, test, n.clone())?; + self.ancestors(interp, &mut out, axis, test, n)?; + } + Axis::FollowingSibling | Axis::PrecedingSibling => self.siblings(interp, &mut out, axis, test, n)?, + Axis::Following => self.following(interp, &mut out, axis, test, n)?, + Axis::Preceding => self.preceding(interp, &mut out, axis, test, n)?, + Axis::Attribute => self.attributes(interp, &mut out, axis, test, n)?, + Axis::Namespace => self.namespaces(interp, &mut out, axis, test, n)?, + } + Ok(out) + } + + // ---- string values and conversions ---- + + /// The string-value of a node (XPath 1.0 section 5): the text under an element or the root, + /// the value of any other node, and a namespace node's URI. + fn string_value(&mut self, interp: &mut Interp, n: &XNode) -> JsResult { + let x = match n { + XNode::Ns { uri, .. } => return Ok(Text::plain(interp, uri.clone())), + XNode::Root(t) => *t, + XNode::Node(x) => *x, + }; + let kind = interp.xml_kind(x)?; + if kind == XmlKind::Element { + return self.text_under(interp, x); + } + if matches!(n, XNode::Root(_)) && kind != XmlKind::Text { + return Ok(Text::plain(interp, empty())); + } + let value = interp.xml_node(x)?.value.clone(); + let units = flat_charged(interp, &value)?; + charge_units(interp, units.len())?; + Ok(Text::plain(interp, units)) + } + + fn text_under(&mut self, interp: &mut Interp, x: ObjId) -> JsResult { + let mut buf = TextBuf::new(interp); + let mut held = HeldBytes::new(interp); + let mut stack = Vec::new(); + push_held(interp, &mut held, &mut stack, (x, 0usize))?; + while let Some(&(p, at)) = stack.last() { + interp.use_fuel()?; + let Some(c) = interp.xml_node(p)?.children.get(at).copied() else { + stack.pop(); + continue; + }; + if let Some(frame) = stack.last_mut() { + frame.1 += 1; + } + match interp.xml_kind(c)? { + XmlKind::Text => { + let value = interp.xml_node(c)?.value.clone(); + let units = flat_charged(interp, &value)?; + buf.push(interp, &units)?; + } + XmlKind::Element => push_held(interp, &mut held, &mut stack, (c, 0))?, + _ => {} + } + } + Ok(buf.finish()) + } + + fn text_of(&mut self, interp: &mut Interp, v: Val) -> JsResult { + match v { + Val::Set(s) => match s.list.first() { + Some(n) => self.string_value(interp, n), + None => Ok(Text::plain(interp, empty())), + }, + Val::Bool(b) => Ok(Text::plain(interp, key(if b { "true" } else { "false" }))), + Val::Num(n) => Ok(Text::plain(interp, key(&num_text(n)))), + Val::Str(t) => { + // The caller reads the units, so they take fuel each time a value is used. + charge_units(interp, t.units.len())?; + Ok(t) + } + } + } + + /// The number a node's string-value stands for. + fn node_number(&mut self, interp: &mut Interp, n: &XNode) -> JsResult { + let t = self.string_value(interp, n)?; + str_num(interp, &t.units) + } + + fn number_of(&mut self, interp: &mut Interp, v: Val) -> JsResult { + match v { + Val::Num(n) => Ok(n), + Val::Bool(b) => Ok(f64::from(u8::from(b))), + other => { + let t = self.text_of(interp, other)?; + str_num(interp, &t.units) + } + } + } + + // ---- comparisons and operators ---- + + fn compare(&mut self, interp: &mut Interp, op: Bin, a: Val, b: Val) -> JsResult { + match (a, b) { + (Val::Set(x), Val::Set(y)) => self.compare_sets(interp, op, &x, &y), + (Val::Set(x), other) => self.compare_set(interp, op, &x, other), + (other, Val::Set(y)) => self.compare_set(interp, flip(op), &y, other), + (x, y) => self.compare_values(interp, op, x, y), + } + } + + fn compare_values(&mut self, interp: &mut Interp, op: Bin, a: Val, b: Val) -> JsResult { + if !matches!(op, Bin::Eq | Bin::Ne) { + let (x, y) = (self.number_of(interp, a)?, self.number_of(interp, b)?); + return Ok(compare_numbers(op, x, y)); + } + let equal = if matches!(a, Val::Bool(_)) || matches!(b, Val::Bool(_)) { + to_bool(&a) == to_bool(&b) + } else if matches!(a, Val::Num(_)) || matches!(b, Val::Num(_)) { + let (x, y) = (self.number_of(interp, a)?, self.number_of(interp, b)?); + return Ok(compare_numbers(op, x, y)); + } else { + self.text_of(interp, a)?.units == self.text_of(interp, b)?.units + }; + Ok(equal == (op == Bin::Eq)) + } + + /// Compares each node of `set` with `other`, which is not a node-set; `set` is on the left. + fn compare_set(&mut self, interp: &mut Interp, op: Bin, set: &Nodes, other: Val) -> JsResult { + if let Val::Str(t) = &other { + charge_units(interp, t.units.len())?; + } + let n = match other { + Val::Bool(b) => return self.compare_values(interp, op, Val::Bool(!set.list.is_empty()), Val::Bool(b)), + Val::Str(t) if matches!(op, Bin::Eq | Bin::Ne) => { + for node in &set.list { + if (self.string_value(interp, node)?.units == t.units) == (op == Bin::Eq) { + return Ok(true); + } + } + return Ok(false); + } + Val::Str(t) => str_num(interp, &t.units)?, + Val::Num(n) => n, + Val::Set(_) => return Err(internal()), + }; + for node in &set.list { + let v = self.node_number(interp, node)?; + if compare_numbers(op, v, n) { + return Ok(true); + } + } + Ok(false) + } + + fn strings_of(&mut self, interp: &mut Interp, held: &mut HeldBytes, set: &Nodes) -> JsResult> { + let mut out = HashSet::new(); + for node in &set.list { + let t = self.string_value(interp, node)?; + held.add(interp, ENTRY_BYTES.saturating_add(t.units.len().saturating_mul(2)))?; + out.insert(t.units); + } + Ok(out) + } + + /// The smallest and largest numbers the nodes' string-values stand for, leaving out NaN. + fn number_range(&mut self, interp: &mut Interp, set: &Nodes) -> JsResult> { + let mut range: Option<(f64, f64)> = None; + for node in &set.list { + let v = self.node_number(interp, node)?; + if !v.is_nan() { + range = Some(range.map_or((v, v), |(lo, hi)| (lo.min(v), hi.max(v)))); + } + } + Ok(range) + } + + fn compare_sets(&mut self, interp: &mut Interp, op: Bin, a: &Nodes, b: &Nodes) -> JsResult { + if a.list.is_empty() || b.list.is_empty() { + return Ok(false); + } + if matches!(op, Bin::Eq | Bin::Ne) { + let mut held = HeldBytes::new(interp); + let right = self.strings_of(interp, &mut held, b)?; + for node in &a.list { + let s = self.string_value(interp, node)?; + let found = if op == Bin::Eq { right.contains(&s.units) } else { right.len() > 1 || !right.contains(&s.units) }; + if found { + return Ok(true); + } + } + return Ok(false); + } + let (Some((a_lo, a_hi)), Some((b_lo, b_hi))) = (self.number_range(interp, a)?, self.number_range(interp, b)?) else { return Ok(false) }; + Ok(match op { + Bin::Lt | Bin::Le => compare_numbers(op, a_lo, b_hi), + _ => compare_numbers(op, a_hi, b_lo), + }) + } + + fn binary(&mut self, interp: &mut Interp, op: Bin, a: Val, b: Val) -> JsResult { + match op { + Bin::Union => { + let (Val::Set(mut x), Val::Set(y)) = (a, b) else { + return Err(interp.type_error("both sides of an XPath | must select nodes")); + }; + if x.list.is_empty() { + return Ok(Val::Set(y)); + } + for n in y.list { + x.push(interp, n)?; + } + Ok(Val::Set(self.sort(interp, x)?)) + } + Bin::Add | Bin::Sub | Bin::Mul | Bin::Div | Bin::Mod => { + let (x, y) = (self.number_of(interp, a)?, self.number_of(interp, b)?); + Ok(Val::Num(match op { + Bin::Add => x + y, + Bin::Sub => x - y, + Bin::Mul => x * y, + Bin::Div => x / y, + _ => x % y, + })) + } + Bin::Or | Bin::And => Err(internal()), + _ => Ok(Val::Bool(self.compare(interp, op, a, b)?)), + } + } + + // ---- functions ---- + + fn set_arg(interp: &mut Interp, v: Option, name: &str) -> JsResult { + match v { + Some(Val::Set(s)) => Ok(s), + _ => Err(interp.type_error(&format!("the XPath function {name} needs a node-set"))), + } + } + + fn text_arg(&mut self, interp: &mut Interp, v: Option, ctx: &Ctx) -> JsResult { + match v { + Some(v) => self.text_of(interp, v), + None => self.string_value(interp, &ctx.node), + } + } + + fn number_arg(&mut self, interp: &mut Interp, v: Option) -> JsResult { + let v = v.ok_or_else(internal)?; + self.number_of(interp, v) + } + + fn call(&mut self, interp: &mut Interp, f: Func, args: Vec, ctx: &Ctx) -> JsResult { + let mut args = args.into_iter(); + Ok(match f { + Func::Last => Val::Num(ctx.size as f64), + Func::Position => Val::Num(ctx.pos as f64), + Func::Count => Val::Num(Self::set_arg(interp, args.next(), "count")?.list.len() as f64), + Func::Id => Val::Set(Nodes::new(interp)), + Func::LocalName | Func::NamespaceUri | Func::Name => Val::Str(self.name_function(interp, f, args.next(), ctx)?), + Func::Sum => { + let set = Self::set_arg(interp, args.next(), "sum")?; + let mut total = 0.0; + for n in &set.list { + total += self.node_number(interp, n)?; + } + Val::Num(total) + } + Func::Boolean => Val::Bool(to_bool(&args.next().ok_or_else(internal)?)), + Func::Not => Val::Bool(!to_bool(&args.next().ok_or_else(internal)?)), + Func::True => Val::Bool(true), + Func::False => Val::Bool(false), + Func::Lang => { + let wanted = self.text_arg(interp, args.next(), ctx)?; + Val::Bool(self.lang(interp, &ctx.node, &wanted.units)?) + } + Func::Number => match args.next() { + Some(v) => Val::Num(self.number_of(interp, v)?), + None => Val::Num(self.node_number(interp, &ctx.node)?), + }, + Func::Floor => Val::Num(self.number_arg(interp, args.next())?.floor()), + Func::Ceiling => Val::Num(self.number_arg(interp, args.next())?.ceil()), + Func::Round => Val::Num(round(self.number_arg(interp, args.next())?)), + _ => return self.string_function(interp, f, args.collect(), ctx), + }) + } + + fn string_function(&mut self, interp: &mut Interp, f: Func, args: Vec, ctx: &Ctx) -> JsResult { + let mut texts = Vec::new(); + let mut held = HeldBytes::new(interp); + for v in args { + let t = self.text_of(interp, v)?; + push_held(interp, &mut held, &mut texts, t)?; + } + if texts.is_empty() && matches!(f, Func::String | Func::StringLength | Func::NormalizeSpace) { + texts.push(self.string_value(interp, &ctx.node)?); + } + if f == Func::String { + return Ok(Val::Str(texts.into_iter().next().ok_or_else(internal)?)); + } + let units = |at: usize| texts.get(at).map(|t| &*t.units).unwrap_or_default(); + Ok(match f { + Func::StringLength => Val::Num(char::decode_utf16(units(0).iter().copied()).count() as f64), + Func::StartsWith => Val::Bool(units(0).starts_with(units(1))), + Func::Contains => Val::Bool(find(interp, units(0), units(1))?.is_some()), + Func::SubstringBefore => { + let at = find(interp, units(0), units(1))?; + Val::Str(self.slice(interp, at.and_then(|i| units(0).get(..i)).unwrap_or_default())?) + } + Func::SubstringAfter => { + let at = find(interp, units(0), units(1))?; + Val::Str(self.slice(interp, at.and_then(|i| units(0).get(i + units(1).len()..)).unwrap_or_default())?) + } + Func::Concat => { + let mut buf = TextBuf::new(interp); + for t in &texts { + buf.push(interp, &t.units)?; + } + Val::Str(buf.finish()) + } + Func::NormalizeSpace => Val::Str(normalize_space(interp, units(0))?), + Func::Translate => Val::Str(translate(interp, units(0), units(1), units(2))?), + _ => return Err(internal()), + }) + } + + fn slice(&mut self, interp: &mut Interp, units: &[u16]) -> JsResult { + let mut buf = TextBuf::new(interp); + buf.push(interp, units)?; + Ok(buf.finish()) + } + + fn substring(&mut self, interp: &mut Interp, args: Vec) -> JsResult { + let mut args = args.into_iter(); + let text = self.text_of(interp, args.next().ok_or_else(internal)?)?; + let start = round(self.number_arg(interp, args.next())?); + let end = match args.next() { + Some(len) => start + round(self.number_of(interp, len)?), + None => f64::INFINITY, + }; + charge_units(interp, text.units.len())?; + let mut held = HeldBytes::new(interp); + // The code points take 4 bytes each, and the result up to twice its 2-byte units. + held.add(interp, text.units.len().saturating_mul(8))?; + let mut out = Vec::new(); + for (i, p) in code_points(&text.units).into_iter().enumerate() { + let position = (i + 1) as f64; + if position >= start && position < end { + push_point(&mut out, p); + } + } + Ok(Val::Str(Text { units: Rc::from(out), _held: held })) + } + + fn name_function(&mut self, interp: &mut Interp, f: Func, arg: Option, ctx: &Ctx) -> JsResult { + let node = match arg { + None => Some(ctx.node.clone()), + Some(Val::Set(s)) => s.list.into_iter().next(), + Some(_) => return Err(interp.type_error("the XPath name functions need a node-set")), + }; + let units = match node { + None | Some(XNode::Root(_)) => empty(), + Some(XNode::Ns { prefix, .. }) => { + if f == Func::NamespaceUri { + empty() + } else { + prefix + } + } + Some(XNode::Node(x)) => return node_name(interp, f, x), + }; + Ok(Text::plain(interp, units)) + } + + /// Whether the context node's language, from the nearest `xml:lang` attribute on it or an + /// ancestor, is `wanted` or a sublanguage of it, ignoring case. + fn lang(&mut self, interp: &mut Interp, n: &XNode, wanted: &[u16]) -> JsResult { + let mut cur = match n { + XNode::Root(_) => None, + XNode::Node(x) => Some(*x), + XNode::Ns { owner, .. } => Some(*owner), + }; + let xml = key(XML_URI); + while let Some(x) = cur { + interp.use_fuel()?; + let node = interp.xml_node(x)?; + let parent = node.parent; + let count = node.attrs.len(); + for i in 0..count { + interp.use_fuel()?; + let Some(a) = interp.xml_node(x)?.attrs.get(i).copied() else { break }; + let attr = interp.xml_node(a)?; + if attr.name.as_ref().is_some_and(|q| name_uri(q) == &*xml && units_are(&q.local, "lang")) { + let value = attr.value.clone(); + let value = flat_charged(interp, &value)?; + let head = value.get(..wanted.len()).unwrap_or_default(); + return Ok(same_ignoring_case(head, wanted) && (value.len() == wanted.len() || value.get(wanted.len()) == Some(&DASH))); + } + } + cur = parent; + } + Ok(false) + } + + // ---- running ---- + + fn task(&mut self, interp: &mut Interp, t: Task) -> JsResult<()> { + push_held(interp, &mut self.held, &mut self.tasks, t) + } + + fn val(&mut self, interp: &mut Interp, v: Val) -> JsResult<()> { + push_held(interp, &mut self.held, &mut self.vals, v) + } + + fn pop(&mut self) -> JsResult { + self.vals.pop().ok_or_else(internal) + } + + fn root_of(interp: &mut Interp, n: &XNode) -> JsResult { + Ok(match n { + XNode::Root(t) => XNode::Root(*t), + XNode::Node(x) => XNode::Root(top_of(interp, *x)?), + XNode::Ns { owner, .. } => XNode::Root(top_of(interp, *owner)?), + }) + } + + fn bound_value(&mut self, interp: &mut Interp, at: usize) -> JsResult { + Ok(match self.bound.get(at).ok_or_else(internal)? { + Bound::Bool(b) => Val::Bool(*b), + Bound::Num(n) => Val::Num(*n), + Bound::Str(s) => Val::Str(Text::plain(interp, s.clone())), + Bound::Set(list) => { + let list = list.clone(); + let mut nodes = Nodes::new(interp); + nodes.held.add(interp, list.len().saturating_mul(size_of::()))?; + nodes.list = list; + Val::Set(nodes) + } + }) + } + + fn eval(&mut self, interp: &mut Interp, e: usize, ctx: Ctx) -> JsResult<()> { + let parsed = self.parsed; + match parsed.exprs.get(e).ok_or_else(internal)? { + Expr::Num(n) => self.val(interp, Val::Num(*n)), + Expr::Lit(s) => { + let t = Text::plain(interp, s.clone()); + self.val(interp, Val::Str(t)) + } + Expr::Var(at) => { + let v = self.bound_value(interp, *at)?; + self.val(interp, v) + } + Expr::Neg(a) => { + self.task(interp, Task::Neg)?; + self.task(interp, Task::Eval(*a, ctx)) + } + Expr::Bin(op @ (Bin::And | Bin::Or), a, b) => { + self.task(interp, Task::Logic { and: *op == Bin::And, rhs: *b, ctx: ctx.clone() })?; + self.task(interp, Task::Eval(*a, ctx)) + } + Expr::Bin(op, a, b) => { + self.task(interp, Task::Bin(*op))?; + self.task(interp, Task::Eval(*b, ctx.clone()))?; + self.task(interp, Task::Eval(*a, ctx)) + } + Expr::Call(f, args) => { + self.task(interp, Task::Call(*f, args.len(), ctx.clone()))?; + for a in args.iter().rev() { + self.task(interp, Task::Eval(*a, ctx.clone()))?; + } + Ok(()) + } + Expr::Path { filter: Some((primary, _)), .. } => { + self.task(interp, Task::PathStart(e))?; + self.task(interp, Task::Eval(*primary, ctx)) + } + Expr::Path { filter: None, absolute, steps } => { + let start = if *absolute { Self::root_of(interp, &ctx.node)? } else { ctx.node }; + let mut inputs = Nodes::new(interp); + inputs.push(interp, start)?; + if steps.is_empty() { + return self.val(interp, Val::Set(inputs)); + } + let first = self.step_axis(interp, e, 1, &inputs.list.first().cloned().ok_or_else(internal)?)?; + let run = self.new_run(interp, e, 1, inputs, first); + self.run_path(interp, Box::new(run)) + } + } + } + + fn new_run(&self, interp: &Interp, path: usize, stage: usize, inputs: Nodes, cur: Nodes) -> PathRun { + PathRun { + path, + stage, + inputs, + ci: 0, + cur, + pred: 0, + at: 0, + kept: Nodes::new(interp), + waiting: false, + out: Nodes::new(interp), + seen: HashSet::new(), + seen_held: HeldBytes::new(interp), + } + } + + fn step(&mut self, interp: &mut Interp, t: Task) -> JsResult<()> { + match t { + Task::Eval(e, ctx) => self.eval(interp, e, ctx), + Task::Bin(op) => { + let b = self.pop()?; + let a = self.pop()?; + let v = self.binary(interp, op, a, b)?; + self.val(interp, v) + } + Task::Neg => { + let a = self.pop()?; + let n = self.number_of(interp, a)?; + self.val(interp, Val::Num(-n)) + } + Task::Logic { and, rhs, ctx } => { + let left = to_bool(&self.pop()?); + if left != and { + return self.val(interp, Val::Bool(left)); + } + self.task(interp, Task::Bool)?; + self.task(interp, Task::Eval(rhs, ctx)) + } + Task::Bool => { + let v = to_bool(&self.pop()?); + self.val(interp, Val::Bool(v)) + } + Task::Call(f, n, ctx) => { + let args = self.vals.split_off(self.vals.len().checked_sub(n).ok_or_else(internal)?); + let v = if f == Func::Substring { self.substring(interp, args)? } else { self.call(interp, f, args, &ctx)? }; + self.val(interp, v) + } + Task::PathStart(e) => { + let Val::Set(set) = self.pop()? else { + return Err(interp.type_error("an XPath predicate or step follows a value that is not a node-set")); + }; + let run = self.new_run(interp, e, 0, Nodes::new(interp), set); + self.run_path(interp, Box::new(run)) + } + Task::Path(run) => self.run_path(interp, run), + } + } + + /// The predicates of a path's stage, and its step for a stage after the filter's. + fn stage_of(&self, path: usize, stage: usize) -> JsResult<(&'p [usize], Option<&'p Step>)> { + let parsed = self.parsed; + let Some(Expr::Path { filter, steps, .. }) = parsed.exprs.get(path) else { return Err(internal()) }; + match stage.checked_sub(1) { + None => Ok((filter.as_ref().map(|(_, p)| p.as_slice()).unwrap_or_default(), None)), + Some(s) => { + let step = steps.get(s).ok_or_else(internal)?; + Ok((&step.preds, Some(step))) + } + } + } + + fn step_axis(&self, interp: &mut Interp, path: usize, stage: usize, n: &XNode) -> JsResult { + let (_, step) = self.stage_of(path, stage)?; + let step = step.ok_or_else(internal)?; + self.axis(interp, step.axis, &step.test, n) + } + + /// Runs a path until a predicate needs evaluating, which it schedules before itself, or until + /// the path's node-set is complete, which it pushes. + fn run_path(&mut self, interp: &mut Interp, mut r: Box) -> JsResult<()> { + loop { + interp.use_fuel()?; + if r.waiting { + r.waiting = false; + let v = self.pop()?; + let keep = match v { + Val::Num(n) => n == (r.at + 1) as f64, + other => to_bool(&other), + }; + if keep && let Some(n) = r.cur.list.get(r.at).cloned() { + r.kept.push(interp, n)?; + } + r.at += 1; + } + let (preds, _) = self.stage_of(r.path, r.stage)?; + if let Some(&pred) = preds.get(r.pred) { + if let Some(node) = r.cur.list.get(r.at).cloned() { + let ctx = Ctx { node, pos: r.at + 1, size: r.cur.list.len() }; + r.waiting = true; + self.task(interp, Task::Path(r))?; + return self.task(interp, Task::Eval(pred, ctx)); + } + r.cur = replace(&mut r.kept, Nodes::new(interp)); + r.pred += 1; + r.at = 0; + continue; + } + if !self.next_context(interp, &mut r)? { + return Ok(()); + } + } + } + + /// Adds the current context's nodes to the stage's result and moves to the next context or + /// stage. Returns false when the path is complete and its node-set has been pushed. + fn next_context(&mut self, interp: &mut Interp, r: &mut PathRun) -> JsResult { + let cur = replace(&mut r.cur, Nodes::new(interp)); + if r.inputs.list.len() > 1 { + for n in cur.list { + if !r.seen.contains(&n) { + r.seen_held.add(interp, ENTRY_BYTES)?; + r.seen.insert(n.clone()); + r.out.push(interp, n)?; + } + } + } else { + r.out = cur; + } + r.ci += 1; + if let Some(n) = r.inputs.list.get(r.ci).cloned() { + r.cur = self.step_axis(interp, r.path, r.stage, &n)?; + r.pred = 0; + r.at = 0; + return Ok(true); + } + let out = replace(&mut r.out, Nodes::new(interp)); + let (_, step) = self.stage_of(r.path, r.stage)?; + let done = if r.inputs.list.len() > 1 { + self.sort(interp, out)? + } else if step.is_some_and(|s| s.axis.reverse()) { + let mut out = out; + out.list.reverse(); + out + } else { + out + }; + r.seen.clear(); + r.seen_held = HeldBytes::new(interp); + r.stage += 1; + let more = self.stage_of(r.path, r.stage).is_ok(); + let Some(first) = done.list.first().cloned().filter(|_| more) else { + self.val(interp, Val::Set(done))?; + return Ok(false); + }; + r.inputs = done; + r.ci = 0; + r.cur = self.step_axis(interp, r.path, r.stage, &first)?; + r.pred = 0; + r.at = 0; + Ok(true) + } + + fn run(&mut self, interp: &mut Interp, e: usize, ctx: Ctx) -> JsResult { + self.tasks.clear(); + self.vals.clear(); + self.task(interp, Task::Eval(e, ctx))?; + while let Some(t) = self.tasks.pop() { + interp.use_fuel()?; + self.step(interp, t)?; + } + let v = self.pop()?; + if !self.vals.is_empty() { + return Err(internal()); + } + Ok(v) + } + + /// Binds the expression's prefixes to the namespaces in scope on `x`. + fn resolve_prefixes(&mut self, interp: &mut Interp, x: ObjId) -> JsResult<()> { + self.uris.clear(); + if self.parsed.prefixes.is_empty() { + return Ok(()); + } + let scope = scope_of(interp, Some(x))?; + let parsed = self.parsed; + for p in &parsed.prefixes { + let uri = if units_are(p, "xml") { + key(XML_URI) + } else { + match scope.list.iter().find(|ns| ns.prefix.as_ref() == Some(p)) { + Some(ns) if !ns.uri.is_empty() => ns.uri.clone(), + _ => { + let shown = String::from_utf16_lossy(p); + return Err(interp.type_error(&format!("the XPath prefix {shown} is not bound to a namespace"))); + } + } + }; + self.held.add(interp, ENTRY_BYTES)?; + self.uris.insert(p.clone(), uri); + } + Ok(()) + } + + /// The nodes the expression selects with `x` as the context node. + fn select(&mut self, interp: &mut Interp, x: ObjId) -> JsResult> { + self.resolve_prefixes(interp, x)?; + let root = self.parsed.root; + let Val::Set(set) = self.run(interp, root, Ctx { node: XNode::Node(x), pos: 1, size: 1 })? else { + return Err(interp.type_error("the XPath expression does not evaluate to a node-set")); + }; + let mut out = Vec::new(); + let mut held = HeldBytes::new(interp); + for n in set.list { + match n { + XNode::Node(id) => push_held(interp, &mut held, &mut out, id)?, + XNode::Root(_) => return Err(interp.type_error("the XPath expression selects the root node, which is not an XML value")), + XNode::Ns { .. } => return Err(interp.type_error("the XPath expression selects a namespace node, which is not an XML value")), + } + } + Ok(out) + } +} + +fn node_name(interp: &mut Interp, f: Func, x: ObjId) -> JsResult { + let node = interp.xml_node(x)?; + let (kind, parent) = (node.kind, node.parent); + let Some(name) = node.name.clone() else { return Ok(Text::plain(interp, empty())) }; + let units = match (f, kind) { + (_, XmlKind::Text | XmlKind::Comment) => empty(), + (Func::NamespaceUri, XmlKind::Pi) => empty(), + (Func::NamespaceUri, _) => Rc::from(name_uri(&name)), + (Func::LocalName, _) | (_, XmlKind::Pi) => name.local, + _ => return qualified_name(interp, x, parent, &name, kind == XmlKind::Attribute), + }; + Ok(Text::plain(interp, units)) +} + +/// An element's or attribute's name as a QName, with a prefix declared for its namespace. The units +/// of a prefixed name are held against the heap limit while the text lives. +fn qualified_name(interp: &mut Interp, x: ObjId, parent: Option, name: &XmlName, attribute: bool) -> JsResult { + let uri = name_uri(name); + if uri.is_empty() { + return Ok(Text::plain(interp, name.local.clone())); + } + let prefix = if units_are(uri, XML_URI) { + key("xml") + } else { + match &name.prefix { + Some(p) if !(attribute && p.is_empty()) => p.clone(), + _ => { + let scope = scope_of(interp, if attribute { parent } else { Some(x) })?; + let usable = |ns: &XmlNs| *ns.uri == *uri && ns.prefix.as_ref().is_some_and(|p| !(attribute && p.is_empty())); + scope.list.iter().find(|ns| usable(ns)).and_then(|ns| ns.prefix.clone()).unwrap_or_else(empty) + } + } + }; + if prefix.is_empty() { + return Ok(Text::plain(interp, name.local.clone())); + } + let mut buf = TextBuf::new(interp); + buf.push(interp, &prefix)?; + buf.push(interp, &[COLON])?; + buf.push(interp, &name.local)?; + Ok(buf.finish()) +} + +/// The first index where `needle` occurs in `hay`. Every position tried takes fuel. +fn find(interp: &mut Interp, hay: &[u16], needle: &[u16]) -> JsResult> { + string_builtins::find(interp, hay, needle, 0) +} + +fn normalize_space(interp: &mut Interp, units: &[u16]) -> JsResult { + let mut buf = TextBuf::new(interp); + for word in units.split(|&c| is_xml_space(c)).filter(|w| !w.is_empty()) { + if !buf.units.is_empty() { + buf.push(interp, &[0x20])?; + } + buf.push(interp, word)?; + } + Ok(buf.finish()) +} + +fn translate(interp: &mut Interp, units: &[u16], from: &[u16], to: &[u16]) -> JsResult { + charge_units(interp, units.len() + from.len() + to.len())?; + let mut held = HeldBytes::new(interp); + held.add(interp, from.len().saturating_add(units.len()).saturating_add(to.len()).saturating_mul(ENTRY_BYTES))?; + let to = code_points(to); + let mut map: HashMap> = HashMap::new(); + for (i, p) in code_points(from).into_iter().enumerate() { + map.entry(p).or_insert_with(|| to.get(i).copied()); + } + let mut out = Vec::new(); + for p in code_points(units) { + match map.get(&p) { + Some(Some(t)) => push_point(&mut out, *t), + Some(None) => {} + None => push_point(&mut out, p), + } + } + Ok(Text { units: Rc::from(out), _held: held }) +} + +/// Reads the variables the expression names from `variables`. +fn bind(interp: &mut Interp, held: &mut HeldBytes, parsed: &Parsed, variables: &Value) -> JsResult> { + let mut out = Vec::new(); + for name in &parsed.vars { + let v = match variables { + Value::Object(o) if interp.has_property(*o, name)? => interp.get_from(*o, name, variables)?, + _ => Value::Undefined, + }; + if matches!(v, Value::Undefined) { + let shown = String::from_utf16_lossy(name); + return Err(interp.type_error(&format!("the XPath variable ${shown} is not bound"))); + } + interp.temp_roots.push(v.clone()); + let b = match (interp.classify(&v), &v) { + (Xv::Node(n), _) => Bound::Set(vec![XNode::Node(n)]), + (Xv::List(l), _) => { + // A later getter may change the list, so its items are held as roots themselves. + let count = interp.xml_list(l)?.items.len(); + held.add(interp, count.saturating_mul(size_of::() + size_of::() + size_of::()))?; + let items = interp.xml_list(l)?.items.clone(); + interp.temp_roots.extend(items.iter().map(|&n| Value::Object(n))); + Bound::Set(items.into_iter().map(XNode::Node).collect()) + } + (Xv::Other, Value::Bool(b)) => Bound::Bool(*b), + (Xv::Other, Value::Number(n)) => Bound::Num(*n), + (Xv::Other, _) => { + let s = interp.to_str(&v)?; + Bound::Str(flat_charged(interp, &s)?) + } + }; + push_held(interp, held, &mut out, b)?; + } + Ok(out) +} + +/// The nodes an expression runs on: the XML value itself, or each element of an XMLList. +fn contexts(interp: &mut Interp, held: &mut HeldBytes, this: &Value) -> JsResult> { + match interp.classify(this) { + Xv::Node(n) => Ok(vec![n]), + Xv::List(l) => { + let count = interp.xml_list(l)?.items.len(); + let mut out = Vec::new(); + for i in 0..count { + interp.use_fuel()?; + let Some(item) = interp.xml_list(l)?.items.get(i).copied() else { break }; + if interp.xml_kind(item)? == XmlKind::Element { + push_held(interp, held, &mut out, item)?; + } + } + Ok(out) + } + Xv::Other => Err(interp.type_error("the method needs an XML value")), + } +} + +/// `xpath(expression[, variables])`: the nodes the XPath 1.0 `expression` selects with this XML +/// value as the context node, or, for an XMLList, with each of its elements in turn, as one +/// XMLList. Each property of `variables` binds the variable of its name. +pub(crate) fn xpath(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + if matches!(interp.classify(&this), Xv::Other) { + return Err(interp.type_error("the method needs an XML value")); + } + let Value::String(source) = arg(args, 0) else { + return Err(interp.type_error("xpath needs the expression as a string")); + }; + let variables = arg(args, 1); + if !matches!(variables, Value::Undefined | Value::Object(_)) { + return Err(interp.type_error("xpath needs its variables as an object")); + } + interp.rooted(&[this.clone(), variables.clone()], |i| { + let units = flat_charged(i, &source)?; + let parsed = parse(i, &units)?; + let mut held = HeldBytes::new(i); + let bound = bind(i, &mut held, &parsed, &variables)?; + let items = contexts(i, &mut held, &this)?; + let out = i.new_xml_list(None, None)?; + i.xml_keep(out); + let mut ev = Ev::new(i, &parsed, bound)?; + for item in items { + for id in ev.select(i, item)? { + i.list_push(out, id)?; + } + } + Ok(Value::Object(out)) + }) +} diff --git a/crates/mcp/src/headless.rs b/crates/mcp/src/headless.rs index 00e914ddba..69c7b5ba0e 100644 --- a/crates/mcp/src/headless.rs +++ b/crates/mcp/src/headless.rs @@ -56,6 +56,24 @@ fn s<'a>(p: &'a Value, k: &str) -> Option<&'a str> { p.get(k).and_then(Value::as_str) } +/// An optional param read with `read`: none when it is omitted or null, else an error naming the +/// key when `read` gets nothing from its value. +fn opt(p: &Value, k: &str, read: impl Fn(&Value) -> Option, what: &str) -> Result, String> { + match p.get(k) { + None | Some(Value::Null) => Ok(None), + Some(v) => read(v).map(Some).ok_or_else(|| format!("`{k}` must be {what}")), + } +} + +fn opt_bool(p: &Value, k: &str) -> Result, String> { + opt(p, k, Value::as_bool, "true or false") +} + +/// A pointer packet's `mods`: none when omitted or null, else an object of booleans. +fn packet_mods(p: &Value) -> Result, String> { + opt(p, "mods", |m| m.as_object().and_then(|_| serde_json::from_value(m.clone()).ok()), "an object of true or false values") +} + pub(crate) fn pointer_kind(k: &str) -> Option { Some(match k { "down" => PointerKind::Down, @@ -210,28 +228,30 @@ impl Headless { fn pointer(&mut self, p: &Value) -> Result { let events = p.get("events").and_then(Value::as_array).ok_or("missing `events`")?; - let base: Mods = p.get("mods").and_then(|m| serde_json::from_value(m.clone()).ok()).unwrap_or_default(); + let base = packet_mods(p)?.unwrap_or_default(); let default = PointerEvent::json_backquote(p, false)?; let held = events.iter().map(|e| PointerEvent::json_backquote(e, default)).collect::, _>>()?; + // Every event is read before any is sent, so a malformed packet sends none of them. + let read = events + .iter() + .zip(held) + .map(|(e, backquote)| { + let mods = packet_mods(e)?.unwrap_or(base); + let kind = s(e, "kind").unwrap_or(""); + let kind = pointer_kind(kind).ok_or_else(|| format!("unknown pointer kind `{kind}` (down|drag|up|move|doubleclick)"))?; + PointerEvent::json_check(e)?; + if s(e, "space") == Some("screen") { + return Err("screen-space pointer events need the desktop app; use document coordinates".to_string()); + } + let x = e.get("x").and_then(Value::as_f64).ok_or("pointer event needs numeric `x`")?; + let y = e.get("y").and_then(Value::as_f64).ok_or("pointer event needs numeric `y`")?; + Ok((e, kind, Point::new(x, y), mods, backquote)) + }) + .collect::, String>>()?; self.ensure_document(); let mut requests = vec![]; - for (e, backquote) in events.iter().zip(held) { - let kind = s(e, "kind").unwrap_or(""); - let kind = pointer_kind(kind).ok_or_else(|| format!("unknown pointer kind `{kind}` (down|drag|up|move|doubleclick)"))?; - if s(e, "space") == Some("screen") { - return Err("screen-space pointer events need the desktop app; use document coordinates".into()); - } - let x = e.get("x").and_then(Value::as_f64).ok_or("pointer event needs numeric `x`")?; - let y = e.get("y").and_then(Value::as_f64).ok_or("pointer event needs numeric `y`")?; - let mods = e.get("mods").and_then(|m| serde_json::from_value(m.clone()).ok()).unwrap_or(base); - let ev = PointerEvent { - kind, - pos: Point::new(x, y), - mods, - backquote, - pressure: PointerEvent::json_pressure(e), - pen: PointerEvent::json_pen(e), - }; + for (e, kind, pos, mods, backquote) in read { + let ev = PointerEvent { kind, pos, mods, backquote, pressure: PointerEvent::json_pressure(e), pen: PointerEvent::json_pen(e) }; let reqs = self.session.pointer(&ev, self.view).map_err(|e| e.to_string())?; self.apply_ui_requests(reqs, &mut requests)?; // With no frames to show the highlight or apply an edit in later, each event waits for @@ -253,8 +273,8 @@ impl Headless { fn key(&mut self, p: &Value) -> Result { let key = s(p, "key").ok_or("missing `key`")?; - let b = |n: &str| p.get(n).and_then(Value::as_bool).unwrap_or(false); - let mods = Mods { shift: b("shift"), alt: b("alt"), cmd: b("cmd"), ctrl: b("ctrl"), ..Mods::default() }; + let b = |n: &str| opt_bool(p, n).map(|on| on.unwrap_or(false)); + let mods = Mods { shift: b("shift")?, alt: b("alt")?, cmd: b("cmd")?, ctrl: b("ctrl")?, ..Mods::default() }; // A letter reaches the tool only when the tool claims it without Cmd, Ctrl or Alt (E while // a selection marquee is dragged); otherwise it is a shortcut. let mut tk = tool_key(key); @@ -296,16 +316,18 @@ impl Headless { } fn render(&mut self, p: &Value) -> Result { + let idx = opt(p, "artboard", |v| v.as_u64().and_then(|i| usize::try_from(i).ok()), "a whole number of 0 or more")?.unwrap_or(0); + let scale = opt(p, "scale", Value::as_f64, "a number")?.unwrap_or(1.0).clamp(0.01, 16.0); + let trace_views = opt_bool(p, "traceViews")? == Some(true); + let data = opt_bool(p, "data")? == Some(true); let st = self.session.active().ok_or("no document")?; let doc = st.doc.clone(); - let idx = p.get("artboard").and_then(Value::as_u64).unwrap_or(0) as usize; let r = doc.artboards.get(idx).map(|a| a.rect).ok_or("no such artboard")?; - let scale = p.get("scale").and_then(Value::as_f64).unwrap_or(1.0).clamp(0.01, 16.0); vectorcraft_render::raster_size(r, scale)?; // Rendered with the options of a PNG export on white, so its pixels are the exported file's. // `traceViews: true` draws Image Trace objects as their View shows them, as the canvas does. let mut opts = RasterExportOptions { background: Some([255; 3]), ..Default::default() }.render_options(RasterFormat::Png); - opts.trace_views = p.get("traceViews").and_then(Value::as_bool) == Some(true); + opts.trace_views = trace_views; let img = self.renderer.render_region_with(&doc, r, scale, &opts); // A cancelled render stops drawing: the picture is not whole and is not written. vectorcraft_engine::cancel::check().map_err(|e| e.to_string())?; @@ -317,7 +339,7 @@ impl Headless { vectorcraft_format::write_atomic(std::path::Path::new(path), &png).map_err(|e| format!("write {path}: {e}"))?; out["path"] = json!(path); // `data: true` asks for the image as well as the file. - if p.get("data").and_then(Value::as_bool) == Some(true) { + if data { out["pngBase64"] = json!(vectorcraft_format::base64_encode(&png)); } } diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index d7de8dd7fb..6529cf175d 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -45,10 +45,62 @@ fn text_of(result: &Value) -> String { result["content"].as_array().unwrap().iter().filter(|c| c["type"] == "text").map(|c| c["text"].as_str().unwrap().to_string()).collect() } -fn tmp(name: &str) -> std::path::PathBuf { - let dir = std::env::temp_dir().join(format!("vectorcraft-mcp-test-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - dir.join(name) +/// A test's own folder under the temp dir, `vectorcraft-mcp--`, made empty when created +/// and removed with everything in it when dropped, also when the test panics. A removal that fails +/// (a file still open) is ignored. +struct TempFolder(std::path::PathBuf); + +impl TempFolder { + fn new(tag: &str) -> Self { + let dir = std::env::temp_dir().join(format!("vectorcraft-mcp-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Self(dir) + } + + /// The path of `name` in the folder. + fn file(&self, name: &str) -> std::path::PathBuf { + self.0.join(name) + } +} + +impl std::ops::Deref for TempFolder { + type Target = std::path::Path; + fn deref(&self) -> &std::path::Path { + &self.0 + } +} + +impl Drop for TempFolder { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// A `TempFolder` starts empty, and dropping it removes it with the files and folders in it, also +/// when the test that holds it panics. +#[test] +fn temp_folders_start_empty_and_are_removed_when_dropped() { + let leftover = std::env::temp_dir().join(format!("vectorcraft-mcp-drop-check-{}", std::process::id())); + std::fs::create_dir_all(&leftover).unwrap(); + std::fs::write(leftover.join("old.txt"), b"old").unwrap(); + let dir = TempFolder::new("drop-check"); + assert_eq!(std::fs::read_dir(&*dir).unwrap().count(), 0, "a leftover folder is emptied"); + std::fs::write(dir.file("a.txt"), b"a").unwrap(); + std::fs::create_dir(dir.file("sub")).unwrap(); + std::fs::write(dir.file("sub").join("b.txt"), b"b").unwrap(); + let path = dir.to_path_buf(); + drop(dir); + assert!(!path.exists(), "{} is removed", path.display()); + + let panicked = std::panic::catch_unwind(|| { + let dir = TempFolder::new("panic-check"); + std::fs::write(dir.file("a.txt"), b"a").unwrap(); + panic!("the test fails with {} in use", dir.display()); + }); + assert!(panicked.is_err()); + let path = std::env::temp_dir().join(format!("vectorcraft-mcp-panic-check-{}", std::process::id())); + assert!(!path.exists(), "{} is removed after a panic", path.display()); } // ---------- framing ---------- @@ -286,6 +338,7 @@ fn headless_command_list_includes_ui_commands() { #[test] fn headless_end_to_end() { + let dir = TempFolder::new("headless-end-to-end"); let mut s = server(); rpc(&mut s, 1, "initialize", json!({"protocolVersion": PROTOCOL_VERSION})); s.handle_line(r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#); @@ -334,7 +387,7 @@ fn headless_end_to_end() { assert_eq!(call(&mut s, 44, "doc_inspect", json!({"ids": [999_999]}))["isError"], true); // Screenshot returns image content (base64 PNG) and text. - let shot_path = tmp("shot.png"); + let shot_path = dir.file("shot.png"); let r = call(&mut s, 5, "screenshot", json!({"path": shot_path.to_str().unwrap()})); assert_eq!(r["isError"], false, "{r}"); let img = r["content"].as_array().unwrap().iter().find(|c| c["type"] == "image").expect("image content"); @@ -344,14 +397,14 @@ fn headless_end_to_end() { assert_eq!(std::fs::read(&shot_path).unwrap(), png); // Export SVG. - let svg_path = tmp("out.svg"); + let svg_path = dir.file("out.svg"); let r = call(&mut s, 6, "export", json!({"path": svg_path.to_str().unwrap()})); assert_eq!(r["isError"], false, "{r}"); let svg = std::fs::read_to_string(&svg_path).unwrap(); assert!(svg.contains(" image::Rgb([220, 30, 30]), (35..55, 5..35) => image::Rgb([30, 60, 200]), @@ -441,8 +495,9 @@ fn trace_and_style_prompt_steps_run_in_order() { /// result, as exports do. The image is a dark disc (r = 30 px) on blue, traced with Ignore White. #[test] fn screenshot_and_render_preview_draw_the_trace_view_with_trace_views() { + let dir = TempFolder::new("trace-views"); let mut s = server(); - let png = tmp("trace-views.png"); + let png = dir.file("trace-views.png"); image::RgbImage::from_fn(100, 100, |x, y| { let (dx, dy) = (f64::from(x) + 0.5 - 50.0, f64::from(y) + 0.5 - 50.0); if dx * dx + dy * dy <= 900.0 { image::Rgb([0, 0, 0]) } else { image::Rgb([170, 210, 255]) } @@ -490,6 +545,7 @@ fn screenshot_and_render_preview_draw_the_trace_view_with_trace_views() { #[test] fn headless_path_gesture_undo() { + let dir = TempFolder::new("path-gesture-undo"); let mut s = server(); let count = |s: &mut Server| -> u64 { let r = call(s, 90, "inspect_document", json!({})); @@ -543,9 +599,9 @@ fn headless_path_gesture_undo() { assert_eq!(r["isError"], false, "{r}"); let r = call(&mut s, 11, "select_tool", json!({"tool": "pen"})); assert_eq!(r["isError"], false, "{r}"); - let r = call(&mut s, 12, "export", json!({"path": tmp("x.png").to_str().unwrap(), "scale": 0.5})); + let r = call(&mut s, 12, "export", json!({"path": dir.file("x.png").to_str().unwrap(), "scale": 0.5})); assert_eq!(r["isError"], false, "{r}"); - assert_eq!(&std::fs::read(tmp("x.png")).unwrap()[..4], b"\x89PNG"); + assert_eq!(&std::fs::read(dir.file("x.png")).unwrap()[..4], b"\x89PNG"); } /// A hover's reply comes once the tool's highlight is ready, also when the tool finds it on another @@ -1074,8 +1130,9 @@ fn relative_to_cwd(p: &std::path::Path) -> Option { #[test] fn headless_file_tools_take_relative_paths() { + let dir = TempFolder::new("relative-paths"); let mut s = server(); - let file = tmp("relative.vectorcraft"); + let file = dir.file("relative.vectorcraft"); let Some(rel) = relative_to_cwd(&file) else { return }; let rel = rel.to_str().unwrap(); assert!(std::path::Path::new(rel).is_relative()); @@ -1452,6 +1509,44 @@ fn headless_backend_methods() { assert!(h.call("ui.resize", json!({})).is_err()); } +/// The headless key, pointer and screenshot calls refuse a value of the wrong type and change +/// nothing; omitting it or giving null keeps its default. +#[test] +fn headless_methods_refuse_params_of_the_wrong_type() { + let mut h = Headless::new(); + h.call("engine.execute", json!({"command": "file.new", "params": {"width": 300, "height": 200}})).unwrap(); + h.call("ui.tool.select", json!({"tool": "rectangle"})).unwrap(); + let before = h.call("document.json", json!({})).unwrap(); + let drag = |mods: Value| json!({"events": [{"kind": "down", "x": 10, "y": 10}, {"kind": "drag", "x": 60, "y": 60, "mods": mods}, {"kind": "up", "x": 60, "y": 60}]}); + let after_rect = |last: Value| json!({"events": [{"kind": "down", "x": 10, "y": 10}, {"kind": "drag", "x": 60, "y": 60}, {"kind": "up", "x": 60, "y": 60}, last]}); + for (method, params, key) in [ + ("ui.render", json!({"artboard": "0"}), "artboard"), + ("ui.render", json!({"scale": "2"}), "scale"), + ("ui.render", json!({"traceViews": 1}), "traceViews"), + ("ui.screenshot", json!({"data": "yes", "path": "x.png"}), "data"), + ("ui.key", json!({"key": "Delete", "shift": "true"}), "shift"), + ("ui.pointer", drag(json!({"shift": "yes"})), "mods"), + ("ui.pointer", json!({"mods": 1, "events": []}), "mods"), + ("ui.pointer", drag(json!([true])), "mods"), + // A whole rectangle comes before the malformed event, and none of it is drawn. + ("ui.pointer", after_rect(json!({"kind": "move", "x": "bad", "y": 0})), "x"), + ("ui.pointer", after_rect(json!({"kind": "wiggle", "x": 0, "y": 0})), "wiggle"), + ("ui.pointer", after_rect(json!({"kind": "move", "x": 1, "y": 1, "pressure": "bad"})), "pressure"), + ("ui.pointer", after_rect(json!({"kind": "move", "x": 1, "y": 1, "holdMs": true})), "holdMs"), + ("ui.pointer", after_rect(json!({"kind": "move", "x": 1, "y": 1, "tiltX": "5"})), "tiltX"), + ("ui.pointer", after_rect(json!({"kind": "move", "x": 1, "y": 1, "rotation": [0]})), "rotation"), + ("ui.pointer", after_rect(json!({"kind": "move", "x": 1, "y": 1, "space": "screeen"})), "space"), + ] { + let e = h.call(method, params.clone()).unwrap_err(); + assert!(e.contains(&format!("`{key}`")), "{method} {params}: {e}"); + } + assert_eq!(h.call("document.json", json!({})).unwrap(), before, "a refused call changes nothing"); + let r = h.call("ui.render", json!({"artboard": null, "scale": null, "traceViews": null})).unwrap(); + assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(300), Some(200))); + h.call("ui.pointer", drag(Value::Null)).unwrap(); + assert_ne!(h.call("document.json", json!({})).unwrap(), before, "null mods keep the packet's"); +} + // ---------- workflow tools ---------- fn id_of(result: &Value) -> u64 { @@ -1509,13 +1604,14 @@ fn text_effect_pathfinder_transform_graph_and_wrap_tools() { #[test] fn oversized_screenshot_and_png_export_are_errors() { // 16383 pt at the maximum scale (16) is 262 128 px a side: an error result, not a crashed server. + let dir = TempFolder::new("oversized-export"); let mut s = server(); let r = call(&mut s, 1, "run_command", json!({"command": "file.new", "params": {"width": 16383, "height": 16383}})); assert_eq!(r["isError"], false, "{r}"); let r = call(&mut s, 2, "screenshot", json!({"scale": 16})); assert_eq!(r["isError"], true, "{r}"); assert!(text_of(&r).contains("pixels"), "{r}"); - let path = tmp("huge.png"); + let path = dir.file("huge.png"); let r = call(&mut s, 3, "export", json!({"path": path.to_str().unwrap(), "scale": 16})); assert_eq!(r["isError"], true, "{r}"); assert!(!path.exists()); @@ -1966,6 +2062,10 @@ fn drawing_gestures_snap_to_smart_guides() { let b = &made["bounds"]; [&b["x"], &b["y"], &b["width"], &b["height"]].map(|v| v.as_f64().unwrap()) }; + // The rectangle drawn first stays selected, and the press lands on its box's corner handle, + // which would scale it instead of drawing. + let r = call(&mut s, 30, "run_command", json!({"command": "select.none", "params": {}})); + assert_eq!(r["isError"], false, "{r}"); let events = json!([{"kind": "move", "x": 202, "y": 203}, {"kind": "down", "x": 202, "y": 203}, {"kind": "drag", "x": 330, "y": 341}, {"kind": "up", "x": 330, "y": 341}]); assert_eq!(bounds(&mut s, 3, events, "rectangle"), [200.0, 200.0, 130.0, 141.0]); let r = call(&mut s, 5, "run_command", json!({"command": "select.none", "params": {}})); diff --git a/crates/mcp/src/tests/concurrency.rs b/crates/mcp/src/tests/concurrency.rs index d291d1e9fe..8e244b4eb0 100644 --- a/crates/mcp/src/tests/concurrency.rs +++ b/crates/mcp/src/tests/concurrency.rs @@ -10,6 +10,7 @@ use std::time::{Duration, Instant}; use serde_json::{Value, json}; use vectorcraft_engine::cancel; +use super::TempFolder; use crate::{Backend, Server}; /// A backend whose `engine.execute` runs until cancelled (or for `limit`), like a long export. @@ -318,8 +319,8 @@ impl Backend for Gated { #[test] fn a_cancelled_export_through_the_real_engine_writes_nothing_and_leaves_the_session_usable() { - let path = vectorcraft_testkit::temp_dir("mcp-cancel").join("out.pdf"); - std::fs::remove_file(&path).ok(); + let dir = TempFolder::new("cancel"); + let path = dir.file("out.pdf"); let (read, mut to_server) = std::io::pipe().unwrap(); let (tx, replies) = mpsc::channel(); let (started_tx, started) = mpsc::channel(); diff --git a/crates/mcp/src/tests/conventions.rs b/crates/mcp/src/tests/conventions.rs index 0b7352bf4a..3618f9214f 100644 --- a/crates/mcp/src/tests/conventions.rs +++ b/crates/mcp/src/tests/conventions.rs @@ -313,6 +313,84 @@ fn window_captures_take_max_side() { assert!(r["content"][0]["text"].as_str().unwrap().contains("`scale`"), "{r}"); } +/// The path an app from before `ui.screenshot {data}` was sent, with the mode of the folder holding +/// it on unix (`None` elsewhere). +type SeenPaths = std::sync::Arc)>>>; + +/// An app from before `ui.screenshot {data}`: it writes `png` (nothing when `None`) to the `path` +/// it is sent, keeps the path in `seen` and answers `reply`. A capture without a path is answered +/// with its size alone. +struct OldWindow { + png: Option>, + reply: Result, + seen: SeenPaths, +} +impl Backend for OldWindow { + fn call(&mut self, method: &str, p: Value) -> Result { + if method != "ui.screenshot" { + return Err(format!("unexpected {method}")); + } + // Without a path it ignores `data` and sends the size alone. + let Some(path) = p["path"].as_str().map(str::to_owned) else { return Ok(json!({"width": 2, "height": 1})) }; + #[cfg(unix)] + let mode = { + use std::os::unix::fs::PermissionsExt as _; + std::path::Path::new(&path).parent().and_then(|d| std::fs::metadata(d).ok()).map(|m| m.permissions().mode() & 0o777) + }; + #[cfg(not(unix))] + let mode = None; + self.seen.lock().unwrap().push((path.clone(), mode)); + if let Some(png) = &self.png { + std::fs::write(&path, png).map_err(|e| format!("{path}: {e}"))?; + } + self.reply.clone() + } + fn has_ui(&self) -> bool { + true + } + fn describe(&self) -> String { + "old window".into() + } +} + +/// An app without `ui.screenshot {data}` writes the window capture to a file in a new folder of its +/// own inside the system's temporary folder (owner-only on unix), never to a fixed name in the +/// shared folder itself. The folder is removed after the capture is read, and also when the app +/// fails after writing it or the file can't be read. +#[test] +fn an_old_app_captures_the_window_in_a_new_private_folder() { + let temp = std::env::temp_dir(); + let png = b"window capture".to_vec(); + let size = json!({"width": 2, "height": 1}); + let mut folders = Vec::new(); + for (written, reply, ok) in [ + (Some(png.clone()), Ok(size.clone()), true), + (Some(png.clone()), Ok(size.clone()), true), + (Some(png.clone()), Err("the capture failed".to_string()), false), + (None, Ok(size.clone()), false), + ] { + let seen = SeenPaths::default(); + let mut s = Server::new(Box::new(OldWindow { png: written, reply, seen: seen.clone() })); + let r = call(&mut s, "screenshot", json!({"window": true})); + assert_eq!(r["isError"], !ok, "{r}"); + if ok { + assert_eq!(vectorcraft_format::base64_decode(r["content"][0]["data"].as_str().unwrap()).unwrap(), png, "{r}"); + } + let seen = seen.lock().unwrap().clone(); + let [(path, mode)] = seen.as_slice() else { panic!("one capture: {seen:?}") }; + let dir = std::path::Path::new(path).parent().unwrap().to_path_buf(); + assert_eq!(dir.parent(), Some(temp.as_path()), "{path} is in a folder of its own inside {}", temp.display()); + assert!(!dir.exists(), "{} is removed", dir.display()); + if cfg!(unix) { + assert_eq!(*mode, Some(0o700), "{path}"); + } + folders.push(dir); + } + folders.sort(); + folders.dedup(); + assert_eq!(folders.len(), 4, "each capture has a new folder: {folders:?}"); +} + /// Each tool with another name for the same call names it in its description. #[test] fn alias_tools_name_their_pair() { diff --git a/crates/mcp/src/tests/exportas.rs b/crates/mcp/src/tests/exportas.rs index bc6e422d70..4e41002bf0 100644 --- a/crates/mcp/src/tests/exportas.rs +++ b/crates/mcp/src/tests/exportas.rs @@ -3,6 +3,7 @@ use serde_json::{Value, json}; +use super::TempFolder; use crate::{Backend, Headless, call_tool}; fn text(r: &crate::ToolResult) -> Value { @@ -39,18 +40,28 @@ fn an_option_no_format_takes_is_an_error() { assert!(e.contains(named), "{method}: {e}"); } } - // One object can still carry several formats' options. + // One object can still carry several formats' options; the warnings name those the file + // doesn't read. let r = call_tool(&mut h, "export", &json!({"format": "pdf", "options": {"quality": 80, "styling": "style"}})); assert!(!r.is_error, "{r:?}"); + let warnings = text(&r)["warnings"].clone(); + for key in ["quality", "styling"] { + assert!(warnings.as_array().unwrap().contains(&json!(format!("`{key}` was not used: PDF files don't read it"))), "{warnings}"); + } + // `app.export` and `file.export` give the same warning. + let params = json!({"format": "pdf", "quality": 80}); + let note = json!("`quality` was not used: PDF files don't read it"); + let r = h.call("app.export", params.clone()).unwrap(); + assert!(r["warnings"].as_array().unwrap().contains(¬e), "app.export: {r}"); + let r = h.call("engine.execute", json!({"command": "file.export", "params": params})).unwrap(); + assert!(r["warnings"].as_array().unwrap().contains(¬e), "file.export: {r}"); } /// `app.save`, `file.save` and `file.exportForScreens` refuse a key no format takes before they /// write anything. #[test] fn a_save_or_screens_option_no_format_takes_is_an_error() { - let dir = std::env::temp_dir().join(format!("vc-mcp-save-options-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); + let dir = TempFolder::new("save-options"); let mut h = Headless::new(); h.call("engine.execute", json!({"command": "file.new", "params": {"width": 50, "height": 30}})).unwrap(); let pdf = dir.join("a.pdf").to_string_lossy().into_owned(); @@ -71,9 +82,8 @@ fn a_save_or_screens_option_no_format_takes_is_an_error() { let e = h.call("engine.execute", json!({"command": "file.exportForScreens", "params": params})).unwrap_err(); assert!(e.contains(named), "file.exportForScreens: {e}"); } - assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "nothing was written"); + assert_eq!(std::fs::read_dir(&*dir).unwrap().count(), 0, "nothing was written"); h.call("app.save", json!({"path": pdf})).unwrap(); - let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -97,8 +107,7 @@ fn raster_export_uses_document_resolution_unless_overridden() { #[test] fn export_with_a_range_writes_one_file_per_artboard() { let mut h = three_boards(); - let dir = std::env::temp_dir().join(format!("vectorcraft-mcp-exportas-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); + let dir = TempFolder::new("exportas"); let path = dir.join("icon.png").to_string_lossy().to_string(); let args = json!({"path": path, "range": "1, 3", "options": {"useArtboards": true, "ppi": 144, "background": "white"}}); let r = text(&call_tool(&mut h, "export", &args)); @@ -120,5 +129,4 @@ fn export_with_a_range_writes_one_file_per_artboard() { let r = text(&call_tool(&mut h, "export", &json!({"format": format, "range": "1, 3"}))); assert_eq!(r["files"].as_array().map(Vec::len), Some(2), "{format}: {r}"); } - let _ = std::fs::remove_dir_all(dir); } diff --git a/crates/mcp/src/tests/fileio.rs b/crates/mcp/src/tests/fileio.rs index 00ff3a2d77..3a89588ecd 100644 --- a/crates/mcp/src/tests/fileio.rs +++ b/crates/mcp/src/tests/fileio.rs @@ -5,12 +5,12 @@ use std::io::{BufRead, BufReader, Write}; use serde_json::{Value, json}; +use super::TempFolder; use crate::{Backend, Headless, Remote, Server, call_tool, tool_definitions}; -fn tmp(name: &str) -> String { - let dir = std::env::temp_dir().join(format!("vectorcraft-mcp-fileio-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - dir.join(name).to_string_lossy().to_string() +/// The path of `name` in `dir`, as a string. +fn tmp(dir: &TempFolder, name: &str) -> String { + dir.file(name).to_string_lossy().to_string() } fn text(r: &crate::ToolResult) -> Value { @@ -29,22 +29,23 @@ fn two_boards() -> Headless { #[test] fn headless_opens_pdf_ai_and_templates() { + let dir = TempFolder::new("fileio-open"); let mut h = two_boards(); let pdf = h.call("engine.execute", json!({"command": "document.serialize", "params": {"format": "pdf"}})).unwrap(); let pdf = vectorcraft_format::base64_decode(pdf["dataBase64"].as_str().unwrap()).unwrap(); for name in ["x.pdf", "x.ai"] { - let path = tmp(name); + let path = tmp(&dir, name); std::fs::write(&path, &pdf).unwrap(); let r = text(&call_tool(&mut h, "open_file", &json!({"path": path}))); assert_eq!(r["title"], name); assert_eq!(h.session.doc().unwrap().doc.artboards.len(), 2, "one artboard per page"); } - let ait = tmp("x.ait"); + let ait = tmp(&dir, "x.ait"); std::fs::write(&ait, &pdf).unwrap(); let r = text(&call_tool(&mut h, "open_file", &json!({"path": ait}))); assert!(r["title"].as_str().unwrap().starts_with("Untitled-"), "{r}"); - let saved = h.call("engine.execute", json!({"command": "file.saveAsTemplate", "params": {"path": tmp("t.vectorcraft")}})).unwrap(); - let tpl = tmp("t.vctemplate"); + let saved = h.call("engine.execute", json!({"command": "file.saveAsTemplate", "params": {"path": tmp(&dir, "t.vectorcraft")}})).unwrap(); + let tpl = tmp(&dir, "t.vctemplate"); assert_eq!(saved["path"], tpl.as_str(), "saved with the template's extension: {saved}"); let r = text(&call_tool(&mut h, "open_file", &json!({"path": tpl}))); assert!(r["title"].as_str().unwrap().starts_with("Untitled-"), "{r}"); @@ -77,6 +78,7 @@ fn export_tool_lists_engine_formats_and_options() { "eps", "emf", "wmf", + "hpgl", "tga", "psd" ]) @@ -146,10 +148,11 @@ fn the_raster_scale_leaves_other_formats_alone() { #[test] fn exporting_native_keeps_the_document_path() { + let dir = TempFolder::new("fileio-keep-path"); let mut h = two_boards(); - let doc = tmp("keep.vectorcraft"); + let doc = tmp(&dir, "keep.vectorcraft"); h.call("app.save", json!({"path": doc})).unwrap(); - let copy = tmp("copy.vectorcraft"); + let copy = tmp(&dir, "copy.vectorcraft"); let r = text(&call_tool(&mut h, "export", &json!({"path": copy}))); assert_eq!(r["format"], "vectorcraft"); assert_eq!(h.session.doc().unwrap().path.as_deref(), Some(doc.as_str())); @@ -166,9 +169,9 @@ fn exporting_native_keeps_the_document_path() { assert_eq!(h.session.doc().unwrap().path.as_deref(), Some(doc.as_str())); } -/// The bytes `save_file` writes to `name` with `args`. -fn saved_with(h: &mut Headless, name: &str, mut args: Value) -> Vec { - let path = tmp(name); +/// The bytes `save_file` writes to `name` in `dir` with `args`. +fn saved_with(h: &mut Headless, dir: &TempFolder, name: &str, mut args: Value) -> Vec { + let path = tmp(dir, name); args["path"] = json!(path); let r = text(&call_tool(h, "save_file", &args)); assert_eq!(r["format"], "vectorcraft", "{r}"); @@ -177,22 +180,23 @@ fn saved_with(h: &mut Headless, name: &str, mut args: Value) -> Vec { #[test] fn save_file_takes_the_native_save_options() { + let dir = TempFolder::new("fileio-save-options"); let mut h = two_boards(); - let gz = saved_with(&mut h, "gz.vectorcraft", json!({"compress": true})); + let gz = saved_with(&mut h, &dir, "gz.vectorcraft", json!({"compress": true})); assert_eq!(gz[..2], [0x1f, 0x8b], "gzipped"); - let plain = saved_with(&mut h, "plain.vectorcraft", json!({"compress": false})); + let plain = saved_with(&mut h, &dir, "plain.vectorcraft", json!({"compress": false})); assert_eq!(plain[0], b'{', "plain JSON"); let nodes = h.session.doc().unwrap().doc.node_count(); for name in ["gz.vectorcraft", "plain.vectorcraft"] { let mut back = Headless::new(); - text(&call_tool(&mut back, "open_file", &json!({"path": tmp(name)}))); + text(&call_tool(&mut back, "open_file", &json!({"path": tmp(&dir, name)}))); assert_eq!(back.session.doc().unwrap().doc.node_count(), nodes, "{name} reopens"); } - let opt = saved_with(&mut h, "opt.vectorcraft", json!({"options": {"compress": true}})); + let opt = saved_with(&mut h, &dir, "opt.vectorcraft", json!({"options": {"compress": true}})); assert_eq!(opt[..2], [0x1f, 0x8b], "`options` carries them too"); - let v3: Value = serde_json::from_slice(&saved_with(&mut h, "v3.vectorcraft", json!({"version": 3, "preview": null}))).unwrap(); + let v3: Value = serde_json::from_slice(&saved_with(&mut h, &dir, "v3.vectorcraft", json!({"version": 3, "preview": null}))).unwrap(); assert_eq!(v3["version"], 3); - let shown = saved_with(&mut h, "preview.vectorcraft", json!({"preview": true})); + let shown = saved_with(&mut h, &dir, "preview.vectorcraft", json!({"preview": true})); assert!(vectorcraft_format::preview(&shown).is_some(), "a preview"); assert!(vectorcraft_format::preview(&plain).is_none(), "off by default"); // `precision` rounds the path coordinates of that save only. @@ -200,12 +204,12 @@ fn save_file_takes_the_native_save_options() { p.call("engine.execute", json!({"command": "file.new", "params": {"width": 100, "height": 100}})).unwrap(); p.call("engine.execute", json!({"command": "path.create", "params": {"anchors": [{"x": 10.123456, "y": 20.654321}, {"x": 30.5, "y": 40.25}]}})) .unwrap(); - let exact = String::from_utf8(saved_with(&mut p, "exact.vectorcraft", json!({"compress": false}))).unwrap(); + let exact = String::from_utf8(saved_with(&mut p, &dir, "exact.vectorcraft", json!({"compress": false}))).unwrap(); assert!(exact.contains("10.123456") && exact.contains("20.654321"), "{exact}"); - let rounded = String::from_utf8(saved_with(&mut p, "rounded.vectorcraft", json!({"compress": false, "precision": 1}))).unwrap(); + let rounded = String::from_utf8(saved_with(&mut p, &dir, "rounded.vectorcraft", json!({"compress": false, "precision": 1}))).unwrap(); assert!(!rounded.contains("10.123456") && !rounded.contains("20.654321") && rounded.contains("20.7"), "{rounded}"); // Version 2 files can't be compressed: the engine's error comes back. - let r = call_tool(&mut h, "save_file", &json!({"path": tmp("v2.vectorcraft"), "version": 2, "compress": true})); + let r = call_tool(&mut h, "save_file", &json!({"path": tmp(&dir, "v2.vectorcraft"), "version": 2, "compress": true})); assert!(r.is_error && r.content[0]["text"].as_str().unwrap().contains("can't be compressed"), "{r:?}"); // The options are in the schema; a misspelled one is still refused. @@ -213,9 +217,9 @@ fn save_file_takes_the_native_save_options() { let call = |s: &mut Server, args: Value| { s.handle(json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "save_file", "arguments": args}})).unwrap() }; - let r = call(&mut s, json!({"path": tmp("ok.vectorcraft"), "compress": true})); + let r = call(&mut s, json!({"path": tmp(&dir, "ok.vectorcraft"), "compress": true})); assert_eq!(r["result"]["isError"], false, "{r}"); - let r = call(&mut s, json!({"path": tmp("typo.vectorcraft"), "compresss": true})); + let r = call(&mut s, json!({"path": tmp(&dir, "typo.vectorcraft"), "compresss": true})); assert_eq!(r["error"]["code"], -32602, "{r}"); assert!(r["error"]["message"].as_str().unwrap().contains("unknown argument `compresss`"), "{r}"); } @@ -224,12 +228,13 @@ fn save_file_takes_the_native_save_options() { /// that disagrees with the same key in `options` is an error. #[test] fn save_file_warns_about_options_it_does_not_use() { + let dir = TempFolder::new("fileio-unused-options"); let mut h = two_boards(); let warnings = |r: &Value| -> Vec { r["warnings"].as_array().unwrap().iter().map(|w| w.as_str().unwrap().to_string()).collect() }; let ignored = |w: &[String], key: &str| w.iter().any(|w| w.starts_with(&format!("`{key}` was not used"))); // SVG reads none of them, at the top level or in `options`. - let path = tmp("ignored.svg"); + let path = tmp(&dir, "ignored.svg"); let r = text(&call_tool(&mut h, "save_file", &json!({"path": path, "compress": true, "version": 3, "options": {"preview": true}}))); assert_eq!(r["format"], "svg", "{r}"); let w = warnings(&r); @@ -238,16 +243,15 @@ fn save_file_warns_about_options_it_does_not_use() { assert!(w.iter().any(|w| w.contains("SVG")), "names the format: {w:?}"); assert!(std::fs::read(&path).unwrap().starts_with(b"<"), "plain SVG"); // A .ai file reads `compress` but not `version`. - let r = text(&call_tool(&mut h, "save_file", &json!({"path": tmp("ignored.ai"), "compress": false, "version": 3}))); + let r = text(&call_tool(&mut h, "save_file", &json!({"path": tmp(&dir, "ignored.ai"), "compress": false, "version": 3}))); let w = warnings(&r); assert!(ignored(&w, "version") && !ignored(&w, "compress"), "{w:?}"); // `precision` is read by native files only. - let r = text(&call_tool(&mut h, "save_file", &json!({"path": tmp("ignored-precision.svg"), "precision": 2}))); + let r = text(&call_tool(&mut h, "save_file", &json!({"path": tmp(&dir, "ignored-precision.svg"), "precision": 2}))); assert!(ignored(&warnings(&r), "precision"), "{r}"); // A top-level value that disagrees with `options` is refused, and nothing is written. - let path = tmp("both.vectorcraft"); - let _ = std::fs::remove_file(&path); + let path = tmp(&dir, "both.vectorcraft"); let r = call_tool(&mut h, "save_file", &json!({"path": path, "compress": true, "options": {"compress": false}})); let e = r.content[0]["text"].as_str().unwrap(); assert!(r.is_error && e.contains("`compress: true` and `options.compress: false` disagree"), "{r:?}"); @@ -256,7 +260,7 @@ fn save_file_warns_about_options_it_does_not_use() { for mut args in [json!({"compress": true, "options": {"compress": true}}), json!({"compress": false, "version": 3, "preview": true, "precision": 4})] { - args["path"] = json!(tmp("quiet.vectorcraft")); + args["path"] = json!(tmp(&dir, "quiet.vectorcraft")); let r = text(&call_tool(&mut h, "save_file", &args)); assert_eq!(r["warnings"], json!([]), "{args}: {r}"); } @@ -285,6 +289,7 @@ fn save_file_warns_about_options_it_does_not_use() { /// when the save reuses the options the document was last saved with. #[test] fn save_file_notes_name_the_ai_file_it_writes() { + let dir = TempFolder::new("fileio-ai-notes"); let mut h = Headless::with_document(); let notes = |r: &Value| -> Vec { r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).filter(|w| w.contains("was not used")).map(str::to_string).collect() @@ -295,21 +300,22 @@ fn save_file_notes_name_the_ai_file_it_writes() { ("no-pdf.ai", json!({"pdfCompatible": false, "preview": true}), "non-PDF-compatible .ai"), ("pdf.ai", json!({"pdfCompatible": true, "preview": true}), "PDF-compatible .ai"), ] { - let r = text(&call_tool(&mut h, "save_file", &json!({"path": tmp(name), "version": 3, "options": options}))); + let r = text(&call_tool(&mut h, "save_file", &json!({"path": tmp(&dir, name), "version": 3, "options": options}))); let expected = [format!("`version` was not used: {label} files don't read it"), format!("`options.preview` was not used: {label} files don't read it")]; assert_eq!(notes(&r), expected, "{name}: {r}"); } // A save given no option the file reads writes it as last saved: a legacy `.ai` again. - text(&call_tool(&mut h, "save_file", &json!({"path": tmp("again.ai"), "options": {"aiVersion": "7"}}))); - let r = text(&call_tool(&mut h, "save_file", &json!({"path": tmp("again.ai"), "options": {"preview": true}}))); + text(&call_tool(&mut h, "save_file", &json!({"path": tmp(&dir, "again.ai"), "options": {"aiVersion": "7"}}))); + let r = text(&call_tool(&mut h, "save_file", &json!({"path": tmp(&dir, "again.ai"), "options": {"preview": true}}))); assert_eq!(notes(&r), ["`options.preview` was not used: legacy .ai (version 7) files don't read it"], "{r}"); - assert!(std::fs::read(tmp("again.ai")).unwrap().starts_with(b"%!PS"), "a legacy .ai is written"); + assert!(std::fs::read(tmp(&dir, "again.ai")).unwrap().starts_with(b"%!PS"), "a legacy .ai is written"); } #[test] fn save_file_is_the_same_call_in_the_app_and_headless() { - let path = tmp("app.vectorcraft"); + let dir = TempFolder::new("fileio-app-save"); + let path = tmp(&dir, "app.vectorcraft"); let (addr, app) = recording_app(); let mut remote = Remote::connect(&addr).unwrap(); let args = json!({"path": path, "compress": true, "version": 3, "preview": null, "precision": 2, "options": {"preview": true}}); @@ -357,6 +363,29 @@ fn save_file_waits_for_the_file_in_the_app() { } } +#[test] +fn readonly_save_file_keeps_the_stable_error_prefix() { + struct Refused(bool); + impl Backend for Refused { + fn call(&mut self, method: &str, params: Value) -> Result { + assert_eq!(method, "app.save"); + assert_eq!(params.get("wait").and_then(Value::as_bool), self.0.then_some(true)); + Err(vectorcraft_engine::EngineError::ReadOnlyLocation("Poster.svg: injected refusal".into()).to_string()) + } + fn has_ui(&self) -> bool { + self.0 + } + fn describe(&self) -> String { + "injected save refusal".into() + } + } + for desktop in [false, true] { + let r = call_tool(&mut Refused(desktop), "save_file", &json!({})); + assert!(r.is_error); + assert_eq!(r.content[0]["text"], "save_file: READ_ONLY_LOCATION: Poster.svg: injected refusal"); + } +} + fn pdf_pages(pdf: &[u8]) -> usize { let mut h = Headless::new(); h.call("engine.execute", json!({"command": "document.open", "params": {"name": "p.pdf", "dataBase64": vectorcraft_format::base64_encode(pdf)}})) @@ -368,7 +397,8 @@ fn pdf_pages(pdf: &[u8]) -> usize { /// only, in the document and in the exported PDF. #[test] fn document_color_mode_puts_rgb_greys_on_the_black_plate() { - let svg = tmp("greys.svg"); + let dir = TempFolder::new("fileio-greys"); + let svg = tmp(&dir, "greys.svg"); std::fs::write( &svg, r##" @@ -423,7 +453,8 @@ fn open_file_passes_the_importer_on() { let tools = tool_definitions(); let open = tools.iter().find(|t| t["name"] == "open_file").unwrap(); assert!(open["inputSchema"]["properties"].get("importer").is_some(), "{open}"); - let svg = tmp("importer.svg"); + let dir = TempFolder::new("fileio-importer"); + let svg = tmp(&dir, "importer.svg"); std::fs::write(&svg, r#""#).unwrap(); let mut h = Headless::new(); assert_eq!(text(&call_tool(&mut h, "open_file", &json!({"path": svg})))["format"], "svg"); diff --git a/crates/mcp/src/tests/links.rs b/crates/mcp/src/tests/links.rs index 20298fc612..61d660a8d8 100644 --- a/crates/mcp/src/tests/links.rs +++ b/crates/mcp/src/tests/links.rs @@ -3,6 +3,7 @@ use serde_json::{Value, json}; +use super::TempFolder; use crate::{Headless, call_tool}; fn run(h: &mut Headless, command: &str, params: Value) -> Value { @@ -13,9 +14,8 @@ fn run(h: &mut Headless, command: &str, params: Value) -> Value { #[test] fn headless_links_report_missing_files_and_relink() { - let dir = std::env::temp_dir().join(format!("vectorcraft-mcp-links-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let file = |n: &str| dir.join(n).to_string_lossy().into_owned(); + let dir = TempFolder::new("links"); + let file = |n: &str| dir.file(n).to_string_lossy().into_owned(); let mut h = Headless::new(); run(&mut h, "file.new", json!({"width": 300, "height": 200})); let png = run(&mut h, "document.serialize", json!({"format": "png"})); @@ -30,5 +30,4 @@ fn headless_links_report_missing_files_and_relink() { let r = run(&mut h, "links.relink", json!({"ids": [id], "path": file("b.png")})); assert_eq!(r["relinked"], json!([id])); assert_eq!(run(&mut h, "links.check", json!({}))["links"][0]["status"], "ok"); - let _ = std::fs::remove_dir_all(dir); } diff --git a/crates/mcp/src/tools/definitions.rs b/crates/mcp/src/tools/definitions.rs index 17c7ecc912..d4d69c945f 100644 --- a/crates/mcp/src/tools/definitions.rs +++ b/crates/mcp/src/tools/definitions.rs @@ -259,7 +259,7 @@ pub fn tool_definitions() -> Vec { "radius1": num("Star outer radius"), "radius2": num("Star inner radius"), "points": {"type": "integer", "minimum": 3, "description": "Star points (default 5)"}, - "rotation": num("Rotation in degrees clockwise (polygon/star; 0: a corner or point straight up)"), + "rotation": num("Rotation in degrees clockwise about the centre (rectangle/ellipse: 0 upright; polygon/star: 0 a corner or point straight up)"), "x1": num("Line start x"), "y1": num("Line start y"), "x2": num("Line end x"), @@ -393,14 +393,14 @@ pub fn tool_definitions() -> Vec { tool( "export", "Export", - "Export the active document with the engine's document.export (the same bytes in the app and headless), in any format of the `format` enum: vectors (svg/svgz with the artboard as viewBox, eps, dxf, emf, wmf), pdf and ai (one page per artboard: all, or `artboard` / `range`; ai is the PDF-compatible .ai file that Save writes, which carries the document when every artboard is written in order), rasters (one rendered artboard: png, jpg, webp, gif, png8 as an indexed .png, tiff, bmp, tga, psd with its layers), txt (the stories, back to front), vectorcraft or template (a native copy or template; the document keeps its path). run_command document.formats lists each format's options. For SVG/SVGZ, top-level `outlineText: true` writes text as paths; DXF takes it too (its type is outlined anyway unless `preserve: editability`). PDF instead uses `options.advanced.outlineText: true`, default false (live text). `selection: true` exports only the selected objects, cropped to their bounds. Template layers are left out; live effects are kept (geometry baked, SVG filters for shadows/glows/blur). Without `path` the bytes come back as dataBase64.", + "Export the active document with the engine's document.export (the same bytes in the app and headless), in any format of the `format` enum: vectors (svg/svgz with the artboard as viewBox, eps, dxf, emf, wmf, hpgl pen moves for plotters and cutters), pdf and ai (one page per artboard: all, or `artboard` / `range`; ai is the PDF-compatible .ai file that Save writes, which carries the document when every artboard is written in order), rasters (one rendered artboard: png, jpg, webp, gif, png8 as an indexed .png, tiff, bmp, tga, psd with its layers), txt (the stories, back to front), vectorcraft or template (a native copy or template; the document keeps its path). run_command document.formats lists each format's options. For SVG/SVGZ, top-level `outlineText: true` writes text as paths; DXF takes it too (its type is outlined anyway unless `preserve: editability`). PDF instead uses `options.advanced.outlineText: true`, default false (live text). `selection: true` exports only the selected objects, cropped to their bounds. Template layers are left out; live effects are kept (geometry baked, SVG filters for shadows/glows/blur). Without `path` the bytes come back as dataBase64.", obj( json!({ "format": {"type": "string", "enum": FORMATS.iter().filter(|f| f.write).map(|f| f.id).collect::>(), "description": "Default: from the path's extension"}, "path": string("Destination file (omit to get dataBase64)"), "scale": num("Raster pixels per point (without scale or options.ppi, uses the document's raster effects resolution; options.ppi wins)"), "artboard": {"type": "integer", "minimum": 0, "description": "0-based artboard (default: the first; PDF and .ai default: all)"}, - "range": string("1-based artboards such as \"1-3, 5\" (PDF and .ai: one page each; SVG and SVGZ: one file each; EPS: one file each, after a central file of the whole document when there are two or more and art shows; rasters, DXF, EMF and WMF: one, or one file each with options.useArtboards: true)"), + "range": string("1-based artboards such as \"1-3, 5\" (PDF and .ai: one page each; SVG and SVGZ: one file each; EPS: one file each, after a central file of the whole document when there are two or more and art shows; rasters, DXF, EMF, WMF and HP-GL: one, or one file each with options.useArtboards: true)"), "selection": {"type": "boolean", "description": "Export only the selection, cropped to it"}, "outlineText": {"type": "boolean", "description": "SVG/SVGZ: true writes text as outlines (viewable without the fonts). DXF takes it too (type outlined anyway unless preserve: editability). PDF uses options.advanced.outlineText instead (default false: live text)"}, "options": {"type": "object", "description": "More format options, passed through (see run_command document.formats), e.g. {\"quality\": 80} for jpg or {\"advanced\": {\"outlineText\": true}} for PDF text as outlines (default false: live text)"}, diff --git a/crates/mcp/src/tools/handlers.rs b/crates/mcp/src/tools/handlers.rs index e76b5704ae..39d3f3f8e1 100644 --- a/crates/mcp/src/tools/handlers.rs +++ b/crates/mcp/src/tools/handlers.rs @@ -437,18 +437,52 @@ pub(super) fn screenshot(b: &mut dyn Backend, a: &Args) -> Result) -> Result { - let tmp = std::env::temp_dir().join(format!("vectorcraft-window-{}.png", std::process::id())).to_string_lossy().to_string(); - let r = b.call("ui.screenshot", json!({"path": tmp}))?; - let png = std::fs::read(&tmp).map_err(|e| format!("read {tmp}: {e}"))?; - // Best effort: a temporary file left behind is harmless. - std::fs::remove_file(&tmp).ok(); + let dir = new_capture_folder(&std::env::temp_dir())?; + let tmp = dir.join("window.png").to_string_lossy().to_string(); + let captured = b.call("ui.screenshot", json!({"path": tmp})).and_then(|r| Ok((std::fs::read(&tmp).map_err(|e| format!("read {tmp}: {e}"))?, r))); + // Best effort: a folder that can't be removed holds only this capture, and on unix only its + // owner can open it. + let _ = std::fs::remove_dir_all(&dir); + let (png, r) = captured?; let mut info = json!({"window": true, "width": r.get("width"), "height": r.get("height"), "path": Value::Null}); let png = fit_capture(png, max, &mut info)?; Ok(image_result(&png, info)) } +/// A new folder in `parent` named `vectorcraft-window-` followed by the process id, `-` and a count +/// of the process's captures; on unix only its owner can open it. A name that is already taken, by +/// an earlier process with the same id or by anyone else, is skipped for the next count. +fn new_capture_folder(parent: &std::path::Path) -> Result { + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + loop { + let dir = parent.join(format!("vectorcraft-window-{}-{}", std::process::id(), NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed))); + match private_folder().create(&dir) { + Ok(()) => return Ok(dir), + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {} + Err(e) => return Err(format!("{}: {e}", dir.display())), + } + } +} + +/// A builder for folders that only their owner can read, write or open (mode 0o700). +#[cfg(unix)] +fn private_folder() -> std::fs::DirBuilder { + let mut b = std::fs::DirBuilder::new(); + std::os::unix::fs::DirBuilderExt::mode(&mut b, 0o700); + b +} + +/// A builder for folders: a plain one outside unix. +#[cfg(not(unix))] +fn private_folder() -> std::fs::DirBuilder { + std::fs::DirBuilder::new() +} + /// `max_side`: absent, or an integer in 1..4096. pub(super) fn max_side(a: &Args) -> Result, String> { match a.get("max_side") { diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 0f2d10d89f..dcde7c5076 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -39,7 +39,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "file.save", "Save", "Cmd+S", - "{path?, format?, options?, svg?: {…SVG options}} = document.save, written through the app (a document saved as SVG, PDF or .ai, or opened from one Save can write back, saves as that again, with the same options); with no path known (never saved, converted) the Save As panel asks first", + "{path?, format?, options?, svg?: {…SVG options}} = document.save, written through the app (a document saved as SVG, PDF or .ai, or opened from one Save can write back, saves as that again, with the same options); with no path known (never saved, converted) the Save As panel asks first; ordinary Save to the document's existing file refused by filesystem permissions or a read-only volume opens Save As in Documents with the same name, format and options; cancelling keeps the original path and modified state. Explicit destinations and Close/Quit keep their existing error dialog. Automation gets READ_ONLY_LOCATION: followed by the reason and no panel", ), ( "file.place", @@ -195,7 +195,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ ("view.pixelPreview", "Pixel Preview", "Cmd+Alt+Y", "{}"), ("view.trimView", "Trim View", "", "{} toggle: hide everything outside the artboards"), ("view.cornerWidget", "Hide Corner Widget", "", "{} toggle the live corner widgets"), - ("view.snapToPixel", "Snap to Pixel", "", "{} toggle: drawing and moving land on whole pixels"), + ( + "view.snapToPixel", + "Snap to Pixel", + "", + "{} toggle: drawing, moving and scaling land on whole pixels, each while its option in view.snapToPixel.options is on", + ), ( "view.snapToGlyph", "Snap to Glyph", @@ -261,91 +266,91 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "align.horizontalLeft", "Horizontal Align Left", "", - "{} the Align panel's Horizontal Align Left button: object.align {horizontal: \"left\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice", + "{} the Align panel's Horizontal Align Left button: object.align {horizontal: \"left\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice; with the Artboard tool chosen, artboard.align with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) while Align to Artboard is chosen, else \"selection\"", ), ( "align.horizontalCenter", "Horizontal Align Center", "", - "{} the Align panel's Horizontal Align Center button: object.align {horizontal: \"center\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice", + "{} the Align panel's Horizontal Align Center button: object.align {horizontal: \"center\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice; with the Artboard tool chosen, artboard.align with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) while Align to Artboard is chosen, else \"selection\"", ), ( "align.horizontalRight", "Horizontal Align Right", "", - "{} the Align panel's Horizontal Align Right button: object.align {horizontal: \"right\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice", + "{} the Align panel's Horizontal Align Right button: object.align {horizontal: \"right\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice; with the Artboard tool chosen, artboard.align with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) while Align to Artboard is chosen, else \"selection\"", ), ( "align.horizontalVerticalCenter", "Horizontal & Vertical Align Center", "", - "{} the Align panel's Horizontal & Vertical Align Center button: object.align {horizontal: \"center\", vertical: \"center\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice", + "{} the Align panel's Horizontal & Vertical Align Center button: object.align {horizontal: \"center\", vertical: \"center\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice; with the Artboard tool chosen, artboard.align with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) while Align to Artboard is chosen, else \"selection\"", ), ( "align.verticalTop", "Vertical Align Top", "", - "{} the Align panel's Vertical Align Top button: object.align {vertical: \"top\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice", + "{} the Align panel's Vertical Align Top button: object.align {vertical: \"top\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice; with the Artboard tool chosen, artboard.align with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) while Align to Artboard is chosen, else \"selection\"", ), ( "align.verticalCenter", "Vertical Align Center", "", - "{} the Align panel's Vertical Align Center button: object.align {vertical: \"center\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice", + "{} the Align panel's Vertical Align Center button: object.align {vertical: \"center\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice; with the Artboard tool chosen, artboard.align with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) while Align to Artboard is chosen, else \"selection\"", ), ( "align.verticalBottom", "Vertical Align Bottom", "", - "{} the Align panel's Vertical Align Bottom button: object.align {vertical: \"bottom\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice", + "{} the Align panel's Vertical Align Bottom button: object.align {vertical: \"bottom\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice; with the Artboard tool chosen, artboard.align with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) while Align to Artboard is chosen, else \"selection\"", ), ( "align.distributeVerticalTop", "Vertical Distribute Top", "", - "{} the Align panel's Vertical Distribute Top button: object.distribute {vertical: \"top\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key", + "{} the Align panel's Vertical Distribute Top button: object.distribute {vertical: \"top\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key; with the Artboard tool chosen, the artboard command of the same name (artboard.distribute, artboard.distributeSpacing) with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) and spacing: the Distribute Spacing value while Align to Artboard is chosen, else \"selection\"", ), ( "align.distributeVerticalCenter", "Vertical Distribute Center", "", - "{} the Align panel's Vertical Distribute Center button: object.distribute {vertical: \"center\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key", + "{} the Align panel's Vertical Distribute Center button: object.distribute {vertical: \"center\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key; with the Artboard tool chosen, the artboard command of the same name (artboard.distribute, artboard.distributeSpacing) with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) and spacing: the Distribute Spacing value while Align to Artboard is chosen, else \"selection\"", ), ( "align.distributeVerticalBottom", "Vertical Distribute Bottom", "", - "{} the Align panel's Vertical Distribute Bottom button: object.distribute {vertical: \"bottom\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key", + "{} the Align panel's Vertical Distribute Bottom button: object.distribute {vertical: \"bottom\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key; with the Artboard tool chosen, the artboard command of the same name (artboard.distribute, artboard.distributeSpacing) with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) and spacing: the Distribute Spacing value while Align to Artboard is chosen, else \"selection\"", ), ( "align.distributeHorizontalLeft", "Horizontal Distribute Left", "", - "{} the Align panel's Horizontal Distribute Left button: object.distribute {horizontal: \"left\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key", + "{} the Align panel's Horizontal Distribute Left button: object.distribute {horizontal: \"left\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key; with the Artboard tool chosen, the artboard command of the same name (artboard.distribute, artboard.distributeSpacing) with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) and spacing: the Distribute Spacing value while Align to Artboard is chosen, else \"selection\"", ), ( "align.distributeHorizontalCenter", "Horizontal Distribute Center", "", - "{} the Align panel's Horizontal Distribute Center button: object.distribute {horizontal: \"center\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key", + "{} the Align panel's Horizontal Distribute Center button: object.distribute {horizontal: \"center\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key; with the Artboard tool chosen, the artboard command of the same name (artboard.distribute, artboard.distributeSpacing) with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) and spacing: the Distribute Spacing value while Align to Artboard is chosen, else \"selection\"", ), ( "align.distributeHorizontalRight", "Horizontal Distribute Right", "", - "{} the Align panel's Horizontal Distribute Right button: object.distribute {horizontal: \"right\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key", + "{} the Align panel's Horizontal Distribute Right button: object.distribute {horizontal: \"right\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key; with the Artboard tool chosen, the artboard command of the same name (artboard.distribute, artboard.distributeSpacing) with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) and spacing: the Distribute Spacing value while Align to Artboard is chosen, else \"selection\"", ), ( "align.distributeVerticalSpace", "Vertical Distribute Space", "", - "{} the Align panel's Vertical Distribute Space button: object.distributeSpacing {axis: \"vertical\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key", + "{} the Align panel's Vertical Distribute Space button: object.distributeSpacing {axis: \"vertical\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key; with the Artboard tool chosen, the artboard command of the same name (artboard.distribute, artboard.distributeSpacing) with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) and spacing: the Distribute Spacing value while Align to Artboard is chosen, else \"selection\"", ), ( "align.distributeHorizontalSpace", "Horizontal Distribute Space", "", - "{} the Align panel's Horizontal Distribute Space button: object.distributeSpacing {axis: \"horizontal\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key", + "{} the Align panel's Horizontal Distribute Space button: object.distributeSpacing {axis: \"horizontal\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key; with the Artboard tool chosen, the artboard command of the same name (artboard.distribute, artboard.distributeSpacing) with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) and spacing: the Distribute Spacing value while Align to Artboard is chosen, else \"selection\"", ), ( "type.bold", @@ -404,7 +409,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "view.actualSize", "Actual Size", "Cmd+1", - "{} 100%: with Display Print Size at 100% Zoom off, one document point per screen point; on, one document inch fills 96 screen points (an inch at the system's reference density, whatever the display scaling)", + "{} 100%: with Display Print Size at 100% Zoom off, one document point per screen point; on, one document inch fills 96 screen points (an inch at the system's reference density, whatever the display scaling); the same at every UI Scaling", ), ("view.setZoom", "Set Zoom", "", "{zoom: percent, center?: [x,y]}"), ( @@ -469,7 +474,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "window.control.dock", "Dock Control Bar", "", - "{edge: \"top\"|\"bottom\"} dock the Control bar to the top of the window, under the menu bar, or to its bottom, as the bar's panel menu (Dock to Top, Dock to Bottom) and a drag of its gripper do; kept with the workspace; another edge is an error and changes nothing; returns {edge}", + "{edge: \"top\"|\"bottom\"|\"float\"} dock the Control bar to the top of the window, under the menu bar, or to its bottom, as the bar's panel menu (Dock to Top, Dock to Bottom) and a drag of its gripper do, or float it over the window at the position it last floated at (first: its top-left corner at 60, 80 in window points), as a gripper drag released away from both edges does; kept with the workspace; another edge is an error and changes nothing; returns {edge}", ), ( "window.control.options", @@ -563,7 +568,24 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{name: string} delete the toolbar made with New Toolbar called `name`, and the groups torn off it, from the current workspace, as Manage Toolbars' trash can does", ), - ("window.toolbar.list", "List Toolbars", "", "{} the toolbars made with New Toolbar in the current workspace: [{name, shown, double, slots}]"), + ( + "window.toolbar.dock", + "Dock Toolbar", + "", + "{name: string, side?: left|right, order?: int} dock the toolbar made with New Toolbar called `name` in the lane along the window's left or right edge (omitted: the edge it docked at last, the left at first), as Dock to Left and Dock to Right in its title bar's context menu and dropping its title bar on that edge do; `order` is its place in that edge's stack, 0 at the top (omitted: the end, or where it is when it is docked at that edge already); a bad `side` or `order` is an error and changes nothing; returns {toolbar, floating, side, order, pos}", + ), + ( + "window.toolbar.float", + "Float Toolbar", + "", + "{name: string, x?: number, y?: number} float the toolbar made with New Toolbar called `name` with its top-left corner at x, y in screen points (both or neither; omitted: where it floated last), as Float Toolbar in its title bar's context menu and dragging its title bar out of its lane do; returns {toolbar, floating, side, order, pos}", + ), + ( + "window.toolbar.list", + "List Toolbars", + "", + "{} the toolbars made with New Toolbar in the current workspace: [{name, shown, double, slots, floating, side, order}], `side` the edge it docks at (while floating, the edge it docked at last) and `order` its place in that edge's stack while docked (else null)", + ), ("window.taskBar", "Contextual Task Bar", "", "{}"), ( "window.pathfinder.compoundShapes", @@ -594,7 +616,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "window.panel", "Show Panel", "", - "{panel: id, toggle?: bool} e.g. layers, swatches, stroke (case-insensitive; display labels like \"Layers\" work too); toggle (the Window menu) hides a panel that shows, and shows it again where it was", + "{panel: id, toggle?: bool} e.g. layers, swatches, stroke (case-insensitive; display labels like \"Layers\" work too); toggle (the Window menu) hides a panel that can be seen, and shows it again where it was; with the dock hidden by Tab or Shift+Tab, the dock shows again with the panel in front, leaving the toolbar and Control bar as they are; fails and changes nothing in Presentation Mode, which hides every panel", ), ( "window.panel.layout", @@ -634,6 +656,54 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{collapsed?: bool} collapse every expanded dock column to icons (true), expand the outer dock column, Properties | Layers | Libraries (false), or toggle the outer column (omitted), as the double arrow at the top of the dock does; returns the new state", ), + ( + "window.learn", + "Learn", + "", + "{show?: bool} show (true), hide (false) or toggle (omitted or null) the Learn panel, as Window › Learn and the app bar's Explore tutorials button do; any other value is an error and changes nothing; returns whether the panel shows", + ), + ( + "learn.list", + "List Tutorials", + "", + "{} the Learn panel's skills in the order its Skills tab lists them: {skills: [{id, title, tutorials: [{id, title, steps: number of steps}]}]}", + ), + ( + "learn.skills", + "Back to Skills", + "", + "{} show the Learn panel on its Skills tab with the list of skills, with no skill and no tutorial open, as Back to skills after a skill's last tutorial and the Quick skill guide card do; returns what learn.list returns", + ), + ( + "learn.show", + "Show Tutorial", + "", + "{tutorial: id (see learn.list)} show the Learn panel on its Skills tab with that tutorial's numbered steps, as choosing its skill and then the tutorial does; a missing, non-string or unknown id is an error and changes nothing; returns {skill, tutorial, title, steps: [text]}", + ), + ( + "learn.locateTool", + "Show Tool Location", + "", + "{tool: a tool id, as tool.select takes} mark where that tool is for 3 seconds without choosing it, as the link on a tool's name in a Learn tutorial step does: its toolbar button, a row of its collapsed group's flyout (which opens), its group's torn-off strip (which comes to the front), or, when no shown toolbar holds it, its row in the All Tools drawer (which opens); a Tools panel hidden with Window › Tools shows again; Escape or the next locate removes the mark; a missing, non-string or unknown id is an error and changes nothing; returns {tool, location: toolbar|flyout|strip|allTools|unavailable, toolbar: the name of the toolbar made with New Toolbar that holds it, or null}, with reason when Presentation Mode or Tab hides the toolbars", + ), + ( + "learn.openSample", + "Open Tutorial Sample", + "", + "{tutorial: id (see learn.list)} open that tutorial's practice sample as a new untitled document, which becomes the active one, and move the Learn view to the tutorial, as its View more button does; each call opens another copy and open documents stay as they are; a missing, non-string or unknown id is an error and changes nothing; returns {tutorial, index, title} of the new document", + ), + ( + "learn.finish", + "Finish Tutorial", + "", + "{tutorial: id (see learn.list)} mark a tutorial whose sample learn.openSample opened as finished, as its Finish tutorial button does; finishing it again keeps one entry; a missing, non-string or unknown id, or a tutorial whose sample was not opened, is an error and changes nothing; returns {tutorial, finished: true, next: id of the next tutorial in its skill, or null after the skill's last one}", + ), + ( + "learn.next", + "Next Tutorial", + "", + "{tutorial: id (see learn.list)} show the Learn panel on the tutorial after a finished one in the same skill, as its Next Up button does, without opening a sample; a missing, non-string or unknown id, a tutorial not finished, or a skill's last tutorial is an error and changes nothing; returns {skill, tutorial, title} of the next tutorial", + ), ("window.brightness", "UI Brightness", "", "{brightness: dark|mediumDark|mediumLight|light}"), ( "window.workspace", @@ -707,6 +777,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{key, value} | {values: {key: value…}}, tool?: id (default: the active tool) → the tool's options (`{}` reads them). The options a tool keeps (Liquify brush and tool options, Mirror & Cut, Puppet Warp, drawing tools…) last across tool switches and are saved with the preferences; another tool's are stored for when it is chosen", ), + ( + "tool.toggleTouchMode", + "Switch Selection and Drawing Modes", + "", + "{} from the Selection, Direct Selection, Group Selection, Magic Wand, Lasso or Perspective Selection tool, choose the drawing tool chosen last in this window (none yet: the Pencil tool); from any other tool, choose the Selection tool, remembering the tool left as the drawing tool unless it is the Hand, Rotate View, Zoom or Print Tiling tool → {tool}. A two-finger tap on the canvas runs it in the Touch workspace (Enable Touch Gestures on)", + ), ( "effect.dialog", "Effect…", @@ -748,6 +824,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} open the Safe Mode dialog (dialog `safeMode`): whether VectorCraft is in Safe Mode, and the disabled plug-ins, each with Enable on Re-launch (engine: plugin.setEnabled). Closing it leaves Safe Mode as it is; Safe Mode is chosen at launch (--safe-mode, or the choice after a launch that stopped while a plug-in was loading, dialog `pluginStopped`)", ), + ( + "help.copyTroubleshootingInfo", + "Copy Troubleshooting Info", + "", + "{} put text for a bug report on the clipboard: the version, and in the desktop app the platform, the window system, the graphics processor, the commands and frame times of the last few frames, and the hang reports of this session and the session before (no document contents or file paths) → {chars}", + ), ("app.quit", "Quit VectorCraft", "Cmd+Q", "{}"), ( "ui.swatchOptions", @@ -777,7 +859,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.sampleScreenColor", "Sample Color from Screen", "", - "{} or {stroke?: bool (default: the active proxy), picker?: bool (the open Color Picker instead)} show the system's color sampler (macOS; browsers with an EyeDropper) and answer at once; the color the person picks anywhere on the screen then runs paint.setFill / paint.setStroke (one undo step) or becomes the Color Picker's color (field `color`), converted from display sRGB into the working RGB space; Escape cancels it and the colors stay as they were. ui.inspect reports `screenSampler: true` until it answers. An error without a sampler, while one is open, or with `picker` and no Color Picker open", + "{} or {stroke?: bool (default: the active proxy), picker?: bool (the open Color Picker instead)} show the system's color sampler (macOS; Linux through the XDG desktop portal's PickColor; browsers with an EyeDropper) and answer at once; the color the person picks anywhere on the screen then runs paint.setFill / paint.setStroke (one undo step) or becomes the Color Picker's color (field `color`), converted from display sRGB into the working RGB space; a cancel (Escape on macOS and in browsers) leaves the colors as they were. ui.inspect reports `screenSampler: true` until it answers; on Linux, a session without a portal that has PickColor, a portal that does not return from the call within 25 seconds (VectorCraft's own limit) or leaves the bus before it answers, and a portal that ends the request another way end the wait with a status message. An error without a sampler, while one is open, or with `picker` and no Color Picker open", ), ( "ui.newBrush", @@ -863,6 +945,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} open Saturate for the selection (dialog `saturate`, fields `intensity` −100..100, `preview`): previews live, OK runs edit.colors.saturate as one undo step", ), + ( + "ui.indexedColorDialog", + "Convert to Indexed Color…", + "", + "{} open Convert to Indexed Color for the selection (dialog `indexedColor`, fields `reduction`, `colors` 2..256, `dither`, `ditherAmount` 0..100, `preview`): previews live, OK runs edit.colors.toIndexed as one undo step", + ), ( "window.swatchLibrary", "Swatch Library", @@ -915,6 +1003,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{ids?|id?} open Layer Options for Layers panel rows (default: the highlighted rows, else the current layer), filled in from the first: dialog `layerOptions`, fields name, color (a preset name such as \"Light Blue\" or #rrggbb), template, locked, visible, printable, preview, dimImages (bool), dimPercent (0–100); an object's row has name, visible and locked. OK runs layer.setProps (one undo step); for several rows it sends only the fields set in the dialog", ), + ( + "ui.layerDelete", + "Delete Selection", + "", + "{ids?|id?, doc?, confirmed?: bool} Delete Selection as the Layers panel runs it (its trash button, rows dropped on the trash, its menu, Delete and Backspace), on the rows layer.delete takes (default: the highlighted rows, else the current layer). When a layer or sublayer among them holds art (an object other than a guide; hidden, locked and nested objects count) it asks first: dialog `confirm` with `message`; OK deletes those rows by id with layer.delete (one undo step), Cancel keeps them. OK runs ui.layerDelete again with the rows, `doc` (the document's uid) and `confirmed: true`: with another document active then, nothing is deleted. Other rows (an empty layer, groups and objects alone) and rows layer.delete refuses go to layer.delete at once → layer.delete's {deleted}, or null while the question is open", + ), ( "ui.rename", "Rename", @@ -1170,7 +1264,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.smoothAuto", "Auto-Smooth", "", - "{} the open Smooth slider (Object › Path › Smooth opens it: dialog `smoothSlider` with field `level` 0..100, object.path.smooth's level, opening at the level object.path.smooth {auto: true} picks, previewed on the canvas until ui.dialog.confirm keeps it as one undo step) moves to the level object.path.smooth {auto: true} picks and previews it → {level}; an error when the slider isn't open", + "{} the open Smooth slider (Object › Path › Smooth and the canvas context menu's Smooth… open it: dialog `smoothSlider` with field `level` 0..100, object.path.smooth's level, opening at the level object.path.smooth {auto: true} picks, previewed on the canvas until ui.dialog.confirm keeps it as one undo step) moves to the level object.path.smooth {auto: true} picks and previews it → {level}; an error when the slider isn't open", ), ( "ui.simplifyMoreOptions", @@ -1212,13 +1306,19 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorPanel", "Color Panel Options", "", - "{mode?: grayscale|rgb|hsb|cmyk|websafe, options?: bool} pick the Color panel's mode as its panel menu does (the active color converts to the mode's model as one undo step), and Show Options (true) or Hide Options (false); both are kept with the preferences; RGB, HSB, Web Safe RGB and hex values use the working RGB space (ui.inspect: ui.color_mode, ui.color_hide_options) → {mode (null: none picked yet), options, shown: the mode the panel shows the color in, or tint for a tint of a global or spot swatch}", + "{mode?: grayscale|rgb|hsb|cmyk|websafe, options?: bool, recentColors?: bool, rgbPercent?: bool} pick the Color panel's mode as its panel menu does (the active color converts to the mode's model as one undo step), Show Options (true) or Hide Options (false), check (true) or uncheck (false) Show Recent Colors, which shows or hides the panel's Recent Colors row (applied colors still join the list while it is hidden; the Swatches panel keeps its row), and show the RGB mode's R, G and B in percent (true) or from 0 to 255 (false), as a double-click right of an RGB field switches them (the color does not change; Web Safe RGB and the hex field stay in 0 to 255); all four are kept with the preferences; RGB, HSB, Web Safe RGB and hex values use the working RGB space (ui.inspect: ui.color_mode, ui.color_hide_options, ui.color_show_recent_colors, ui.color_rgb_percent) → {mode (null: none picked yet), options, recentColors, rgbPercent, shown: the mode the panel shows the color in, or tint for a tint of a global or spot swatch}", + ), + ( + "ui.colorRgbPercent", + "Toggle RGB Percent", + "", + "{} switch the Color panel's R, G and B between percent and 0 to 255, as a double-click right of an RGB field does (ui.colorPanel {rgbPercent}); the color does not change, and the choice is kept with the preferences; a parameter is an error and changes nothing → true when they show in percent", ), ( "ui.savePdfDialog", "Save PDF Dialog", "", - "{path?, preset?, range?, …document.exportPdf options} open the Save PDF dialog with these options (fields = the options, sections are objects; OK writes path, else asks)", + "{path?, preset?, range?, useArtboards?, …document.exportPdf options} open the Save PDF dialog with these options (fields = the options, sections are objects; OK writes path, else asks); useArtboards: false: one page of the visible art's bounds, with no Artboards section", ), ( "file.exportAs", @@ -1347,25 +1447,25 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.action.rename", "Rename Action", "", - "{set: index, action: index, name} rename the Actions panel's action at action in set (0 is the top set) to name, with spaces trimmed from both ends; its steps, function key and color stay. An index past the last set or action, or an empty name, is an error and renames nothing → {name}", + "{set: index, action: index, name} rename the Actions panel's action at action in set (0 is the top set) to name, with spaces trimmed from both ends; its steps, function key and color stay. An index past the last set or action, an empty name, or a name that would give the set's action set file more than 8 MiB (counting the steps the recording in progress adds to it; a name that leaves the file as large or makes it smaller is never refused) is an error and renames nothing → {name}", ), ( "ui.action.stepsIncluded", "Include Action Steps", "", - "{set: index, action?: index, step?: index, included: bool, others?: bool} include or exclude the playback of every step in a set, every step in one action, or one step. With a step and others: true, leave that step unchanged and apply included to every other step in its action (Alt/Option-click). Invalid indexes change nothing → {set, action?, step?, included}", + "{set: index, action?: index, step?: index, included: bool, others?: bool} include or exclude the playback of every step in a set, every step in one action, or one step. With a step and others: true, leave that step unchanged and apply included to every other step in its action (Alt/Option-click). Invalid indexes change nothing. An exclusion that would give the set's action set file more than 8 MiB, counting the steps the recording in progress adds to the set, is an error and changes nothing; a change that leaves the file as large or makes it smaller is never refused → {set, action?, step?, included}", ), ( "ui.action.new", "New Action", "", - "{set: index, name, key?: 0-15, cmd?, shift?, color?: red|yellow|green|blue|violet} add an action named name (spaces trimmed from both ends) after the last action of the Actions panel's set at set (0 is the top set) and start recording into it; Stop Playing/Recording (ui.action.stop) ends the recording. key 1 to 15 is the function key F1 to F15 that plays the action (0 or null: none), with cmd (Ctrl, Command on macOS) and shift; color is its Button Mode color (null or \"\": none), which the panel does not show. Action function keys take priority over command shortcuts and preserve the command's binding. On Windows F1, Ctrl+F4 and Ctrl+F6 cannot be used. The set becomes current and the new action is selected. The panel's Create New Action button and menu's New Action… (dialog `actionNew` with set, name, key, cmd, shift and color) run this on Record. While an action is recording, and for an index past the last set, an empty name, or a key or color that is not one of these, it is an error and nothing is added → {set, action}", + "{set: index, name, key?: 0-15, cmd?, shift?, color?: red|yellow|green|blue|violet} add an action named name (spaces trimmed from both ends) after the last action of the Actions panel's set at set (0 is the top set) and start recording into it; Stop Playing/Recording (ui.action.stop) ends the recording. key 1 to 15 is the function key F1 to F15 that plays the action (0 or null: none), with cmd (Ctrl, Command on macOS) and shift; color is its Button Mode color (null or \"\": none), which the panel does not show. Action function keys take priority over command shortcuts and preserve the command's binding. On Windows F1, Ctrl+F4 and Ctrl+F6 cannot be used. The set becomes current and the new action is selected. The panel's Create New Action button and menu's New Action… (dialog `actionNew` with set, name, key, cmd, shift and color) run this on Record. While an action is recording, and for an index past the last set, an empty name, a key or color that is not one of these, or an action that would give the set more than 1,000 actions or an action set file larger than 8 MiB, it is an error, nothing is added and no recording starts → {set, action}", ), ( "ui.action.options", "Action Options", "", - "{set: index, action: index, name?, key?: 0-15, cmd?, shift?, color?: red|yellow|green|blue|violet} change the Actions panel's action at action in set (0 is the top set); its steps stay. name renames it (spaces trimmed from both ends), key 1 to 15 with cmd (Ctrl, Command on macOS) and shift sets the function key F1 to F15 that plays it (0 or null: none), and color sets its Button Mode color (null or \"\": none); a param left out keeps what the action has, and cmd or shift alone changes that modifier of its key. Action function keys take priority over command shortcuts and preserve the command's binding. The panel menu's Action Options… (dialog `actionSetOptions` with set, action, name, key, cmd, shift and color) runs this for the selected action. An index past the last set or action, an empty name, or a key or color that is not one of these is an error and changes nothing → {name, key, color}", + "{set: index, action: index, name?, key?: 0-15, cmd?, shift?, color?: red|yellow|green|blue|violet} change the Actions panel's action at action in set (0 is the top set); its steps stay. name renames it (spaces trimmed from both ends), key 1 to 15 with cmd (Ctrl, Command on macOS) and shift sets the function key F1 to F15 that plays it (0 or null: none), and color sets its Button Mode color (null or \"\": none); a param left out keeps what the action has, and cmd or shift alone changes that modifier of its key. Action function keys take priority over command shortcuts and preserve the command's binding. The panel menu's Action Options… (dialog `actionSetOptions` with set, action, name, key, cmd, shift and color) runs this for the selected action. An index past the last set or action, an empty name, a key or color that is not one of these, or a change that would give the set's action set file more than 8 MiB (counting the steps the recording in progress adds to it; a change that leaves the file as large or makes it smaller is never refused) is an error and changes nothing → {name, key, color}", ), ( "ui.action.play", @@ -1383,19 +1483,37 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.action.record", "Begin Recording", "", - "{set?: index} begin recording an automatically named Action N in the Actions panel's set at set (0 is the top set), by default the current set or the first set; with no sets, make Set 1. The set becomes current, and ui.action.stop adds the recorded action after that set's existing actions. An explicit invalid set or an existing recording is an error and changes nothing → {set, name}", + "{set?: index, action?: index, after?: index} begin recording an automatically named Action N in the Actions panel's set at set (0 is the top set), by default the current set or the first set; with no sets, make Set 1. The set becomes current, and ui.action.stop adds the recorded action after that set's existing actions. With action, record into the action at action in set instead: ui.action.stop puts the recorded steps after step after of that action, else after its last step, and the steps after them keep whether they are excluded. The panel's Begin Recording button passes the selected action and its selected step. action without set, after without action, an index past the last set, action or step, an explicit invalid set, an existing recording, or a set where the new action would give it more than 1,000 actions or an action set file larger than 8 MiB is an error and changes nothing. While an action records, a recorded command whose step would give the action more than 10,000 steps or its set's action set file more than 8 MiB is an error and does not run, and the recording goes on. A recorded command whose step passes a limit only as it runs, from values it adds to its step, keeps its edit and result; the status bar names the limit, later recorded commands are an error and do not run, and ui.action.stop leaves its step out → {set, name}, or with action {set, action, name}", ), ( "ui.action.stop", "Stop Playing/Recording", "", - "{} end the Actions panel's recording and keep its steps, in the action ui.action.new made for it, else in a new action after the last action of its set, as the panel's Stop Playing/Recording button does. It also ends an action playing step by step or with pauses, or one waiting at a stop, whose message box closes: the steps played stay and the rest do not run. With nothing recording or playing it changes nothing → {stopped}", + "{} end the Actions panel's recording and keep its steps, in the action ui.action.new made for it or the action ui.action.record named, at the place it named, else in a new action after the last action of its set, as the panel's Stop Playing/Recording button does. It also ends an action playing step by step or with pauses, or one waiting at a stop, whose message box closes: the steps played stay and the rest do not run. Recorded steps still past 10,000 in the action, or past 8 MiB in its set's action set file, are left out, and the status bar names the limit. With nothing recording or playing it changes nothing → {stopped}", ), ( "ui.action.insertStop", "Insert Stop", "", - "{set?: index, action?: index, step?: index, message?, allowContinue?: bool} insert a stop, at which a playing action waits and shows message. With set and action (0 is the top set or action), the stop goes into that action, after step, else after its last step; without them it goes into the recording in progress, after the steps recorded so far. message defaults to none, and allowContinue, which offers Continue in the message box, defaults to false. A stop in an action becomes the panel's selected step, and its action and set become the selected ones. An index past the last set, action or step, a param of another type, params that are not an object, or no action and no recording is an error and changes nothing. The panel menu's Insert Stop… (dialog `actionStopRecord` with message, allowContinue, set, action and step) runs this on OK → {set, action, step}, or {recording: true}", + "{set?: index, action?: index, step?: index, message?, allowContinue?: bool} insert a stop, at which a playing action waits and shows message. With set and action (0 is the top set or action), the stop goes into that action, after step, else after its last step; without them it goes into the recording in progress, after the steps recorded so far. message defaults to none, and allowContinue, which offers Continue in the message box, defaults to false. A stop in an action becomes the panel's selected step, and its action and set become the selected ones. An index past the last set, action or step, a param of another type, params that are not an object, no action and no recording, or a stop that would give the action more than 10,000 steps or its set's file more than 8 MiB, counting the steps that the recording in progress adds to the set, is an error and changes nothing. The panel menu's Insert Stop… (dialog `actionStopRecord` with message, allowContinue, set, action and step) runs this on OK → {set, action, step}, or {recording: true}", + ), + ( + "ui.action.insertMenuItem", + "Insert Menu Item", + "", + "{set?: index, action?: index, step?: index, command, params?: object} insert the command of a menu item as a step, without running it; the step plays as choosing the item runs it. command and params (default {}) must be those of a menu item that can be a step: one that runs an engine command, whose label does not end with \"…\", outside the VectorCraft, File, Window and Help menus, and that is not Undo, Redo, a Paste, a batch (command.batch), a preference (prefs.*) or action (action.*) command, an Object › Align item, Image Trace's Make or Make and Expand, Pattern's Make or Edit Pattern, a saved selection, saved view or recent font item, or a plug-in's item. The place is as ui.action.insertStop takes it: with set and action, after step, else after the action's last step; without them, the recording in progress. The new step becomes the panel's selected step, and its action and set become the selected ones. A command and params that no such menu item has, a param of another type, params that are not an object, no action and no recording, or a step that would give the action more than 10,000 steps or its set's file more than 8 MiB, counting the steps that the recording in progress adds to the set, is an error and changes nothing. The panel menu's Insert Menu Item… (dialog `actionInsertMenuItem` with find, command, params, set, action and step) runs this on OK → {set, action, step}, or {recording: true}", + ), + ( + "ui.action.insertSelectPath", + "Insert Select Path", + "", + "{set?: index, action?: index, step?: index} insert a Select Path step for the path selected in the active document, without changing the selection: the step `select.storedPath {id, fingerprint}` stores the path's id and a fingerprint of its kind, fill rule and anchors, and playback selects only that path while it is still there unchanged and can be selected, else the step is an error. The selection must be one whole path or compound path that can be selected: not anchors or segments alone, several objects, a group, type or another kind of object, a guide, a member of a compound path, or a hidden or locked object. The place is as ui.action.insertStop takes it: with set and action, after step, else after the action's last step; without them, the recording in progress. The new step becomes the panel's selected step, and its action and set become the selected ones. No document, a selection that is not such a path, a param of another type, params that are not an object, no action and no recording, or a step that would give the action more than 10,000 steps or its set's file more than 8 MiB, counting the steps that the recording in progress adds to the set, is an error and changes nothing. The panel menu's Insert Select Path runs this, for the selected step or action or the recording in progress → {set, action, step}, or {recording: true}", + ), + ( + "ui.action.insertSelectObject", + "Select Object", + "", + "{set?: index, action?: index, step?: index, note, caseSensitive?: bool, wholeWord?: bool} insert a Select Object step, without running it: playback runs select.byNote {note, caseSensitive, wholeWord}, which selects the objects whose Attributes note matches note, and a playback that finds no such object stops there with an error. note loses its leading and trailing spaces and must then be 1 to 1,024 bytes; caseSensitive and wholeWord default to false. The place is as ui.action.insertStop takes it: with set and action, after step, else after the action's last step; without them, the recording in progress. The new step becomes the panel's selected step, and its action and set become the selected ones. A missing or empty note, a param of another type, params that are not an object, no action and no recording, or a step that would give the action more than 10,000 steps or its set's file more than 8 MiB, counting the steps that the recording in progress adds to the set, is an error and changes nothing. The panel menu's Select Object… (dialog `actionSelectObject`, Set Selection, with note, caseSensitive, wholeWord, set, action and step) runs this on OK → {set, action, step}, or {recording: true}", ), ( "ui.action.continue", @@ -1409,6 +1527,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{set: index, action: index, step: index} delete one step, a stop or a command, of the Actions panel's action at action in set (0 is the top set, action or step). The steps after it keep whether they are excluded, and no step of that action stays selected. A Record Stop dialog open on that step closes, and one open on a later step of the action follows it up. A missing or invalid index is an error and changes nothing. Undo does not bring the step back. The panel's Delete Selection runs this for the selected step → {set, action, step}", ), + ( + "ui.action.moveStep", + "Move Action Step", + "", + "{set: index, action: index, step: index, toSet?: index, toAction?: index, before: index} move one step, a stop or a command, of the Actions panel's action at action in set (0 is the top set, action or step) into the action at toAction in toSet (default: the same set and action), before the step at index before there, or after its last step when before is its number of steps; before counts the steps as they are before the move. The step keeps its params and whether it is excluded, and the other steps keep theirs. A selected step stays selected, and a moved selected step makes its new action the selected one and its set the current one. A Record Stop dialog open on a step follows the step, and the steps that the recording in progress adds to either action stay after the steps that were before them. A step put back just before or just after itself does not move. A missing or invalid index, or a move that would give the action more than 10,000 steps or its set's file more than 8 MiB, counting the steps that the recording in progress adds to the set, is an error and changes nothing. Undo does not move the step back. Dragging a step row in the panel runs this → {set, action, step, moved}", + ), ( "ui.batchDialog", "Batch…", @@ -1425,7 +1549,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.actionSet.load", "Load Actions…", "", - "{path? | data?: the file's text} read an action set file (.vcactions) at path, else a picked one, and add its set after the Actions panel's sets; a set named like one in the panel gets the next free number (Print 2), and the other sets stay. Files of another version, over 8 MiB, with more than 1,000 actions or with an action of more than 10,000 steps are refused; the panel menu's Load Actions… (disabled where there is no open dialog, the web) → {set: index, name, actions: n}. An action set another app saved as text (.aia, starting /version; read with actionSet.read) comes in with its actions. A step with a label and no recorded values comes in when exactly one menu command has that label (in English or the interface language, any case, no final …), and that command is directly in a top menu, can be recorded in actions, is what its menu bar item runs with no values and opens no dialog (never a submenu's item, a file or document command, Paste, Undo, Redo or an add-on's command), with no params and excluded from playback when it is off in the file; the other steps, every step with no label and every step recorded with values (a recorded menu item too) among them, are left out → {set, name, actions, skipped: [{action, step: its label, else its name}] (the first 1,000), leftOut: n}, and the status bar says how many were left out; a set with no name takes the file's name, else Actions; a file actionSet.read marks truncated is refused, and text that starts /version and isn't an action set gives \"not an action set file\"", + "{path? | data?: the file's text} read an action set file (.vcactions) at path, else a picked one, and add its set after the Actions panel's sets; a set named like one in the panel gets the next free number (Print 2), and the other sets stay. Files of another version, over 8 MiB, with more than 1,000 actions or with an action of more than 10,000 steps are refused, and so is any set, .aia ones too, that Save Actions… would write larger than 8 MiB (a file with less white space, or a name that gets a number); the panel menu's Load Actions… (disabled where there is no open dialog, the web) → {set: index, name, actions: n}. An action set another app saved as text (.aia, starting /version; read with actionSet.read) comes in with its actions. A step with a label and no recorded values comes in when exactly one menu command has that label (in English or the interface language, any case, no final …), and that command is directly in a top menu, can be recorded in actions, is what its menu bar item runs with no values and opens no dialog (never a submenu's item, a file or document command, Paste, Undo, Redo or an add-on's command), with no params and excluded from playback when it is off in the file; the other steps, every step with no label and every step recorded with values (a recorded menu item too) among them, are left out → {set, name, actions, skipped: [{action, step: its label, else its name}] (the first 1,000), leftOut: n}, and the status bar says how many were left out; a set with no name takes the file's name, else Actions; a file actionSet.read marks truncated is refused, and text that starts /version and isn't an action set gives \"not an action set file\"", ), ( "ui.actionSet.delete", @@ -1437,7 +1561,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.actionSet.duplicate", "Duplicate Action or Action Set", "", - "{set?: index, action?: index} copy the Actions panel's action at action in set (0 is the top set) to right after it in the same set; without action, copy set with all its actions to right after it (default: the current set). The copy is named after the original with \" copy\" added, a copied set gets an id of its own, and the copy is selected. The panel menu's Duplicate runs this for the selected action, else the current set. An index past the last set or action is an error → {set, action?}", + "{set?: index, action?: index} copy the Actions panel's action at action in set (0 is the top set) to right after it in the same set; without action, copy set with all its actions to right after it (default: the current set). The copy is named after the original with \" copy\" added, a copied set gets an id of its own, and the copy is selected. The panel menu's Duplicate runs this for the selected action, else the current set. An index past the last set or action, or a copy that would give its set more than 1,000 actions or an action set file larger than 8 MiB, is an error and copies nothing → {set, action?}", ), ("file.showPackage", "Show Package", "", "{folder} show a package folder (file.package's folder) in the file manager → {folder}"), ( @@ -1480,7 +1604,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "css.exportFile", "Export CSS…", "", - "{path?, scope?: selection|all (default selection), …css.selection options} css.export written to path, else a picked file (the web downloads it), with the pictures of rasterized art next to it (CSS Properties panel: Export Selected CSS…, Export All…) → {path, rules, images: [path…], warnings (css.export's; the status bar shows the first)}", + "{path?, scope?: selection|all (default selection), …css.selection options} css.export written to path, else a picked file (the web downloads it), with the pictures of rasterized art next to it (CSS Properties panel: Export Selected CSS…, Export All…) → {path, rules, images: [path…], warnings (css.export's; the status bar shows the first and how many there are, and hovering the message lists up to 30 of them, fewer when the window is small, with how many were left out)}", ), ( "file.print", @@ -1511,25 +1635,25 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "plugin.dialog", "Plug-in…", "", - "{id: an object filter plug-in (plugin.list), params?: {…}} Object › Plug-ins: run the filter at once when it takes no parameters or params are given (plugin.run), else open its dialog (dialog `plugin`: a field per parameter, `__plugin` the id, live preview; OK runs plugin.run as one undo step)", + "{id: an object filter plug-in (plugin.list), params?: {…}} Object › Plug-ins: run the filter at once when it takes no parameters or params are given (plugin.run), else open its dialog (dialog `plugin`: a field per parameter, `__plugin` the id, live preview; OK runs plugin.run as one undo step). A heavy filter, and a filter that lists `progress` and no commandAllowlist, run in the background when they run at once or OK runs them without a kept preview → {background: true, status} (see plugin.cancelRuns)", ), ( "ui.installPlugin", "Install Plug-in…", "", - "{path?: a .wasm file | dataBase64?: the module, name?: the file name shown as its source (with dataBase64), replace?: bool (true: the user agreed it takes the place of the plug-in with its id, as plugin.install), hash?: the module's SHA-256 (as plugin.install)} install a WebAssembly plug-in (plugin.install); without a path pick one (the web opens the browser's file picker; File › Open of a .wasm installs it too). A plug-in that lists permissions the user hasn't granted it asks the user first, showing its name, id, version, file SHA-256 and what each permission lets it do, so does a filter that asks for a heavy budget, and so does one without replace that would take the place of another module with its id and get its settings and cache (needsReplace in plugin.inspect), showing its id and file SHA-256: OK installs it if the file still has the SHA-256 shown, Cancel installs nothing. Only a person can press OK when it asks about permissions or a heavy budget: ui.dialog.confirm, answer_dialog and synthetic input are refused → plugin.install's result | {pending: \"pluginInstall\"} while it asks about permissions or a heavy budget | {pending: \"confirm\"} while it asks only about replacing", + "{path?: a .wasm file | dataBase64?: the module, name?: the file name shown as its source (with dataBase64), replace?: bool (true: the user agreed it takes the place of the plug-in with its id, as plugin.install), hash?: the module's SHA-256 (as plugin.install)} install a WebAssembly plug-in (plugin.install); without a path pick one (the web opens the browser's file picker; File › Open of a .wasm installs it too). A plug-in that lists permissions the user hasn't granted it asks the user first, showing its name, id, version, file SHA-256 and what each permission lets it do, so does a filter that asks for a heavy budget, and so does one without replace that would take the place of another module with its id and get its settings and cache (needsReplace in plugin.inspect), showing its id and file SHA-256: OK installs it if the file still has the SHA-256 shown, Cancel installs nothing. Only a person can press OK: ui.dialog.confirm, answer_dialog and synthetic input are refused. When automation asked (a control or MCP request, synthetic input, or a file dialog one of them opened, even when the person picked the file), replace: true doesn't skip the question about replacing, and nothing in the dialog installs it, the person's OK included: the person chooses Object › Plug-ins › Install Plug-in… to install it → plugin.install's result | {pending: \"pluginInstall\"} while it asks | {pending: \"pluginInstall\", approval: \"personMustStartInstall\"} while it asks what automation asked | null on the web without path or dataBase64, once the browser's file picker opens (the picked file is handled as above)", ), ( "plugin.cancelRuns", "Cancel Plug-in Run", "", - "{} stop every heavy filter running in the background (its progress window's Cancel): it stops at the next slice of its budget and changes nothing → {cancelled: n}", + "{} stop every filter running in the background (its progress window's Cancel): it stops at the next slice of its budget and changes nothing → {cancelled: n}", ), ( "plugin.hideRuns", "Continue in Background", "", - "{} close the progress window of the heavy filters running in the background; they go on, shown in the status bar → {hidden: n}", + "{} close the progress window of the filters running in the background; they go on, shown in the status bar → {hidden: n}", ), ( "imageTrace.cancelRuns", diff --git a/crates/mcp/tests/automation_roots.rs b/crates/mcp/tests/automation_roots.rs index d45ecc7142..74bd95d455 100644 --- a/crates/mcp/tests/automation_roots.rs +++ b/crates/mcp/tests/automation_roots.rs @@ -5,8 +5,11 @@ // Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] -use std::path::{Path, PathBuf}; +mod common; +use std::path::Path; + +use common::TempFolder; use serde_json::{Value, json}; use vectorcraft_engine::file_access::AutomationRoots; use vectorcraft_mcp::{Headless, Server}; @@ -14,9 +17,10 @@ use vectorcraft_mcp::{Headless, Server}; const SVG: &str = r#""#; /// A folder holding `in` (the read root, with `a.svg`), `out` (the write root), `outside` (with -/// `b.svg`) and `in2`, and a server confined to `in` and `out` (either may be left out). -fn confined(tag: &str, read: bool, write: bool) -> (Server, PathBuf) { - let base = vectorcraft_testkit::temp_dir(&format!("roots-{tag}")); +/// `b.svg`) and `in2`, and a server confined to `in` and `out` (either may be left out). The +/// folder is removed when the returned [`TempFolder`] is dropped. +fn confined(tag: &str, read: bool, write: bool) -> (Server, TempFolder) { + let base = TempFolder::new(&format!("roots-{tag}")); for d in ["in", "out", "outside", "in2"] { std::fs::create_dir_all(base.join(d)).unwrap(); } @@ -55,6 +59,29 @@ fn refused(server: &mut Server, name: &str, args: Value, why: &str) { assert!(error && text.contains(why), "{name} {args} should be refused ({why}): {text}"); } +/// A `TempFolder` is removed with the files and folders in it when dropped, also when the test +/// that holds it panics. +#[test] +fn temp_folders_are_removed_when_dropped() { + let dir = TempFolder::new("roots-drop-check"); + std::fs::create_dir(dir.join("sub")).unwrap(); + std::fs::write(dir.join("sub/a.svg"), SVG).unwrap(); + let path = dir.to_path_buf(); + drop(dir); + assert!(!path.exists(), "{} is removed", path.display()); + + let mut held = None; + let panicked = vectorcraft_testkit::catch_quiet(|| { + let dir = TempFolder::new("roots-panic-check"); + std::fs::write(dir.join("a.svg"), SVG).unwrap(); + held = Some(dir.to_path_buf()); + panic!("the test fails with {} in use", dir.display()); + }); + assert!(panicked.is_err()); + let path = held.unwrap(); + assert!(!path.exists(), "{} is removed after a panic", path.display()); +} + #[test] fn files_open_only_from_inside_the_read_root() { let (mut server, base) = confined("open", true, true); diff --git a/crates/mcp/tests/common/mod.rs b/crates/mcp/tests/common/mod.rs new file mode 100644 index 0000000000..08954ca21e --- /dev/null +++ b/crates/mcp/tests/common/mod.rs @@ -0,0 +1,28 @@ +//! Shared helpers for the MCP integration tests. + +use std::path::{Path, PathBuf}; + +/// A test's own folder, made by [`vectorcraft_testkit::temp_dir`] (with its checks against a +/// folder made by someone else) and removed with everything in it when dropped, also when the +/// test panics. A removal that fails (a file still open) is ignored. Tests that run at the same +/// time use different tags. +pub struct TempFolder(PathBuf); + +impl TempFolder { + pub fn new(tag: &str) -> Self { + Self(vectorcraft_testkit::temp_dir(tag)) + } +} + +impl std::ops::Deref for TempFolder { + type Target = Path; + fn deref(&self) -> &Path { + &self.0 + } +} + +impl Drop for TempFolder { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} diff --git a/crates/mcp/tests/protocol_props.rs b/crates/mcp/tests/protocol_props.rs index f9dc065ff1..b3145a20b9 100644 --- a/crates/mcp/tests/protocol_props.rs +++ b/crates/mcp/tests/protocol_props.rs @@ -4,6 +4,9 @@ // 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)] +mod common; + +use common::TempFolder; use proptest::prelude::*; use serde_json::{Value, json}; use vectorcraft_doc::Document; @@ -98,7 +101,7 @@ fn tool_definitions_are_valid() { #[test] fn every_tool_survives_empty_and_junk_arguments() { - let dir = vectorcraft_testkit::temp_dir("mcp-junk"); + let dir = TempFolder::new("mcp-junk"); let safe = dir.join("junk.vectorcraft").to_string_lossy().to_string(); let mut failures = vec![]; for t in tool_definitions() { @@ -169,7 +172,7 @@ proptest! { tail in junk_tail(), tool in prop::sample::select(vec!["open_file", "save_file", "export", "screenshot"]), ) { - let base = vectorcraft_testkit::temp_dir("mcp-confined"); + let base = TempFolder::new("mcp-confined"); let root = base.join("a/b/c/root"); std::fs::create_dir_all(&root).unwrap(); std::fs::create_dir_all(base.join("outside")).unwrap(); diff --git a/crates/metafile/Cargo.toml b/crates/metafile/Cargo.toml index fe54a67f6e..01b5d6434a 100644 --- a/crates/metafile/Cargo.toml +++ b/crates/metafile/Cargo.toml @@ -3,7 +3,7 @@ name = "vectorcraft-metafile" version.workspace = true edition.workspace = true license.workspace = true -description = "VectorCraft Windows metafiles: hand-written EMF and WMF writers and readers" +description = "VectorCraft metafiles: hand-written EMF and WMF writers and readers, and a QuickDraw picture (PICT) reader" [lints] workspace = true diff --git a/crates/metafile/src/dib.rs b/crates/metafile/src/dib.rs index fefd8a200c..4aeb5b4381 100644 --- a/crates/metafile/src/dib.rs +++ b/crates/metafile/src/dib.rs @@ -11,8 +11,8 @@ const MAX_SIDE: u32 = 8192; /// Most pixels an image the writers store holds. const MAX_PIXELS: u64 = 1 << 24; /// Most pixels along a side, and in all, of a bitmap the reader decodes. -const MAX_READ_SIDE: u32 = 1 << 15; -const MAX_READ_PIXELS: u64 = 1 << 26; +pub(crate) const MAX_READ_SIDE: u32 = 1 << 15; +pub(crate) const MAX_READ_PIXELS: u64 = 1 << 26; /// Most pixels the bitmaps of one file may decode to together (four of the largest one), so a small /// file of many image records can't cost minutes of decoding (#3600). pub(crate) const MAX_FILE_PIXELS: u64 = 1 << 28; @@ -141,8 +141,30 @@ fn channel(v: u32, mask: u32) -> u8 { ((x * 255 + max / 2) / max.max(1)).min(255) as u8 } +/// PNG `bytes` without its compressed or text ancillary chunks (`iCCP`, `zTXt`, `iTXt`, `tEXt`), +/// which the pixels don't need and which a decoder expands when it is made. Other bytes, and a PNG +/// whose chunks don't read to the end, are returned as they are. +fn png_without_metadata(bytes: &[u8]) -> std::borrow::Cow<'_, [u8]> { + const SIGNATURE: &[u8] = b"\x89PNG\r\n\x1a\n"; + if !bytes.starts_with(SIGNATURE) { + return bytes.into(); + } + let mut out = SIGNATURE.to_vec(); + let mut at = SIGNATURE.len(); + while at < bytes.len() { + let (Some(len), Some(kind)) = (bytes.get(at..at + 4), bytes.get(at + 4..at + 8)) else { return bytes.into() }; + let len = u32::from_be_bytes([len[0], len[1], len[2], len[3]]) as usize; + let Some(end) = at.checked_add(12).and_then(|n| n.checked_add(len)).filter(|end| *end <= bytes.len()) else { return bytes.into() }; + if !matches!(kind, b"iCCP" | b"zTXt" | b"iTXt" | b"tEXt") { + out.extend_from_slice(&bytes[at..end]); + } + at = end; + } + out.into() +} + /// Take a bitmap of `w` × `h` from what is `left` of the file's budget, before it is decoded. -fn charge(w: u32, h: u32, left: &mut u64) -> Result<(), String> { +pub(crate) fn charge(w: u32, h: u32, left: &mut u64) -> Result<(), String> { let n = u64::from(w) * u64::from(h); *left = left.checked_sub(n).ok_or(OVER_BUDGET)?; Ok(()) @@ -175,12 +197,15 @@ pub(crate) fn decode(bmi: &[u8], bits: &[u8], alpha: Alpha, left: &mut u64) -> R }; if compression == BI_JPEG || compression == BI_PNG { // The size comes from the image header, so an over-limit bitmap is refused before any pixels are decoded. - let (w, h) = image::ImageReader::new(Cursor::new(bits)).with_guessed_format().map_err(|_| bad())?.into_dimensions().map_err(|_| bad())?; + // A PNG's compressed ICC profile and text chunks expand when its decoder is made, and + // nothing here uses them: they are left out before the size is read and the pixels decoded. + let bits = png_without_metadata(bits); + let (w, h) = image::ImageReader::new(Cursor::new(&*bits)).with_guessed_format().map_err(|_| bad())?.into_dimensions().map_err(|_| bad())?; if w > MAX_READ_SIDE || h > MAX_READ_SIDE || u64::from(w) * u64::from(h) > MAX_READ_PIXELS { return Err("a bitmap is too large to read".into()); } charge(w, h, left)?; - let img = image::load_from_memory(bits).map_err(|_| bad())?.to_rgba8(); + let img = image::load_from_memory(&bits).map_err(|_| bad())?.to_rgba8(); return Ok(Rgba { width: w, height: h, pixels: img.into_raw() }); } if compression != BI_RGB && compression != BI_BITFIELDS { @@ -297,6 +322,23 @@ pub(crate) fn split(packed: &[u8]) -> Option<(&[u8], &[u8])> { mod tests { use super::*; + #[test] + fn a_pngs_compressed_metadata_is_left_out_before_it_is_decoded() { + use image::ImageEncoder; + let mut png = vec![]; + let mut encoder = image::codecs::png::PngEncoder::new(&mut png); + encoder.set_icc_profile(vec![0; 1 << 20]).unwrap(); + encoder.write_image(&[10, 20, 30], 1, 1, image::ExtendedColorType::Rgb8).unwrap(); + assert!(png.windows(4).any(|w| w == b"iCCP")); + let stripped = png_without_metadata(&png); + assert!(!stripped.windows(4).any(|w| w == b"iCCP") && stripped.len() < png.len()); + let img = image::load_from_memory(&stripped).unwrap().to_rgba8(); + assert_eq!(img.get_pixel(0, 0).0, [10, 20, 30, 255]); + // Not a PNG, or a PNG cut short: unchanged. + assert_eq!(&*png_without_metadata(b"BM...."), b"BM...."); + assert_eq!(&*png_without_metadata(&png[..png.len() - 3]), &png[..png.len() - 3]); + } + fn sample() -> Rgba { // 3 × 2: red, green, blue / half-transparent black, transparent, white. let pixels = vec![255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 0, 0, 0, 128, 0, 0, 0, 0, 255, 255, 255, 255]; diff --git a/crates/metafile/src/import.rs b/crates/metafile/src/import.rs index 0a3d791ee2..da7816663e 100644 --- a/crates/metafile/src/import.rs +++ b/crates/metafile/src/import.rs @@ -1,6 +1,7 @@ -//! The metafile reader: the format parsers (`emf`, `wmf`) play their records on a [`Player`], a -//! small model of the device context they draw into (objects, transforms, the current position, -//! the path bracket, the clip), which turns what they draw into document objects. +//! The metafile reader: the format parsers (`emf`, `wmf`, and `pict` for QuickDraw pictures) play +//! their records on a [`Player`], a small model of the device context they draw into (objects, +//! transforms, the current position, the path bracket, the clip), which turns what they draw into +//! document objects. //! //! Fills and strokes become paths with a fill and a stroke; lines drawn one after another with the //! same pen join into one path. Clips become clipping groups around what they clip. Images keep @@ -8,6 +9,7 @@ //! doesn't know are counted and skipped, with one warning. mod emf; +pub(crate) mod pict; mod wmf; use std::sync::Arc; @@ -787,15 +789,25 @@ impl Player { if img.width == 0 || img.height == 0 { return; } + let (w, h) = (f64::from(img.width), f64::from(img.height)); + self.image_xf(img, Affine::translate((dest.x0, dest.y0)) * Affine::scale_non_uniform(dest.width() / w, dest.height() / h), opacity); + } + + /// An image placed by `xf` (its pixels, from the top-left, → logical), at `opacity`. An image + /// that `xf` flattens or sends past finite numbers is left out, and adds nothing to the + /// document's images. + pub(crate) fn image_xf(&mut self, img: Rgba, xf: Affine, opacity: f64) { + if img.width == 0 || img.height == 0 { + return; + } + let xf = self.xf() * xf; + if !xf.as_coeffs().iter().all(|v| v.is_finite()) || xf.determinant().abs() < 1e-12 { + return; + } let Ok(png) = img.to_png() else { return self.warn(BAD_IMAGE) }; let blob = ImageBlob::new("image/png", png); let key = blob.content_key(); self.doc.images.entry(key.clone()).or_insert(blob); - let (w, h) = (f64::from(img.width), f64::from(img.height)); - let xf = self.xf() * Affine::translate((dest.x0, dest.y0)) * Affine::scale_non_uniform(dest.width() / w, dest.height() / h); - if !xf.as_coeffs().iter().all(|v| v.is_finite()) || xf.determinant().abs() < 1e-12 { - return; - } let im = ImageObject { key, width: img.width, height: img.height, xf, link: None, placement: Default::default(), pixels: None }; let mut n = Node::new(vectorcraft_doc::NodeId(0), NodeKind::Image(Box::new(im))); n.opacity = opacity.clamp(0.0, 1.0) as f32; diff --git a/crates/metafile/src/import/pict.rs b/crates/metafile/src/import/pict.rs new file mode 100644 index 0000000000..a9b4cae9da --- /dev/null +++ b/crates/metafile/src/import/pict.rs @@ -0,0 +1,1173 @@ +//! QuickDraw pictures (PICT, versions 1 and 2), played on the [`Player`] by the opcodes and data +//! lengths of Apple's *Imaging With QuickDraw*, appendix A. +//! +//! A PICT file holds 512 bytes of application data before the picture; a picture on its own (as +//! a `PICT` resource holds it) reads too. A unit is a point, and the artboard is the picture's +//! frame; an extended version 2 header's source rectangle is mapped onto the frame. +//! +//! - Lines, rectangles, rounded rectangles, ovals, arcs and wedges, polygons and regions become +//! paths. A framed shape is stroked inside its outline at the pen's size, and a line below and +//! to the right of its points, where the pen draws; painted, filled and erased shapes are filled +//! with the pen, fill or background pattern. A pattern of two colors is filled with their +//! average. +//! - Text becomes point type in the font the picture names, read as Mac Roman. +//! - Bitmaps and pixel maps (1 to 8 bits with their color table, 16 and 32 bits, packed or not) +//! become images, clipped to their mask region; QuickTime JPEG images become images. +//! - The clip region clips what follows it. +//! +//! What isn't read (inverted shapes, transfer modes other than a copy, other QuickTime formats) +//! comes back as one warning each. Apple's table gives every opcode's length, so opcodes that draw +//! nothing VectorCraft reads are skipped; a picture cut short keeps what came before. + +use std::collections::HashMap; +use std::io::Cursor; + +use vectorcraft_geom::{Affine, BezPath, FillRule, Point, Rect, Shape, Vec2, shapes}; + +use super::{BAD_IMAGE, BrushObj, FontObj, PS_GEOMETRIC, PenObj, Player, SRCCOPY, TOO_MANY_PIXELS, crop, round_rect}; +use crate::dib::{self, Rgba}; +use crate::{Imported, Kind}; + +/// What a file that holds no picture is refused with. +const NOT_PICT: &str = "not a PICT file"; +/// The application data before the picture in a PICT file. +const FILE_HEADER: usize = 512; +/// Most opcodes one picture plays (a small file can't keep the reader busy for minutes). +const MAX_OPS: usize = 1 << 22; +/// Most rectangles one region breaks into. +const MAX_RECTS: usize = 1 << 16; +/// Steps the regions of one picture may take to read (each inversion point and band costs some). +const MAX_REGION_WORK: u64 = 1 << 28; +/// Most bytes the unpacked rows of one image may hold. +const MAX_ROW_BYTES: u64 = 1 << 28; +/// Most bytes the unpacked rows of one picture's images and patterns may hold together. +const MAX_FILE_ROW_BYTES: u64 = 1 << 30; +/// Most bytes a row may hold past what its pixels need. +const ROW_SLACK: usize = 64; +/// Most pixels, and bytes of unpacked rows, a pixel pattern may hold. +const MAX_PATTERN_PIXELS: usize = 1 << 16; +const MAX_PATTERN_ROW_BYTES: usize = 1 << 20; +/// Curves made for ovals and arcs are this close to the true curve, points. +const TOLERANCE: f64 = 0.01; +/// GDI text alignment on the baseline, which QuickDraw's text location is. +const TA_BASELINE: u32 = 0x18; +/// Pen style flags: square and flat ends, mitered joins. +const SQUARE: u32 = 0x100; +const FLAT: u32 = 0x200; +const MITER: u32 = 0x2000; + +const CUT_SHORT: &str = "the picture is cut short or damaged: what came before was imported"; +const TOO_MANY_OPS: &str = "the picture holds more opcodes than one file may: the rest was left out"; +const INVERTED: &str = "inverted shapes were left out"; +const PATTERNS: &str = "patterns are filled with the average of their colors"; +const MODES: &str = "art drawn in transfer modes other than a copy is drawn as a copy"; +const FRAMED_REGIONS: &str = "framed regions are outlined rectangle by rectangle"; +const BIG_REGIONS: &str = "regions larger than one picture may hold were left out"; +const CODECS: &str = "QuickTime images in formats other than JPEG were left out"; +const NOTHING: &str = "the picture draws nothing VectorCraft reads"; + +/// Big-endian reads from a slice, never past its end. +struct Be<'a> { + data: &'a [u8], + pos: usize, +} + +impl<'a> Be<'a> { + fn new(data: &'a [u8], pos: usize) -> Self { + Self { data, pos } + } + fn bytes(&mut self, n: usize) -> Option<&'a [u8]> { + let b = self.data.get(self.pos..self.pos.checked_add(n)?)?; + self.pos += n; + Some(b) + } + fn array(&mut self) -> Option<[u8; N]> { + self.bytes(N)?.try_into().ok() + } + fn skip(&mut self, n: usize) -> Option<()> { + self.bytes(n).map(drop) + } + fn u8(&mut self) -> Option { + self.array().map(|[b]: [u8; 1]| b) + } + fn u16(&mut self) -> Option { + self.array().map(u16::from_be_bytes) + } + fn i16(&mut self) -> Option { + self.array().map(i16::from_be_bytes) + } + fn u32(&mut self) -> Option { + self.array().map(u32::from_be_bytes) + } + fn i32(&mut self) -> Option { + self.array().map(i32::from_be_bytes) + } + /// A QuickDraw point: vertical, then horizontal. + fn point(&mut self) -> Option { + let v = self.i16()?; + let h = self.i16()?; + Some(Point::new(h.into(), v.into())) + } + /// A size stored as a point (a pen or an oval: height, then width). + fn size(&mut self) -> Option { + self.point().map(Point::to_vec2) + } + /// A QuickDraw rectangle: top, left, bottom, right. + fn rect(&mut self) -> Option { + let (top, left, bottom, right) = (self.i16()?, self.i16()?, self.i16()?, self.i16()?); + Some(Rect::new(left.into(), top.into(), right.into(), bottom.into())) + } + /// An `RGBColor` (16 bits a component), 8 bits a component. + fn rgb(&mut self) -> Option<[u8; 3]> { + let [r, g, b] = [self.u16()?, self.u16()?, self.u16()?]; + Some([r, g, b].map(|c| (c >> 8) as u8)) + } +} + +/// Where a picture is, its frame and whether it is version 2. +struct Header { + frame: Rect, + v2: bool, + /// Where its first opcode starts. + ops: usize, +} + +/// The picture whose `picSize` is at `at`, if a version opcode follows its frame. +fn header(bytes: &[u8], at: usize) -> Option
{ + let mut r = Be::new(bytes, at.checked_add(2)?); + let frame = r.rect()?; + let (v2, ops) = match r.array::<2>()? { + [0x11, 0x01] => (false, r.pos), + [0x00, 0x11] if r.array::<4>()? == [0x02, 0xFF, 0x0C, 0x00] => (true, at + 10), + _ => return None, + }; + (frame.width() > 0.0 && frame.height() > 0.0).then_some(Header { frame, v2, ops }) +} + +/// The picture of a file (after its application data), else the picture `bytes` start with. +fn find(bytes: &[u8]) -> Option
{ + header(bytes, FILE_HEADER).or_else(|| header(bytes, 0)) +} + +/// Do `bytes` hold a version 2 picture, after a file's application data or on their own? The +/// version 1 signature is two bytes, too short to tell a file by. +pub(crate) fn is_pict(bytes: &[u8]) -> bool { + [FILE_HEADER, 0].into_iter().any(|at| header(bytes, at).is_some_and(|h| h.v2)) +} + +/// A pattern: eight rows of eight bits (set bits in the foreground color, the others in the +/// background color), or one color. +#[derive(Clone, Copy)] +enum Pat { + Bits([u8; 8]), + Rgb([u8; 3]), +} + +/// What a shape opcode does with its shape. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Verb { + Frame, + Paint, + Erase, + Invert, + Fill, +} + +/// The verb of a shape opcode (its low three bits; 5 to 7 are reserved). +fn verb(op: u16) -> Option { + match op & 7 { + 0 => Some(Verb::Frame), + 1 => Some(Verb::Paint), + 2 => Some(Verb::Erase), + 3 => Some(Verb::Invert), + 4 => Some(Verb::Fill), + _ => None, + } +} + +/// An old-style QuickDraw color (`blackColor` 33 … `blueColor` 409) as RGB. +fn old_color(c: u32) -> [u8; 3] { + match c { + 30 => [255; 3], + 69 => [255, 255, 0], + 137 => [255, 0, 255], + 205 => [255, 0, 0], + 273 => [0, 255, 255], + 341 => [0, 255, 0], + 409 => [0, 0, 255], + _ => [0; 3], + } +} + +/// `a` and `b` mixed: `t` of `a`. +fn mix(a: [u8; 3], b: [u8; 3], t: f64) -> [u8; 3] { + let m = |x: u8, y: u8| (f64::from(x) * t + f64::from(y) * (1.0 - t)).round() as u8; + [m(a[0], b[0]), m(a[1], b[1]), m(a[2], b[2])] +} + +/// Byte `b` of Mac Roman. +fn mac_roman(b: u8) -> char { + const HIGH: [char; 128] = [ + 'Ä', 'Å', 'Ç', 'É', 'Ñ', 'Ö', 'Ü', 'á', 'à', 'â', 'ä', 'ã', 'å', 'ç', 'é', 'è', // + 'ê', 'ë', 'í', 'ì', 'î', 'ï', 'ñ', 'ó', 'ò', 'ô', 'ö', 'õ', 'ú', 'ù', 'û', 'ü', // + '†', '°', '¢', '£', '§', '•', '¶', 'ß', '®', '©', '™', '´', '¨', '≠', 'Æ', 'Ø', // + '∞', '±', '≤', '≥', '¥', 'µ', '∂', '∑', '∏', 'π', '∫', 'ª', 'º', 'Ω', 'æ', 'ø', // + '¿', '¡', '¬', '√', 'ƒ', '≈', '∆', '«', '»', '…', '\u{A0}', 'À', 'Ã', 'Õ', 'Œ', 'œ', // + '–', '—', '“', '”', '‘', '’', '÷', '◊', 'ÿ', 'Ÿ', '⁄', '€', '‹', '›', 'fi', 'fl', // + '‡', '·', '‚', '„', '‰', 'Â', 'Ê', 'Á', 'Ë', 'È', 'Í', 'Î', 'Ï', 'Ì', 'Ó', 'Ô', // + '\u{F8FF}', 'Ò', 'Ú', 'Û', 'Ù', 'ı', 'ˆ', '˜', '¯', '˘', '˙', '˚', '¸', '˝', '˛', 'ˇ', + ]; + match b { + 0x80.. => HIGH.get(usize::from(b - 0x80)).copied().unwrap_or(char::REPLACEMENT_CHARACTER), + _ => char::from(b), + } +} + +/// The family name of a classic Macintosh font number. +fn font_family(id: u16) -> &'static str { + match id { + 0 => "Chicago", + 1 | 3 => "Geneva", + 2 => "New York", + 4 => "Monaco", + 20 => "Times", + 21 => "Helvetica", + 22 => "Courier", + 23 => "Symbol", + _ => "", + } +} + +/// The arc of the oval in `r` from `start` degrees clockwise from 12 o'clock, over `sweep` +/// degrees (clockwise when positive). Angles are measured on the rectangle, so 45° runs through +/// its top-right corner. A wedge closes through the center. +fn arc(r: Rect, start: i16, sweep: i16, wedge: bool) -> BezPath { + let c = r.center(); + let radii = Vec2::new(r.width() / 2.0, r.height() / 2.0); + let mut bp = BezPath::new(); + if sweep == 0 { + return bp; + } + let a0 = (f64::from(start) - 90.0).to_radians(); + let sweep = f64::from(sweep).clamp(-360.0, 360.0).to_radians(); + let arc = kurbo::Arc { center: c, radii, start_angle: a0, sweep_angle: sweep, x_rotation: 0.0 }; + if wedge { + bp.move_to(c); + bp.line_to(c + Vec2::new(radii.x * a0.cos(), radii.y * a0.sin())); + arc.append_iter(TOLERANCE).for_each(|el| bp.push(el)); + bp.close_path(); + } else { + kurbo::Shape::path_elements(&arc, TOLERANCE).for_each(|el| bp.push(el)); + } + bp +} + +/// The outlines of `rects`, as one path. +fn rects_path(rects: &[Rect]) -> BezPath { + let mut bp = BezPath::new(); + for r in rects { + bp.extend(shapes::rectangle(*r).to_bezpath()); + } + bp +} + +/// Take `n` steps from `work`; false when too few are left. +fn spend(work: &mut u64, n: usize) -> bool { + match work.checked_sub(n as u64) { + Some(left) => { + *work = left; + true + } + None => false, + } +} + +/// A region (its size, bounding box and inversion points), read at `r`, as rectangles: `None` +/// when the data runs past the end; the flag is false when the region is larger than `work` or +/// [`MAX_RECTS`] allows, and then no rectangles are given. +fn region(r: &mut Be, work: &mut u64) -> Option<(Vec, bool)> { + let size = usize::from(r.u16()?); + let mut b = Be::new(r.bytes(size.checked_sub(2)?)?, 0); + let bbox = b.rect()?; + if size <= 10 { + let whole = bbox.width() > 0.0 && bbox.height() > 0.0; + return Some((if whole { vec![bbox] } else { vec![] }, true)); + } + Some(bands(&mut b, work).map_or((vec![], false), |rects| (rects, true))) +} + +/// The rectangles of a region's scanlines: each lists the x coordinates where being inside the +/// region changes from the scanline before. Bands of the same spans one after another are one +/// rectangle. +fn bands(b: &mut Be, work: &mut u64) -> Option> { + let mut out: Vec = vec![]; + let mut active: Vec = vec![]; + let mut last_band = 0; + let mut prev_y = 0.0; + while let Some(y) = b.i16().filter(|y| *y != 0x7FFF) { + let y = f64::from(y); + let spans: Vec<(f64, f64)> = active.as_chunks::<2>().0.iter().map(|[a, b]| (f64::from(*a), f64::from(*b))).collect(); + if !spans.is_empty() && y > prev_y { + if !spend(work, spans.len() + 1) { + return None; + } + let prev = out.get_mut(last_band..).unwrap_or_default(); + let same = prev.len() == spans.len() && prev.iter().zip(&spans).all(|(r, (x0, x1))| r.x0 == *x0 && r.x1 == *x1 && r.y1 == prev_y); + if same { + prev.iter_mut().for_each(|r| r.y1 = y); + } else { + last_band = out.len(); + out.extend(spans.iter().map(|&(x0, x1)| Rect::new(x0, prev_y, x1, y))); + if out.len() > MAX_RECTS { + return None; + } + } + } + prev_y = y; + while let Some(x) = b.i16().filter(|x| *x != 0x7FFF) { + if !spend(work, active.len() + 1) { + return None; + } + match active.binary_search(&x) { + Ok(i) => { + active.remove(i); + } + Err(i) => active.insert(i, x), + } + } + } + Some(out) +} + +/// Skip the data of opcode `op`, by the length Apple's table gives it. +fn skip(op: u16, r: &mut Be) -> Option<()> { + let n = match op { + 0x00 | 0x17..=0x19 | 0x1C | 0x1E | 0xB0..=0xCF | 0x8000..=0x80FF => 0, + 0x04 => 1, + 0x03 | 0x05 | 0x08 | 0x0D | 0x11 | 0x15 | 0x16 | 0xA0 => 2, + 0x06 | 0x07 | 0x0B | 0x0C | 0x0E | 0x0F => 4, + 0x1A | 0x1B | 0x1D | 0x1F => 6, + 0x02 | 0x09 | 0x0A | 0x10 => 8, + // Reserved opcodes with a 16-bit length, and the font name. + 0x24..=0x27 | 0x2C..=0x2F | 0x92..=0x97 | 0x9C..=0x9F | 0xA2..=0xAF => usize::from(r.u16()?), + // Reserved for Apple: two bytes for each unit of the high byte (the 24-byte header 0x0C00). + 0x0100..=0x7FFF => usize::from(op >> 8) * 2, + // 0xD0–0xFE and 0x8100–0xFFFF (QuickTime images among them): a 32-bit length. + _ => usize::try_from(r.u32()?).ok()?, + }; + r.skip(n) +} + +/// How a bitmap's or pixel map's pixels are stored. +struct PixMap { + row_bytes: usize, + bounds: Rect, + /// Bits a pixel. + size: u16, + pack: u16, + cmps: u16, + /// Indexed pixels' colors; a bitmap has none (its set bits are the foreground color). + palette: Option>, + /// Rows of 8 bytes or more may be packed with PackBits, as the packing says. + packed: bool, +} + +impl PixMap { + /// From `rowBytes` on: a pixel map when `rowBytes` has its high bit set or `pixmap` says so, + /// else a bitmap; a pixel map's color table follows unless `direct`. + fn read(r: &mut Be, pixmap: bool, direct: bool) -> Option { + let raw = r.u16()?; + let mut pm = PixMap { row_bytes: usize::from(raw & 0x3FFF), bounds: r.rect()?, size: 1, pack: 0, cmps: 1, palette: None, packed: true }; + if pixmap || raw & 0x8000 != 0 { + r.skip(2)?; + pm.pack = r.u16()?; + r.skip(14)?; + pm.size = r.u16()?; + pm.cmps = r.u16()?; + r.skip(14)?; + if !direct { + pm.palette = Some(color_table(r)?); + } + } + Some(pm) + } + + /// The width and height of its pixels. + fn dims(&self) -> Option<(usize, usize)> { + let (w, h) = (self.bounds.width(), self.bounds.height()); + (w > 0.0 && h > 0.0).then_some((w as usize, h as usize)) + } + + /// The packing: 0 is 4 for 32-bit pixels and 3 for 16-bit ones. + fn packing(&self) -> u16 { + match (self.size, self.pack) { + (32, 0) => 4, + (16, 0) => 3, + (_, p) => p, + } + } + + /// Rows are stored as they are (no byte count, no PackBits). + fn raw_rows(&self) -> bool { + !self.packed || self.row_bytes < 8 || self.packing() == 1 || (self.size == 32 && self.packing() == 2) + } + + /// Bytes of an unpacked row: a component plane each for packing 4, three bytes a pixel for + /// packing 2, else `rowBytes`. + fn row_len(&self, w: usize) -> usize { + match self.packing() { + 4 if self.size == 32 && self.row_bytes >= 8 => w * usize::from(self.cmps), + 2 if self.size == 32 => w * 3, + _ => self.row_bytes, + } + } + + /// Whether its pixels can be read: a depth QuickDraw has, and rows long enough for them and at + /// most [`ROW_SLACK`] bytes longer. + fn decodable(&self, w: usize) -> bool { + let need = match self.size { + 1 | 2 | 4 | 8 => (w * usize::from(self.size)).div_ceil(8), + 16 => 2 * w, + 32 if self.packing() == 4 && self.row_bytes >= 8 => { + if !matches!(self.cmps, 3 | 4) { + return false; + } + w * usize::from(self.cmps) + } + 32 if self.packing() == 2 => 3 * w, + 32 => 4 * w, + _ => return false, + }; + (need..=need + ROW_SLACK).contains(&self.row_len(w)) + } + + /// Read `h` rows of pixel data, unpacked into one buffer when `keep`, else only stepped over. + /// `None` when the data runs past the end; the flag is false when a row didn't unpack to its + /// length. + fn rows(&self, r: &mut Be, w: usize, h: usize, keep: bool) -> Option<(Vec, bool)> { + let len = self.row_len(w); + let unit = if self.packing() == 3 { 2 } else { 1 }; + let mut out = vec![]; + let mut ok = true; + let mut keep = keep; + for _ in 0..h { + if self.raw_rows() { + let row = r.bytes(len)?; + if keep { + out.extend_from_slice(row); + } + continue; + } + let n = if self.row_bytes > 250 { usize::from(r.u16()?) } else { usize::from(r.u8()?) }; + let packed = r.bytes(n)?; + // After a row that doesn't unpack, the rest are only stepped over. + if keep && !unpack(packed, len, unit, &mut out) { + ok = false; + keep = false; + out = vec![]; + } + } + Some((out, ok)) + } + + /// The color of pixel `x` of `row` (the foreground and background colors for a bitmap's bits). + fn pixel(&self, row: &[u8], x: usize, w: usize, fg: [u8; 3], bg: [u8; 3]) -> Option<[u8; 3]> { + let at = |i: usize| row.get(i).copied(); + match self.size { + 1 | 2 | 4 | 8 => { + let bits = usize::from(self.size); + let shift = 8 - bits - x * bits % 8; + let index = usize::from((at(x * bits / 8)? >> shift) & ((1u16 << bits) - 1) as u8); + match &self.palette { + Some(p) => p.get(index).copied(), + None => Some(if index == 0 { bg } else { fg }), + } + } + 16 => { + let v = u16::from_be_bytes([at(2 * x)?, at(2 * x + 1)?]); + let c = |s: u16| (((v >> s) & 31) * 255 / 31) as u8; + Some([c(10), c(5), c(0)]) + } + _ if self.packing() == 4 && self.row_bytes >= 8 => { + // Component planes, alpha first when there are four (QuickDraw doesn't draw it). + let first = usize::from(self.cmps) - 3; + Some([at(first * w + x)?, at((first + 1) * w + x)?, at((first + 2) * w + x)?]) + } + _ if self.packing() == 2 => Some([at(3 * x)?, at(3 * x + 1)?, at(3 * x + 2)?]), + _ => Some([at(4 * x + 1)?, at(4 * x + 2)?, at(4 * x + 3)?]), + } + } + + /// Unpacked rows as opaque pixels. + fn to_rgba(&self, data: &[u8], w: usize, h: usize, fg: [u8; 3], bg: [u8; 3]) -> Option { + let len = self.row_len(w); + let mut pixels = Vec::with_capacity(w * h * 4); + for y in 0..h { + let row = data.get(y * len..(y + 1) * len)?; + for x in 0..w { + pixels.extend(self.pixel(row, x, w, fg, bg)?); + pixels.push(255); + } + } + Some(Rgba { width: u32::try_from(w).ok()?, height: u32::try_from(h).ok()?, pixels }) + } +} + +/// A `ColorTable`: indexed pixels' colors (entry by entry for a device table, else by each +/// entry's value). +fn color_table(r: &mut Be) -> Option> { + r.skip(4)?; + let flags = r.u16()?; + let n = usize::from(r.u16()?) + 1; + let mut palette = vec![[0u8; 3]; 256]; + for i in 0..n { + let value = usize::from(r.u16()?); + let c = r.rgb()?; + if let Some(e) = palette.get_mut(if flags & 0x8000 != 0 { i } else { value }) { + *e = c; + } + } + Some(palette) +} + +/// Unpack PackBits `data` (runs of `unit`-byte elements) onto `out`, `len` bytes; false when the +/// data is damaged or short (the row is padded with zeros). +fn unpack(data: &[u8], len: usize, unit: usize, out: &mut Vec) -> bool { + let start = out.len(); + let mut i = 0; + let mut ok = true; + while out.len() - start < len { + let Some(&n) = data.get(i) else { + ok = false; + break; + }; + i += 1; + let n = n as i8; + if n >= 0 { + let k = (n as usize + 1) * unit; + let Some(lit) = data.get(i..i + k) else { + ok = false; + break; + }; + out.extend_from_slice(lit); + i += k; + } else if n != -128 { + let Some(v) = data.get(i..i + unit) else { + ok = false; + break; + }; + for _ in 0..(1 - isize::from(n)) { + out.extend_from_slice(v); + } + i += unit; + } + } + out.resize(start + len, 0); + ok +} + +/// The picture being played: QuickDraw's drawing state, and the player that makes the objects. +struct Pict { + p: Player, + frame: Rect, + /// Picture space → document. + base: Affine, + origin: Vec2, + fg: [u8; 3], + bg: [u8; 3], + pen: Vec2, + pen_mode: u16, + pen_pat: Pat, + fill_pat: Pat, + back_pat: Pat, + oval: Vec2, + pen_loc: Point, + font: u16, + face: u8, + text_size: i16, + text_loc: Point, + /// Font numbers the picture names. + names: HashMap, + /// The last rectangle of the rectangle, rounded rectangle, oval and arc opcodes. + last: [Rect; 4], + region_work: u64, + /// Bytes of unpacked rows the picture's images and patterns may still take. + row_bytes_left: u64, +} + +impl Pict { + fn new(frame: Rect) -> Self { + let base = Affine::translate(-frame.origin().to_vec2()); + let artboard = Rect::new(0.0, 0.0, frame.width(), frame.height()); + // A picture's coordinates map straight onto the document, as a WMF's do. + let p = Player::new(Kind::Wmf, base, 25.4 / 72.0, artboard); + Self { + p, + frame, + base, + origin: Vec2::ZERO, + fg: [0; 3], + bg: [255; 3], + pen: Vec2::new(1.0, 1.0), + pen_mode: 8, + pen_pat: Pat::Bits([0xFF; 8]), + fill_pat: Pat::Bits([0xFF; 8]), + back_pat: Pat::Bits([0; 8]), + oval: Vec2::ZERO, + pen_loc: Point::ZERO, + font: 0, + face: 0, + text_size: 0, + text_loc: Point::ZERO, + names: HashMap::new(), + last: [Rect::ZERO; 4], + region_work: MAX_REGION_WORK, + row_bytes_left: MAX_FILE_ROW_BYTES, + } + } + + /// Charge the `w` × `h` pixels of `pm`, and the bytes of its unpacked rows, to the picture's + /// budgets: false, and nothing charged, when either is spent. + fn charge(&mut self, pm: &PixMap, w: usize, h: usize) -> bool { + let bytes = (pm.row_len(w) as u64).saturating_mul(h as u64); + let Some(rows_left) = self.row_bytes_left.checked_sub(bytes) else { return false }; + let (Ok(wide), Ok(high)) = (u32::try_from(w), u32::try_from(h)) else { return false }; + if dib::charge(wide, high, &mut self.p.pixels_left).is_err() { + return false; + } + self.row_bytes_left = rows_left; + true + } + + /// Play opcode `op`, its data at `r`; `None` when the data runs past the end. + fn op(&mut self, op: u16, r: &mut Be) -> Option<()> { + if !matches!(op, 0x20..=0x23) { + self.p.flush(); + } + match op { + 0x01 => self.clip(r), + 0x0C => self.move_origin(r), + 0x20..=0x23 => self.line(op, r), + 0x28..=0x2B => self.text(op, r), + 0x2C => self.font_name(r), + 0x30..=0x6F => self.shape(op, r), + 0x70..=0x77 => self.poly(verb(op), r), + 0x80..=0x87 => self.region_shape(verb(op), r), + // The same polygon and region: Apple's table gives them no data and no drawing. + 0x78..=0x7F | 0x88..=0x8F => Some(()), + 0x90 | 0x91 | 0x98..=0x9B => self.bits(op, r), + 0xA1 => { + r.skip(2)?; + let n = usize::from(r.u16()?); + r.skip(n) + } + 0x0C00 => self.header(r), + 0x8200 => self.quicktime(r), + _ => self.state(op, r), + } + } + + /// The opcodes that set the drawing state; the others are skipped. + fn state(&mut self, op: u16, r: &mut Be) -> Option<()> { + match op { + 0x02 => self.back_pat = Pat::Bits(r.array()?), + 0x03 => self.font = r.u16()?, + 0x04 => self.face = r.u8()?, + 0x07 => self.pen = r.size()?, + 0x08 => self.pen_mode = r.u16()?, + 0x09 => self.pen_pat = Pat::Bits(r.array()?), + 0x0A => self.fill_pat = Pat::Bits(r.array()?), + 0x0B => self.oval = r.size()?, + 0x0D => self.text_size = r.i16()?, + 0x0E => self.fg = old_color(r.u32()?), + 0x0F => self.bg = old_color(r.u32()?), + 0x12 => self.back_pat = self.pix_pat(r)?, + 0x13 => self.pen_pat = self.pix_pat(r)?, + 0x14 => self.fill_pat = self.pix_pat(r)?, + 0x1A => self.fg = r.rgb()?, + 0x1B => self.bg = r.rgb()?, + _ => return skip(op, r), + } + Some(()) + } + + /// The version 2 header: an extended one's source rectangle maps onto the frame. + fn header(&mut self, r: &mut Be) -> Option<()> { + let mut b = Be::new(r.bytes(24)?, 0); + if b.i16() == Some(-2) + && let Some(src) = b.skip(10).and_then(|()| b.rect()) + && src.width() > 0.0 + && src.height() > 0.0 + { + let k = Vec2::new(self.frame.width() / src.width(), self.frame.height() / src.height()); + self.base = Affine::scale_non_uniform(k.x, k.y) * Affine::translate(-src.origin().to_vec2()); + self.p.dev_to_doc = self.base * Affine::translate(-self.origin); + } + Some(()) + } + + /// The origin moves by (dh, dv): a point drawn after it is that much nearer the top left. + fn move_origin(&mut self, r: &mut Be) -> Option<()> { + let (dh, dv) = (r.i16()?, r.i16()?); + self.origin += Vec2::new(dh.into(), dv.into()); + self.p.dev_to_doc = self.base * Affine::translate(-self.origin); + Some(()) + } + + /// A pixel pattern: its color (the average of a color pattern's pixels), else its bitmap. + fn pix_pat(&mut self, r: &mut Be) -> Option { + let kind = r.u16()?; + let bits: [u8; 8] = r.array()?; + match kind { + 1 => { + let pm = PixMap::read(r, true, false)?; + let (w, h) = pm.dims()?; + let small = w * h <= MAX_PATTERN_PIXELS && pm.row_len(w) * h <= MAX_PATTERN_ROW_BYTES; + let keep = small && pm.decodable(w) && self.charge(&pm, w, h); + let (data, _) = pm.rows(r, w, h, keep)?; + let avg = keep.then(|| pm.to_rgba(&data, w, h, self.fg, self.bg)).flatten().map(|img| self.average(&img)); + Some(avg.map_or(Pat::Bits(bits), Pat::Rgb)) + } + 2 => Some(Pat::Rgb(r.rgb()?)), + _ => Some(Pat::Bits(bits)), + } + } + + /// The average color of `img`, with a warning when its pixels differ. + fn average(&mut self, img: &Rgba) -> [u8; 3] { + let px = img.pixels.as_chunks::<4>().0; + if px.windows(2).any(|w| w[0] != w[1]) { + self.p.warn(PATTERNS); + } + let n = px.len().max(1) as u64; + let sum = |i: usize| (px.iter().map(|p| u64::from(p[i])).sum::() / n) as u8; + [sum(0), sum(1), sum(2)] + } + + /// The color a pattern fills with: its own, or its two colors mixed as its bits are. + fn pat_color(&mut self, pat: Pat) -> [u8; 3] { + match pat { + Pat::Rgb(c) => c, + Pat::Bits(b) => { + let ones: u32 = b.iter().map(|x| x.count_ones()).sum(); + if ones != 0 && ones != 64 { + self.p.warn(PATTERNS); + } + mix(self.fg, self.bg, f64::from(ones) / 64.0) + } + } + } + + /// The pen's color (a warning when its mode isn't a copy). + fn pen_color(&mut self) -> [u8; 3] { + if !matches!(self.pen_mode, 0 | 8) { + self.p.warn(MODES); + } + self.pat_color(self.pen_pat) + } + + /// The color painting, erasing or filling an area takes; `None` for the other verbs. + fn area_color(&mut self, verb: Verb) -> Option<[u8; 3]> { + match verb { + Verb::Paint => Some(self.pen_color()), + Verb::Erase => Some(self.pat_color(self.back_pat)), + Verb::Fill => Some(self.pat_color(self.fill_pat)), + Verb::Frame | Verb::Invert => None, + } + } + + fn has_pen(&self) -> bool { + self.pen.x > 0.0 && self.pen.y > 0.0 + } + + /// Fill `bp` (picture space) with `color`. + fn fill(&mut self, mut bp: BezPath, color: [u8; 3], rule: FillRule) { + bp.apply_affine(self.p.xf()); + self.p.dc.brush = BrushObj::Solid(color); + self.p.dc.fill_rule = rule; + self.p.draw(bp, true, false); + } + + /// The pen as a stroke of `color` with `ends`, as wide as the pen's average side. + fn set_pen(&mut self, color: [u8; 3], ends: u32) { + let width = (self.pen.x + self.pen.y) / 2.0; + self.p.dc.pen = PenObj { style: PS_GEOMETRIC | ends | MITER, width, color, entries: vec![] }; + } + + /// Stroke `bp` (picture space) with the pen in `color`. + fn stroke(&mut self, mut bp: BezPath, color: [u8; 3], ends: u32) { + self.set_pen(color, ends); + bp.apply_affine(self.p.xf()); + self.p.draw(bp, false, true); + } + + /// Draw a framed shape: its outline (from `outline` of a rectangle and an oval size) stroked + /// inside `r`, or filled when the pen is as large as the shape. + fn frame(&mut self, r: Rect, outline: impl Fn(Rect, Vec2) -> BezPath, ends: u32) { + if !self.has_pen() { + return; + } + let color = self.pen_color(); + let half = self.pen / 2.0; + let inner = Rect::new(r.x0 + half.x, r.y0 + half.y, r.x1 - half.x, r.y1 - half.y); + if inner.width() <= 0.0 || inner.height() <= 0.0 { + return self.fill(outline(r, self.oval), color, FillRule::NonZero); + } + self.stroke(outline(inner, self.oval - self.pen), color, ends); + } + + /// The rectangle, rounded rectangle, oval and arc opcodes. + fn shape(&mut self, op: u16, r: &mut Be) -> Option<()> { + let family = op >> 4; + let slot = usize::from(family - 3); + let rect = if op & 8 != 0 { self.last.get(slot).copied()? } else { r.rect()? }; + let angles = if family == 6 { Some((r.i16()?, r.i16()?)) } else { None }; + let Some(verb) = verb(op) else { return Some(()) }; + if let Some(l) = self.last.get_mut(slot) { + *l = rect; + } + if rect.width() <= 0.0 || rect.height() <= 0.0 { + return Some(()); + } + let outline = move |r: Rect, oval: Vec2, wedge: bool| match family { + 3 => shapes::rectangle(r).to_bezpath(), + 4 => round_rect(r, oval.x, oval.y), + 5 => kurbo::Ellipse::from_rect(r).to_path(TOLERANCE), + _ => angles.map_or_else(BezPath::new, |(start, sweep)| arc(r, start, sweep, wedge)), + }; + match verb { + Verb::Frame => self.frame(rect, |r, oval| outline(r, oval, false), if family == 6 { FLAT } else { SQUARE }), + Verb::Invert => self.p.warn(INVERTED), + _ => { + if let Some(c) = self.area_color(verb) { + self.fill(outline(rect, self.oval, true), c, FillRule::NonZero); + } + } + } + Some(()) + } + + /// A polygon opcode: framed along its points, else filled. + fn poly(&mut self, verb: Option, r: &mut Be) -> Option<()> { + let size = usize::from(r.u16()?); + let mut b = Be::new(r.bytes(size.checked_sub(2)?)?, 8); + let Some(verb) = verb else { return Some(()) }; + let mut pts = vec![]; + while let Some(p) = b.point() { + pts.push(p); + } + let Some((first, rest)) = pts.split_first() else { return Some(()) }; + let closed = pts.len() > 2 && pts.first() == pts.last(); + match verb { + Verb::Frame if self.has_pen() => { + let half = self.pen / 2.0; + let mut bp = BezPath::new(); + bp.move_to(*first + half); + rest.iter().for_each(|p| bp.line_to(*p + half)); + if closed { + bp.close_path(); + } + let color = self.pen_color(); + self.stroke(bp, color, SQUARE); + } + Verb::Frame => {} + Verb::Invert => self.p.warn(INVERTED), + _ => { + let mut bp = BezPath::new(); + bp.move_to(*first); + rest.iter().for_each(|p| bp.line_to(*p)); + bp.close_path(); + if let Some(c) = self.area_color(verb) { + self.fill(bp, c, FillRule::EvenOdd); + } + } + } + Some(()) + } + + /// A region's rectangles, with a warning when it was too large to read. + fn read_region(&mut self, r: &mut Be) -> Option> { + let (rects, whole) = region(r, &mut self.region_work)?; + if !whole { + self.p.warn(BIG_REGIONS); + } + Some(rects) + } + + /// A region opcode: each rectangle framed, else the region filled. + fn region_shape(&mut self, verb: Option, r: &mut Be) -> Option<()> { + let rects = self.read_region(r)?; + let Some(verb) = verb.filter(|_| !rects.is_empty()) else { return Some(()) }; + match verb { + Verb::Frame if self.has_pen() => { + if rects.len() > 1 { + self.p.warn(FRAMED_REGIONS); + } + let half = self.pen / 2.0; + let inner: Vec = rects.iter().map(|r| Rect::new(r.x0 + half.x, r.y0 + half.y, r.x1 - half.x, r.y1 - half.y)).collect(); + let color = self.pen_color(); + self.stroke(rects_path(&inner), color, SQUARE); + } + Verb::Frame => {} + Verb::Invert => self.p.warn(INVERTED), + _ => { + if let Some(c) = self.area_color(verb) { + self.fill(rects_path(&rects), c, FillRule::NonZero); + } + } + } + Some(()) + } + + /// The clip region: it replaces the clip. An empty region clips away everything after it, as + /// a clip of no area at the frame's corner; one too large to read leaves the clip as it was. + fn clip(&mut self, r: &mut Be) -> Option<()> { + let (mut rects, whole) = region(r, &mut self.region_work)?; + if !whole { + self.p.warn(BIG_REGIONS); + return Some(()); + } + if rects.is_empty() { + let corner = Point::new(self.frame.x0, self.frame.y0); + rects.push(Rect::from_points(corner, corner)); + } + let mut bp = rects_path(&rects); + bp.apply_affine(self.p.xf()); + self.p.push_clip(bp, FillRule::NonZero, true); + Some(()) + } + + /// The line opcodes: the pen drawn from point to point, hanging below and to the right of + /// the line; lines one after another join into one path. + fn line(&mut self, op: u16, r: &mut Be) -> Option<()> { + let delta = |r: &mut Be| Some(Vec2::new(f64::from(r.u8()? as i8), f64::from(r.u8()? as i8))); + let (from, to) = match op { + 0x20 => (r.point()?, r.point()?), + 0x21 => (self.pen_loc, r.point()?), + 0x22 => { + let a = r.point()?; + (a, a + delta(r)?) + } + _ => (self.pen_loc, self.pen_loc + delta(r)?), + }; + self.pen_loc = to; + if !self.has_pen() { + return Some(()); + } + let color = self.pen_color(); + if from == to { + // A dot: the pen's rectangle. + self.p.flush(); + self.fill(shapes::rectangle(Rect::from_points(from, from + self.pen)).to_bezpath(), color, FillRule::NonZero); + return Some(()); + } + let pen = PenObj { style: PS_GEOMETRIC | SQUARE | MITER, width: (self.pen.x + self.pen.y) / 2.0, color, entries: vec![] }; + if self.p.dc.pen != pen { + self.p.flush(); + self.p.dc.pen = pen; + } + let half = self.pen / 2.0; + let xf = self.p.xf(); + let (a, b) = (xf * (from + half), xf * (to + half)); + if self.p.pending.elements().last().and_then(|e| e.end_point()) != Some(a) { + self.p.pending.move_to(a); + } + self.p.pending.line_to(b); + Some(()) + } + + /// The text opcodes: a string at the text location, moved to or by the opcode's data. + fn text(&mut self, op: u16, r: &mut Be) -> Option<()> { + match op { + 0x28 => self.text_loc = r.point()?, + 0x29 => self.text_loc.x += f64::from(r.u8()?), + 0x2A => self.text_loc.y += f64::from(r.u8()?), + _ => { + self.text_loc.x += f64::from(r.u8()?); + self.text_loc.y += f64::from(r.u8()?); + } + } + let n = usize::from(r.u8()?); + let s: String = r.bytes(n)?.iter().map(|&b| mac_roman(b)).filter(|c| !c.is_control()).collect(); + let size = if self.text_size > 0 { self.text_size } else { 12 }; + let face = self.names.get(&self.font).cloned().unwrap_or_else(|| font_family(self.font).to_string()); + self.p.dc.font = FontObj { + height: -f64::from(size), + escapement: 0.0, + weight: if self.face & 1 != 0 { 700 } else { 400 }, + italic: self.face & 2 != 0, + face, + }; + self.p.dc.text_color = self.fg; + self.p.dc.text_align = TA_BASELINE; + self.p.text(self.text_loc, &s); + Some(()) + } + + /// A font's name for its number. + fn font_name(&mut self, r: &mut Be) -> Option<()> { + let n = usize::from(r.u16()?); + let mut b = Be::new(r.bytes(n)?, 0); + if let Some(id) = b.u16() + && let Some(len) = b.u8() + && let Some(name) = b.bytes(usize::from(len)) + { + let name: String = name.iter().map(|&c| mac_roman(c)).collect(); + self.names.insert(id, name.trim().to_string()); + } + Some(()) + } + + /// A bitmap or pixel map copied into a rectangle (`Rgn` opcodes: clipped to a mask region). + fn bits(&mut self, op: u16, r: &mut Be) -> Option<()> { + let direct = matches!(op, 0x9A | 0x9B); + if direct { + r.skip(4)?; + } + let mut pm = PixMap::read(r, direct, direct)?; + // BitsRect and BitsRgn store their rows unpacked. + pm.packed = op >= 0x98; + let (src, dst, mode) = (r.rect()?, r.rect()?, r.u16()?); + let mask = if op & 1 != 0 { Some(self.read_region(r)?) } else { None }; + let (w, h) = pm.dims()?; + let (wide, high) = (w as u64, h as u64); + let fits = wide * high <= dib::MAX_READ_PIXELS && pm.row_len(w) as u64 * high <= MAX_ROW_BYTES; + let readable = pm.decodable(w); + let keep = fits && readable && self.charge(&pm, w, h); + let (data, ok) = pm.rows(r, w, h, keep)?; + if !keep { + self.p.warn(if readable { TOO_MANY_PIXELS } else { BAD_IMAGE }); + return Some(()); + } + let Some(mut img) = pm.to_rgba(&data, w, h, self.fg, self.bg).filter(|_| ok) else { + self.p.warn(BAD_IMAGE); + return Some(()); + }; + self.transfer(&mut img, mode, pm.size == 1 && pm.palette.is_none()); + if dst.width() <= 0.0 || dst.height() <= 0.0 || mask.as_ref().is_some_and(Vec::is_empty) { + return Some(()); + } + let saved = self.p.dc.clips.clone(); + if let Some(rects) = &mask { + let mut bp = rects_path(rects); + bp.apply_affine(self.p.xf()); + self.p.push_clip(bp, FillRule::NonZero, false); + } + self.p.image(Ok(img), src - pm.bounds.origin().to_vec2(), dst, SRCCOPY, 1.0); + self.p.dc.clips = saved; + Some(()) + } + + /// Transfer mode `mode` on copied pixels: OR of a bitmap and the transparent mode leave the + /// background color out; the others are copied, with a warning. + fn transfer(&mut self, img: &mut Rgba, mode: u16, bitmap: bool) { + // 64 dithers, which doesn't change what is copied. + let clear = match mode & !64 { + 0 => false, + 1 if bitmap => true, + 36 => true, + _ => { + self.p.warn(MODES); + false + } + }; + if clear { + let bg = self.bg; + img.pixels.as_chunks_mut::<4>().0.iter_mut().filter(|p| [p[0], p[1], p[2]] == bg).for_each(|p| p[3] = 0); + } + } + + /// A compressed QuickTime image: a JPEG one becomes an image placed by its matrix. + fn quicktime(&mut self, r: &mut Be) -> Option<()> { + let n = usize::try_from(r.u32()?).ok()?; + let data = r.bytes(n)?; + match qt_image(data) { + Some((ctype, xf, src, image)) if &ctype == b"jpeg" => match self.jpeg(image) { + Ok(img) => { + let img = crop(img, src); + self.p.image_xf(img, xf * Affine::translate(src.origin().to_vec2()), 1.0); + } + Err(w) => self.p.warn(w), + }, + Some(_) => self.p.warn(CODECS), + None => self.p.warn(BAD_IMAGE), + } + Some(()) + } + + /// A JPEG stream's pixels, taken from the file's pixel budget. + fn jpeg(&mut self, data: &[u8]) -> Result { + let reader = || image::ImageReader::with_format(Cursor::new(data), image::ImageFormat::Jpeg); + let (w, h) = reader().into_dimensions().map_err(|_| BAD_IMAGE)?; + if w > dib::MAX_READ_SIDE || h > dib::MAX_READ_SIDE || u64::from(w) * u64::from(h) > dib::MAX_READ_PIXELS { + return Err(TOO_MANY_PIXELS); + } + dib::charge(w, h, &mut self.p.pixels_left).map_err(|_| TOO_MANY_PIXELS)?; + let img = reader().decode().map_err(|_| BAD_IMAGE)?.to_rgba8(); + Ok(Rgba { width: img.width(), height: img.height(), pixels: img.into_raw() }) + } +} + +/// A QuickTime image's compressor type, matrix (image → picture space), source rectangle and +/// compressed data, from its header and image description. +fn qt_image(d: &[u8]) -> Option<([u8; 4], Affine, Rect, &[u8])> { + let mut b = Be::new(d, 2); + let mut m = [0.0; 9]; + for v in &mut m { + *v = f64::from(b.i32()?) / 65536.0; + } + let matte = usize::try_from(b.u32()?).ok()?; + b.skip(10)?; + let src = b.rect()?; + b.skip(4)?; + let mask = usize::try_from(b.u32()?).ok()?; + b.skip(matte)?; + b.skip(mask)?; + let start = b.pos; + let id_size = usize::try_from(b.u32()?).ok()?; + let ctype = b.array::<4>()?; + b.skip(36)?; + let size = usize::try_from(b.u32()?).ok()?; + let at = start.checked_add(id_size)?; + let data = d.get(at..at.checked_add(size)?).or_else(|| d.get(at..))?; + // The rows of a QuickTime matrix are [a b u] [c d v] [tx ty w]; u, v and w (perspective) are + // left out. + let xf = Affine::new([m[0], m[1], m[3], m[4], m[6], m[7]]); + Some((ctype, xf, src, data)) +} + +/// Read a picture. +pub(crate) fn play(bytes: &[u8]) -> Result { + let h = find(bytes).ok_or(NOT_PICT)?; + let mut q = Pict::new(h.frame); + let mut r = Be::new(bytes, h.ops); + // Why the picture stopped before its end opcode, if it did. + let mut stopped = Some(TOO_MANY_OPS); + for _ in 0..MAX_OPS { + // Version 2 opcodes start on even bytes. + if h.v2 && r.pos % 2 == 1 && r.skip(1).is_none() { + stopped = Some(CUT_SHORT); + break; + } + let Some(op) = (if h.v2 { r.u16() } else { r.u8().map(u16::from) }) else { + stopped = Some(CUT_SHORT); + break; + }; + if op == 0x00FF { + stopped = None; + break; + } + if q.op(op, &mut r).is_none() { + stopped = Some(CUT_SHORT); + break; + } + } + if let Some(why) = stopped { + q.p.warn(why); + } + q.p.flush(); + if q.p.out.is_empty() { + q.p.warn(NOTHING); + } + Ok(q.p.finish()) +} diff --git a/crates/metafile/src/lib.rs b/crates/metafile/src/lib.rs index 5326e2f307..0e699236d7 100644 --- a/crates/metafile/src/lib.rs +++ b/crates/metafile/src/lib.rs @@ -15,13 +15,14 @@ //! //! [`import`] reads either format back into a document of one artboard (the picture's frame) and //! one layer: paths with fills and strokes, clipping, images and text. Records it doesn't read are -//! skipped, with one warning. +//! skipped, with one warning. [`import_pict`] reads QuickDraw pictures (PICT, versions 1 and 2) +//! into the same kind of document. //! //! - `bytes`: little-endian writing and bounds-checked reading. //! - `dib`: device-independent bitmaps, both ways. //! - `scene`: the document walk both writers share. //! - `emf`, `wmf`: the writers. -//! - `import`: the reader. +//! - `import`: the readers. mod bytes; mod dib; @@ -84,7 +85,7 @@ pub fn export(doc: &Document, region: Rect, kind: Kind) -> Result emf::write(&ops, r, &doc.title), + Kind::Emf => emf::write(&ops, r, doc.info_title()), Kind::Wmf => wmf::write(&ops, r, &mut warnings), }; Ok(Output { bytes, warnings }) @@ -107,5 +108,28 @@ pub fn import(bytes: &[u8]) -> Result { Ok(i) } +/// A QuickDraw picture read into a document. +#[derive(Clone, Debug)] +pub struct Picture { + pub document: Document, + /// What was approximated or skipped. + pub warnings: Vec, +} + +/// Do `bytes` hold a version 2 QuickDraw picture, after a PICT file's 512 bytes of application +/// data or on their own? A version 1 picture is known by its file's name. +pub fn is_pict(bytes: &[u8]) -> bool { + import::pict::is_pict(bytes) +} + +/// Read a QuickDraw picture (version 1 or 2; a PICT file, or a picture on its own) into a document +/// whose one artboard is the picture's frame. +pub fn import_pict(bytes: &[u8]) -> Result { + let i = import::pict::play(bytes)?; + let mut p = Picture { document: i.document, warnings: i.warnings }; + p.document.limit_depth_noting(&mut p.warnings); + Ok(p) +} + #[cfg(test)] mod tests; diff --git a/crates/metafile/src/scene.rs b/crates/metafile/src/scene.rs index 343b422093..ecba61ce8e 100644 --- a/crates/metafile/src/scene.rs +++ b/crates/metafile/src/scene.rs @@ -213,7 +213,7 @@ impl<'a> Scene<'a> { self.node(&o, true); } } - NodeKind::Image(im) => self.image(im), + NodeKind::Image(im) => self.image(&self.doc.shown_image(n, im)), NodeKind::SymbolInstance { symbol, xf } => { if let Some(sym) = self.doc.symbols.iter().find(|s| &s.name == symbol) && self.nest < MAX_NEST @@ -415,13 +415,13 @@ impl<'a> Scene<'a> { field.display_grid(area, cols, rows).flat_map(|(c, a)| [q(c[0]), q(c[1]), q(c[2]), q(a)]).collect() } else { let geom = g.resolve(bounds); - let sample = g.gradient.sampler(); + let (sample, spread) = (g.gradient.sampler(), g.gradient.spreader()); let (cw, ch) = (area.width() / f64::from(cols), area.height() / f64::from(rows)); (0..usize::from(rows) * usize::from(cols)) .flat_map(|i| { let (x, y) = (i % usize::from(cols), i / usize::from(cols)); let p = Point::new(area.x0 + (x as f64 + 0.5) * cw, area.y0 + (y as f64 + 0.5) * ch); - let t = geom.param_at(g.gradient.kind, p); + let t = spread(geom.param_at(g.gradient.kind, p)); let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 }; let (c, a) = sample(t as f32); c.to_rgba8(a) diff --git a/crates/metafile/src/tests.rs b/crates/metafile/src/tests.rs index 23bcfdc672..602db3d55f 100644 --- a/crates/metafile/src/tests.rs +++ b/crates/metafile/src/tests.rs @@ -12,6 +12,7 @@ use vectorcraft_geom::{Affine, PathData, Point, Rect, shapes}; use crate::*; mod import; +mod pict; /// Add `n` (with a fresh id) on top of `d`'s first layer. pub(crate) fn add(d: &mut Document, mut n: Node) { diff --git a/crates/metafile/src/tests/pict.rs b/crates/metafile/src/tests/pict.rs new file mode 100644 index 0000000000..055e88c95b --- /dev/null +++ b/crates/metafile/src/tests/pict.rs @@ -0,0 +1,466 @@ +//! QuickDraw pictures read from hand-built opcodes: versions 1 and 2, with and without the file's +//! application data; shapes, lines, regions, patterns, text, bitmaps, pixel maps and QuickTime +//! JPEG images; and pictures that are cut short, damaged or never end. + +use vectorcraft_doc::{AppearanceItem, Document, Node, NodeKind}; +use vectorcraft_geom::{Point, Rect}; + +use crate::import_pict; + +/// Big-endian words. +fn be(v: &[i16]) -> Vec { + v.iter().flat_map(|x| x.to_be_bytes()).collect() +} + +/// A QuickDraw rectangle: top, left, bottom, right. +fn rect(top: i16, left: i16, bottom: i16, right: i16) -> Vec { + be(&[top, left, bottom, right]) +} + +/// A version 2 PICT file: 512 bytes of application data, then a picture of `frame` (top, left, +/// bottom, right) holding `ops`, each padded to an even length, and the end opcode. +fn v2(frame: [i16; 4], ops: &[(u16, Vec)]) -> Vec { + let mut b = vec![0xA5; 512]; + b.extend([0, 0]); + b.extend(be(&frame)); + b.extend([0x00, 0x11, 0x02, 0xFF, 0x0C, 0x00]); + b.extend(be(&[-1, 0])); + b.extend([0; 20]); + for (op, data) in ops { + b.extend(op.to_be_bytes()); + b.extend(data); + if b.len() % 2 == 1 { + b.push(0); + } + } + b.extend([0x00, 0xFF]); + b +} + +/// An RGB foreground color. +fn fg(r: u16, g: u16, b: u16) -> (u16, Vec) { + (0x1A, [r, g, b].iter().flat_map(|c| c.to_be_bytes()).collect()) +} + +/// Every object of the imported document, depth first. +fn all(d: &Document) -> Vec { + let mut v = vec![]; + for l in &d.layers { + for c in l.children().into_iter().flatten() { + c.walk(&mut |n| v.push(n.clone())); + } + } + v +} + +fn paths(d: &Document) -> Vec { + all(d).into_iter().filter(|n| matches!(n.kind, NodeKind::Path { clipping: false, .. })).collect() +} + +fn near(a: Rect, b: Rect, tol: f64) -> bool { + [(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(x, y)| (x - y).abs() <= tol) +} + +fn fill_rgb(n: &Node) -> Option<[u8; 3]> { + n.appearance.items.iter().find_map(|i| match i { + AppearanceItem::Fill(f) => f.paint.color().map(|c| { + let [r, g, b, _] = c.to_rgba8(1.0); + [r, g, b] + }), + _ => None, + }) +} + +fn stroke(n: &Node) -> Option<([u8; 3], f64)> { + n.appearance.items.iter().find_map(|i| match i { + AppearanceItem::Stroke(s) => s.paint.color().map(|c| { + let [r, g, b, _] = c.to_rgba8(1.0); + ([r, g, b], s.width) + }), + _ => None, + }) +} + +/// The images of `d` with their pixels. +fn images(d: &Document) -> Vec<(Node, image::RgbaImage)> { + all(d) + .into_iter() + .filter_map(|n| match &n.kind { + NodeKind::Image(im) => { + let png = image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_rgba8(); + Some((n.clone(), png)) + } + _ => None, + }) + .collect() +} + +#[test] +fn a_version_2_picture_opens_as_shapes_in_its_frame() { + let bytes = v2( + [10, 20, 110, 220], + &[ + fg(0xFFFF, 0, 0), + // paintRect + (0x31, rect(20, 30, 60, 80)), + (0x07, be(&[4, 4])), + fg(0, 0, 0xFFFF), + // frameRect: stroked inside the rectangle. + (0x30, rect(20, 120, 80, 200)), + // A line, and one from its end: one path. + (0x20, be(&[90, 40, 90, 140])), + (0x21, be(&[100, 140])), + ], + ); + assert!(crate::is_pict(&bytes)); + let p = import_pict(&bytes).unwrap(); + assert!(p.warnings.is_empty(), "{:?}", p.warnings); + let a = p.document.artboards[0].rect; + assert!(near(a, Rect::new(0.0, 0.0, 200.0, 100.0), 1e-9), "{a:?}"); + let v = paths(&p.document); + assert_eq!(v.len(), 3, "{v:?}"); + assert_eq!(fill_rgb(&v[0]), Some([255, 0, 0])); + assert!(near(v[0].geometric_bounds().unwrap(), Rect::new(10.0, 10.0, 60.0, 50.0), 1e-6)); + assert!(v[0].appearance.stroke().is_none()); + // The pen's outer edge is the rectangle. + assert_eq!(stroke(&v[1]), Some(([0, 0, 255], 4.0))); + assert!(near(v[1].geometric_bounds().unwrap(), Rect::new(102.0, 12.0, 178.0, 68.0), 1e-6)); + assert!(fill_rgb(&v[1]).is_none()); + // The pen hangs below and to the right of the line. + assert_eq!(stroke(&v[2]), Some(([0, 0, 255], 4.0))); + assert!(near(v[2].geometric_bounds().unwrap(), Rect::new(22.0, 82.0, 122.0, 92.0), 1e-6)); +} + +#[test] +fn a_bare_picture_and_a_version_1_picture_open() { + // A version 2 picture without the file's application data. + let file = v2([0, 0, 50, 50], &[(0x31, rect(10, 10, 20, 20))]); + let bare = &file[512..]; + assert!(crate::is_pict(bare)); + assert_eq!(paths(&import_pict(bare).unwrap().document).len(), 1); + // Version 1: byte opcodes, known by name only. + let mut v1 = vec![0, 0]; + v1.extend(rect(0, 0, 40, 60)); + v1.extend([0x11, 0x01, 0x31]); + v1.extend(rect(5, 5, 15, 25)); + v1.extend([0xA0, 0x00, 0x05, 0x50]); + v1.extend(rect(20, 20, 30, 30)); + v1.push(0xFF); + assert!(!crate::is_pict(&v1)); + let p = import_pict(&v1).unwrap(); + assert!(p.warnings.is_empty(), "{:?}", p.warnings); + assert_eq!(p.document.artboards[0].rect.size(), (60.0, 40.0).into()); + let v = paths(&p.document); + assert_eq!(v.len(), 2); + assert!(near(v[0].geometric_bounds().unwrap(), Rect::new(5.0, 5.0, 25.0, 15.0), 1e-6)); + // The default pen: one point, black. + assert_eq!(stroke(&v[1]), Some(([0, 0, 0], 1.0))); + // Inside a file's application data too. + let mut file = vec![0; 512]; + file.extend(&v1); + assert_eq!(paths(&import_pict(&file).unwrap().document).len(), 2); +} + +#[test] +fn files_that_are_not_pictures_are_refused() { + assert_eq!(import_pict(&[0; 600]).unwrap_err(), "not a PICT file"); + assert_eq!(import_pict(b"").unwrap_err(), "not a PICT file"); + // An empty frame. + let mut b = vec![0, 0]; + b.extend(rect(10, 10, 10, 50)); + b.extend([0x11, 0x01, 0xFF]); + assert!(import_pict(&b).is_err()); +} + +#[test] +fn rounded_rectangles_ovals_arcs_and_same_shapes() { + let bytes = v2( + [0, 0, 100, 100], + &[ + (0x0B, be(&[20, 20])), + (0x41, rect(0, 0, 50, 50)), + (0x51, rect(50, 0, 100, 50)), + // A wedge from 12 to 3 o'clock. + (0x61, [rect(0, 50, 100, 150), be(&[0, 90])].concat()), + fg(0, 0xFFFF, 0), + // paintSameRect after paintRect: the same rectangle. + (0x31, rect(60, 60, 70, 80)), + (0x39, vec![]), + ], + ); + let p = import_pict(&bytes).unwrap(); + let v = paths(&p.document); + assert_eq!(v.len(), 5, "{v:?}"); + assert!(near(v[0].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 50.0, 50.0), 1e-6)); + assert!(near(v[1].geometric_bounds().unwrap(), Rect::new(0.0, 50.0, 50.0, 100.0), 1e-3)); + assert!(near(v[2].geometric_bounds().unwrap(), Rect::new(100.0, 0.0, 150.0, 50.0), 1e-3), "{:?}", v[2].geometric_bounds()); + assert_eq!(v[3].geometric_bounds(), v[4].geometric_bounds()); + assert_eq!(fill_rgb(&v[4]), Some([0, 255, 0])); +} + +#[test] +fn polygons_and_regions_fill_and_clip() { + // An L: the top band 20 wide, the bottom band 10. + let region = [be(&[36]), rect(0, 0, 20, 20), be(&[0, 0, 20, 0x7FFF, 10, 10, 20, 0x7FFF, 20, 0, 10, 0x7FFF, 0x7FFF])].concat(); + let poly = [be(&[22]), rect(0, 0, 40, 40), be(&[0, 0, 40, 40, 0, 40])].concat(); + let bytes = v2([0, 0, 100, 100], &[(0x81, region.clone()), (0x71, poly), (0x01, region), (0x31, rect(0, 0, 100, 100))]); + let p = import_pict(&bytes).unwrap(); + assert!(p.warnings.is_empty(), "{:?}", p.warnings); + let v = paths(&p.document); + assert_eq!(v.len(), 3); + let NodeKind::Path { path, .. } = &v[0].kind else { panic!("a path") }; + assert_eq!(path.subpaths.len(), 2, "two bands"); + assert!(near(v[0].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 20.0, 20.0), 1e-9)); + assert!(near(v[1].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 40.0, 40.0), 1e-9)); + // The rectangle after the clip region is clipped to it. + let layer = p.document.layers[0].children().unwrap(); + let NodeKind::Group { children, clip: true } = &layer[2].kind else { panic!("a clipping group: {:?}", layer[2].kind) }; + assert!(near(children[0].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 20.0, 20.0), 1e-9)); +} + +#[test] +fn patterns_fill_with_their_average_color() { + let gray = vec![0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55]; + let bytes = v2( + [0, 0, 10, 10], + &[(0x0A, gray), (0x34, rect(0, 0, 10, 10)), (0x12, [be(&[2]), vec![0; 8], be(&[0, -1, 0])].concat()), (0x32, rect(0, 0, 5, 5))], + ); + let p = import_pict(&bytes).unwrap(); + let v = paths(&p.document); + assert_eq!(fill_rgb(&v[0]), Some([128, 128, 128])); + // eraseRect with an RGB background pattern. + assert_eq!(fill_rgb(&v[1]), Some([0, 255, 0])); + assert!(p.warnings.iter().any(|w| w.contains("average of their colors")), "{:?}", p.warnings); +} + +#[test] +fn text_comes_in_as_point_type_in_the_named_font() { + let name = [be(&[9, 300]), vec![6], b"Geneva".to_vec()].concat(); + let bytes = v2( + [0, 0, 100, 200], + &[(0x2C, name), (0x03, be(&[300])), (0x0D, be(&[18])), (0x04, vec![1]), (0x28, [be(&[50, 10]), vec![4], b"Caf\x8E".to_vec()].concat())], + ); + let p = import_pict(&bytes).unwrap(); + let texts: Vec<_> = all(&p.document).into_iter().filter(|n| matches!(n.kind, NodeKind::Text(_))).collect(); + let NodeKind::Text(t) = &texts[0].kind else { panic!("text") }; + assert_eq!(t.plain_text(), "Café"); + let st = &t.runs[0].style; + assert_eq!((st.font_family.as_str(), st.font_style.as_str(), st.size), ("Geneva", "Bold", 18.0)); + // The text location is the baseline's start. + assert_eq!(t.xf.translation(), Point::new(10.0, 50.0).to_vec2()); +} + +/// A pixel map's fields after `rowBytes` and its bounds: version, packing, resolution, depth and +/// components. +fn pixmap_fields(pack: i16, size: i16, cmps: i16) -> Vec { + be(&[0, pack, 0, 0, 72, 0, 72, 0, 0, size, cmps, 8, 0, 0, 0, 0, 0, 0]) +} + +#[test] +fn a_packed_indexed_pixel_map_becomes_an_image() { + let table = be(&[0, 0, 0, 1, 0, -1, 0, 0, 1, 0, 0, -1]); + // An 8 × 2 map: a run of red, then blue and red by turns. + let rows = [vec![2, 0xF9, 0], vec![9, 7, 1, 0, 1, 0, 1, 0, 1, 0]].concat(); + let data = + [be(&[0x8008u16 as i16]), rect(0, 0, 2, 8), pixmap_fields(0, 8, 1), table, rect(0, 0, 2, 8), rect(10, 20, 14, 36), be(&[0]), rows].concat(); + let p = import_pict(&v2([0, 0, 50, 50], &[(0x98, data)])).unwrap(); + assert!(p.warnings.is_empty(), "{:?}", p.warnings); + let imgs = images(&p.document); + assert_eq!(imgs.len(), 1); + let (n, px) = &imgs[0]; + assert_eq!(px.dimensions(), (8, 2)); + assert_eq!(px.get_pixel(0, 0).0, [255, 0, 0, 255]); + assert_eq!(px.get_pixel(0, 1).0, [0, 0, 255, 255]); + assert_eq!(px.get_pixel(1, 1).0, [255, 0, 0, 255]); + // Drawn into its destination, twice its size. + assert!(near(n.geometric_bounds().unwrap(), Rect::new(20.0, 10.0, 36.0, 14.0), 1e-9)); +} + +#[test] +fn direct_pixel_maps_and_masked_bitmaps() { + // 32-bit, packed by component planes: red, then green. + let row = vec![7, 5, 255, 0, 0, 255, 0, 0]; + let direct = + [be(&[0, 0xFF, 0x8008u16 as i16]), rect(0, 0, 1, 2), pixmap_fields(4, 32, 3), rect(0, 0, 1, 2), rect(0, 0, 1, 2), be(&[0]), row].concat(); + // A one-bit bitmap ORed in (its clear bits left out), masked by a region. + let mask = [be(&[10]), rect(0, 0, 1, 1)].concat(); + let bitmap = [be(&[2]), rect(0, 0, 1, 2), rect(0, 0, 1, 2), rect(5, 0, 6, 2), be(&[1]), mask, vec![0x80, 0]].concat(); + let p = import_pict(&v2([0, 0, 10, 10], &[(0x9A, direct), (0x91, bitmap)])).unwrap(); + assert!(p.warnings.is_empty(), "{:?}", p.warnings); + let imgs = images(&p.document); + assert_eq!(imgs.len(), 2); + assert_eq!(imgs[0].1.get_pixel(0, 0).0, [255, 0, 0, 255]); + assert_eq!(imgs[0].1.get_pixel(1, 0).0, [0, 255, 0, 255]); + assert_eq!(imgs[1].1.get_pixel(0, 0).0, [0, 0, 0, 255]); + assert_eq!(imgs[1].1.get_pixel(1, 0).0[3], 0, "the clear bit is left out"); + let layer = p.document.layers[0].children().unwrap(); + assert!(matches!(layer[1].kind, NodeKind::Group { clip: true, .. }), "the mask region clips the bitmap"); +} + +/// A pixel map's rows may be only a little longer than its pixels need: a map one pixel wide +/// with rows of 16,383 bytes is left out, and a pixel pattern like it fills with its bitmap. +#[test] +fn rows_far_longer_than_their_pixels_are_refused() { + let table = be(&[0, 0, 0, 1, 0, -1, 0, 0, 1, -1, 0, 0]); + // A row of 16,383 ones: 127 runs of 128 and one of 127, after its byte count. + let mut row = be(&[256]); + (0..127).for_each(|_| row.extend([0x81, 1])); + row.extend([0x82, 1]); + let rows = row.repeat(4); + let map = [be(&[0xBFFFu16 as i16]), rect(0, 0, 4, 1), pixmap_fields(0, 8, 1), table.clone()].concat(); + let data = [map, rect(0, 0, 4, 1), rect(0, 0, 4, 1), be(&[0]), rows].concat(); + let p = import_pict(&v2([0, 0, 10, 10], &[(0x98, data)])).unwrap(); + assert!(images(&p.document).is_empty()); + assert!(p.warnings.iter().any(|w| w.contains("couldn't be read")), "{:?}", p.warnings); + + let pattern = [be(&[1]), vec![0xFF; 8], be(&[0xBFFFu16 as i16]), rect(0, 0, 1, 1), pixmap_fields(0, 8, 1), table, row].concat(); + let p = import_pict(&v2([0, 0, 10, 10], &[(0x12, pattern), (0x32, rect(0, 0, 5, 5))])).unwrap(); + assert_eq!(fill_rgb(&paths(&p.document)[0]), Some([0, 0, 0]), "the pattern's bitmap in the foreground color"); +} + +/// BitsRect rows are stored unpacked, also when a row is 8 bytes or longer. +#[test] +fn bitmap_rows_of_eight_bytes_or_more_are_read_unpacked() { + let row = vec![0x80, 0, 0, 0, 0, 0, 0, 0]; + let bitmap = [be(&[8]), rect(0, 0, 1, 16), rect(0, 0, 1, 16), rect(0, 0, 1, 16), be(&[0]), row].concat(); + let p = import_pict(&v2([0, 0, 10, 20], &[(0x90, bitmap), (0x31, rect(2, 2, 4, 4))])).unwrap(); + assert!(p.warnings.is_empty(), "{:?}", p.warnings); + let imgs = images(&p.document); + assert_eq!(imgs.len(), 1); + assert_eq!(imgs[0].1.dimensions(), (16, 1)); + assert_eq!(imgs[0].1.get_pixel(0, 0).0, [0, 0, 0, 255]); + assert_eq!(imgs[0].1.get_pixel(1, 0).0, [255, 255, 255, 255]); + assert_eq!(paths(&p.document).len(), 1, "the rectangle after it"); +} + +/// An empty clip region clips away what follows it. +#[test] +fn an_empty_clip_region_hides_what_follows() { + let empty = [be(&[10]), rect(0, 0, 0, 0)].concat(); + let p = import_pict(&v2([0, 0, 50, 50], &[(0x01, empty), (0x31, rect(0, 0, 10, 10))])).unwrap(); + let layer = p.document.layers[0].children().unwrap(); + let NodeKind::Group { children, clip: true } = &layer[0].kind else { panic!("a clipping group: {:?}", layer[0].kind) }; + let b = children[0].geometric_bounds().unwrap(); + assert_eq!((b.width(), b.height()), (0.0, 0.0), "{b:?}"); +} + +/// A QuickTime image of `ctype` with `matrix` (a, b, c, d, tx, ty in points) and source rectangle +/// `w` × `h`, holding `data`. +fn quicktime(ctype: &[u8; 4], matrix: [f64; 6], w: i16, h: i16, data: &[u8]) -> Vec { + let fixed = |v: f64| ((v * 65536.0) as i32).to_be_bytes(); + let [a, b, c, d, tx, ty] = matrix; + let mut q = be(&[0]); + for v in [a, b, 0.0, c, d, 0.0, tx, ty] { + q.extend(fixed(v)); + } + q.extend((1i32 << 30).to_be_bytes()); + q.extend([0; 4]); + q.extend([0; 8]); + q.extend(be(&[0])); + q.extend(rect(0, 0, h, w)); + q.extend([0; 4]); + q.extend([0; 4]); + let mut desc = vec![]; + desc.extend(86u32.to_be_bytes()); + desc.extend(ctype); + desc.extend([0; 24]); + desc.extend(be(&[w, h])); + desc.extend([0; 8]); + desc.extend((data.len() as u32).to_be_bytes()); + desc.resize(86, 0); + q.extend(desc); + q.extend(data); + [(q.len() as u32).to_be_bytes().to_vec(), q].concat() +} + +fn red_jpeg() -> Vec { + let img = image::RgbImage::from_pixel(4, 2, image::Rgb([255, 0, 0])); + let mut out = std::io::Cursor::new(vec![]); + img.write_to(&mut out, image::ImageFormat::Jpeg).unwrap(); + out.into_inner() +} + +#[test] +fn quicktime_jpeg_images_are_placed_by_their_matrix() { + let jpeg = red_jpeg(); + let ops = [ + (0x8200, quicktime(b"jpeg", [2.0, 0.0, 0.0, 2.0, 10.0, 5.0], 4, 2, &jpeg)), + (0x8200, quicktime(b"rle ", [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], 4, 2, &[1, 2, 3])), + ]; + let p = import_pict(&v2([0, 0, 50, 50], &ops)).unwrap(); + let imgs = images(&p.document); + assert_eq!(imgs.len(), 1); + let (n, px) = &imgs[0]; + assert_eq!(px.dimensions(), (4, 2)); + let [r, g, b, _] = px.get_pixel(1, 1).0; + assert!(r > 240 && g < 16 && b < 16, "{r} {g} {b}"); + assert!(near(n.geometric_bounds().unwrap(), Rect::new(10.0, 5.0, 18.0, 9.0), 1e-9)); + assert!(p.warnings.iter().any(|w| w.contains("other than JPEG")), "{:?}", p.warnings); +} + +/// An image whose matrix flattens it is left out, and adds nothing to the document's images. +#[test] +fn a_flattened_image_adds_no_image_data() { + let p = import_pict(&v2([0, 0, 50, 50], &[(0x8200, quicktime(b"jpeg", [0.0; 6], 4, 2, &red_jpeg()))])).unwrap(); + assert!(images(&p.document).is_empty()); + assert!(p.document.images.is_empty(), "{:?}", p.document.images.keys().collect::>()); +} + +#[test] +fn pictures_cut_short_keep_what_came_before() { + let full = v2([0, 0, 50, 50], &[(0x31, rect(0, 0, 10, 10)), (0x31, rect(20, 20, 30, 30))]); + // Cut inside the second rectangle. + let cut = &full[..full.len() - 6]; + let p = import_pict(cut).unwrap(); + assert_eq!(paths(&p.document).len(), 1); + assert!(p.warnings.iter().any(|w| w.contains("cut short")), "{:?}", p.warnings); + // A long comment longer than the file. + let p = import_pict(&v2([0, 0, 50, 50], &[(0x31, rect(0, 0, 10, 10)), (0xA1, be(&[100, 5000]))])).unwrap(); + assert_eq!(paths(&p.document).len(), 1); + assert!(p.warnings.iter().any(|w| w.contains("cut short")), "{:?}", p.warnings); + // Nothing drawn. + let p = import_pict(&v2([0, 0, 50, 50], &[(0xA0, be(&[100]))])).unwrap(); + assert!(p.warnings.iter().any(|w| w.contains("draws nothing")), "{:?}", p.warnings); +} + +#[test] +fn reserved_opcodes_are_skipped_by_their_lengths() { + let ops = [ + // A 16-bit length, a fixed length for Apple's reserved words, and a 32-bit length. + (0x0024, be(&[4, 1, 2])), + (0x0200, be(&[1, 2])), + (0x00D0, [8u32.to_be_bytes().to_vec(), vec![9; 8]].concat()), + (0x8201, [2u32.to_be_bytes().to_vec(), vec![9; 2]].concat()), + (0x31, rect(0, 0, 10, 10)), + ]; + let p = import_pict(&v2([0, 0, 50, 50], &ops)).unwrap(); + assert_eq!(paths(&p.document).len(), 1, "{:?}", p.warnings); +} + +/// A picture of nothing but no-ops stops at the opcode limit. +#[test] +fn a_picture_that_never_ends_stops_at_the_opcode_limit() { + let mut b = v2([0, 0, 50, 50], &[(0x31, rect(0, 0, 10, 10))]); + b.truncate(b.len() - 2); + b.resize(b.len() + 2 * ((1 << 22) + 1), 0); + let p = import_pict(&b).unwrap(); + assert_eq!(paths(&p.document).len(), 1); + assert!(p.warnings.iter().any(|w| w.contains("more opcodes")), "{:?}", p.warnings); +} + +/// Regions share one budget of inversion points per picture: past it, a region is left out. +#[test] +fn regions_past_the_picture_budget_are_left_out() { + // One scanline of 16,000 inversion points: 8,000 rectangles. + let mut words = vec![0]; + words.extend(0..16_000i16); + words.extend([0x7FFF, 1, 0x7FFF, 0x7FFF]); + let body = [rect(0, 0, 1, 16_000), be(&words)].concat(); + let region = [be(&[(body.len() + 2) as i16]), body].concat(); + let p = import_pict(&v2([0, 0, 300, 300], &[(0x81, region.clone()), (0x81, region.clone()), (0x81, region)])).unwrap(); + assert!(p.warnings.iter().any(|w| w.contains("regions larger")), "{:?}", p.warnings); + let v = paths(&p.document); + assert_eq!(v.len(), 2); + let NodeKind::Path { path, .. } = &v[0].kind else { panic!("a path") }; + assert_eq!(path.subpaths.len(), 8_000); +} diff --git a/crates/pathops/src/addons.rs b/crates/pathops/src/addons.rs index 3896d02d05..436ba984bd 100644 --- a/crates/pathops/src/addons.rs +++ b/crates/pathops/src/addons.rs @@ -10,12 +10,15 @@ //! - [`segment_reshape`]: bending a segment by dragging a point on it (shared by the tools that //! reshape segments directly). //! - [`pen`]: the Smart Pen's straight and curved segments and its point edits. +//! - [`stencil`]: Stencil Bridges, the strips cut out of art so that a stencil cut from it keeps +//! its islands attached. pub mod cleanup; pub mod keep_shape; pub mod pathtools; pub mod pen; pub mod segment_reshape; +pub mod stencil; pub use cleanup::{ Rejoined, close_nearly_closed, merge_duplicate_anchors, near_point_groups, rejoin, remove_collinear_anchors, retract_tiny_handles, diff --git a/crates/pathops/src/addons/cleanup.rs b/crates/pathops/src/addons/cleanup.rs index edb3489007..75cf45b583 100644 --- a/crates/pathops/src/addons/cleanup.rs +++ b/crates/pathops/src/addons/cleanup.rs @@ -3,7 +3,7 @@ //! nearly closed paths; [`near_point_groups`] finds anchors to snap together, and [`rejoin`] welds //! open pieces whose ends meet back into paths. -use std::collections::HashMap; +use std::collections::{BTreeSet, HashMap}; use kurbo::{Point, Vec2}; use vectorcraft_geom::{Anchor, AnchorKind, EPS, SubPath}; @@ -23,24 +23,64 @@ fn moved(p: Point, a_p: Point, h: Point) -> Point { /// Remove the corner anchors (no handles, straight segments both sides) where a straight run goes /// on in the same direction: the sine of the angle it turns there is at most `tolerance`. Open ends /// stay, and a subpath keeps two anchors (three when closed) → how many went. +/// +/// Each anchor is tested once, first to last, against the nearest anchors still kept on either +/// side. On a closed subpath, an anchor with none kept before it has the last anchor as its +/// previous neighbor, and the last anchor has the first one kept as its next neighbor. The kept +/// anchors move into place once at the end, so the work grows linearly with the number of anchors. pub fn remove_collinear_anchors(sp: &mut SubPath, tolerance: f64) -> usize { - let mut removed = 0; - let mut i = 0; - while i < sp.anchors.len() && sp.anchors.len() > min_anchors(sp) { - let n = sp.anchors.len(); - let inner = sp.closed || (i > 0 && i + 1 < n); - let (Some(prev), Some(cur), Some(next)) = (sp.anchors.get((i + n - 1) % n), sp.anchors.get(i), sp.anchors.get((i + 1) % n)) else { break }; + let n = sp.anchors.len(); + let min = min_anchors(sp); + if n <= min { + return 0; + } + let mut keep = vec![true; n]; + let (mut left, mut first_kept, mut last_kept) = (n, None, None); + #[cfg(test)] + let mut work = 0; + for i in 0..n { + if left <= min { + break; + } + #[cfg(test)] + { + work += 1; + } + // Every anchor after `i` is still there, the last one included. + let p = last_kept.unwrap_or(n - 1); + let q = if i + 1 < n { i + 1 } else { first_kept.unwrap_or(i) }; + let inner = sp.closed || (last_kept.is_some() && i + 1 < n); + let (Some(prev), Some(cur), Some(next)) = (sp.anchors.get(p), sp.anchors.get(i), sp.anchors.get(q)) else { break }; let straight = !prev.has_out() && !cur.has_in() && !cur.has_out() && !next.has_in(); let (a, b) = (cur.p - prev.p, next.p - cur.p); let len = a.hypot() * b.hypot(); if inner && straight && len > EPS && a.dot(b) > 0.0 && a.cross(b).abs() / len <= tolerance { - sp.anchors.remove(i); - removed += 1; + if let Some(k) = keep.get_mut(i) { + *k = false; + } + left -= 1; } else { - i += 1; + first_kept.get_or_insert(i); + last_kept = Some(i); } } - removed + if left < n { + let mut kept = keep.iter(); + sp.anchors.retain(|_| kept.next().copied().unwrap_or(true)); + #[cfg(test)] + { + work += n; + } + } + #[cfg(test)] + COLLINEAR_WORK.with(|w| w.set(work)); + n - left +} + +#[cfg(test)] +thread_local! { + /// Anchors tested plus anchors moved by the last [`remove_collinear_anchors`] on this thread. + static COLLINEAR_WORK: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Merge each anchor lying within `distance` of the one before it (and a closed subpath's last @@ -101,58 +141,203 @@ pub fn close_nearly_closed(sp: &mut SubPath, distance: f64) -> bool { true } +/// The cell of a grid of `size`-wide squares that `p` lies in. +fn grid_cell(p: Point, size: f64) -> (i64, i64) { + ((p.x / size).floor() as i64, (p.y / size).floor() as i64) +} + +/// The cell `(x, y)` and the cells around it, each once. +fn around((x, y): (i64, i64)) -> Vec<(i64, i64)> { + let mut out: Vec<(i64, i64)> = [-1, 0, 1].into_iter().flat_map(|dx| [-1, 0, 1].map(|dy| (x.saturating_add(dx), y.saturating_add(dy)))).collect(); + out.sort_unstable(); + out.dedup(); + out +} + +/// The root of `i`'s set in the union-find forest `parent`. +fn root(parent: &mut [usize], mut i: usize) -> usize { + while let Some(&p) = parent.get(i).filter(|&&p| p != i) { + let up = parent.get(p).copied().unwrap_or(p); + if let Some(slot) = parent.get_mut(i) { + *slot = up; + } + i = p; + } + i +} + /// Groups of `points` to snap together: points within `distance` of one another (and so on, one /// to the next) that aren't all at the same place, skipping the pairs `linked` names (such as /// neighbouring anchors of one path). Each group lists its points in order; snapping them all to /// the first one makes them coincide. Non-finite points and a distance that isn't a positive number /// find nothing. +/// +/// Two points are compared when their cells of a `distance`-wide grid touch. Each group grows from +/// one point at a time, which looks only at points no group has taken yet, so a cluster of points +/// all within `distance` of one another is grouped with work that grows linearly with its size. pub fn near_point_groups(points: &[Point], distance: f64, linked: impl Fn(usize, usize) -> bool) -> Vec> { if !(distance > 0.0 && distance.is_finite()) { return vec![]; } - let cell = |p: Point| ((p.x / distance).floor() as i64, (p.y / distance).floor() as i64); - let mut grid: HashMap<(i64, i64), Vec> = HashMap::new(); - for (i, p) in points.iter().enumerate().filter(|(_, p)| p.is_finite()) { - grid.entry(cell(*p)).or_default().push(i); - } - let mut parent: Vec = (0..points.len()).collect(); - fn root(parent: &mut [usize], mut i: usize) -> usize { - while let Some(&p) = parent.get(i).filter(|&&p| p != i) { - let up = parent.get(p).copied().unwrap_or(p); - if let Some(slot) = parent.get_mut(i) { - *slot = up; - } - i = p; + let mut cells = buckets(points, distance); + let mut near = Near { + distance, + linked, + parent: (0..points.len()).collect(), + taken: points.iter().map(|p| !p.is_finite()).collect(), + queue: vec![], + #[cfg(test)] + work: 0, + }; + for (start, &p) in points.iter().enumerate() { + if near.taken.get(start) != Some(&false) { + continue; } - i - } - for (&(cx, cy), members) in &grid { - for (dx, dy) in [(0, 0), (1, 0), (-1, 1), (0, 1), (1, 1)] { - let Some(others) = grid.get(&(cx.saturating_add(dx), cy.saturating_add(dy))) else { continue }; - for &i in members { - for &j in others.iter().filter(|&&j| (dx, dy) != (0, 0) || j > i) { - let (Some(a), Some(b)) = (points.get(i), points.get(j)) else { continue }; - let d = a.distance(*b); - if d <= distance && d > 0.0 && !linked(i.min(j), i.max(j)) { - let (ri, rj) = (root(&mut parent, i), root(&mut parent, j)); - if let Some(slot) = parent.get_mut(ri.max(rj)) { - *slot = ri.min(rj); - } - } - } - } + if let Some(t) = near.taken.get_mut(start) { + *t = true; + } + let mut at = Some((start, p)); + while let Some((i, p)) = at { + near.reach(&mut cells, i, p); + at = near.queue.pop().and_then(|j| Some((j, *points.get(j)?))); } } + #[cfg(test)] + NEAR_WORK.with(|w| w.set(near.work)); // Only pairs that aren't at the same place were joined, so no group is all at one place. let mut groups: HashMap> = HashMap::new(); for i in 0..points.len() { - groups.entry(root(&mut parent, i)).or_default().push(i); + groups.entry(root(&mut near.parent, i)).or_default().push(i); } let mut out: Vec> = groups.into_values().filter(|g| g.len() > 1).collect(); out.sort_unstable(); out } +#[cfg(test)] +thread_local! { + /// Buckets, places and points looked at by the last [`near_point_groups`] on this thread. + static NEAR_WORK: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The finite points of one cell of a grid that lie in one square a quarter of a cell wide, with +/// the box around them. +struct Bucket { + lo: Point, + hi: Point, + /// Each place (bit for bit) and the points there that no group has taken yet, though some of + /// them may have been taken since. + places: Vec<(Point, Vec)>, +} + +impl Bucket { + /// Whether [`Point::distance`] puts every point here further than `distance` from `p`: one + /// coordinate alone differs by more. The square of a `distance` of 1e-150 or more does not + /// underflow, so the measured distance is at least that difference. + fn beyond(&self, p: Point, distance: f64) -> bool { + distance >= 1e-150 && [self.lo.x - p.x, p.x - self.hi.x, self.lo.y - p.y, p.y - self.hi.y].into_iter().any(|g| g > distance) + } +} + +/// The finite `points` in buckets, by grid cell. +fn buckets(points: &[Point], distance: f64) -> HashMap<(i64, i64), Vec> { + let quarter = distance / 4.0; + let mut cells: HashMap<(i64, i64), Vec> = HashMap::new(); + // Each bucket by its cell and square, and each place by its cell, bucket and coordinates. + let mut bucket_at: HashMap<[i64; 4], usize> = HashMap::new(); + let mut place_at: HashMap<(usize, [i64; 2], [u64; 2]), usize> = HashMap::new(); + for (i, &p) in points.iter().enumerate().filter(|(_, p)| p.is_finite()) { + let c = grid_cell(p, distance); + let list = cells.entry(c).or_default(); + let square = grid_cell(p, quarter); + let b = *bucket_at.entry([c.0, c.1, square.0, square.1]).or_insert_with(|| { + list.push(Bucket { lo: p, hi: p, places: vec![] }); + list.len() - 1 + }); + let Some(bucket) = list.get_mut(b) else { continue }; + bucket.lo = Point::new(bucket.lo.x.min(p.x), bucket.lo.y.min(p.y)); + bucket.hi = Point::new(bucket.hi.x.max(p.x), bucket.hi.y.max(p.y)); + let at = *place_at.entry((b, [c.0, c.1], [p.x.to_bits(), p.y.to_bits()])).or_insert_with(|| { + bucket.places.push((p, vec![])); + bucket.places.len() - 1 + }); + if let Some((_, here)) = bucket.places.get_mut(at) { + here.push(i); + } + } + cells +} + +/// The grouping behind [`near_point_groups`]. +struct Near { + distance: f64, + linked: F, + /// The union-find forest of the groups. + parent: Vec, + /// Whether each point is in a group being grown or grown already (non-finite ones never are). + taken: Vec, + /// Points taken into the group being grown whose own neighbors are still to be looked at. + queue: Vec, + #[cfg(test)] + work: usize, +} + +impl bool> Near { + /// Take into `i`'s group every point no group has taken yet that lies within the distance of + /// `p`, `i`'s place, in the cells around it, at a different place and not linked to `i`. + fn reach(&mut self, cells: &mut HashMap<(i64, i64), Vec>, i: usize, p: Point) { + for c in around(grid_cell(p, self.distance)) { + let Some(buckets) = cells.get_mut(&c) else { continue }; + buckets.retain_mut(|b| { + #[cfg(test)] + { + self.work += 1; + } + if !b.beyond(p, self.distance) { + b.places.retain_mut(|place| { + self.visit(i, p, place); + !place.1.is_empty() + }); + } + !b.places.is_empty() + }); + } + } + + /// Take into `i`'s group the points at `place` that `i` joins, and drop the ones taken. + fn visit(&mut self, i: usize, p: Point, (at, here): &mut (Point, Vec)) { + #[cfg(test)] + { + self.work += 1; + } + let d = p.distance(*at); + if !(d <= self.distance && d > 0.0) { + return; + } + here.retain(|&j| { + if self.taken.get(j) != Some(&false) { + return false; + } + #[cfg(test)] + { + self.work += 1; + } + if (self.linked)(i.min(j), i.max(j)) { + return true; + } + let (ri, rj) = (root(&mut self.parent, i), root(&mut self.parent, j)); + if let Some(slot) = self.parent.get_mut(ri.max(rj)) { + *slot = ri.min(rj); + } + if let Some(t) = self.taken.get_mut(j) { + *t = true; + } + self.queue.push(j); + false + }); + } +} + /// Open pieces welded into one path by [`rejoin`]: `members` index the pieces in the order they /// run along `path`. #[derive(Clone, Debug, PartialEq)] @@ -179,6 +364,12 @@ fn outward(sp: &SubPath, last: bool) -> Option { /// Each junction keeps the earlier piece's anchor and the later piece's out handle. Pieces that are /// closed, have fewer than two anchors or a non-finite coordinate stay out. → the chains of two or /// more pieces, and the single pieces that closed. +/// +/// Two ends are compared when their cells of a `gap`-wide grid touch, and pairs are taken in order +/// of the turn, then the distance, then the order of the ends. Each end looks for its first +/// partner in that order among the ends still free, searching outward from the reverse of its own +/// direction, and two ends that are each other's first partner meet; these are the pairs that +/// taking every pair in that order gives. pub fn rejoin(pieces: &[SubPath], gap: f64) -> Vec { if !(gap >= 0.0 && gap.is_finite()) { return vec![]; @@ -187,7 +378,7 @@ pub fn rejoin(pieces: &[SubPath], gap: f64) -> Vec { !sp.closed && sp.anchors.len() >= 2 && sp.anchors.iter().all(|a| a.p.is_finite() && a.h_in.is_finite() && a.h_out.is_finite()) }; // Each usable end: where it is and the way out of its piece there. - let ends: Vec<(End, Point, Vec2)> = pieces + let ends: Vec = pieces .iter() .enumerate() .filter(|(_, sp)| usable(sp)) @@ -197,49 +388,254 @@ pub fn rejoin(pieces: &[SubPath], gap: f64) -> Vec { Some(((i, last), a.p, outward(sp, last)?)) }) .collect(); - let points: Vec = ends.iter().map(|e| e.1).collect(); - // Every pair of ends within the gap, by the turn across the junction. - let mut pairs: Vec<(f64, f64, End, End)> = vec![]; - for (a, b) in candidate_pairs(&points, gap.max(1e-9)) { - let (Some(&(ea, pa, oa)), Some(&(eb, pb, ob))) = (ends.get(a), ends.get(b)) else { continue }; - // A piece's own two ends meet only when closing it leaves a shape (three anchors). - if ea.0 == eb.0 && pieces.get(ea.0).is_none_or(|sp| sp.anchors.len() < 3) { - continue; - } - let d = pa.distance(pb); - if d <= gap { - pairs.push((oa.dot(-ob).clamp(-1.0, 1.0).acos(), d, ea, eb)); - } - } - pairs.sort_by(|x, y| x.0.total_cmp(&y.0).then(x.1.total_cmp(&y.1))); - let mut link: HashMap = HashMap::new(); - for (_, _, a, b) in pairs { - if !link.contains_key(&a) && !link.contains_key(&b) { - link.insert(a, b); - link.insert(b, a); - } - } + let link = Weld::new(pieces, &ends, gap).link(); chains(pieces, &link) } -/// Pairs (a < b) of `points` that may lie within `gap`: those in neighbouring grid cells. -fn candidate_pairs(points: &[Point], gap: f64) -> Vec<(usize, usize)> { - let cell = |p: Point| ((p.x / gap).floor() as i64, (p.y / gap).floor() as i64); - let mut grid: HashMap<(i64, i64), Vec> = HashMap::new(); - for (i, p) in points.iter().enumerate() { - grid.entry(cell(*p)).or_default().push(i); - } - let mut out = vec![]; - for (i, p) in points.iter().enumerate() { - let (cx, cy) = cell(*p); - for dx in -1..=1 { - for dy in -1..=1 { - let Some(others) = grid.get(&(cx.saturating_add(dx), cy.saturating_add(dy))) else { continue }; - out.extend(others.iter().filter(|&&j| j > i).map(|&j| (i, j))); +/// An end, where it lies and the unit direction pointing out of its piece there. +type EndAt = (End, Point, Vec2); + +/// Where a pair of ends (`a` < `b` in the list of ends) comes in the order [`rejoin`] takes pairs: +/// the turn across the junction, the distance between the ends, `a`, the place of `b`'s grid cell +/// among the cells around `a`'s, and `b`. +type Order = (f64, f64, usize, usize, usize); + +/// Whether pair `x` comes before pair `y`. +fn earlier(x: &Order, y: &Order) -> bool { + x.0.total_cmp(&y.0).then(x.1.total_cmp(&y.1)).then((x.2, x.3, x.4).cmp(&(y.2, y.3, y.4))).is_lt() +} + +/// The place of cell `to` among the cells around `from`, listed by x step and then y step from -1 +/// to 1 (cells past the end of the grid repeat their neighbor; the first place counts). +fn listed_at(from: (i64, i64), to: (i64, i64)) -> usize { + let mut steps = [-1, 0, 1].into_iter().flat_map(|dx| [-1, 0, 1].map(|dy| (from.0.saturating_add(dx), from.1.saturating_add(dy)))); + steps.position(|c| c == to).unwrap_or(9) +} + +/// `angle` as an integer in the same order. +fn angle_key(angle: f64) -> i64 { + let bits = angle.to_bits() as i64; + bits ^ (((bits >> 63) as u64) >> 1) as i64 +} + +/// The angle between the directions at angles `a` and `b`, from 0 to π. +fn apart(a: f64, b: f64) -> f64 { + let d = (a - b).abs(); + d.min(std::f64::consts::TAU - d) +} + +/// How far past the turn of the best pair found so far [`Weld::first_partner`] still looks. The +/// turn [`rejoin`] measures (the arc cosine of a dot product of unit vectors) is within 1e-7 of +/// the angle between the directions, and the angles the search sorts by are within 1e-14 of it. +const TURN_SLACK: f64 = 1e-6; + +/// Ends in one grid cell at one place with one outward direction (bit for bit): every other end +/// pairs with each of them at the same turn and distance. +struct Class { + at: Point, + angle: f64, + /// The ends here no pair has taken yet. + free: BTreeSet, +} + +/// The pairing behind [`rejoin`]. +struct Weld<'a> { + pieces: &'a [SubPath], + ends: &'a [EndAt], + gap: f64, + /// The width of the grid's cells. + size: f64, + classes: Vec, + /// Each end's class. + class_of: Vec, + /// Each grid cell's classes with free ends, by the angle of their direction. + cells: HashMap<(i64, i64), BTreeSet<(i64, usize)>>, + /// Whether each end is still free. + free: Vec, + /// Whether each end has looked for its first partner. Another end's first partner in a class + /// is one of the class's first three free ends, so the ends after those cannot meet next and + /// look only once they move up. + awake: Vec, + /// Each awake end's first partner, and where that pair comes in the order. + first: Vec>, + /// The ends whose first partner each end is (some may have moved on since). + wanted_by: Vec>, + /// Ends to check for a partner whose first partner they are. + todo: Vec, + #[cfg(test)] + work: std::cell::Cell, +} + +impl<'a> Weld<'a> { + fn new(pieces: &'a [SubPath], ends: &'a [EndAt], gap: f64) -> Self { + let size = gap.max(1e-9); + let (mut classes, mut class_of, mut cells) = (vec![], vec![], HashMap::new()); + let mut class_at: HashMap<((i64, i64), [u64; 4]), usize> = HashMap::new(); + for (i, &(_, p, out)) in ends.iter().enumerate() { + let c = grid_cell(p, size); + let k = *class_at.entry((c, [p.x, p.y, out.x, out.y].map(f64::to_bits))).or_insert_with(|| { + let angle = out.y.atan2(out.x); + cells.entry(c).or_insert_with(BTreeSet::new).insert((angle_key(angle), classes.len())); + classes.push(Class { at: p, angle, free: BTreeSet::new() }); + classes.len() - 1 + }); + if let Some(class) = classes.get_mut(k) { + class.free.insert(i); } + class_of.push(k); + } + let n = ends.len(); + Weld { + pieces, + ends, + gap, + size, + classes, + class_of, + cells, + free: vec![true; n], + awake: vec![false; n], + first: vec![None; n], + wanted_by: vec![vec![]; n], + todo: vec![], + #[cfg(test)] + work: std::cell::Cell::new(0), } } - out + + /// The links between the ends that meet: two free ends that are each other's first partner + /// meet, and the ends that wanted either of them look again, until no such pair is left. + fn link(mut self) -> HashMap { + for k in 0..self.classes.len() { + self.wake(k); + } + let mut link: HashMap = HashMap::new(); + while let Some(v) = self.todo.pop() { + let Some(w) = self.partner(v) else { continue }; + if self.free.get(v) != Some(&true) || self.free.get(w) != Some(&true) || self.partner(w) != Some(v) { + continue; + } + let (Some(&(ev, ..)), Some(&(ew, ..))) = (self.ends.get(v), self.ends.get(w)) else { continue }; + link.insert(ev, ew); + link.insert(ew, ev); + self.take(v); + self.take(w); + for e in [v, w] { + if let Some(&k) = self.class_of.get(e) { + self.wake(k); + } + } + let waiting: Vec = [v, w].iter().flat_map(|&e| self.wanted_by.get_mut(e).map(std::mem::take).unwrap_or_default()).collect(); + for x in waiting { + if self.free.get(x) == Some(&true) && matches!(self.partner(x), Some(p) if p == v || p == w) { + self.look(x); + } + } + } + #[cfg(test)] + REJOIN_WORK.with(|w| w.set(self.work.get())); + link + } + + /// End `v`'s first partner, once it has looked. + fn partner(&self, v: usize) -> Option { + self.first.get(v).and_then(|f| f.as_ref()).map(|f| f.1) + } + + /// Have the first three free ends of class `k` that have not looked for a partner look. + fn wake(&mut self, k: usize) { + let Some(class) = self.classes.get(k) else { return }; + let sleeping: Vec = class.free.iter().take(3).copied().filter(|&e| self.awake.get(e) == Some(&false)).collect(); + for e in sleeping { + if let Some(a) = self.awake.get_mut(e) { + *a = true; + } + self.look(e); + } + } + + /// Find free end `e`'s first partner, and queue `e` to check whether that end wants it too. + fn look(&mut self, e: usize) { + let next = self.first_partner(e); + if let Some(list) = next.as_ref().and_then(|f| self.wanted_by.get_mut(f.1)) { + list.push(e); + } + if let Some(f) = self.first.get_mut(e) { + *f = next; + } + self.todo.push(e); + } + + /// End `e` has met another: it is no longer free. + fn take(&mut self, e: usize) { + if let Some(f) = self.free.get_mut(e) { + *f = false; + } + let Some(&k) = self.class_of.get(e) else { return }; + let Some(class) = self.classes.get_mut(k) else { return }; + class.free.remove(&e); + if class.free.is_empty() + && let Some(&(_, p, _)) = self.ends.get(e) + && let Some(set) = self.cells.get_mut(&grid_cell(p, self.size)) + { + set.remove(&(angle_key(class.angle), k)); + } + } + + /// The free end `v` meets first, and where that pair comes in the order: the classes in the + /// cells around `v`'s are looked at by how far their direction is from the reverse of `v`'s, + /// until that is more than [`TURN_SLACK`] past the best turn found. + fn first_partner(&self, v: usize) -> Option<(Order, usize)> { + let &((piece, _), p, out) = self.ends.get(v)?; + let toward = (-out.y).atan2(-out.x); + let split = (angle_key(toward), 0); + let mut best: Option<(Order, usize)> = None; + for c in around(grid_cell(p, self.size)) { + let Some(set) = self.cells.get(&c) else { continue }; + // Both ways round from `toward`; between them they meet every class once. + let mut up = set.range(split..).chain(set.range(..split)).peekable(); + let mut down = set.range(..split).rev().chain(set.range(split..).rev()).peekable(); + let turn = |e: Option<&&(i64, usize)>| e.and_then(|e| self.classes.get(e.1)).map_or(f64::INFINITY, |k| apart(k.angle, toward)); + for _ in 0..set.len() { + let (tu, td) = (turn(up.peek()), turn(down.peek())); + if best.as_ref().is_some_and(|b| tu.min(td) > b.0.0 + TURN_SLACK) { + break; + } + let Some(&(_, k)) = (if tu <= td { up.next() } else { down.next() }) else { break }; + if let Some(pair) = self.pair_with(v, p, piece, k) + && best.as_ref().is_none_or(|b| earlier(&pair.0, &b.0)) + { + best = Some(pair); + } + } + } + best + } + + /// The first free end of class `k` that free end `v` (at `p`, on `piece`) may meet, and where + /// that pair comes in the order. Within a class the pairs differ only in the ends' order, so + /// the end listed first comes first. + fn pair_with(&self, v: usize, p: Point, piece: usize, k: usize) -> Option<(Order, usize)> { + #[cfg(test)] + self.work.set(self.work.get() + 1); + let class = self.classes.get(k)?; + if p.distance(class.at) > self.gap { + return None; + } + // A piece's own two ends meet only when closing it leaves a shape (three anchors). + let short = self.pieces.get(piece).is_none_or(|sp| sp.anchors.len() < 3); + let u = *class.free.iter().find(|&&u| u != v && !(short && self.ends.get(u).is_some_and(|e| e.0.0 == piece)))?; + let (a, b) = (v.min(u), v.max(u)); + let (&(_, pa, oa), &(_, pb, ob)) = (self.ends.get(a)?, self.ends.get(b)?); + let at = listed_at(grid_cell(pa, self.size), grid_cell(pb, self.size)); + Some(((oa.dot(-ob).clamp(-1.0, 1.0).acos(), pa.distance(pb), a, at, b), u)) + } +} + +#[cfg(test)] +thread_local! { + /// Classes of ends looked at by the last [`rejoin`] on this thread. + static REJOIN_WORK: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Walk the links between piece ends into chains. diff --git a/crates/pathops/src/addons/cleanup/tests.rs b/crates/pathops/src/addons/cleanup/tests.rs index 3e1c58d42b..d262128234 100644 --- a/crates/pathops/src/addons/cleanup/tests.rs +++ b/crates/pathops/src/addons/cleanup/tests.rs @@ -1,7 +1,12 @@ -use kurbo::{Point, Vec2}; -use vectorcraft_geom::{Anchor, AnchorKind, SubPath}; +use std::collections::HashMap; -use super::{close_nearly_closed, merge_duplicate_anchors, near_point_groups, rejoin, remove_collinear_anchors, retract_tiny_handles}; +use kurbo::{Point, Vec2}; +use vectorcraft_geom::{Anchor, AnchorKind, EPS, SubPath}; + +use super::{ + End, Rejoined, chains, close_nearly_closed, merge_duplicate_anchors, near_point_groups, outward, rejoin, remove_collinear_anchors, + retract_tiny_handles, root, +}; fn line(pts: &[(f64, f64)], closed: bool) -> SubPath { SubPath::polyline(&pts.iter().map(|&p| p.into()).collect::>(), closed) @@ -30,6 +35,174 @@ fn collinear_anchors_go_and_corners_stay() { assert_eq!(remove_collinear_anchors(&mut bend, 0.005), 1); } +/// The collinear-anchor removal done one `Vec::remove` at a time, testing the anchor that moves +/// into the gap next: the result [`remove_collinear_anchors`] gives. +fn one_at_a_time(sp: &mut SubPath, tolerance: f64) -> usize { + let min = if sp.closed { 3 } else { 2 }; + let mut removed = 0; + let mut i = 0; + while i < sp.anchors.len() && sp.anchors.len() > min { + let n = sp.anchors.len(); + let inner = sp.closed || (i > 0 && i + 1 < n); + let (prev, cur, next) = (sp.anchors[(i + n - 1) % n], sp.anchors[i], sp.anchors[(i + 1) % n]); + let straight = !prev.has_out() && !cur.has_in() && !cur.has_out() && !next.has_in(); + let (a, b) = (cur.p - prev.p, next.p - cur.p); + let len = a.hypot() * b.hypot(); + if inner && straight && len > EPS && a.dot(b) > 0.0 && a.cross(b).abs() / len <= tolerance { + sp.anchors.remove(i); + removed += 1; + } else { + i += 1; + } + } + removed +} + +/// A subpath's closed flag and every anchor's coordinates bit for bit, with its kind. +fn bits(sp: &SubPath) -> (bool, Vec<([u64; 6], AnchorKind)>) { + let anchors = sp.anchors.iter().map(|a| ([a.p.x, a.p.y, a.h_in.x, a.h_in.y, a.h_out.x, a.h_out.y].map(f64::to_bits), a.kind)); + (sp.closed, anchors.collect()) +} + +/// Check that [`remove_collinear_anchors`] gives `sp` the count and anchors [`one_at_a_time`] does. +fn same_as_one_at_a_time(sp: &SubPath, tolerance: f64) { + let (mut fast, mut slow) = (sp.clone(), sp.clone()); + let got = remove_collinear_anchors(&mut fast, tolerance); + let want = one_at_a_time(&mut slow, tolerance); + assert_eq!(got, want, "count at tolerance {tolerance} for {sp:?}"); + assert_eq!(bits(&fast), bits(&slow), "anchors at tolerance {tolerance} for {sp:?}"); +} + +/// xorshift64: the same numbers on every run. +struct Rng(u64); + +impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + + fn pick(&mut self, xs: &[T]) -> T { + xs[(self.next() % xs.len() as u64) as usize] + } +} + +/// A subpath of `n` anchors stepping mostly straight along one direction, with repeated points, +/// small and large bends, reversals, short and long handles and non-finite or huge coordinates. +fn generated(r: &mut Rng, n: usize, closed: bool) -> SubPath { + let dir = r.pick(&[Vec2::new(1.0, 0.0), Vec2::new(0.0, -1.0), Vec2::new(0.6, 0.8), Vec2::new(-1.0, 1.0)]); + let side = Vec2::new(-dir.y, dir.x); + let mut at = Point::new(r.pick(&[0.0, 3.0, -7.5]), r.pick(&[0.0, 2.0])); + let anchors = (0..n) + .map(|_| { + at += dir * r.pick(&[1.0, 1.0, 1.0, 2.0, 0.5, 0.0, -1.0]); + let bend = r.pick(&[0.0, 0.0, 0.0, 0.0, 1e-3, 0.004, 0.005, 0.006, 1.0]); + let mut p = at + side * bend; + match r.next() % 40 { + 0 => p.x = f64::NAN, + 1 => p.y = f64::INFINITY, + 2 => p.x = f64::NEG_INFINITY, + 3 => p = Point::new(p.x * 1e300, p.y * 1e300), + 4 => p = Point::new(1e-300, -1e-300), + _ => {} + } + let handle = |r: &mut Rng| p + Vec2::new(r.pick(&[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1e-10, 1.0]), 0.0); + let (h_in, h_out) = (handle(r), handle(r)); + Anchor { p, h_in, h_out, kind: r.pick(&[AnchorKind::Corner, AnchorKind::Corner, AnchorKind::Smooth]) } + }) + .collect(); + SubPath::new(anchors, closed) +} + +const TOLERANCES: [f64; 12] = [-1.0, -0.0, 0.0, 1e-9, 0.001, 0.005, 0.5, 1.0, 2.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY]; + +#[test] +fn collinear_anchors_go_as_when_removed_one_at_a_time() { + let mut r = Rng(0x9e37_79b9_7f4a_7c15); + for n in (0..40).chain([64, 100, 257]) { + for _ in 0..40 { + for closed in [false, true] { + let sp = generated(&mut r, n, closed); + for tolerance in TOLERANCES { + same_as_one_at_a_time(&sp, tolerance); + } + } + } + } +} + +#[test] +fn collinear_anchors_keep_their_neighbors_order_and_ends() { + let ring = |pts: &[(f64, f64)]| line(pts, true); + let cases = [ + // A closed run whose first anchor goes: the last anchor's next neighbor is then the second. + ring(&[(5.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0), (0.0, 0.0)]), + ring(&[(0.0, 0.0), (1.0, 0.0), (2.0, 0.0), (3.0, 0.0), (4.0, 0.0), (5.0, 0.0), (2.0, 4.0)]), + // Every anchor on one line: the path stops at three (closed) or two (open) anchors. + ring(&[(0.0, 0.0), (1.0, 0.0), (2.0, 0.0), (3.0, 0.0), (4.0, 0.0)]), + line(&[(0.0, 0.0), (1.0, 0.0), (2.0, 0.0), (3.0, 0.0), (4.0, 0.0)], false), + // The last anchor lies between the first one kept and the one before it. + ring(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0), (0.0, 5.0)]), + // Repeated and zero-length points. + line(&[(0.0, 0.0), (0.0, 0.0), (1.0, 0.0), (1.0, 0.0), (2.0, 0.0)], false), + ring(&[(0.0, 0.0), (0.0, 0.0), (0.0, 0.0), (0.0, 0.0)]), + // Products of huge coordinates overflow; tiny ones underflow. + line(&[(0.0, 0.0), (1e200, 1e200), (2e200, 2e200), (f64::MAX, f64::MAX)], false), + line(&[(0.0, 0.0), (1e-200, 0.0), (2e-200, 0.0)], false), + line(&[(0.0, 0.0), (f64::NAN, 0.0), (2.0, 0.0), (f64::INFINITY, 0.0), (5.0, 0.0)], false), + ]; + for sp in &cases { + for tolerance in TOLERANCES { + same_as_one_at_a_time(sp, tolerance); + } + } + let mut first = cases[0].clone(); + assert_eq!(remove_collinear_anchors(&mut first, 0.0), 1); + assert_eq!(points(&first), [(10.0, 0.0), (10.0, 10.0), (0.0, 10.0), (0.0, 0.0)]); + let (mut closed, mut open) = (cases[2].clone(), cases[3].clone()); + assert_eq!((remove_collinear_anchors(&mut closed, 0.0), closed.anchors.len()), (2, 3)); + assert_eq!(remove_collinear_anchors(&mut open, 0.0), 3); + assert_eq!(points(&open), [(0.0, 0.0), (4.0, 0.0)], "open ends stay"); + // A handle on either side of either segment keeps the anchor between them. + for side in 0..4 { + let mut sp = line(&[(0.0, 0.0), (1.0, 0.0), (2.0, 0.0)], false); + let (i, h) = [(0, 1), (1, 0), (1, 1), (2, 0)][side]; + for kind in [AnchorKind::Corner, AnchorKind::Smooth] { + let a = &mut sp.anchors[i]; + a.kind = kind; + *(if h == 0 { &mut a.h_in } else { &mut a.h_out }) = a.p + Vec2::new(0.0, 1.0); + same_as_one_at_a_time(&sp, 0.005); + assert_eq!(remove_collinear_anchors(&mut sp.clone(), 0.005), 0, "handle {h} on anchor {i}"); + } + } +} + +#[test] +fn collinear_anchors_at_the_tolerance_go_and_just_past_it_stay() { + let sp = line(&[(0.0, 0.0), (100.0, 0.1), (200.0, 0.0)], false); + let (a, b) = (sp.anchors[1].p - sp.anchors[0].p, sp.anchors[2].p - sp.anchors[1].p); + let sine = a.cross(b).abs() / (a.hypot() * b.hypot()); + for (tolerance, removed) in [(sine, 1), (sine.next_down(), 0), (sine.next_up(), 1)] { + same_as_one_at_a_time(&sp, tolerance); + assert_eq!(remove_collinear_anchors(&mut sp.clone(), tolerance), removed, "{tolerance}"); + } +} + +#[test] +fn collinear_anchors_go_in_linear_work() { + for (n, closed) in [(10_000, false), (20_000, false), (20_000, true)] { + let pts: Vec = (0..n).map(|i| Point::new(i as f64, 0.0)).collect(); + let mut sp = SubPath::polyline(&pts, closed); + let removed = remove_collinear_anchors(&mut sp, 0.005); + // A closed straight run stops at three anchors; an open one keeps its two ends. + assert_eq!((removed, sp.anchors.len()), if closed { (n - 3, 3) } else { (n - 2, 2) }); + let work = super::COLLINEAR_WORK.with(std::cell::Cell::get); + assert!(work <= 2 * n, "{n} anchors took {work} steps"); + } +} + #[test] fn duplicate_anchors_merge_keeping_the_outer_handles() { let mut sp = SubPath::new( @@ -89,6 +262,244 @@ fn near_points_group_but_linked_and_equal_ones_do_not() { assert!(near_point_groups(&far, 1e-300, |_, _| false).is_empty()); } +/// Nearly Coincident Anchors' grouping comparing every pair of points in touching grid cells: the +/// groups [`near_point_groups`] gives. +fn near_groups_pair_by_pair(points: &[Point], distance: f64, linked: impl Fn(usize, usize) -> bool) -> Vec> { + if !(distance > 0.0 && distance.is_finite()) { + return vec![]; + } + let cell = |p: Point| ((p.x / distance).floor() as i64, (p.y / distance).floor() as i64); + let mut grid: HashMap<(i64, i64), Vec> = HashMap::new(); + for (i, p) in points.iter().enumerate().filter(|(_, p)| p.is_finite()) { + grid.entry(cell(*p)).or_default().push(i); + } + let mut parent: Vec = (0..points.len()).collect(); + for (&(cx, cy), members) in &grid { + for (dx, dy) in [(0, 0), (1, 0), (-1, 1), (0, 1), (1, 1)] { + let Some(others) = grid.get(&(cx.saturating_add(dx), cy.saturating_add(dy))) else { continue }; + for &i in members { + for &j in others.iter().filter(|&&j| (dx, dy) != (0, 0) || j > i) { + let d = points[i].distance(points[j]); + if d <= distance && d > 0.0 && !linked(i.min(j), i.max(j)) { + let (ri, rj) = (root(&mut parent, i), root(&mut parent, j)); + parent[ri.max(rj)] = ri.min(rj); + } + } + } + } + } + let mut groups: HashMap> = HashMap::new(); + for i in 0..points.len() { + groups.entry(root(&mut parent, i)).or_default().push(i); + } + let mut out: Vec> = groups.into_values().filter(|g| g.len() > 1).collect(); + out.sort_unstable(); + out +} + +/// Points around a few spots on a lattice, many at the same place, with signed zeros, huge, tiny +/// and non-finite coordinates. +fn generated_points(r: &mut Rng, n: usize, distance: f64) -> Vec { + let spots: Vec = (0..1 + r.next() % 6).map(|_| Point::new((r.next() % 5) as f64 * distance, (r.next() % 5) as f64 * distance)).collect(); + (0..n) + .map(|_| { + let jitter = |r: &mut Rng| r.pick(&[0.0, 0.0, -0.0, 0.1, 0.3, 0.5, 0.7, 0.99, 1.0, 1.01, 2.0, -0.5, -1.0]) * distance; + let at = r.pick(&spots); + let p = Point::new(at.x + jitter(r), at.y + jitter(r)); + match r.next() % 50 { + 0 => Point::new(f64::NAN, p.y), + 1 => Point::new(p.x, f64::INFINITY), + 2 => Point::new(-0.0, -0.0), + 3 => Point::new(p.x * 1e300, p.y), + 4 => Point::new(1e-300, 1e-300), + _ => p, + } + }) + .collect() +} + +#[test] +fn near_points_group_as_when_every_pair_is_compared() { + let mut r = Rng(0x2545_f491_4f6c_dd1d); + let linked: [fn(usize, usize) -> bool; 5] = + [|_, _| false, |a, b| b == a + 1, |a, b| (a * 31 + b * 17) % 5 == 0, |a, b| (a + b) % 2 == 0, |_, _| true]; + for n in (0..30).chain([64, 150, 300]) { + for _ in 0..12 { + for distance in [0.01, 0.5, 1.0, 3.0, 1e-200, 1e300] { + let pts = generated_points(&mut r, n, distance); + for (k, linked) in linked.iter().enumerate() { + let want = near_groups_pair_by_pair(&pts, distance, linked); + assert_eq!(near_point_groups(&pts, distance, linked), want, "linked {k} at {distance} for {pts:?}"); + } + } + } + } +} + +/// A tight cluster of `n` points around `at`, no two at the same place. +fn cluster(at: Point, radius: f64, n: usize) -> Vec { + (0..n).map(|i| at + Vec2::from_angle(i as f64 * 2.399_963) * (radius * ((i + 1) as f64 / n as f64).sqrt())).collect() +} + +#[test] +fn near_points_in_a_dense_cell_group_in_linear_work() { + let n = 4_000; + let neighbours = |a: usize, b: usize| b == a + 1; + let one_cluster = cluster(Point::new(0.005, 0.005), 0.004, n); + let mut two_clusters = cluster(Point::new(0.001, 0.001), 0.0009, n / 2); + two_clusters.extend(cluster(Point::new(0.019, 0.019), 0.0009, n / 2)); + let same_place = vec![Point::new(0.005, 0.005); n]; + let cases = [(&one_cluster, 1, n), (&two_clusters, 2, n / 2), (&same_place, 0, 0)]; + for (pts, count, size) in cases { + let groups = near_point_groups(pts, 0.01, neighbours); + let work = super::NEAR_WORK.with(std::cell::Cell::get); + assert_eq!(groups, near_groups_pair_by_pair(pts, 0.01, neighbours)); + assert_eq!(groups.len(), count); + assert!(groups.iter().all(|g| g.len() == size), "{:?}", groups.iter().map(Vec::len).collect::>()); + assert!(work <= 4 * n, "{n} points took {work} steps"); + } +} + +/// One pair of ends (`a` < `b` in the list of ends) for [`rejoin_sorting_every_pair`]: the turn, +/// the distance, and the two ends. +type Pair = (f64, f64, End, End); + +/// Rejoin listing every pair of ends in touching grid cells and sorting them by turn and then +/// distance: the joins [`rejoin`] makes. +fn rejoin_sorting_every_pair(pieces: &[SubPath], gap: f64) -> Vec { + if !(gap >= 0.0 && gap.is_finite()) { + return vec![]; + } + let usable = |sp: &&SubPath| { + !sp.closed && sp.anchors.len() >= 2 && sp.anchors.iter().all(|a| a.p.is_finite() && a.h_in.is_finite() && a.h_out.is_finite()) + }; + let ends: Vec<(End, Point, Vec2)> = pieces + .iter() + .enumerate() + .filter(|(_, sp)| usable(sp)) + .flat_map(|(i, sp)| [(i, sp, false), (i, sp, true)]) + .filter_map(|(i, sp, last)| { + let a = if last { sp.anchors.last() } else { sp.anchors.first() }?; + Some(((i, last), a.p, outward(sp, last)?)) + }) + .collect(); + let size = gap.max(1e-9); + let cell = |p: Point| ((p.x / size).floor() as i64, (p.y / size).floor() as i64); + let mut grid: HashMap<(i64, i64), Vec> = HashMap::new(); + for (i, e) in ends.iter().enumerate() { + grid.entry(cell(e.1)).or_default().push(i); + } + let mut pairs: Vec = vec![]; + for (a, &(ea, pa, oa)) in ends.iter().enumerate() { + let (cx, cy) = cell(pa); + for dx in -1..=1 { + for dy in -1..=1 { + let Some(others) = grid.get(&(cx.saturating_add(dx), cy.saturating_add(dy))) else { continue }; + for &b in others.iter().filter(|&&b| b > a) { + let (eb, pb, ob) = ends[b]; + if ea.0 == eb.0 && pieces[ea.0].anchors.len() < 3 { + continue; + } + let d = pa.distance(pb); + if d <= gap { + pairs.push((oa.dot(-ob).clamp(-1.0, 1.0).acos(), d, ea, eb)); + } + } + } + } + } + pairs.sort_by(|x, y| x.0.total_cmp(&y.0).then(x.1.total_cmp(&y.1))); + let mut link: HashMap = HashMap::new(); + for (_, _, a, b) in pairs { + if !link.contains_key(&a) && !link.contains_key(&b) { + link.insert(a, b); + link.insert(b, a); + } + } + chains(pieces, &link) +} + +/// Check that [`rejoin`] joins `pieces` as [`rejoin_sorting_every_pair`] does, bit for bit. +fn same_as_sorting_every_pair(pieces: &[SubPath], gap: f64) { + let (got, want) = (rejoin(pieces, gap), rejoin_sorting_every_pair(pieces, gap)); + let shape = |out: &[Rejoined]| out.iter().map(|j| (j.members.clone(), bits(&j.path))).collect::>(); + assert_eq!(shape(&got), shape(&want), "gap {gap} for {pieces:?}"); +} + +/// Pieces of two to four anchors whose ends sit on or near a few lattice points, often at the +/// same place, some curving, closed or non-finite. +fn generated_pieces(r: &mut Rng, n: usize, gap: f64) -> Vec { + let spot = |r: &mut Rng| { + let near = r.pick(&[0.0, 0.0, 0.0, 0.25, 0.5, 1.0, 1.5]) * gap; + Point::new((r.next() % 3) as f64 + near, (r.next() % 3) as f64 + r.pick(&[0.0, 0.0, near, -near])) + }; + (0..n) + .map(|_| { + let count = 2 + (r.next() % 3) as usize; + let mut pts: Vec = (0..count).map(|_| spot(r)).collect(); + if r.next().is_multiple_of(30) { + pts[0].x = f64::NAN; + } + let mut sp = SubPath::polyline(&pts, r.next().is_multiple_of(15)); + if r.next().is_multiple_of(4) { + let a = &mut sp.anchors[0]; + a.h_out = a.p + r.pick(&[Vec2::new(0.3, 0.1), Vec2::new(0.0, -0.2), Vec2::new(-0.1, -0.1)]); + } + sp + }) + .collect() +} + +#[test] +fn rejoin_joins_as_when_every_pair_is_sorted() { + let mut r = Rng(0xd1b5_4a32_d192_ed03); + for n in (0..25).chain([40, 80, 160]) { + for _ in 0..15 { + for gap in [0.0, 0.05, 0.1, 0.5, 1.0, 3.0] { + same_as_sorting_every_pair(&generated_pieces(&mut r, n, gap), gap); + } + } + } + // Ends meeting from directions that tie: a plus sign, a doubled star and stacked copies. + let plus: Vec = [(1.0, 0.0), (0.0, 1.0), (-1.0, 0.0), (0.0, -1.0)].map(|(x, y)| line(&[(0.0, 0.0), (x, y)], false)).to_vec(); + let mut doubled = plus.clone(); + doubled.extend(plus.iter().map(|sp| { + let mut sp = sp.clone(); + sp.reverse(); + sp + })); + let stacked = vec![line(&[(0.0, 0.0), (1.0, 0.0), (2.0, 1.0)], false); 7]; + for pieces in [&plus, &doubled, &stacked] { + for gap in [0.0, 0.1, 5.0] { + same_as_sorting_every_pair(pieces, gap); + } + } +} + +#[test] +fn rejoin_pairs_coincident_ends_in_near_linear_work() { + let n = 2_000; + let ray = |angle: f64| { + let tip = Vec2::from_angle(angle) * 100.0; + line(&[(0.0, 0.0), (tip.x, tip.y)], false) + }; + let star: Vec = (0..n).map(|i| ray(i as f64 * std::f64::consts::TAU / n as f64)).collect(); + let mut r = Rng(0x9e37_79b9_7f4a_7c15); + let scattered: Vec = (0..n).map(|_| ray((r.next() % 1_000_000) as f64 * 1e-6 * std::f64::consts::TAU)).collect(); + let stacked = vec![line(&[(0.0, 0.0), (10.0, 0.0)], false); n]; + for (name, pieces) in [("star", &star), ("scattered", &scattered), ("stacked", &stacked)] { + let out = rejoin(pieces, 0.1); + let work = super::REJOIN_WORK.with(std::cell::Cell::get); + let want = rejoin_sorting_every_pair(pieces, 0.1); + assert_eq!( + out.iter().map(|j| (j.members.clone(), bits(&j.path))).collect::>(), + want.iter().map(|j| (j.members.clone(), bits(&j.path))).collect::>(), + "{name}" + ); + assert!(work <= 20 * n, "{name}: {n} pieces took {work} steps"); + } +} + #[test] fn rejoin_welds_pieces_within_the_gap() { // Three pieces of one zig-zag, the middle one drawn backwards, plus one too far away. diff --git a/crates/pathops/src/addons/pathtools/crossings.rs b/crates/pathops/src/addons/pathtools/crossings.rs index e1d96ed0fd..d216a2f4b3 100644 --- a/crates/pathops/src/addons/pathtools/crossings.rs +++ b/crates/pathops/src/addons/pathtools/crossings.rs @@ -182,7 +182,19 @@ pub fn insert_at(sp: &SubPath, places: &[(usize, f64)]) -> (SubPath, BTreeSet(); + // How many anchors were added before each anchor, counted in one pass for all of them. + let mut before = vec![0usize; n + 1]; + for (&seg, ts) in &inner { + if let Some(b) = before.get_mut(seg + 1) { + *b += ts.len(); + } + } + let mut sum = 0; + for b in &mut before { + sum += *b; + *b = sum; + } + let added_before = |j: usize| before.get(j).copied().unwrap_or(0); let mut marks: BTreeSet = at_anchor.into_iter().map(|j| j + added_before(j)).collect(); for (&seg, ts) in &inner { let base = seg + added_before(seg); diff --git a/crates/pathops/src/addons/stencil.rs b/crates/pathops/src/addons/stencil.rs new file mode 100644 index 0000000000..a5412fa328 --- /dev/null +++ b/crates/pathops/src/addons/stencil.rs @@ -0,0 +1,653 @@ +//! Stencil Bridges: the art a stencil is cut from, with strips cut out of it so that every island +//! of the stencil sheet stays attached. +//! +//! The art is the area the stencil's holes take. Each bounded area outside the art (the inside of +//! an O, any hole of a shape) is an island of the sheet. A bridge is a straight strip of a set +//! width cut out of the art, from an island across the art to the sheet beyond it, or to another +//! island. The bridges are picked as a spanning tree over the islands and the sheet (shortest +//! crossings first), so every island that has room for one is joined to the sheet, then each +//! island gets more bridges, spread around it, up to the number asked for. +//! +//! Crossings are measured along straight lines in one direction at a time (vertical, horizontal, +//! or every 15 degrees for the shortest crossing), spaced half a bridge width apart. + +#[cfg(test)] +mod tests; + +use std::cell::Cell; + +use kurbo::{BezPath, ParamCurve, PathEl, Point}; +use vectorcraft_geom::{FillRule, PathData, SubPath}; + +use crate::{BoolOp, DEFAULT_PRECISION, PathOpsError, try_boolean, try_unite_all}; + +/// The narrowest and widest bridge, in points. +pub const BRIDGE_WIDTH_RANGE: (f64, f64) = (0.01, 1000.0); +/// The most bridges one island is given. +pub const MAX_BRIDGES_PER_ISLAND: usize = 16; +/// The most straight segments the art is followed by. +pub const MAX_STENCIL_SEGMENTS: usize = 200_000; +/// The most outlines the art may have. +pub const MAX_STENCIL_CONTOURS: usize = 4000; +/// How far from the origin the art and its handles may reach, in points: beyond the coordinates a +/// document holds. +pub const MAX_STENCIL_EXTENT: f64 = 1.0e7; +/// The most segments all lines across the art may look at together. +const MAX_WORK: usize = 300_000_000; +/// The most edges the outlines are tested against when finding which ones bound islands. +const MAX_NESTING_WORK: usize = 50_000_000; +/// The most bands one direction's segments are listed in. +const MAX_LINES: f64 = 1000.0; +/// The most lines all islands are looked across along, in every direction together. +const MAX_ISLAND_LINES: usize = 400_000; +/// The most lines on each side of an island's middle, in one direction. +const MAX_LINES_PER_SIDE: usize = 64; +/// The most times segments are listed against the lines they reach, in one direction. +const MAX_BIN_ENTRIES: usize = 20_000_000; +/// The lines across one bridge its width is checked along. +const CHECKS: usize = 5; +/// The directions the shortest crossing is looked for in, in degrees. +const SHORTEST_STEP_DEG: usize = 15; + +/// Which way bridges run. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BridgeDirection { + Vertical, + Horizontal, + /// The shortest crossing in any of 12 directions, 15 degrees apart. + Shortest, +} + +/// What [`stencil_bridges`] makes. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct BridgeSpec { + /// Each bridge's width (pt), in [`BRIDGE_WIDTH_RANGE`]. + pub width: f64, + /// The bridges each island is given, 1 to [`MAX_BRIDGES_PER_ISLAND`] (fewer where it has no + /// room for more, and more where other islands are joined to the sheet through it). + pub count: usize, + pub direction: BridgeDirection, +} + +/// The art with its bridges cut out. +#[derive(Clone, Debug, PartialEq)] +pub struct Bridged { + /// The art as one area, less the bridges. + pub path: PathData, + /// The islands the art held. + pub islands: usize, + /// The bridges cut. + pub bridges: usize, + /// The islands the cut result still encloses: no bridge of the width fits, or the bridges that + /// fit join them only to each other. + pub unbridged: usize, +} + +/// `art` (each path with its fill rule; open subpaths are closed as a fill closes them) as one +/// area with bridges cut out of it as `spec` says. With no islands, the area is returned as it is +/// and no bridge is cut. +pub fn stencil_bridges(art: &[(&PathData, FillRule)], spec: BridgeSpec) -> Result { + let (lo, hi) = BRIDGE_WIDTH_RANGE; + if !(spec.width.is_finite() && (lo..=hi).contains(&spec.width)) || !(1..=MAX_BRIDGES_PER_ISLAND).contains(&spec.count) { + return Err(PathOpsError::Degenerate); + } + if too_large(art) { + return Err(PathOpsError::TooComplex); + } + let closed: Vec = + art.iter().map(|(p, _)| PathData::new(p.subpaths.iter().map(|sp| SubPath { closed: true, ..sp.clone() }).collect())).collect(); + let refs: Vec<(&PathData, FillRule)> = closed.iter().zip(art).map(|(p, (_, r))| (p, *r)).collect(); + bridge_region(try_unite_all(&refs)?, spec) +} + +/// Whether `art` has more than [`MAX_STENCIL_SEGMENTS`] anchors or reaches past +/// [`MAX_STENCIL_EXTENT`]: art refused before it is united. +fn too_large(art: &[(&PathData, FillRule)]) -> bool { + let anchors: usize = art.iter().flat_map(|(p, _)| &p.subpaths).map(|sp| sp.anchors.len()).sum(); + anchors > MAX_STENCIL_SEGMENTS || !art.iter().all(|(p, _)| within_extent(&p.to_bezpath())) +} + +/// [`stencil_bridges`] on `region`, an area with no overlaps. +fn bridge_region(region: PathData, spec: BridgeSpec) -> Result { + let contours = contours(®ion, spec.width)?; + let holes = contours.iter().filter(|c| c.hole).count(); + if holes == 0 { + return Ok(Bridged { path: region, islands: 0, bridges: 0, unbridged: 0 }); + } + let (chosen, unjoined) = choose(&contours, spec, MAX_WORK)?; + if chosen.is_empty() { + return Ok(Bridged { path: region, islands: holes, bridges: 0, unbridged: unjoined }); + } + let strips = PathData::new(chosen.iter().map(|c| SubPath::polyline(&c.strip, true)).collect()); + let path = try_boolean(®ion, FillRule::NonZero, &strips, FillRule::NonZero, BoolOp::Difference, DEFAULT_PRECISION)?; + // The islands the result still encloses, counted on the cut outlines themselves (removing art + // never encloses a new one). + let unbridged = match self::contours(&path, spec.width) { + Ok(left) => left.iter().filter(|c| c.hole).count(), + Err(_) => unjoined, + }; + Ok(Bridged { path, islands: holes, bridges: chosen.len(), unbridged }) +} + +/// The bridges `spec` asks for across the art that `contours` outline, and how many islands they +/// leave apart from the sheet. Lines across the art look at no more than `work` segments in all; +/// past that, the art is refused when the islands are not all joined yet, and otherwise the extra +/// bridges found so far are kept. +fn choose(contours: &[Contour], spec: BridgeSpec, work: usize) -> Result<(Vec, usize), PathOpsError> { + let degrees: Vec = match spec.direction { + BridgeDirection::Vertical => vec![90.0], + BridgeDirection::Horizontal => vec![0.0], + BridgeDirection::Shortest => (0..180).step_by(SHORTEST_STEP_DEG).map(|d| d as f64).collect(), + }; + let budget = work / degrees.len().max(1); + let mut views = vec![]; + for deg in degrees { + views.push(View::new(contours, deg.to_radians(), spec.width, budget)?); + } + let mut picker = Picker::new(contours, &views, spec.width); + picker.connect(); + if views.iter().any(View::exhausted) && picker.unjoined() > 0 { + return Err(PathOpsError::TooComplex); + } + picker.spread(spec.count); + let unjoined = picker.unjoined(); + Ok((picker.chosen, unjoined)) +} + +/// One closed outline of the art, followed in straight segments. +struct Contour { + points: Vec, + /// Whether it bounds an island (it lies inside an odd number of the others). + hole: bool, + /// Its area, without sign. + area: f64, + /// Its box: (min x, min y, max x, max y). + bounds: (f64, f64, f64, f64), +} + +/// The outlines of `region` (an area with no overlaps) followed within a tolerance set by the +/// bridge width: a twentieth of it, from 0.002 to 0.25 pt, raised for a curve that would need more +/// than [`vectorcraft_geom::MAX_FLATTEN_PER_CURVE`] segments. Art reaching past +/// [`MAX_STENCIL_EXTENT`] is refused. +fn contours(region: &PathData, width: f64) -> Result, PathOpsError> { + if !within_extent(®ion.to_bezpath()) { + return Err(PathOpsError::TooComplex); + } + let tolerance = (width / 20.0).clamp(0.002, 0.25); + let mut out: Vec = vec![]; + let mut segments = 0usize; + for sp in ®ion.subpaths { + let room = MAX_STENCIL_SEGMENTS.saturating_sub(segments); + let mut bp = BezPath::new(); + sp.to_bezpath_into(&mut bp); + let mut points = follow(&bp, tolerance, room)?; + while points.len() > 1 && points.first() == points.last() { + points.pop(); + } + if points.len() < 3 { + continue; + } + segments += points.len(); + if segments > MAX_STENCIL_SEGMENTS || out.len() >= MAX_STENCIL_CONTOURS { + return Err(PathOpsError::TooComplex); + } + if points.iter().any(|p| !(p.x.is_finite() && p.y.is_finite())) { + return Err(PathOpsError::NonFinite); + } + let area = signed_area(&points).abs(); + let bounds = points.iter().fold((f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY), |b, p| { + (b.0.min(p.x), b.1.min(p.y), b.2.max(p.x), b.3.max(p.y)) + }); + out.push(Contour { points, hole: false, area, bounds }); + } + // An outline too small to see is dropped, so its inside counts as art (or, for a speck of art, + // as the area around it). + let tiny = (tolerance * tolerance).max(1e-9); + out.retain(|c| c.area > tiny); + // An outline inside an odd number of others bounds an island. Each outline is placed by the + // middle of its longest edge: outlines of an area with no overlaps meet at most at corners, so + // that point lies on no other outline. + let mut work = 0usize; + let mut depths = Vec::with_capacity(out.len()); + for (i, c) in out.iter().enumerate() { + let p = longest_edge_middle(&c.points); + let mut depth = 0usize; + for (j, o) in out.iter().enumerate() { + if j == i || o.area < c.area || !holds_box(o.bounds, c.bounds) { + continue; + } + work += o.points.len(); + if work > MAX_NESTING_WORK { + return Err(PathOpsError::TooComplex); + } + if contains(o, p) { + depth += 1; + } + } + depths.push(depth); + } + for (c, depth) in out.iter_mut().zip(depths) { + c.hole = depth % 2 == 1; + } + Ok(out) +} + +/// The middle of the longest edge of the closed outline through `points`. +fn longest_edge_middle(points: &[Point]) -> Point { + let n = points.len(); + (0..n) + .map(|i| (points[i], points[(i + 1) % n])) + .max_by(|(a, b), (c, d)| a.distance(*b).total_cmp(&c.distance(*d))) + .map_or(Point::ZERO, |(a, b)| a.midpoint(b)) +} + +/// Whether box `outer` holds box `inner`, edges included. Boxes are (min x, min y, max x, max y). +fn holds_box(outer: (f64, f64, f64, f64), inner: (f64, f64, f64, f64)) -> bool { + outer.0 <= inner.0 && outer.1 <= inner.1 && outer.2 >= inner.2 && outer.3 >= inner.3 +} + +/// Whether `bp` and its handles stay within [`MAX_STENCIL_EXTENT`] of the origin. +fn within_extent(bp: &BezPath) -> bool { + let reach = bp.control_box(); + [reach.x0, reach.y0, reach.x1, reach.y1].iter().all(|v| v.abs() <= MAX_STENCIL_EXTENT) +} + +/// The points that follow outline `bp` within `tolerance`, segment by segment, or +/// [`PathOpsError::TooComplex`] once they pass `room` (and one more for a closed outline's +/// repeated start, which the caller drops). It stops at the first segment past the limit. +fn follow(bp: &BezPath, tolerance: f64, room: usize) -> Result, PathOpsError> { + let limit = room.saturating_add(1); + let mut points: Vec = vec![]; + for seg in bp.segments() { + if points.is_empty() { + points.push(seg.start()); + } + let mut over = false; + vectorcraft_geom::flatten([PathEl::MoveTo(seg.start()), seg.as_path_el()], tolerance, |el| match el { + PathEl::LineTo(p) if points.len() < limit => points.push(p), + PathEl::LineTo(_) => over = true, + _ => {} + }); + if over { + return Err(PathOpsError::TooComplex); + } + } + Ok(points) +} + +fn signed_area(points: &[Point]) -> f64 { + let n = points.len(); + (0..n).map(|i| points[i].to_vec2().cross(points[(i + 1) % n].to_vec2())).sum::() / 2.0 +} + +/// Whether `p` is inside contour `c` (even-odd). +fn contains(c: &Contour, p: Point) -> bool { + let (x0, y0, x1, y1) = c.bounds; + if p.x < x0 || p.x > x1 || p.y < y0 || p.y > y1 { + return false; + } + let n = c.points.len(); + let mut inside = false; + for i in 0..n { + let (a, b) = (c.points[i], c.points[(i + 1) % n]); + if (a.y <= p.y) != (b.y <= p.y) && p.x < a.x + (p.y - a.y) * (b.x - a.x) / (b.y - a.y) { + inside = !inside; + } + } + inside +} + +/// The area outside the art that a point is in: 0 for the sheet around the art, `i + 1` for the +/// island contour `i` bounds. +type Area = usize; +const SHEET: Area = 0; + +/// The art seen along lines in one direction: rotated so the lines run along x, with its segments +/// listed by the bands of y they reach. +struct View { + angle: f64, + /// Rotated segments, each with the contour it belongs to. + segments: Vec<(Point, Point, usize)>, + /// The lowest y of the rotated art. + y0: f64, + /// The band height, and the lines' spacing. + step: f64, + bands: Vec>, + /// Each contour's lowest and highest rotated y. + ranges: Vec<(f64, f64)>, + /// The segments lines may still look at; past it, every line is missing. + budget: Cell, +} + +/// Where a line crosses the art: the edges in order (even-odd pairs are the art), and the area +/// each stretch outside the art is in (one more than there are pairs). +struct Line { + xs: Vec, + areas: Vec, +} + +impl View { + fn new(contours: &[Contour], angle: f64, width: f64, budget: usize) -> Result { + let (sin, cos) = angle.sin_cos(); + let rotate = |p: Point| Point::new(p.x * cos + p.y * sin, -p.x * sin + p.y * cos); + let mut segments = vec![]; + let mut ranges = vec![]; + let (mut y0, mut y1) = (f64::INFINITY, f64::NEG_INFINITY); + for (k, c) in contours.iter().enumerate() { + let pts: Vec = c.points.iter().map(|p| rotate(*p)).collect(); + let (lo, hi) = pts.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), p| (lo.min(p.y), hi.max(p.y))); + ranges.push((lo, hi)); + y0 = y0.min(lo); + y1 = y1.max(hi); + for i in 0..pts.len() { + segments.push((pts[i], pts[(i + 1) % pts.len()], k)); + } + } + let span = (y1 - y0).max(width); + let step = (width / 2.0).max(span / MAX_LINES); + let count = (span / step).ceil() as usize + 1; + let mut bands: Vec> = vec![vec![]; count]; + let band = |y: f64| (((y - y0) / step).floor().max(0.0) as usize).min(count - 1); + let mut entries = 0usize; + for (i, (a, b, _)) in segments.iter().enumerate() { + let (from, to) = (band(a.y.min(b.y)), band(a.y.max(b.y))); + entries += to - from + 1; + if entries > MAX_BIN_ENTRIES { + return Err(PathOpsError::TooComplex); + } + for list in &mut bands[from..=to] { + list.push(i as u32); + } + } + Ok(View { angle, segments, y0, step, bands, ranges, budget: Cell::new(budget) }) + } + + /// Whether lines looked at more segments than the budget allows. + fn exhausted(&self) -> bool { + self.budget.get() == 0 + } + + /// The art along the line at rotated y `y`, `None` where its edges don't pair up or the budget + /// is spent. + fn line(&self, y: f64, contours: &[Contour]) -> Option { + let band = ((y - self.y0) / self.step).floor(); + let list = self.bands.get(if band < 0.0 { usize::MAX } else { band as usize })?; + let left = self.budget.get().checked_sub(list.len()).filter(|left| *left > 0); + self.budget.set(left.unwrap_or(0)); + left?; + let mut hits: Vec<(f64, usize)> = vec![]; + for &i in list { + let (a, b, k) = self.segments[i as usize]; + if (a.y <= y) != (b.y <= y) { + hits.push((a.x + (y - a.y) * (b.x - a.x) / (b.y - a.y), k)); + } + } + if hits.len() % 2 == 1 { + return None; + } + hits.sort_by(|p, q| p.0.total_cmp(&q.0)); + // Walking along the line, each contour crossed an odd number of times so far holds the + // point; the smallest island contour holding a stretch outside the art is its island. + let mut open: Vec = vec![]; + let mut areas = vec![SHEET]; + for (n, (_, k)) in hits.iter().enumerate() { + match open.iter().position(|o| o == k) { + Some(at) => { + open.swap_remove(at); + } + None => open.push(*k), + } + if n % 2 == 1 { + let island = open.iter().filter(|o| contours[**o].hole).min_by(|a, b| contours[**a].area.total_cmp(&contours[**b].area)); + areas.push(island.map_or(SHEET, |k| k + 1)); + } + } + Some(Line { xs: hits.into_iter().map(|(x, _)| x).collect(), areas }) + } + + /// The point at rotated `(x, y)` in the art's own coordinates. + fn unrotate(&self, x: f64, y: f64) -> Point { + let (sin, cos) = self.angle.sin_cos(); + Point::new(x * cos - y * sin, x * sin + y * cos) + } +} + +/// A crossing of the art along one line, between the areas on either side of it. +#[derive(Clone, Copy, Debug)] +struct Crossing { + view: usize, + y: f64, + /// Where it enters and leaves the art. + from: f64, + to: f64, + areas: (Area, Area), + /// How far its line is from the middle of the island it starts from. + off_middle: f64, +} + +impl Crossing { + fn len(&self) -> f64 { + self.to - self.from + } +} + +/// A bridge that fits: its crossing, its middle and its strip's corners. +struct Bridge { + areas: (Area, Area), + middle: Point, + strip: Vec, +} + +struct Picker<'a> { + contours: &'a [Contour], + views: &'a [View], + width: f64, + crossings: Vec, + /// The crossings that touch each area. + touching: Vec>, + parent: Vec, + chosen: Vec, +} + +impl<'a> Picker<'a> { + fn new(contours: &'a [Contour], views: &'a [View], width: f64) -> Self { + let areas = contours.len() + 1; + let holes = contours.iter().filter(|c| c.hole).count().max(1); + // Each island is looked across along lines through its middle and out from it on both + // sides, half a width apart, or fewer where there are many islands. + let each_side = (MAX_ISLAND_LINES / (holes * views.len()).max(1)).clamp(1, MAX_LINES_PER_SIDE) as f64; + let mut crossings = vec![]; + for (v, view) in views.iter().enumerate() { + for (k, _) in contours.iter().enumerate().filter(|(_, c)| c.hole) { + let island = k + 1; + let (lo, hi) = view.ranges[k]; + let (middle, reach) = ((lo + hi) / 2.0, (hi - lo) / 2.0); + let step = (width / 2.0).max(reach / each_side); + let mut ys = vec![middle]; + let mut d = step; + while d < reach { + ys.extend([middle - d, middle + d]); + d += step; + } + for y in ys { + let Some(line) = view.line(y, contours) else { continue }; + for (j, pair) in line.xs.as_chunks::<2>().0.iter().enumerate() { + let (a, b) = (line.areas[j], line.areas[j + 1]); + if a == b || (a != island && b != island) { + continue; + } + crossings.push(Crossing { view: v, y, from: pair[0], to: pair[1], areas: (a, b), off_middle: (y - middle).abs() }); + } + } + } + } + // Shortest first; among crossings of about the same length, the one nearest the middle of + // its island. + let grain = width * 0.05; + crossings.sort_by(|p, q| (p.len() / grain).round().total_cmp(&(q.len() / grain).round()).then(p.off_middle.total_cmp(&q.off_middle))); + let mut touching = vec![vec![]; areas]; + for (i, c) in crossings.iter().enumerate() { + touching[c.areas.0].push(i); + touching[c.areas.1].push(i); + } + Picker { contours, views, width, crossings, touching, parent: (0..areas).collect(), chosen: vec![] } + } + + fn root(&mut self, mut a: usize) -> usize { + while self.parent[a] != a { + self.parent[a] = self.parent[self.parent[a]]; + a = self.parent[a]; + } + a + } + + /// Join every island to the sheet by the shortest crossings that fit, as a spanning tree. Bridges + /// that only join islands that stay apart from the sheet are not cut. + fn connect(&mut self) { + let mut apart = self.contours.iter().filter(|c| c.hole).count(); + for i in 0..self.crossings.len() { + if apart == 0 { + break; + } + let c = self.crossings[i]; + let (a, b) = (self.root(c.areas.0), self.root(c.areas.1)); + if a == b { + continue; + } + if let Some(bridge) = self.fit(&c) { + self.parent[a] = b; + self.chosen.push(bridge); + apart -= 1; + } + } + let sheet = self.root(SHEET); + for bridge in std::mem::take(&mut self.chosen) { + if self.root(bridge.areas.0) == sheet { + self.chosen.push(bridge); + } + } + } + + /// Give each island more bridges, up to `count`, each far from the island's others (at least + /// two widths away, and as short as can be among those at least 80% as far as the farthest), + /// and no more than twice as long as its shortest crossing that a bridge fits plus a width. + /// A crossing a bridge does not fit is not tried again, and once the lines' budget is spent no + /// more bridges are found. + fn spread(&mut self, count: usize) { + let sheet = self.root(SHEET); + let mut misfit = vec![false; self.crossings.len()]; + for island in 1..self.touching.len() { + if !self.contours[island - 1].hole || self.root(island) != sheet { + continue; + } + let mut limit = None; + loop { + let mine: Vec = self.chosen.iter().filter(|b| b.areas.0 == island || b.areas.1 == island).map(|b| b.middle).collect(); + if mine.len() >= count { + break; + } + let longest = match limit { + Some(l) => l, + None => { + // The island's crossings are listed shortest first, so the first that fits + // is its shortest bridge. + let mut shortest = None; + for &i in &self.touching[island] { + if misfit[i] { + continue; + } + if self.fit(&self.crossings[i]).is_some() { + shortest = Some(self.crossings[i].len()); + break; + } + misfit[i] = true; + } + let Some(shortest) = shortest else { break }; + *limit.insert(shortest * 2.0 + self.width) + } + }; + let mut ranked: Vec<(f64, usize)> = self.touching[island] + .iter() + .filter(|&&i| !misfit[i] && self.crossings[i].len() <= longest) + .map(|&i| { + let m = self.middle(&self.crossings[i]); + (mine.iter().map(|p| p.distance(m)).fold(f64::INFINITY, f64::min), i) + }) + .filter(|(d, _)| *d >= self.width * 2.0) + .collect(); + // The crossings nearly as far as the farthest go first, in the order `connect` + // takes them (shortest, then nearest the middle); then the rest, farthest first. + let far = ranked.iter().map(|r| r.0).fold(0.0, f64::max) * 0.8; + ranked.sort_by(|p, q| (q.0 >= far).cmp(&(p.0 >= far)).then_with(|| if p.0 >= far { p.1.cmp(&q.1) } else { q.0.total_cmp(&p.0) })); + let mut found = None; + for &(_, i) in &ranked { + match self.fit(&self.crossings[i]) { + Some(bridge) => { + found = Some(bridge); + break; + } + None => misfit[i] = true, + } + } + match found { + Some(bridge) => self.chosen.push(bridge), + None => break, + } + if self.views.iter().any(View::exhausted) { + return; + } + } + } + } + + /// The islands not joined to the sheet. + fn unjoined(&mut self) -> usize { + let sheet = self.root(SHEET); + (1..self.parent.len()).filter(|&a| self.contours[a - 1].hole).filter(|&a| self.root(a) != sheet).count() + } + + fn middle(&self, c: &Crossing) -> Point { + self.views[c.view].unrotate((c.from + c.to) / 2.0, c.y) + } + + /// The bridge of crossing `c`, if a strip of the width fits there: along lines across its + /// width, the art is crossed once between the same two areas, and the strip ends outside the + /// art on each of them. + fn fit(&self, c: &Crossing) -> Option { + let view = &self.views[c.view]; + let half = self.width / 2.0; + let (mut start, mut end) = (f64::INFINITY, f64::NEG_INFINITY); + let (mut room_before, mut room_after) = (f64::NEG_INFINITY, f64::INFINITY); + for k in 0..CHECKS { + let y = c.y - half + self.width * k as f64 / (CHECKS - 1) as f64; + let line = view.line(y, self.contours)?; + let last = line.areas.len() - 1; + // The crossing between the same two areas that overlaps this one, the nearest if several do. + let (j, _) = line + .xs + .as_chunks::<2>() + .0 + .iter() + .enumerate() + .filter(|(j, p)| (line.areas[*j], line.areas[j + 1]) == c.areas && p[1] > c.from - self.width && p[0] < c.to + self.width) + .min_by(|(_, p), (_, q)| (p[0] - c.from).abs().total_cmp(&(q[0] - c.from).abs()))?; + start = start.min(line.xs[2 * j]); + end = end.max(line.xs[2 * j + 1]); + if j > 0 { + room_before = room_before.max(line.xs[2 * j - 1]); + } + if j + 1 < last { + room_after = room_after.min(line.xs[2 * j + 2]); + } + } + if room_before >= start || room_after <= end { + return None; + } + // The strip reaches a little past the art at each end, so no sliver of it is left. + let reach = self.width.min(1.0); + let s0 = (start - reach).max((room_before + start) / 2.0); + let s1 = (end + reach).min((room_after + end) / 2.0); + let strip = [(s0, c.y - half), (s1, c.y - half), (s1, c.y + half), (s0, c.y + half)].map(|(x, y)| view.unrotate(x, y)).to_vec(); + Some(Bridge { areas: c.areas, middle: self.middle(c), strip }) + } +} diff --git a/crates/pathops/src/addons/stencil/tests.rs b/crates/pathops/src/addons/stencil/tests.rs new file mode 100644 index 0000000000..93ea92cdde --- /dev/null +++ b/crates/pathops/src/addons/stencil/tests.rs @@ -0,0 +1,357 @@ +use kurbo::{BezPath, Point, Shape}; +use vectorcraft_geom::{FillRule, PathData, SubPath}; + +use super::*; + +fn rect(x0: f64, y0: f64, x1: f64, y1: f64) -> SubPath { + SubPath::polyline(&[Point::new(x0, y0), Point::new(x1, y0), Point::new(x1, y1), Point::new(x0, y1)], true) +} + +/// A square ring: `outer` with the hole `inner`, each (x0, y0, x1, y1). +fn ring(outer: (f64, f64, f64, f64), inner: (f64, f64, f64, f64)) -> PathData { + PathData::new(vec![rect(outer.0, outer.1, outer.2, outer.3), rect(inner.0, inner.1, inner.2, inner.3)]) +} + +fn spec(width: f64, count: usize, direction: BridgeDirection) -> BridgeSpec { + BridgeSpec { width, count, direction } +} + +fn run(art: &PathData, spec: BridgeSpec) -> Bridged { + stencil_bridges(&[(art, FillRule::EvenOdd)], spec).unwrap() +} + +/// Is `(x, y)` inside the area `p` draws? +fn inside(p: &PathData, x: f64, y: f64) -> bool { + p.to_bezpath().winding(Point::new(x, y)) != 0 +} + +/// The islands left once the bridges are cut. +fn islands_left(b: &Bridged) -> usize { + run(&b.path, spec(1.0, 1, BridgeDirection::Shortest)).islands +} + +/// A letter O made square: 100 pt across with bars 20 pt thick. +fn letter_o() -> PathData { + ring((0.0, 0.0, 100.0, 100.0), (20.0, 20.0, 80.0, 80.0)) +} + +#[test] +fn an_o_gets_a_bridge_and_its_island_joins_the_sheet() { + let b = run(&letter_o(), spec(4.0, 1, BridgeDirection::Vertical)); + assert_eq!((b.islands, b.bridges, b.unbridged), (1, 1, 0)); + assert_eq!(islands_left(&b), 0, "the inside of the O is joined to the sheet"); + // The bridge crosses the top bar at the middle of the hole; the rest of the O stays. + assert!(!inside(&b.path, 50.0, 10.0)); + assert!(inside(&b.path, 30.0, 10.0) && inside(&b.path, 50.0, 90.0) && inside(&b.path, 10.0, 50.0)); +} + +#[test] +fn the_bridge_is_as_wide_as_asked() { + for width in [2.0, 6.0] { + let b = run(&letter_o(), spec(width, 1, BridgeDirection::Vertical)); + let half = width / 2.0; + assert!(!inside(&b.path, 50.0 - half * 0.9, 10.0) && !inside(&b.path, 50.0 + half * 0.9, 10.0), "{width}"); + assert!(inside(&b.path, 50.0 - half * 1.2, 10.0) && inside(&b.path, 50.0 + half * 1.2, 10.0), "{width}"); + } +} + +#[test] +fn horizontal_bridges_cross_the_sides() { + let b = run(&letter_o(), spec(4.0, 1, BridgeDirection::Horizontal)); + assert_eq!((b.bridges, islands_left(&b)), (1, 0)); + assert!(!inside(&b.path, 10.0, 50.0) || !inside(&b.path, 90.0, 50.0)); + assert!(inside(&b.path, 50.0, 10.0) && inside(&b.path, 50.0, 90.0)); +} + +#[test] +fn the_shortest_crossing_takes_the_thinnest_bar() { + // The left bar is 5 pt thick, the others 20. + let art = ring((0.0, 0.0, 100.0, 100.0), (5.0, 20.0, 80.0, 80.0)); + let b = run(&art, spec(4.0, 1, BridgeDirection::Shortest)); + assert_eq!((b.bridges, islands_left(&b)), (1, 0)); + assert!(!inside(&b.path, 2.5, 50.0), "the bridge crosses the thin bar"); + assert!(inside(&b.path, 50.0, 10.0) && inside(&b.path, 90.0, 50.0)); + // Vertical bridges cross a 20 pt bar instead. + let v = run(&art, spec(4.0, 1, BridgeDirection::Vertical)); + assert!(inside(&v.path, 2.5, 50.0) && !inside(&v.path, 42.5, 10.0)); +} + +#[test] +fn a_shape_with_two_holes_gets_a_bridge_for_each() { + let art = PathData::new(vec![rect(0.0, 0.0, 100.0, 50.0), rect(10.0, 10.0, 40.0, 40.0), rect(60.0, 10.0, 90.0, 40.0)]); + let b = run(&art, spec(3.0, 1, BridgeDirection::Vertical)); + assert_eq!((b.islands, b.bridges, b.unbridged), (2, 2, 0)); + assert_eq!(islands_left(&b), 0); + assert!(!inside(&b.path, 25.0, 5.0) && !inside(&b.path, 75.0, 5.0)); +} + +#[test] +fn more_bridges_per_island_spread_around_it() { + let b = run(&letter_o(), spec(4.0, 2, BridgeDirection::Vertical)); + assert_eq!(b.bridges, 2); + assert!(!inside(&b.path, 50.0, 10.0) && !inside(&b.path, 50.0, 90.0), "one at the top, one at the bottom"); +} + +#[test] +fn a_short_crossing_too_narrow_for_a_bridge_does_not_limit_the_others() { + // Hole A has a 2 pt slot B just above it: the 5 pt crossing from A to B is the shortest, but + // no 4 pt bridge fits there. A's 20 pt crossings to the sheet take its two bridges. + let art = PathData::new(vec![rect(0.0, 0.0, 200.0, 100.0), rect(20.0, 20.0, 80.0, 80.0), rect(49.0, 5.0, 51.0, 15.0)]); + let b = run(&art, spec(4.0, 2, BridgeDirection::Vertical)); + assert_eq!((b.islands, b.bridges, b.unbridged), (2, 2, 1)); +} + +#[test] +fn islands_that_only_reach_each_other_get_no_bridge() { + // Holes Y and X, one above the other, with combs of 2 pt slots above Y and below X: no 4 pt + // vertical bridge reaches the sheet from either, so the bridge that fits between them would + // join nothing to the sheet. + let mut subpaths = vec![rect(0.0, 0.0, 100.0, 100.0), rect(20.0, 20.0, 80.0, 30.0), rect(30.0, 40.0, 70.0, 60.0)]; + for k in 0..27 { + let x = 10.0 + 3.0 * k as f64; + subpaths.push(rect(x, 5.0, x + 2.0, 15.0)); + subpaths.push(rect(x, 85.0, x + 2.0, 95.0)); + } + let b = run(&PathData::new(subpaths), spec(4.0, 1, BridgeDirection::Vertical)); + assert_eq!((b.islands, b.bridges, b.unbridged), (56, 0, 56)); +} + +#[test] +fn an_island_inside_an_island_is_joined_through_it() { + // A ring in the hole of a ring: two islands, the gap between the rings and the inner hole. + let art = + PathData::new(vec![rect(0.0, 0.0, 100.0, 100.0), rect(10.0, 10.0, 90.0, 90.0), rect(30.0, 30.0, 70.0, 70.0), rect(40.0, 40.0, 60.0, 60.0)]); + let b = run(&art, spec(2.0, 1, BridgeDirection::Vertical)); + assert_eq!((b.islands, b.bridges, b.unbridged), (2, 2, 0)); + assert_eq!(islands_left(&b), 0); +} + +#[test] +fn an_island_too_narrow_for_the_width_is_counted() { + let art = ring((0.0, 0.0, 100.0, 100.0), (49.0, 20.0, 51.0, 80.0)); + let b = run(&art, spec(4.0, 1, BridgeDirection::Vertical)); + assert_eq!((b.islands, b.bridges, b.unbridged), (1, 0, 1)); + assert_eq!(islands_left(&b), 1); +} + +#[test] +fn art_without_islands_is_left_whole() { + let art = PathData::new(vec![rect(0.0, 0.0, 50.0, 50.0), rect(100.0, 0.0, 150.0, 50.0)]); + let b = run(&art, spec(4.0, 1, BridgeDirection::Shortest)); + assert_eq!((b.islands, b.bridges, b.unbridged), (0, 0, 0)); + assert!(inside(&b.path, 25.0, 25.0) && inside(&b.path, 125.0, 25.0)); +} + +#[test] +fn the_shortest_crossing_may_run_at_an_angle() { + // A diamond ring: its walls are 20 pt across horizontally and vertically but about 14 pt + // across at 45°, so only a diagonal line finds the shortest crossing. + let diamond = |r: f64| { + let pts = [(100.0, 100.0 - r), (100.0 + r, 100.0), (100.0, 100.0 + r), (100.0 - r, 100.0)].map(|(x, y)| Point::new(x, y)); + SubPath::polyline(&pts, true) + }; + let art = PathData::new(vec![diamond(60.0), diamond(40.0)]); + let b = run(&art, spec(2.0, 1, BridgeDirection::Shortest)); + assert_eq!((b.bridges, islands_left(&b)), (1, 0)); + // The middles of the four diagonal walls: one is cut. The middles of the walls straight + // above, below and beside the hole all stay. + let diagonal = [(125.0, 125.0), (75.0, 75.0), (125.0, 75.0), (75.0, 125.0)]; + assert!(diagonal.iter().any(|&(x, y)| !inside(&b.path, x, y)), "a diagonal bridge"); + for (x, y) in [(150.0, 100.0), (50.0, 100.0), (100.0, 150.0), (100.0, 50.0)] { + assert!(inside(&b.path, x, y), "({x}, {y}) stays"); + } + let h = run(&art, spec(2.0, 1, BridgeDirection::Horizontal)); + assert!(diagonal.iter().all(|&(x, y)| inside(&h.path, x, y))); +} + +#[test] +fn a_hole_touching_another_outline_at_a_corner_is_still_an_island() { + // A diamond hole whose bottom corner, where its outline starts, touches the bottom edge of the + // square around it. + let hole = SubPath::polyline(&[(50.0, 100.0), (70.0, 70.0), (50.0, 40.0), (30.0, 70.0)].map(|(x, y)| Point::new(x, y)), true); + let region = PathData::new(vec![rect(0.0, 0.0, 100.0, 100.0), hole]); + let found = contours(®ion, 1.0).unwrap(); + assert_eq!(found.iter().filter(|c| c.hole).count(), 1); +} + +#[test] +fn a_sliver_too_small_to_see_counts_as_art() { + // A hole 10 pt long and 0.005 pt high between the island and the top edge: a bridge that + // reaches only the sliver would join nothing to the sheet. + let region = PathData::new(vec![rect(0.0, 0.0, 100.0, 100.0), rect(40.0, 40.0, 60.0, 60.0), rect(45.0, 20.0, 55.0, 20.005)]); + let b = bridge_region(region, spec(5.0, 1, BridgeDirection::Vertical)).unwrap(); + assert_eq!((b.islands, b.bridges, b.unbridged), (1, 1, 0)); + assert_eq!(islands_left(&b), 0); +} + +#[test] +fn extra_bridges_stay_two_widths_apart() { + // Sixteen 10 pt bridges have no room around a hole 60 pt across with 20 pt between them. + let width = 10.0; + let found = contours(&letter_o(), width).unwrap(); + let (bridges, unjoined) = choose(&found, spec(width, 16, BridgeDirection::Shortest), MAX_WORK).unwrap(); + assert!(bridges.len() > 4 && bridges.len() < 16, "{}", bridges.len()); + assert_eq!(unjoined, 0); + for (i, a) in bridges.iter().enumerate() { + for b in &bridges[i + 1..] { + assert!(a.middle.distance(b.middle) >= width * 2.0, "{:?} {:?}", a.middle, b.middle); + } + } +} + +#[test] +fn bridges_found_before_the_budget_runs_out_are_kept() { + let found = contours(&letter_o(), 4.0).unwrap(); + // The least work that joins the island with one bridge also gives one with up to 16 asked + // for: the extra bridges stop where the budget ends. + let least = (1..100_000).find(|&work| choose(&found, spec(4.0, 1, BridgeDirection::Vertical), work).is_ok()).unwrap(); + let (bridges, unjoined) = choose(&found, spec(4.0, 16, BridgeDirection::Vertical), least).unwrap(); + assert_eq!((bridges.len(), unjoined), (1, 0)); + assert!(matches!(choose(&found, spec(4.0, 1, BridgeDirection::Vertical), least - 1), Err(PathOpsError::TooComplex))); +} + +#[test] +fn joined_art_is_kept_when_lines_in_one_direction_run_out() { + // A ring whose thin left bar has edges of many short zigzag segments: lines across it in the + // horizontal direction look at many more segments than vertical lines across the top bar. + let zigzag = |x: f64, from: f64, to: f64, out: &mut Vec| { + let n = ((to - from).abs() / 0.05) as usize; + out.extend((1..n).map(|i| Point::new(x + if i % 2 == 1 { 0.02 } else { 0.0 }, from + (to - from) * i as f64 / n as f64))); + }; + let mut outer = vec![Point::new(0.0, 0.0), Point::new(200.0, 0.0), Point::new(200.0, 100.0), Point::new(0.0, 100.0)]; + zigzag(0.0, 100.0, 0.0, &mut outer); + let mut hole = vec![Point::new(10.0, 20.0), Point::new(170.0, 20.0), Point::new(170.0, 80.0), Point::new(10.0, 80.0)]; + zigzag(9.98, 80.0, 20.0, &mut hole); + let art = PathData::new(vec![SubPath::polyline(&outer, true), SubPath::polyline(&hole, true)]); + let found = contours(&art, 4.0).unwrap(); + let shortest = spec(4.0, 1, BridgeDirection::Shortest); + let views = (0..180).step_by(SHORTEST_STEP_DEG).count(); + // A share of the work that runs out in the horizontal direction while another direction joins + // the island. + let share = (1..5000) + .find(|&budget| { + let all: Vec = + (0..180).step_by(SHORTEST_STEP_DEG).map(|d| View::new(&found, (d as f64).to_radians(), 4.0, budget).unwrap()).collect(); + let mut picker = Picker::new(&found, &all, 4.0); + picker.connect(); + all.iter().any(View::exhausted) && picker.unjoined() == 0 + }) + .expect("a share of the work that runs out with the island joined"); + let (bridges, unjoined) = choose(&found, shortest, share * views).unwrap(); + assert_eq!((bridges.len(), unjoined), (1, 0)); +} + +#[test] +fn curves_are_followed_within_a_twentieth_of_the_width() { + let circle = PathData::from_bezpath(&kurbo::Circle::new((0.0, 0.0), 100.0).to_path(0.001)); + let mut counts = vec![]; + for (width, tolerance) in [(0.01, 0.002), (1.0, 0.05), (20.0, 0.25)] { + let found = contours(&circle, width).unwrap(); + let points = &found[0].points; + // The sag of each chord below the circle. + let sag = (0..points.len()).map(|i| 100.0 - points[i].midpoint(points[(i + 1) % points.len()]).to_vec2().hypot()).fold(0.0, f64::max); + assert!(sag <= tolerance + 0.002, "{width}: {sag}"); + counts.push(points.len()); + } + assert!(counts[0] > counts[1] && counts[1] > counts[2], "{counts:?}"); +} + +#[test] +fn open_outlines_are_closed_as_a_fill_closes_them() { + let mut art = letter_o(); + art.subpaths[0].closed = false; + let b = run(&art, spec(4.0, 1, BridgeDirection::Vertical)); + assert_eq!((b.islands, b.bridges, b.unbridged), (1, 1, 0)); +} + +#[test] +fn art_too_large_is_refused_before_it_is_combined() { + let far = PathData::new(vec![rect(0.0, 0.0, 1e8, 1e8)]); + let points: Vec = (0..=MAX_STENCIL_SEGMENTS).map(|i| Point::new(i as f64 * 0.01, (i % 2) as f64)).collect(); + let dense = PathData::new(vec![SubPath::polyline(&points, true)]); + assert!(too_large(&[(&far, FillRule::EvenOdd)]) && too_large(&[(&dense, FillRule::EvenOdd)])); + assert!(!too_large(&[(&letter_o(), FillRule::EvenOdd), (&letter_o(), FillRule::NonZero)])); +} + +#[test] +fn outlines_nested_too_deep_to_place_are_refused() { + // Rings of 190-sided polygons, one inside the next: placing each inside the others takes + // about 95 million tests of a point against an edge with 1000 of them, and 8 million with 300. + let polygon = |r: f64| { + let pts: Vec = (0..190).map(|i| (i as f64 / 190.0 * std::f64::consts::TAU).sin_cos()).map(|(s, c)| Point::new(c * r, s * r)).collect(); + SubPath::polyline(&pts, true) + }; + let nested = |n: usize| PathData::new((0..n).map(|i| polygon(10.0 + i as f64)).collect()); + assert!(contours(&nested(300), 1.0).is_ok()); + assert!(matches!(contours(&nested(1000), 1.0), Err(PathOpsError::TooComplex))); +} + +#[test] +fn a_curved_o_is_bridged_at_its_thinnest() { + // Two circles, the hole 8 pt above the middle: the O is 2 pt thick at the top and 18 pt at + // the bottom. + let circle = |cy: f64, r: f64| PathData::from_bezpath(&kurbo::Circle::new((100.0, cy), r).to_path(0.01)); + let mut art = circle(100.0, 60.0); + art.subpaths.extend(circle(92.0, 50.0).subpaths); + let b = run(&art, spec(1.0, 1, BridgeDirection::Vertical)); + assert_eq!((b.islands, b.bridges, islands_left(&b)), (1, 1, 0)); + assert!(!inside(&b.path, 100.0, 41.0), "it crosses the thin top"); + assert!(inside(&b.path, 100.0, 151.0), "the thick bottom stays"); +} + +#[test] +fn art_with_too_many_outlines_is_refused() { + let squares = (0..MAX_STENCIL_CONTOURS + 1) + .map(|i| { + let (x, y) = ((i % 100) as f64 * 3.0, (i / 100) as f64 * 3.0); + rect(x, y, x + 1.0, y + 1.0) + }) + .collect(); + let region = PathData::new(squares); + assert!(matches!(contours(®ion, 1.0), Err(PathOpsError::TooComplex))); + let mut fewer = region.clone(); + fewer.subpaths.pop(); + assert_eq!(contours(&fewer, 1.0).unwrap().len(), MAX_STENCIL_CONTOURS); +} + +#[test] +fn art_as_large_as_a_document_holds_is_followed_and_larger_art_is_refused() { + // An O 8000000 pt across, the most a document holds, with a 60 pt hole near its edge, followed + // within 0.002 pt. + let circle = |c: (f64, f64), r: f64| PathData::from_bezpath(&kurbo::Circle::new(c, r).to_path(0.01)); + let mut art = circle((0.0, 0.0), 4e6); + art.subpaths.extend(circle((0.0, 0.0), 2e6).subpaths); + art.subpaths.extend(circle((4e6 - 100.0, 0.0), 30.0).subpaths); + let found = contours(&art, 0.01).unwrap(); + assert_eq!(found.iter().filter(|c| c.hole).count(), 2); + let far = PathData::new(vec![rect(0.0, 0.0, 1e8, 1e8)]); + assert!(matches!(contours(&far, 0.01), Err(PathOpsError::TooComplex))); + let r = stencil_bridges(&[(&far, FillRule::EvenOdd)], spec(4.0, 1, BridgeDirection::Vertical)); + assert!(matches!(r, Err(PathOpsError::TooComplex))); +} + +#[test] +fn art_with_too_many_anchors_is_refused() { + let points: Vec = (0..=MAX_STENCIL_SEGMENTS).map(|i| Point::new(i as f64 * 0.01, (i % 2) as f64)).collect(); + let art = PathData::new(vec![SubPath::polyline(&points, true)]); + let r = stencil_bridges(&[(&art, FillRule::EvenOdd)], spec(4.0, 1, BridgeDirection::Vertical)); + assert!(matches!(r, Err(PathOpsError::TooComplex))); +} + +#[test] +fn following_stops_past_the_limit_and_allows_the_closing_point() { + // A closed square: its four corners and the start again. + let square = rect(0.0, 0.0, 10.0, 10.0); + let mut bp = BezPath::new(); + square.to_bezpath_into(&mut bp); + assert_eq!(follow(&bp, 0.01, 4).unwrap().len(), 5); + assert!(matches!(follow(&bp, 0.01, 3), Err(PathOpsError::TooComplex))); +} + +#[test] +fn bad_widths_and_counts_are_refused() { + let art = letter_o(); + for s in [spec(0.0, 1, BridgeDirection::Vertical), spec(f64::NAN, 1, BridgeDirection::Vertical), spec(4.0, 0, BridgeDirection::Vertical)] { + assert!(stencil_bridges(&[(&art, FillRule::EvenOdd)], s).is_err(), "{s:?}"); + } +} diff --git a/crates/pathops/src/boolean.rs b/crates/pathops/src/boolean.rs index e12c9fb395..60c2a8b296 100644 --- a/crates/pathops/src/boolean.rs +++ b/crates/pathops/src/boolean.rs @@ -22,6 +22,8 @@ thread_local! { pub(crate) static CONTOUR_PASSES: std::cell::Cell = const { std::cell::Cell::new(0) }; /// The sweeps [`normalize_bez`] made on this thread. static NORMALIZE_SWEEPS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// The input curves [`exact_merge`] tested on this thread. + static EXACT_MERGE_CURVES: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Default curve-refit tolerance (document points) used to merge split curve pieces back together. @@ -663,16 +665,17 @@ fn try_merge(run: &[Seg], tidy: &Tidy) -> Option { } /// If every piece of `run` lies on one input cubic, return the exact sub-curve spanning the run. +/// Only the input curves whose bounds hold both ends of the run are tested +/// ([`Tidy::curves_around`]). fn exact_merge(run: &[Seg], tidy: &Tidy) -> Option { use kurbo::{ParamCurve, ParamCurveNearest}; let a = run[0].c.p0; let b = run[run.len() - 1].c.p3; let scale = 1.0 + a.x.abs().max(a.y.abs()).max(b.x.abs()).max(b.y.abs()); let tol = 1e-6 * scale; - for (r, c) in &tidy.curves { - if !r.contains(a) || !r.contains(b) { - continue; - } + for c in tidy.curves_around(a, b) { + #[cfg(test)] + EXACT_MERGE_CURVES.with(|n| n.set(n.get() + 1)); let na = c.nearest(a, 1e-12); let nb = c.nearest(b, 1e-12); if na.distance_sq.sqrt() > tol || nb.distance_sq.sqrt() > tol { @@ -1366,6 +1369,29 @@ mod tests { assert_eq!(tidy.repair(&lens), lens); } + #[test] + fn rejoining_a_split_curve_tests_only_the_curves_around_it() { + // A row of 1,000 short curves; one of them is cut in three, as the sweep cuts a curve. + let mut row = BezPath::new(); + row.move_to((0.0, 0.0)); + for k in 0..1000 { + let x = f64::from(k); + row.curve_to((x + 0.3, 1.0), (x + 0.7, 1.0), (x + 1.0, 0.0)); + } + let tidy = Tidy::keeping(DEFAULT_PRECISION, [&row]); + let c = CubicBez::new((500.0, 0.0), (500.3, 1.0), (500.7, 1.0), (501.0, 0.0)); + let pieces: Vec = [0.0..0.3, 0.3..0.6, 0.6..1.0].into_iter().map(|t| Seg { c: c.subsegment(t), line: false }).collect(); + EXACT_MERGE_CURVES.with(|n| n.set(0)); + let merged = tidy_segments(pieces, false, &tidy); + let tested = EXACT_MERGE_CURVES.with(std::cell::Cell::get); + assert_eq!(merged.len(), 1); + for (got, want) in [(merged[0].c.p1, c.p1), (merged[0].c.p2, c.p2)] { + assert!(got.distance(want) < 1e-9, "{got:?} {want:?}"); + } + // Each merge attempt tests the curves whose bounds hold both ends of the run, not all 1,000. + assert!(tested <= 4, "{tested} curves tested"); + } + #[test] fn arrangement_new_budgeted_fails_on_complexity_and_open_paths() { let mut bp = BezPath::new(); diff --git a/crates/pathops/src/edit.rs b/crates/pathops/src/edit.rs index a82503391c..960f4036d8 100644 --- a/crates/pathops/src/edit.rs +++ b/crates/pathops/src/edit.rs @@ -22,14 +22,23 @@ pub struct SimplifyOptions { /// How far (points, the spread of a Gaussian along the path) the path is smoothed before it is /// refitted, so that bumps and jags come out as one curve ([`smooth_level`]); 0 for none. pub smooth: f64, + /// With [`smooth`](Self::smooth), refit each stretch fitted as one piece (between corners) within + /// twice the farthest the smoothing moved any of its points when that is less than `tolerance`, and + /// never within less than a tenth of `tolerance`. A stretch that smoothing barely moves anywhere + /// keeps its shape. The limit is the same along the whole stretch, so where smoothing moves some of + /// its points far, all of it is refitted within up to `tolerance`, as without this option. + pub smooth_moved_only: bool, } impl Default for SimplifyOptions { fn default() -> Self { - Self { tolerance: 0.5, corner_angle_deg: 30.0, straight_lines: false, smooth: 0.0 } + Self { tolerance: 0.5, corner_angle_deg: 30.0, straight_lines: false, smooth: 0.0, smooth_moved_only: false } } } +/// The least share of the tolerance that [`SimplifyOptions::smooth_moved_only`] refits within. +const SMOOTH_MOVED_FLOOR: f64 = 0.1; + /// Simplify with the default corner threshold (30°). pub fn simplify(path: &PathData, tolerance: f64) -> PathData { simplify_with(path, &SimplifyOptions { tolerance, ..Default::default() }) @@ -88,7 +97,10 @@ pub fn simplify_with(path: &PathData, opts: &SimplifyOptions) -> PathData { /// whose refit is one segment, or lines that enclose no area, is refitted in two parts, cut at the /// point farthest from its start, or in three when two still give that. When three parts still give /// no area, straight lines follow the subpath within the tolerance, and without straight lines it -/// stays as it is, as does one of a single segment; one that is all in line keeps the refit. +/// stays as it is, as does one of a single segment. When no lines within the limits on pieces enclose +/// an area, it stays as it is, or with straight lines follows the lines between samples of each +/// curved segment when the limits leave room for lines within the tolerance; one that is all in line +/// keeps the refit. fn simplify_subpath(sp: &SubPath, opts: &SimplifyOptions) -> Option { let mut segs = subpath_segs(sp); let n = segs.len(); @@ -139,33 +151,82 @@ fn simplify_subpath(sp: &SubPath, opts: &SimplifyOptions) -> Option { } let ctrl: Vec = segs.iter().flat_map(|s| [s.c.p0, s.c.p1, s.c.p2]).collect(); if flat(&result) && !in_line(&ctrl) { - // Each segment split in 2, 4, 8 and so on, up to 1,024 pieces and 65,536 in all, until every - // piece is within the tolerance of the line between its ends and those lines enclose an - // area: with straight lines they are the result, and without them the loop stays as it is. - // A loop whose points are all in line keeps the lines of the refit. + // Each curved segment split in 2, 4, 8 and so on, up to 1,024 pieces and 65,536 pieces in all + // with the line segments, until every piece is within the tolerance of the line between its + // ends and those lines enclose an area: with straight lines they are the result, and without + // them the loop stays as it is. When no split within those limits encloses an area, the loop + // stays as it is, or with straight lines each curved segment becomes the lines between its + // samples, up to `MAX_RUN_RESULT` lines in all with the line segments; when those do not keep + // some curved segment within the tolerance, the loop stays as it is. A loop whose points are + // all in line keeps the lines of the refit. let near = |c: &CubicBez| [c.p1, c.p2].iter().all(|&p| Line::new(c.p0, c.p3).nearest(p, 1e-9).distance_sq.sqrt() <= opts.tolerance); + let curved = segs.iter().filter(|s| !s.line).count(); for k in 1..=10u32 { let parts = 1u32 << k; - if segs.len().saturating_mul(parts as usize) > 1 << 16 { + if curved.saturating_mul(parts as usize).saturating_add(n - curved) > 1 << 16 { break; } let at = |i: u32| f64::from(i) / f64::from(parts); - let pieces: Vec = segs.iter().flat_map(|s| (0..parts).map(move |i| s.c.subsegment(at(i)..at(i + 1)))).collect(); + let pieces: Vec = segs + .iter() + .flat_map(|s| { + let count = if s.line { 1 } else { parts }; + (0..count).map(move |i| if s.line { s.c } else { s.c.subsegment(at(i)..at(i + 1)) }) + }) + .collect(); let lines: Vec = pieces.iter().map(|c| Seg::line(c.p0, c.p3)).collect(); if pieces.iter().all(near) && !flat(&lines) { if !opts.straight_lines { return Some(sp.clone()); } - result = lines; - break; + return segs_to_subpath(&lines, true); } } + if !opts.straight_lines { + return Some(sp.clone()); + } + let Some(room) = sample_room(curved, n - curved) else { + return Some(sp.clone()); + }; + let mut lines: Vec = Vec::new(); + for s in &segs { + if s.line { + lines.push(Seg::line(s.c.p0, s.c.p3)); + continue; + } + let Some(steps) = steps_within(&s.c, opts.tolerance.max(1e-6), room) else { + return Some(sp.clone()); + }; + let mut pts = Vec::new(); + sample(&s.c, steps, &mut pts, true); + lines.extend(pts.windows(2).map(|p| Seg::line(p[0], p[1]))); + } + return segs_to_subpath(&lines, true); } } let s = segs_to_subpath(&result, sp.closed)?; Some(if opts.straight_lines { s } else { no_worse(sp, s) }) } +/// Most lines between samples of each of `curved` segments, so that they and the `kept` line segments +/// make at most [`MAX_RUN_RESULT`] lines, and each has at most [`MAX_SEGMENT_SAMPLES`]. `None` when +/// that leaves no line for some curved segment. +fn sample_room(curved: usize, kept: usize) -> Option { + let left = MAX_RUN_RESULT.checked_sub(kept)?; + if curved > left { + return None; + } + Some((left / curved.max(1)).min(MAX_SEGMENT_SAMPLES)) +} + +/// How many evenly spaced lines along `c`, at most `room`, follow it: [`sample_steps`] when that +/// fits, or fewer, but never fewer than keep `c` within `tol` of them. `None` when those do not fit +/// in `room`. +fn steps_within(c: &CubicBez, tol: f64, room: usize) -> Option { + let need = line_steps(c, tol).max(1); + (need <= room).then(|| sample_steps(c, tol).min(room).max(need)) +} + /// How far a segment may be from the lines between its samples, as a share of the tolerance. const SAMPLE_GAP: f64 = 0.005; @@ -258,16 +319,27 @@ pub(crate) fn simplify_run_within(run: &[Seg], opts: &SimplifyOptions, mut budge } /// Adds the refit of `part`, consecutive segments with no corner between them and the steps to -/// sample each one with, to `result`. `ends` is the direction it leaves and arrives along, when not -/// those of its first and last segments. -fn refit_part(part: &[(&Seg, usize)], opts: &SimplifyOptions, tol: f64, ends: Option, result: &mut Vec) { +/// sample each one with, to `result`. `ends`, given only when `part` is a whole closed loop, is the +/// direction it leaves and arrives along; when the loop is smoothed, the smoothing runs across its +/// start and the direction comes from the smoothed samples there. +fn refit_part(part: &[(&Seg, usize)], opts: &SimplifyOptions, tol: f64, mut ends: Option, result: &mut Vec) { let (Some((first, _)), Some((last, _))) = (part.first(), part.last()) else { return }; let mut pts = Vec::new(); for (k, (s, steps)) in part.iter().enumerate() { sample(&s.c, *steps, &mut pts, k == 0); } + let mut tol = tol; if opts.smooth > 0.0 { - pts = smooth_points(&pts, opts.smooth); + let smoothed = if ends.is_some() { smooth_loop_points(&pts, opts.smooth) } else { smooth_points(&pts, opts.smooth) }; + if ends.is_some() + && let (Some(&next), Some(&prev)) = (smoothed.get(1), smoothed.len().checked_sub(2).and_then(|i| smoothed.get(i))) + { + ends = unit(next - prev).or(ends); + } + if opts.smooth_moved_only { + tol = tol.min((2.0 * smoothing_moved(&pts, &smoothed)).max(tol * SMOOTH_MOVED_FLOOR)); + } + pts = smoothed; } if opts.straight_lines { let keep = rdp(&pts, tol * (1.0 - SAMPLE_GAP)); @@ -276,14 +348,39 @@ fn refit_part(part: &[(&Seg, usize)], opts: &SimplifyOptions, tol: f64, ends: Op } // The fit may be `tol * 0.98` from the lines between the samples, those lines may be // `SAMPLE_GAP` of `tol` from the path, and the curve the test below turns into a line moves by up - // to 1.5% of `tol`: 3/4 of how far its handles may be from the line. + // to 1.5% of `tol`: 3/4 of how far its handles may be from the line. The fitted curves join + // smoothly, so a curve becomes a line only when the line keeps both of its joins smooth. The last + // curve of a loop fitted across its start leaves along the loop's first segment. let (t0, t1) = ends.map_or((start_tangent(&first.c), end_tangent(&last.c)), |d| (d, d)); - for c in fit_cubics(&pts, t0, t1, tol * 0.98) { - let line = is_straight(&c, tol * 0.02); + let fitted = fit_cubics(&pts, t0, t1, tol * 0.98); + let from = result.len(); + let mut arrive = t0; + for (k, &c) in fitted.iter().enumerate() { + let leave = match fitted.get(k + 1) { + Some(next) => start_tangent(next), + None if ends.is_some() => result.get(from).map_or(t1, |s| start_tangent(&s.c)), + None => t1, + }; + let line = is_straight(&c, tol * 0.02) && line_keeps_joins(&c, arrive, leave); + arrive = if line { unit(c.p3 - c.p0).unwrap_or(arrive) } else { end_tangent(&c) }; result.push(if line { Seg::line(c.p0, c.p3) } else { Seg { c, line } }); } } +/// Most degrees between the line from a refitted curve's start to its end and the directions the +/// path arrives and leaves along, for the curve to become that line: so every join next to such a +/// line turns by at most this much. VectorCraft's own value. +const LINE_JOIN_DEG: f64 = 0.5; + +/// Whether the line from `c.p0` to `c.p3` is within [`LINE_JOIN_DEG`] of `arrive`, the direction the +/// path arrives at `c.p0` along, and of `leave`, the direction it leaves `c.p3` along. A curve whose +/// ends are at one point, or a direction of no length, gives `false`. +fn line_keeps_joins(c: &CubicBez, arrive: Vec2, leave: Vec2) -> bool { + let (Some(dir), Some(arrive), Some(leave)) = (unit(c.p3 - c.p0), unit(arrive), unit(leave)) else { return false }; + let min = LINE_JOIN_DEG.to_radians().cos(); + dir.dot(arrive) >= min && dir.dot(leave) >= min +} + /// `pts` (a run's samples, in order) smoothed along the path: each point becomes the Gaussian-weighted /// mean of the points around it, `sigma` points of arc length wide, the window narrowing towards the /// ends so that the first and last points stay where they are. Consecutive samples within @@ -294,6 +391,66 @@ fn smooth_points(pts: &[Point], sigma: f64) -> Vec { smooth_points_counted(pts, sigma, &mut 0) } +/// [`smooth_points`] for the samples `pts` of a whole closed loop, whose last sample is its first: +/// the samples at its start are smoothed like the others, and the first and last ones move together. +/// The loop is smoothed twice as an open run of the same samples, once from its start and once from +/// the sample nearest halfway round by length, where [`smooth_points`] keeps each run's ends in place. +/// Each sample takes a blend of the two that runs smoothly round the loop, with weights +/// `(1 ± cos θ) / 2`: `θ` goes from 0 at the start to π at the halfway sample and on to 2π at the end, +/// in proportion to length, so the start takes only the second run and the halfway sample only the +/// first, and no sample takes any of a run's fixed ends. +fn smooth_loop_points(pts: &[Point], sigma: f64) -> Vec { + let Some(m) = pts.len().checked_sub(1).filter(|&m| m >= 3) else { return smooth_points(pts, sigma) }; + let mut along = Vec::with_capacity(pts.len()); + let mut total = 0.0; + for (i, p) in pts.iter().enumerate() { + if let Some(prev) = i.checked_sub(1).and_then(|j| pts.get(j)) { + total += prev.distance(*p); + } + along.push(total); + } + if !(total.is_finite() && total > 0.0) { + return smooth_points(pts, sigma); + } + let half = (1..m).min_by(|&a, &b| (along[a] - total / 2.0).abs().total_cmp(&(along[b] - total / 2.0).abs())).unwrap_or(m / 2); + let mid = along[half]; + if !(mid > 0.0 && mid < total) { + return smooth_points(pts, sigma); + } + let ring = &pts[..m]; + let turned: Vec = ring[half..].iter().chain(&ring[..=half]).copied().collect(); + let from_half = smooth_points(&turned, sigma); + let mut out = smooth_points(pts, sigma); + for (i, (p, &s)) in out.iter_mut().zip(&along).enumerate() { + // Sample `i` of the loop is sample `i - half` of `turned`, round the loop. + let Some(&q) = from_half.get((i + m - half) % m) else { continue }; + let theta = if s <= mid { s / mid } else { 1.0 + (s - mid) / (total - mid) } * std::f64::consts::PI; + let w = 0.5 * (1.0 + theta.cos()); + *p = p.lerp(q, w); + } + if let Some(&start) = out.first() + && let Some(end) = out.last_mut() + { + *end = start; + } + out +} + +/// How far [`smooth_points`] moved the samples `pts` to `smoothed` (the same number of points, in +/// order) across the path: the largest distance from a smoothed point to the lines between the +/// samples up to two on either side of the one it came from. +fn smoothing_moved(pts: &[Point], smoothed: &[Point]) -> f64 { + smoothed + .iter() + .enumerate() + .map(|(i, &q)| { + let own = pts.get(i).map_or(f64::INFINITY, |p| p.distance(q)); + let (lo, hi) = (i.saturating_sub(2), (i + 2).min(pts.len().saturating_sub(1))); + (lo..hi).filter_map(|j| Some(Line::new(*pts.get(j)?, *pts.get(j + 1)?).nearest(q, 1e-9).distance_sq.sqrt())).fold(own, f64::min) + }) + .fold(0.0, f64::max) +} + /// How many groups of samples a spread holds at most in [`smooth_points`]. Weighing them in groups /// leaves each smoothed point within a thousandth of a spread of the mean of its samples weighed one /// by one. @@ -626,6 +783,7 @@ pub fn smooth_options(path: &PathData, level: f64) -> SimplifyOptions { corner_angle_deg: SMOOTH_CORNER_DEG, straight_lines: false, smooth: size * 0.05 * level / 100.0, + smooth_moved_only: false, } } @@ -808,27 +966,10 @@ pub fn remove_anchor(sp: &mut SubPath, index: usize) -> bool { return false; } if (sp.closed || (index > 0 && index + 1 < n)) && n >= 3 { - let (pi, ni) = ((index + n - 1) % n, (index + 1) % n); - if !(sp.segment_is_line(pi) && sp.segment_is_line(index)) { - let (left, right) = (sp.segment(pi), sp.segment(index)); - const N: usize = 16; - let mut pts = Vec::with_capacity(2 * N + 1); - sample(&left, N, &mut pts, true); - sample(&right, N, &mut pts, false); - let (t0, t1) = (start_tangent(&left), end_tangent(&right)); - // The new curve passes the removed point at some parameter k: the left samples sit - // at k·i/N, the right ones at k + (1 − k)·i/N. Search k for the closest fit. - let fit = |k: f64| { - let u = (0..=N).map(|i| k * i as f64 / N as f64).chain((1..=N).map(|i| k + (1.0 - k) * i as f64 / N as f64)).collect(); - fit_single_from(&pts, u, t0, t1) - }; - let (c, _, _) = golden_min(fit, 0.0, 1.0); - if c.p1.is_finite() && c.p2.is_finite() { - sp.anchors[pi].h_out = c.p1; - sp.anchors[ni].h_in = c.p2; - } - } + refit_across(&mut sp.anchors, (index + n - 1) % n, index, (index + 1) % n); } + #[cfg(test)] + tests::count_moves(n - index - 1); sp.anchors.remove(index); if !sp.closed { // A new end has nothing beyond it. @@ -845,6 +986,101 @@ pub fn remove_anchor(sp: &mut SubPath, index: usize) -> bool { true } +/// Refit the facing handles of anchors `pi` and `ni` so one cubic follows the two segments that +/// meet at anchor `index` between them ([`remove_anchor`]). Two straight segments are left as +/// they are, and so are the handles when the fit is not finite. +fn refit_across(anchors: &mut [Anchor], pi: usize, index: usize, ni: usize) { + let (Some(&a), Some(&b), Some(&c)) = (anchors.get(pi), anchors.get(index), anchors.get(ni)) else { return }; + let line = |a: &Anchor, b: &Anchor| !a.has_out() && !b.has_in(); + if line(&a, &b) && line(&b, &c) { + return; + } + let (left, right) = (CubicBez::new(a.p, a.h_out, b.h_in, b.p), CubicBez::new(b.p, b.h_out, c.h_in, c.p)); + const N: usize = 16; + let mut pts = Vec::with_capacity(2 * N + 1); + sample(&left, N, &mut pts, true); + sample(&right, N, &mut pts, false); + let (t0, t1) = (start_tangent(&left), end_tangent(&right)); + // The new curve passes the removed point at some parameter k: the left samples sit at k·i/N, + // the right ones at k + (1 − k)·i/N. Search k for the closest fit. + let fit = |k: f64| { + let u = (0..=N).map(|i| k * i as f64 / N as f64).chain((1..=N).map(|i| k + (1.0 - k) * i as f64 / N as f64)).collect(); + fit_single_from(&pts, u, t0, t1) + }; + let (curve, _, _) = golden_min(fit, 0.0, 1.0); + if curve.p1.is_finite() && curve.p2.is_finite() { + anchors[pi].h_out = curve.p1; + anchors[ni].h_in = curve.p2; + } +} + +/// [`remove_anchor`] for each of `indexes`, the last first, with the same result, moving each +/// anchor that stays at most once: removing many anchors from a long subpath one at a time shifts +/// the rest of it each time. Indexes out of range and repeats are skipped. Returns how many +/// anchors were removed. +pub fn remove_anchors(sp: &mut SubPath, indexes: &[usize]) -> usize { + let total = sp.anchors.len(); + let mut targets: Vec = indexes.iter().copied().filter(|&i| i < total).collect(); + targets.sort_unstable_by(|a, b| b.cmp(a)); + targets.dedup(); + if targets.is_empty() { + return 0; + } + // Every anchor below the one being removed is still there, so it keeps its index, the one + // before it is `index - 1` and the first one left is anchor 0 until anchor 0 itself goes. + let mut gone = vec![false; total]; + let mut len = total; + let mut last = total - 1; + // The lowest anchor removed so far and the first one left after it. + let (mut lowest, mut after_lowest) = (total, None); + for &index in &targets { + let next = if index + 1 < lowest { Some(index + 1) } else { after_lowest }; + if (sp.closed || (index > 0 && next.is_some())) && len >= 3 { + let pi = if index > 0 { index - 1 } else { last }; + refit_across(&mut sp.anchors, pi, index, next.unwrap_or(0)); + } + gone[index] = true; + len -= 1; + (lowest, after_lowest) = (index, next); + if next.is_none() { + last = index.saturating_sub(1); + } + if len == 0 { + continue; + } + let first = if index > 0 { 0 } else { next.unwrap_or(0) }; + if !sp.closed { + // A new end has nothing beyond it. + if let Some(a) = sp.anchors.get_mut(first) { + a.h_in = a.p; + } + if let Some(a) = sp.anchors.get_mut(last) { + a.h_out = a.p; + } + } + if len < 3 { + let ends = [first, last].map(|i| sp.anchors.get(i).is_some_and(|a| a.has_in() || a.has_out())); + sp.closed = sp.closed && len == 2 && (ends[0] || ends[1]); + } + } + if len == 0 { + sp.closed = false; + } + let mut kept = 0; + for (i, &g) in gone.iter().enumerate() { + if !g { + if kept != i { + sp.anchors[kept] = sp.anchors[i]; + #[cfg(test)] + tests::count_moves(1); + } + kept += 1; + } + } + sp.anchors.truncate(kept); + targets.len() +} + /// The fit `f` (curve, error, worst point) with the least error for an argument in `[a, b]`, by a /// golden-section search (a bounded number of steps). fn golden_min(f: impl Fn(f64) -> (CubicBez, f64, usize), mut a: f64, mut b: f64) -> (CubicBez, f64, usize) { @@ -1055,6 +1291,129 @@ fn end_point(sp: &SubPath, last: bool) -> Option { mod tests { use super::*; + std::thread_local! { + /// Anchors moved within a subpath's anchor list by [`remove_anchor`] and [`remove_anchors`]. + static MOVES: std::cell::Cell = const { std::cell::Cell::new(0) }; + } + + pub(super) fn count_moves(n: usize) { + MOVES.set(MOVES.get() + n); + } + + /// A subpath of `n` anchors from `seed`: corners, smooth points and points with one handle. + fn random_subpath(seed: &mut u64, n: usize, closed: bool) -> SubPath { + let mut rnd = || { + *seed ^= *seed << 13; + *seed ^= *seed >> 7; + *seed ^= *seed << 17; + *seed + }; + let anchors = (0..n) + .map(|i| { + let p = Point::new(i as f64 * 20.0 + (rnd() % 100) as f64 / 10.0, (rnd() % 400) as f64 / 4.0); + let off = Vec2::new((rnd() % 300) as f64 / 10.0 - 15.0, (rnd() % 300) as f64 / 10.0 - 15.0); + match rnd() % 4 { + 0 => Anchor::corner(p), + 1 => Anchor::smooth(p, p + off), + 2 => Anchor::with_handles(p, p, p + off), + _ => Anchor::with_handles(p, p - off, p), + } + }) + .collect(); + SubPath::new(anchors, closed) + } + + /// `sp` with [`remove_anchor`] run for each of `indexes`, the last first. + fn one_at_a_time(sp: &SubPath, indexes: &[usize]) -> SubPath { + let mut order = indexes.to_vec(); + order.sort_unstable_by(|a, b| b.cmp(a)); + order.dedup(); + let mut out = sp.clone(); + for i in order { + remove_anchor(&mut out, i); + } + out + } + + fn assert_same_bits(got: &SubPath, want: &SubPath, what: &str) { + let bits = |sp: &SubPath| -> Vec<[u64; 6]> { + sp.anchors.iter().map(|a| [a.p.x, a.p.y, a.h_in.x, a.h_in.y, a.h_out.x, a.h_out.y].map(f64::to_bits)).collect() + }; + assert_eq!(got.closed, want.closed, "closed: {what}"); + assert_eq!(bits(got), bits(want), "{what}"); + assert_eq!(got.anchors.iter().map(|a| a.kind).collect::>(), want.anchors.iter().map(|a| a.kind).collect::>(), "{what}"); + } + + #[test] + fn removing_anchors_together_gives_what_removing_them_one_at_a_time_gives() { + let mut seed = 0x9e37_79b9_7f4a_7c15_u64; + for case in 0..600 { + let n = case % 40 + 1; + let closed = case % 2 == 0; + let sp = random_subpath(&mut seed, n, closed); + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + // Up to n + 2 picks over 0..n + 2: runs of neighbors, both ends, everything, repeats + // and indexes past the end. + let picks = (seed % (n as u64 + 3)) as usize; + let mut indexes: Vec = (0..picks).map(|k| ((seed >> (k % 48)) as usize).wrapping_add(k * 7) % (n + 2)).collect(); + if case % 5 == 0 { + indexes = (0..n).collect(); + } + let mut got = sp.clone(); + let removed = remove_anchors(&mut got, &indexes); + let want = one_at_a_time(&sp, &indexes); + let what = format!("case {case}: {n} anchors, closed {closed}, removing {indexes:?}"); + assert_same_bits(&got, &want, &what); + assert_eq!(removed, sp.anchors.len() - want.anchors.len(), "{what}"); + } + } + + #[test] + fn removing_anchors_together_keeps_each_step_of_one_at_a_time() { + let curve = |p: Point, d: f64| Anchor::smooth(p, p + Vec2::new(d, 25.0)); + let pts = [Point::new(0.0, 0.0), Point::new(50.0, 40.0), Point::new(100.0, 0.0), Point::new(150.0, 40.0), Point::new(200.0, 0.0)]; + let cases: Vec<(SubPath, Vec)> = vec![ + // A refit at one removal makes the next segment curved, which the next removal refits. + ( + SubPath::new( + vec![Anchor::corner(pts[0]), Anchor::corner(pts[1]), curve(pts[2], 20.0), Anchor::corner(pts[3]), Anchor::corner(pts[4])], + false, + ), + vec![1, 2, 3], + ), + // The last anchor of an open path goes, then the one before it becomes the end. + (SubPath::new(pts.iter().map(|&p| curve(p, 15.0)).collect(), false), vec![2, 3, 4]), + // The first anchor of a closed path refits across the wrap. + (SubPath::new(pts.iter().map(|&p| curve(p, -10.0)).collect(), true), vec![0, 4]), + // A closed path down to two anchors stays closed with a handle, and opens without one. + (SubPath::new(pts.iter().map(|&p| curve(p, 10.0)).collect(), true), vec![1, 2, 3]), + (SubPath::polyline(&pts, true), vec![1, 2, 3]), + (SubPath::polyline(&pts, true), vec![0, 1, 2, 3]), + (SubPath::polyline(&pts[..1], false), vec![0]), + (SubPath::new(vec![], true), vec![0]), + ]; + for (sp, indexes) in cases { + let mut got = sp.clone(); + remove_anchors(&mut got, &indexes); + assert_same_bits(&got, &one_at_a_time(&sp, &indexes), &format!("{sp:?} removing {indexes:?}")); + } + } + + #[test] + fn removing_anchors_together_moves_each_anchor_left_at_most_once() { + let n = 2001; + let pts: Vec = (0..n).map(|i| Point::new(i as f64, (i % 2) as f64)).collect(); + let mut sp = SubPath::polyline(&pts, false); + let every_other: Vec = (1..n).step_by(2).collect(); + MOVES.set(0); + assert_eq!(remove_anchors(&mut sp, &every_other), n / 2); + assert_eq!(sp.anchors.len(), n - n / 2); + let moves = MOVES.get(); + assert!(moves < n, "{moves} anchors moved to remove {} of {n}", n / 2); + } + /// The samples Object › Path › Smooth at `level` smooths for `sp`, a subpath with no corner, /// and the spread it smooths them with. fn smooth_samples(sp: &SubPath, level: f64) -> (Vec, f64) { @@ -1130,6 +1489,64 @@ mod tests { assert!(work <= 400 * pts.len(), "{work} steps for {} samples", pts.len()); } + /// A spike on a closed loop whose samples are ten times denser on one half than on the other is + /// smoothed out wherever it is, including at the sample halfway through the list, which is only + /// about a quarter of the way round by length. + #[test] + fn loop_smoothing_smooths_a_spike_on_unevenly_sampled_loops() { + let c = Point::new(300.0, 300.0); + let on = |a: f64, r: f64| c + r * Vec2::from_angle(a); + let mut pts: Vec = (0..300).map(|i| on(f64::from(i) / 300.0 * std::f64::consts::PI, 100.0)).collect(); + pts.extend((0..30).map(|i| on(std::f64::consts::PI * (1.0 + f64::from(i) / 30.0), 100.0))); + let m = pts.len(); + pts.push(pts[0]); + for spike in [m / 2, 0, 100] { + let mut p = pts.clone(); + p[spike] = on(std::f64::consts::PI * spike as f64 / 300.0, 105.0); + if spike == 0 { + p[m] = p[0]; + } + let out = smooth_loop_points(&p, 10.0); + assert_eq!(out.len(), p.len()); + assert_eq!(out[0], out[m], "spike at {spike}: the loop stays closed"); + let left = out[spike].distance(c) - 100.0; + assert!(left < 1.0, "spike at {spike}: {left} pt of 5 pt left"); + } + } + + #[test] + fn the_samples_of_a_flat_loop_and_its_line_segments_stay_within_the_result_limit() { + for (curved, kept) in [(1, 0), (32, 1), (40, 1_000_000), (1_000, MAX_RUN_RESULT - 1_000), (3, MAX_RUN_RESULT - 7)] { + let room = sample_room(curved, kept).unwrap_or_else(|| panic!("{curved} curved, {kept} kept: no room")); + assert!((1..=MAX_SEGMENT_SAMPLES).contains(&room), "{curved} curved, {kept} kept: room {room}"); + assert!(curved * room + kept <= MAX_RUN_RESULT, "{curved} curved, {kept} kept: room {room}"); + } + assert_eq!(sample_room(32, 0), Some(MAX_SEGMENT_SAMPLES)); + assert_eq!(sample_room(2, MAX_RUN_RESULT - 1), None); + assert_eq!(sample_room(1, MAX_RUN_RESULT + 5), None); + } + + #[test] + fn lines_with_too_little_room_for_the_tolerance_are_not_used() { + let c = CubicBez::new((0.0, 0.0), (0.0, 100.0), (100.0, 100.0), (100.0, 0.0)); + let tol = 0.01; + let need = line_steps(&c, tol); + assert!(need > 4, "{need}"); + assert_eq!(steps_within(&c, tol, need - 1), None); + for room in [need, need + 3, MAX_SEGMENT_SAMPLES] { + let steps = steps_within(&c, tol, room).unwrap_or_else(|| panic!("room {room}: no steps")); + assert!((need..=room).contains(&steps), "room {room}: {steps} steps"); + let mut pts = Vec::new(); + sample(&c, steps, &mut pts, true); + let lines: Vec = pts.windows(2).map(|p| Line::new(p[0], p[1])).collect(); + for i in 0..=1000 { + let p = c.eval(f64::from(i) / 1000.0); + let gap = lines.iter().map(|l| l.nearest(p, 1e-9).distance_sq.sqrt()).fold(f64::INFINITY, f64::min); + assert!(gap <= tol + 1e-9, "room {room}, {steps} steps: {gap} at {i}"); + } + } + } + #[test] fn smoothing_points_whose_arc_length_overflows_returns_every_point() { let pts: Vec = (0..40).map(|i| Point::new(if i % 2 == 0 { -1e308 } else { 1e308 }, f64::from(i))).collect(); diff --git a/crates/pathops/src/fit.rs b/crates/pathops/src/fit.rs index 6b1f4eb0c1..0411a71f40 100644 --- a/crates/pathops/src/fit.rs +++ b/crates/pathops/src/fit.rs @@ -17,6 +17,9 @@ const MAX_BULGE_SAMPLES: f64 = 1024.0; /// About how many points of a long piece its first fit uses. const COARSE_POINTS: usize = 16; +/// Most times [`fit_through_rec`] splits a run of points, which bounds its recursion. +const MAX_SPLITS: usize = 40; + /// Unit vector or `None` if (nearly) zero. pub(crate) fn unit(v: Vec2) -> Option { let l = v.hypot(); @@ -37,7 +40,7 @@ pub(crate) fn end_tangent(c: &CubicBez) -> Vec2 { /// /// `t0` is the unit tangent leaving `pts[0]`; `t1` is the unit tangent arriving at the last point /// (forward direction). Consecutive output cubics are G1 continuous. -pub(crate) fn fit_cubics(pts: &[Point], t0: Vec2, t1: Vec2, tol: f64) -> Vec { +pub fn fit_cubics(pts: &[Point], t0: Vec2, t1: Vec2, tol: f64) -> Vec { let pts = dedup(pts); if pts.len() < 2 { return Vec::new(); @@ -48,6 +51,43 @@ pub(crate) fn fit_cubics(pts: &[Point], t0: Vec2, t1: Vec2, tol: f64) -> Vec Vec { + let pts = dedup(pts); + let mut out = Vec::new(); + if pts.len() < 2 { + return out; + } + fit_through_rec(&pts, t0, t1, tol.max(1e-9), &mut out, 0); + out +} + +/// Fits all of `pts` with one cubic, splitting at its worst point until each piece is within `tol` +/// of its points (see [`fit_cubics_through`]). `depth` bounds the recursion on hostile points. +fn fit_through_rec(pts: &[Point], t0: Vec2, t1: Vec2, tol: f64, out: &mut Vec, depth: usize) { + let n = pts.len(); + if n == 2 { + let d = pts[0].distance(pts[1]) / 3.0; + out.push(CubicBez::new(pts[0], pts[0] + t0 * d, pts[1] - t1 * d, pts[1])); + return; + } + let (curve, err, split) = fit_single_tol(pts, t0, t1, tol); + if err <= tol || depth >= MAX_SPLITS { + out.push(curve); + return; + } + let split = split.clamp(1, n - 2); + let tc = unit(pts[split + 1] - pts[split - 1]).unwrap_or(t0); + fit_through_rec(&pts[..=split], t0, tc, tol, out, depth + 1); + fit_through_rec(&pts[split..], tc, t1, tol, out, depth + 1); +} + /// The curves of `pieces`, which follow each other along `pts` from its first point, leaving it /// along `t0`. Each curve takes up to [`MAX_JOINS`] of the pieces after its first one, as long as /// the fit of them together is within `tol`. @@ -152,6 +192,32 @@ pub(crate) fn fit_single(pts: &[Point], t0: Vec2, t1: Vec2) -> (CubicBez, f64, u fit_single_from(pts, chord_params(pts), t0, t1) } +/// [`fit_single`] that stops reparameterising once the curve is within `tol` of its points: a +/// curve already that close needs no better fit, and each Newton round reads every point. +fn fit_single_tol(pts: &[Point], t0: Vec2, t1: Vec2, tol: f64) -> (CubicBez, f64, usize) { + let mut u = chord_params(pts); + let mut best = generate(pts, &u, t0, t1); + let (mut best_err, mut best_split) = max_error(pts, &best, &u); + for _ in 0..MAX_REPARAM { + if best_err <= tol { + break; + } + for (i, ui) in u.iter_mut().enumerate() { + *ui = newton(&best, pts[i], *ui); + } + let c = generate(pts, &u, t0, t1); + let (e, s) = max_error(pts, &c, &u); + if e < best_err { + best = c; + best_err = e; + best_split = s; + } else { + break; + } + } + (best, best_err, best_split) +} + /// [`fit_single`] starting from the parameters `u` (one per point, 0 to 1) instead of the /// chord-length ones. pub(crate) fn fit_single_from(pts: &[Point], u: Vec, t0: Vec2, t1: Vec2) -> (CubicBez, f64, usize) { @@ -334,6 +400,25 @@ mod tests { assert!(out[0].p1.distance(c.p1) < 1.0, "{:?}", out[0]); } + /// A curve's samples are followed between the points, not chopped to the chords through + /// them: a smooth outline fitted from coarse samples must keep its bow (an outline's area + /// depends on it), unlike a polyline's samples. + #[test] + fn through_fit_bows_between_coarse_points() { + // The parabola y = 4t(1 - t) over x = 100t, sampled at 8 points. + let node = |t: f64| Point::new(100.0 * t, 4.0 * t * (1.0 - t)); + let pts: Vec = (0..=8).map(|i| node(i as f64 / 8.0)).collect(); + let (t0, t1) = (Vec2::new(1.0, 0.04).normalize(), Vec2::new(1.0, -0.04).normalize()); + let out = fit_cubics_through(&pts, t0, t1, 0.001); + for c in &out { + for k in 0..=100 { + let q = c.eval(k as f64 / 100.0); + let want = 4.0 * (q.x / 100.0) * (1.0 - q.x / 100.0); + assert!((q.y - want).abs() < 0.01, "{:?} at {q:?} wants {want}", c); + } + } + } + #[test] fn splits_when_needed() { // A zig-zag cannot be fitted with one cubic. diff --git a/crates/pathops/src/lib.rs b/crates/pathops/src/lib.rs index b7af34c89a..49b7c051f1 100644 --- a/crates/pathops/src/lib.rs +++ b/crates/pathops/src/lib.rs @@ -23,9 +23,10 @@ pub use boolean::{ }; pub use edit::{ AverageAxis, SIMPLIFY_LEVEL, SMOOTH_AUTO_LEVEL, SimplifiedPart, SimplifyOptions, add_anchor_points, auto_simplify_level, average, join, - remove_anchor, remove_redundant_points, simplify, simplify_level_tolerance, simplify_part, simplify_with, smooth, smooth_level, smooth_options, - split_into_grid, + remove_anchor, remove_anchors, remove_redundant_points, simplify, simplify_level_tolerance, simplify_part, simplify_with, smooth, smooth_level, + smooth_options, split_into_grid, }; +pub use fit::{fit_cubics, fit_cubics_through}; pub use offset::{Cap, Join, MAX_OFFSET_SEGMENT_PAIRS, offset_path, outline_stroke, stroke_region, try_offset_path}; pub use pathfinder::{FaceMerger, PathfinderOp, Region, Shape, merge_regions, pathfinder, pathfinder_with, region_at, regions, regions_within}; pub use planar::{ diff --git a/crates/pathops/src/offset.rs b/crates/pathops/src/offset.rs index bf533476be..6ada08d3b8 100644 --- a/crates/pathops/src/offset.rs +++ b/crates/pathops/src/offset.rs @@ -126,21 +126,49 @@ fn path_is_finite(path: &PathData) -> bool { /// Fallible [`offset_path`] that returns an error when the input is non-finite or exceeds /// the complexity bound ([`MAX_OFFSET_SEGMENT_PAIRS`]), or when planar arrangement fails. pub fn try_offset_path(path: &PathData, delta: f64, join: Join, miter_limit: f64) -> Result { - let src = std::cell::LazyCell::new(|| SegmentTree::new(boxed_segments(&path.to_bezpath()))); - offset_with_check(path, delta, join, miter_limit, |p, r| any_within(&src, p, r)) + offset_with_check(path, delta, join, miter_limit, |part| { + let bp = part.to_bezpath(); + let src = std::cell::LazyCell::new(move || SegmentTree::new(boxed_segments(&bp))); + move |p, r| any_within(&src, p, r) + }) } -/// [`try_offset_path`] with the test of whether some segment of `path` lies closer than a radius to a point. -fn offset_with_check( +/// [`try_offset_path`] with `within_of(part)`, the test of whether some segment of `part` lies +/// closer than a radius to a point. +fn offset_with_check bool>( + path: &PathData, + delta: f64, + join: Join, + miter_limit: f64, + within_of: impl Fn(&PathData) -> W, +) -> Result { + if !delta.is_finite() || !path_is_finite(path) { + return Err(PathOpsError::NonFinite); + } + // An inset keeps only faces inside the closed fill, so it would drop the outline of every + // open subpath (#6427). Inset the closed subpaths, outline the open ones as a positive offset + // does, and unite the two. + if delta < 0.0 && path.subpaths.iter().any(|s| s.anchors.len() > 1 && !close_if_ends_meet(s).closed) { + let (closed, open): (Vec, Vec) = path.subpaths.iter().cloned().partition(|s| close_if_ends_meet(s).closed); + let (closed, open) = (PathData::new(closed), PathData::new(open)); + let inset = offset_region(&closed, delta, join, miter_limit, within_of(&closed))?; + let outline = offset_region(&open, -delta, join, miter_limit, within_of(&open))?; + if inset.is_empty() { + return Ok(outline); + } + return crate::boolean::try_unite_all(&[(&inset, FillRule::NonZero), (&outline, FillRule::NonZero)]); + } + offset_region(path, delta, join, miter_limit, within_of(path)) +} + +/// [`offset_with_check`] of a finite `path` with the `within` test of its own segments. +fn offset_region( path: &PathData, delta: f64, join: Join, miter_limit: f64, within: impl Fn(kurbo::Point, f64) -> bool, ) -> Result { - if !delta.is_finite() || !path_is_finite(path) { - return Err(PathOpsError::NonFinite); - } if path.is_empty() { return Ok(PathData::default()); } @@ -155,10 +183,18 @@ fn offset_with_check( } else { BezPath::new() }; - let arr = Arrangement::new_budgeted( - vec![(fill, FillRule::NonZero), (ring, FillRule::NonZero), (open_bp, FillRule::NonZero)], - MAX_OFFSET_SEGMENT_PAIRS, - )?; + let parts = vec![fill, ring, open_bp]; + match crate::sweep_axis::turned_outlines(&parts) { + Some(turned) => offset_faces(turned, delta, |p, r| within(crate::sweep_axis::unturn_point(p), r)).map(crate::sweep_axis::unturn), + None => offset_faces(parts, delta, within), + } +} + +/// The faces of the offset by `delta` from `parts` (the closed fill, the ring stroked around it and +/// the stroke of the open subpaths, in that order), less the spurious ones that `within` finds. +fn offset_faces(parts: Vec, delta: f64, within: impl Fn(kurbo::Point, f64) -> bool) -> Result { + let d = delta.abs(); + let arr = Arrangement::new_budgeted(parts.into_iter().map(|p| (p, FillRule::NonZero)).collect(), MAX_OFFSET_SEGMENT_PAIRS)?; let c = if delta >= 0.0 { arr.contours_covering(|c| !c.is_empty()) } else { arr.contours_covering(|c| c.contains(&0) && !c.contains(&1)) }; // When `d` exceeds a curvature radius the stroker's inner offset inverts and its loops cancel // winding, leaving faces uncovered that are really within `d` of the path. Every face of the @@ -630,14 +666,17 @@ mod tests { fn offsets_with_the_tree_are_identical_to_offsets_with_the_scan() { let (mut checks, mut hits, mut misses) = (0, 0, 0); for path in offset_inputs() { - let segs = boxed_segments(&path.to_bezpath()); for delta in [0.0, 0.05, 1.0, 5.0, 60.0, -0.05, -1.0, -5.0, -60.0] { for join in [Join::Round, Join::Miter, Join::Bevel] { let found = std::cell::Cell::new((0, 0)); - let by_scan = offset_with_check(&path, delta, join, 4.0, |p, r| { - let v = any_within_by_scan(&segs, p, r); - found.set((found.get().0 + usize::from(v), found.get().1 + usize::from(!v))); - v + let by_scan = offset_with_check(&path, delta, join, 4.0, |part| { + let segs = boxed_segments(&part.to_bezpath()); + let found = &found; + move |p, r| { + let v = any_within_by_scan(&segs, p, r); + found.set((found.get().0 + usize::from(v), found.get().1 + usize::from(!v))); + v + } }); checks += 1; hits += found.get().0; diff --git a/crates/pathops/src/sweep_axis.rs b/crates/pathops/src/sweep_axis.rs index 364325afcd..fb544ad163 100644 --- a/crates/pathops/src/sweep_axis.rs +++ b/crates/pathops/src/sweep_axis.rs @@ -149,6 +149,11 @@ pub(crate) fn unturn(mut path: PathData) -> PathData { path } +/// A point of turned input, turned back. +pub(crate) fn unturn_point(p: kurbo::Point) -> kurbo::Point { + UNTURN * p +} + #[cfg(test)] mod tests { use kurbo::{Join, Stroke, StrokeOpts}; @@ -251,6 +256,39 @@ mod tests { assert_eq!(turns_during(|| drop(stroke_region(std::slice::from_ref(&short)))), 0); } + #[test] + fn offset_path_sweeps_a_long_low_path_turned_with_the_result_of_the_path_on_end() { + let mut rng = Rng(17); + // Grown past the zigzag's bends, where the stroker leaves loops whose faces are dropped by + // the distance test; grown a little; and inset. + for (closed, delta) in [(false, 1.5), (true, 0.5), (true, -0.3)] { + let what = format!("closed {closed}, offset {delta}"); + let low = zigzag(3, 300, 0.4, &mut rng, closed); + let tall = upright(&low); + let offset = |p: &PathData| crate::try_offset_path(p, delta, Join::Round, 4.0).unwrap(); + let mut turned = PathData::default(); + assert_eq!(turns_during(|| turned = offset(&low)), 1, "{what}: low"); + let mut on_end = PathData::default(); + assert_eq!(turns_during(|| on_end = offset(&tall)), 0, "{what}: tall"); + assert!(!turned.is_empty(), "{what}: empty"); + assert_same_region(&turned, &upright(&on_end), &what); + } + // A long plate with a row of round holes: growing it by 1 closes the narrow holes, which + // the distance test drops, and keeps the wide ones. + use kurbo::Shape; + let mut plate = kurbo::Rect::new(0.0, 0.0, 4000.0, 20.0).to_path(0.1); + for i in 0..200u32 { + let r = if i % 2 == 0 { 0.8 } else { 4.0 }; + plate.extend(kurbo::Circle::new((10.0 + 20.0 * f64::from(i), 10.0), r).to_path(0.01).reverse_subpaths()); + } + let plate = PathData::from_bezpath(&plate); + let grow = |p: &PathData| crate::try_offset_path(p, 1.0, Join::Round, 4.0).unwrap(); + let mut grown = PathData::default(); + assert_eq!(turns_during(|| grown = grow(&plate)), 1, "plate"); + assert_eq!(grown.subpaths.len(), 1 + 100, "plate"); + assert_same_region(&grown, &upright(&grow(&upright(&plate))), "plate"); + } + #[test] fn a_repeating_path_is_measured_at_every_position() { // Short segments in a row along the bottom, with a long one stacked above the row after diff --git a/crates/pathops/tests/it/ops.rs b/crates/pathops/tests/it/ops.rs index 9a6fb57138..93f6d4c29c 100644 --- a/crates/pathops/tests/it/ops.rs +++ b/crates/pathops/tests/it/ops.rs @@ -316,6 +316,24 @@ fn offset_of_an_open_path_whose_ends_meet_is_the_closed_shape_offset() { assert_eq!(o.subpaths.len(), 1); } +#[test] +fn a_negative_offset_outlines_an_open_path_as_a_positive_one_does() { + // Issue #6427 (A4): an inset of an open path was empty. Open subpaths are outlined with a + // stroke of width 2|delta| whichever way the offset goes. + let line = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(100.0, 0.0)], false)); + for delta in [2.0, -2.0] { + let o = offset_path(&line, delta, Join::Miter, 4.0); + assert!(close(ar(&o), 400.0, 1e-6), "delta {delta}: {}", ar(&o)); + assert_eq!(o.subpaths.len(), 1, "delta {delta}"); + } + // With a closed shape beside it, the shape is inset and the line still outlined. + let mut both = rect(0.0, 0.0, 20.0, 10.0); + both.subpaths.push(SubPath::polyline(&[Point::new(100.0, 0.0), Point::new(150.0, 0.0)], false)); + let o = offset_path(&both, -2.0, Join::Miter, 4.0); + assert!(close(ar(&o), 16.0 * 6.0 + 50.0 * 4.0, 1e-6), "{}", ar(&o)); + assert_eq!(o.subpaths.len(), 2); +} + #[test] fn outline_stroke_of_line() { let l = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(30.0, 40.0)], false)); @@ -399,6 +417,77 @@ fn simplify_keeps_square_corners() { assert!(!has_curves(&s)); } +/// The largest turn, in degrees, at an anchor of `sp` that is not an end of an open subpath: the +/// angle between the direction a segment arrives along and the one the next leaves along. +fn largest_join_turn(sp: &SubPath) -> f64 { + let dir = |v: kurbo::Vec2, w: kurbo::Vec2, chord: kurbo::Vec2| [v, w, chord].into_iter().find(|d| d.hypot() > 1e-9).unwrap_or(chord); + let n = sp.segment_count(); + let first = usize::from(!sp.closed); + (first..n) + .map(|i| { + let (prev, next) = (sp.segment((i + n - 1) % n), sp.segment(i)); + let arrive = dir(prev.p3 - prev.p2, prev.p3 - prev.p1, prev.p3 - prev.p0); + let leave = dir(next.p1 - next.p0, next.p2 - next.p0, next.p3 - next.p0); + arrive.cross(leave).atan2(arrive.dot(leave)).abs().to_degrees() + }) + .fold(0.0, f64::max) +} + +/// A refitted curve becomes a line only when the line keeps the smooth joins on both sides of it: +/// with no corners kept, the refit of a jagged line or of an arc running into a line turns by at most +/// 0.5° at every anchor. Points that all lie on one line still become one line. +#[test] +fn simplify_turns_a_curve_into_a_line_only_where_the_joins_stay_smooth() { + let mut seed = 7u64; + let mut noise = || { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + ((seed >> 11) as f64 / (1u64 << 53) as f64) * 2.0 - 1.0 + }; + let jagged: Vec = (0..=60).map(|i| Point::new(100.0 + f64::from(i) * 5.0, 200.0 + 6.0 * noise())).collect(); + let mut arc_into_line: Vec = + (0..=40).map(|i| Point::new(50.0 * (f64::from(i) / 80.0 * PI).cos(), 50.0 * (f64::from(i) / 80.0 * PI).sin())).collect(); + arc_into_line.extend((1..=20).map(|i| Point::new(-f64::from(i) * 2.0, 50.0))); + for pts in [&jagged, &arc_into_line] { + let path = PathData::single(SubPath::polyline(pts, false)); + for tolerance in [1.0, 2.5, 5.0] { + let s = simplify_with(&path, &SimplifyOptions { tolerance, corner_angle_deg: 179.0, ..Default::default() }); + let turn = largest_join_turn(&s.subpaths[0]); + assert!(turn <= 0.5 + 1e-9, "{tolerance} pt: an anchor turns {turn}°: {s:?}"); + assert!(max_deviation(&path, &s) <= tolerance + 1e-6, "{tolerance} pt: {}", max_deviation(&path, &s)); + } + } + let in_line: Vec = [0.0, 3.0, 10.0, 11.0, 40.0, 41.5, 90.0, 100.0].map(|x| Point::new(x, 0.5 * x)).to_vec(); + let s = simplify_with(&PathData::single(SubPath::polyline(&in_line, false)), &SimplifyOptions { tolerance: 1.0, ..Default::default() }); + assert_eq!(s.anchor_count(), 2, "{s:?}"); + assert!(!has_curves(&s), "{s:?}"); +} + +/// A smoothed loop with no corner is fitted across its start, and the join there also turns by at +/// most 0.5°. Each loop is a flat side that bends by 0.6° at the loop's start, closed by an arc of +/// `n` lines `height` tall, with `inner` anchors along each half of the side. +#[test] +fn simplify_keeps_the_join_at_the_start_of_a_smoothed_loop_smooth() { + for (half, height, n, inner, tolerance, smooth) in + [(40.0, 20.0, 8, 3, 2.5, 2.0), (80.0, 60.0, 8, 3, 5.0, 0.5), (160.0, 200.0, 24, 3, 10.0, 2.0), (160.0, 20.0, 24, 8, 10.0, 5.0)] + { + let rise = half * 0.3f64.to_radians().tan(); + let along = |i: i32| Point::new(half * f64::from(i) / f64::from(inner), -rise * f64::from(i.abs()) / f64::from(inner)); + let mut pts: Vec = (0..=inner).map(along).collect(); + pts.extend((1..n).map(|i| { + let a = f64::from(i) / f64::from(n) * PI; + Point::new(half * a.cos(), -rise - height * a.sin()) + })); + pts.extend((-inner..0).map(along)); + let path = PathData::single(SubPath::polyline(&pts, true)); + let s = simplify_with(&path, &SimplifyOptions { tolerance, corner_angle_deg: 179.0, smooth, ..Default::default() }); + let sp = &s.subpaths[0]; + assert!(sp.closed && sp.anchors.len() < pts.len(), "{tolerance} pt: {s:?}"); + assert!(sp.segment_is_line(0), "{tolerance} pt: the first segment is a curve: {s:?}"); + let turn = largest_join_turn(sp); + assert!(turn <= 0.5 + 1e-9, "{tolerance} pt: an anchor turns {turn}°: {s:?}"); + } +} + #[test] fn simplify_straight_lines_option() { let c = dense_circle(50.0, 200); @@ -479,6 +568,42 @@ fn simplify_keeps_a_closed_subpath_that_refits_to_one_curve() { assert!(max_deviation(&long, &s) <= 0.1 + 1e-6, "{s:?}"); } +/// An S curve closed by a straight edge of 20,000 anchors, whose curve shows only when it is split in +/// four, keeps its outline within the tolerance. With corner anchors on the edge, only the curve is +/// split. With smooth anchors whose handles lie along the edge, four pieces of every segment pass the +/// limit on pieces: the loop stays as it is, or with straight lines follows lines between samples. +#[test] +fn simplify_keeps_a_flat_loop_with_many_anchors_on_its_edge() { + let n = 20_000; + let step = 100.0 / f64::from(n); + let curve_anchors = vec![ + Anchor::with_handles(Point::new(0.0, 0.0), Point::new(0.0, 0.0), Point::new(0.0, 3.0)), + Anchor::with_handles(Point::new(100.0, 0.0), Point::new(0.0, -3.0), Point::new(100.0, 0.0)), + ]; + let curve = PathData::single(SubPath::new(curve_anchors.clone(), false)); + for smooth_edge in [false, true] { + let mut anchors = curve_anchors.clone(); + anchors.extend((1..n).map(|i| { + let p = Point::new(100.0 - f64::from(i) * step, 0.0); + if smooth_edge { + Anchor::with_handles(p, Point::new(p.x + step / 3.0, 0.0), Point::new(p.x - step / 3.0, 0.0)) + } else { + Anchor::corner(p) + } + })); + let path = PathData::single(SubPath::new(anchors, true)); + for straight_lines in [false, true] { + let s = simplify_with(&path, &SimplifyOptions { tolerance: 4.0, straight_lines, ..Default::default() }); + let at = format!("smooth edge {smooth_edge}, straight lines {straight_lines}"); + assert_eq!(s.subpaths.len(), 1, "{at}"); + let sp = &s.subpaths[0]; + assert!(sp.closed && sp.area().abs() > 1.0, "{at}: area {}", sp.area()); + assert!(max_deviation(&curve, &s) <= 4.0 + 1e-6, "{at}: {}", max_deviation(&curve, &s)); + assert!(!straight_lines || (0..sp.segment_count()).all(|i| sp.segment_is_line(i)), "{at}: a curve is left"); + } + } +} + /// The Simplify slider's levels: 1 pt at 50, doubled for every 10 levels down and halved for every /// 10 up; Auto-Simplify takes the lowest level whose tolerance is at most 1/400 of the size, and /// level 100 for a size under 12.5 pt. diff --git a/crates/pdf/Cargo.toml b/crates/pdf/Cargo.toml index a5a3b83863..d4394dfefa 100644 --- a/crates/pdf/Cargo.toml +++ b/crates/pdf/Cargo.toml @@ -30,6 +30,7 @@ craft-pdf = { workspace = true } log = { workspace = true } chrono = { workspace = true } smallvec = "1" +siphasher = "1" weezl = "0.2" serde = { workspace = true } # The XMP packet that File Info is read from (file_info.rs); the version usvg already uses. diff --git a/crates/pdf/src/export/entry.rs b/crates/pdf/src/export/entry.rs index fc48485216..eabba52d9e 100644 --- a/crates/pdf/src/export/entry.rs +++ b/crates/pdf/src/export/entry.rs @@ -7,8 +7,9 @@ pub fn export(doc: &Document, opts: &PdfOptions) -> Result, PdfError> { export_with_report(doc, opts).map(|r| r.bytes) } -/// Like [`export`], also returning warnings: options accepted but not applied yet (see -/// [`crate::PdfSettings::warnings`]) and features approximated or dropped. +/// Like [`export`], also returning warnings, features approximated or dropped, and notes on the +/// options: options accepted but not applied yet (see [`crate::PdfSettings::warnings`]) or applied +/// another way. pub fn export_with_report(doc: &Document, opts: &PdfOptions) -> Result { // Type in the document's composite fonts is drawn in them, whether or not an app has the document open. let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&doc.composite_fonts); @@ -53,7 +54,9 @@ fn export_with_report_inner(doc: &Document, opts: &PdfOptions, left_out: &mut Ha let raised = for_long_pages(set, &pages)?; let set = raised.as_ref().unwrap_or(set); - let title = crate::pdfx::title(set.standard, opts.title.clone().unwrap_or_else(|| doc.title.clone())); + // The file's Title is File Info's; the page information names the document, as its tab does. + let title = crate::pdfx::title(set.standard, opts.title.clone().unwrap_or_else(|| doc.info_title().to_owned())); + let name = opts.title.as_deref().unwrap_or(&doc.title); // The time of writing (none on the web) dates the editing data and the page information. let now = vectorcraft_doc::metadata::output_time(); let created_at = opts.created.or(now); @@ -61,17 +64,20 @@ fn export_with_report_inner(doc: &Document, opts: &PdfOptions, left_out: &mut Ha let display_doc_title = opts.display_doc_title || opts.title.as_deref().is_some_and(|title| !title.trim().is_empty()); let mut w = Writer::new(doc, set, &title, created_at, doc.color_mode == vectorcraft_doc::ColorMode::Cmyk)?; // Preserve Editing: the native document as an embedded file (`check` refused PDF/A with it). - let mut warnings = set.warnings(); + let mut warnings = vec![]; + let mut settings = set.warnings(); if raised.is_some() { - warnings.push( - "PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6".into(), - ); + settings.push(if opts.settings.compatibility == Compatibility::Pdf14 { + "PDF 1.4 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to stay within PDF/A-2's page limit of 14,400 units: the file is written as PDF 1.6".into() + } else { + "PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6".into() + }); } let native = opts.native.as_deref().filter(|_| set.preserve_editing); if let Some(native) = native { w.pdf.document_mut().embed_file(crate::editing::embedded_file(native, set.compression.compress_text, now.map(date_time))); } else if set.preserve_editing { - warnings.push("Preserve editing needs the native document, which wasn't given: the PDF reopens as plain artwork".into()); + settings.push("Preserve editing needs the native document, which wasn't given: the PDF reopens as plain artwork".into()); } let mut ex = Exporter::new(doc, set); @@ -81,7 +87,7 @@ fn export_with_report_inner(doc: &Document, opts: &PdfOptions, left_out: &mut Ha // A knockout page group draws the layers' objects one by one, not layer by layer. ex.layers = set.writes_layers() && !doc.page_knockout; if set.writes_layers() && doc.page_knockout { - warnings.push("PDF layers can't be written with a knockout page group: every layer is plain page content".into()); + settings.push("PDF layers can't be written with a knockout page group: every layer is plain page content".into()); } ex.overprint = set.advanced.overprint == crate::Overprint::Preserve; let bleed = set.bleed_of(doc); @@ -106,7 +112,7 @@ fn export_with_report_inner(doc: &Document, opts: &PdfOptions, left_out: &mut Ha vectorcraft_doc::cancel::check().map_err(|_| PdfError::Cancelled)?; vectorcraft_doc::cancel::progress(written as u64 + 1, total, &format!("Writing page {} of {total}", written + 1)); let (m, r) = (boxes.media, boxes.bleed); - let info = if marks.page_info { crate::marks::page_info(doc, &title, i, now) } else { String::new() }; + let info = if marks.page_info { crate::marks::page_info(doc, name, i, now) } else { String::new() }; let art = crate::marks::art(doc, &marks, &boxes, bleed, &info); // The page is the media box, y down from its top-left corner (like ours), in units of // `unit` points. @@ -138,7 +144,7 @@ fn export_with_report_inner(doc: &Document, opts: &PdfOptions, left_out: &mut Ha vectorcraft_doc::cancel::check().map_err(|_| PdfError::Cancelled)?; let (layers, overprinted, invisible) = (ex.layers, ex.overprinted, ex.invisible); w.absorb(ex); - let (bytes, more) = match w.finish(left_out, display_doc_title) { + let (bytes, more, catalog) = match w.finish(left_out, display_doc_title) { Ok(done) => done, Err(e) => return Err(writer_error(doc, opts, left_out, &long, e)), }; @@ -151,11 +157,13 @@ fn export_with_report_inner(doc: &Document, opts: &PdfOptions, left_out: &mut Ha // The writer's metadata has no copyright: it is added to the XMP packet. let bytes = crate::post::rights(bytes, &doc.metadata)?; warnings.extend(more); + settings.extend(catalog); let bytes = crate::post::user_units(bytes, &units)?; // A PDF 1.5 file written as PDF 1.6 keeps the encryption PDF 1.5 has (128-bit RC4). - let bytes = crate::post::finish(bytes, opts, native.is_some(), &mut warnings)?; + let bytes = crate::post::finish(bytes, opts, native.is_some(), &mut settings)?; warnings.dedup(); - Ok(ExportReport { bytes, warnings }) + settings.dedup(); + Ok(ExportReport { bytes, warnings, setting_notes: settings }) } /// The artboards `opts` exports, in page order, with the boxes of their pages: Marks and Bleeds @@ -192,10 +200,18 @@ const MIN_PAGE_SIDE: f64 = 3.0; const MAX_PDF14_REAL: f64 = 32_767.0; /// Pages with a side longer than [`MAX_PAGE_SIDE`] are written with a `UserUnit`: in PDF 1.6 and -/// later files that aren't PDF/X files, unless `long_pages_in_points` is on. Other files have +/// later files that aren't PDF/X files, unless `long_pages_in_points` applies. Other files have /// every page in points. fn writes_user_units(set: &PdfSettings) -> bool { - set.compatibility.has_user_unit() && !set.standard.is_pdfx() && !set.long_pages_in_points + set.compatibility.has_user_unit() && !set.standard.is_pdfx() && !long_pages_in_points(set) +} + +/// `long_pages_in_points` is on in a file without a standard. PDF/X files write long pages in +/// points anyway, and PDF/A files keep the `UserUnit`, which keeps their page boundaries within +/// 14,400 units (ISO 19005-2, 6.1.13). A PDF/A file at PDF 1.4 is written as PDF 1.6 to have one +/// ([`for_long_pages`]). +fn long_pages_in_points(set: &PdfSettings) -> bool { + set.long_pages_in_points && set.standard == Standard::None } /// The `UserUnit` (PDF 1.6) of a page `w` × `h` points large: 1 when both sides are at most @@ -221,7 +237,7 @@ pub fn check_page_sizes(doc: &Document, opts: &PdfOptions) -> Result<(), PdfErro /// The settings `set` is written with when one of `pages` has a side longer than /// [`MAX_PAGE_SIDE`]: a PDF 1.5 file that isn't a PDF/X file is written as PDF 1.6, which has a -/// page's `UserUnit`, unless `long_pages_in_points` is on (`None`: `set` as it is). Other files +/// page's `UserUnit`, unless `long_pages_in_points` applies (`None`: `set` as it is). Other files /// without a `UserUnit` have the page in points. The writer puts a whole number as an integer and fails a PDF 1.3 or 1.4 file that has /// a real number past [`MAX_PDF14_REAL`]: a page whose side is past it and not a whole number of /// points is refused here, before anything is drawn ([`page_too_long`]). @@ -229,12 +245,22 @@ fn for_long_pages(set: &PdfSettings, pages: &[(usize, PageBoxes)]) -> Result MAX_PAGE_SIDE) { return Ok(None); } - let raised = (set.compatibility == Compatibility::Pdf15 && !set.standard.is_pdfx() && !set.long_pages_in_points) + let raised = (set.compatibility == Compatibility::Pdf15 && !set.standard.is_pdfx() && !long_pages_in_points(set)) .then(|| PdfSettings { compatibility: Compatibility::Pdf16, ..set.clone() }); + // PDF/A-2 limits page boundaries to 14,400 units (ISO 19005-2, 6.1.13), and PDF 1.4 has no + // `UserUnit`: a PDF/A file at PDF 1.4 is written as PDF 1.6, with the `UserUnit` whether or + // not `long_pages_in_points` is on. + let raised = raised.or_else(|| { + (set.standard == Standard::PdfA2b && set.compatibility == Compatibility::Pdf14).then(|| PdfSettings { + compatibility: Compatibility::Pdf16, + long_pages_in_points: false, + ..set.clone() + }) + }); // The writer's test for a whole number, on the `f32` it writes. let real = |side: f64| side > MAX_PDF14_REAL && (side as f32) as i32 as f32 != side as f32; if let Some((i, b)) = pages.iter().find(|(_, b)| real(b.media.width()) || real(b.media.height())) { - page_too_long(set, *i, b.media.width().max(b.media.height()))?; + page_too_long(raised.as_ref().unwrap_or(set), *i, b.media.width().max(b.media.height()))?; } Ok(raised) } diff --git a/crates/pdf/src/export/images.rs b/crates/pdf/src/export/images.rs index 390fcc3445..c377b9f7e4 100644 --- a/crates/pdf/src/export/images.rs +++ b/crates/pdf/src/export/images.rs @@ -165,6 +165,9 @@ impl Exporter<'_> { pub(super) fn masked_image(&mut self, im: &vectorcraft_doc::ImageObject, m: &vectorcraft_doc::OpacityMask, interpolate: bool) -> Option { let art = &m.art; let NodeKind::Image(mi) = &art.kind else { return None }; + // A color-masked image in the mask's art masks with the pixels it shows. + let shown = self.doc.shown_image(art, mi); + let mi = &*shown; let plain = art.opacity >= 1.0 && art.blend == BlendMode::Normal && art.extras().mask.is_none() && !art.appearance.effects.iter().any(|e| e.visible); if m.invert || !plain || (mi.xf, mi.width, mi.height) != (im.xf, im.width, im.height) { @@ -254,10 +257,20 @@ pub(super) fn png_8_bit(bytes: &[u8]) -> Option> { Some(png) } +/// Most pixels an image may have to be embedded: twice what the app reads (64 million), so every image +/// it holds is still written. +const MAX_EMBED_PIXELS: u64 = 1 << 27; + /// Image `blob` as it is: PNG, JPEG, GIF and WebP through the PDF writer (JPEG data unchanged), /// other formats decoded. Without `sixteen_bit` (a file before PDF 1.5), a PNG of 16 bits a /// sample is written at 8 bits ([`png_8_bit`]). pub(super) fn embed(blob: &vectorcraft_doc::ImageBlob, interpolate: bool, sixteen_bit: bool) -> Option { + // The header's size first: the writer's decoders allocate what it declares, and the encoded + // bytes of an image that is far larger than any the app reads may be a few kilobytes. + let size = image::ImageReader::new(std::io::Cursor::new(blob.bytes.as_slice())).with_guessed_format().ok()?.into_dimensions(); + if size.is_ok_and(|(w, h)| u64::from(w) * u64::from(h) > MAX_EMBED_PIXELS) { + return None; + } let bytes = blob.bytes.as_ref().clone(); let direct = match blob.mime.as_str() { "image/png" if !sixteen_bit && png_16_bit(&bytes) => png_8_bit(&bytes).and_then(|png| Image::from_png(png.into(), interpolate).ok()), @@ -281,6 +294,18 @@ mod tests { use vectorcraft_doc::{Document, ImageBlob, ImageObject}; use vectorcraft_geom::Affine; + #[test] + fn an_image_whose_header_declares_far_more_pixels_than_the_app_reads_is_left_out() { + // A real 8 × 8 PNG whose IHDR (width, height at 16..24) claims 65535 × 65535, with its CRC fixed. + let mut png = vec![]; + image::DynamicImage::ImageRgb8(image::RgbImage::new(8, 8)).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + png[16..24].copy_from_slice(&[0, 0, 0xFF, 0xFF, 0, 0, 0xFF, 0xFF]); + let crc = + !png[12..29].iter().fold(!0u32, |c, b| (0..8).fold(c ^ u32::from(*b), |c, _| if c & 1 == 1 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 })); + png[29..33].copy_from_slice(&crc.to_be_bytes()); + assert!(super::embed(&ImageBlob::png(png), false, true).is_none()); + } + #[test] fn colorized_image_caches_rejected_images() { let mut doc = Document::new(10.0, 10.0); diff --git a/crates/pdf/src/export/nodes.rs b/crates/pdf/src/export/nodes.rs index 760021b25a..f8fb792ec2 100644 --- a/crates/pdf/src/export/nodes.rs +++ b/crates/pdf/src/export/nodes.rs @@ -249,8 +249,9 @@ impl Exporter<'_> { self.shape(s, n, &bp, *rule, page); } NodeKind::Text(t) => self.text(s, n, t, page), - NodeKind::Image(im) => match n.extras().colorize.as_deref() { - Some(p @ Paint::Solid { .. }) if self.doc.image_blob(im).is_none_or(vectorcraft_doc::ImageBlob::takes_colorize) => { + NodeKind::Image(im) => match (n.extras().colorize.as_deref(), self.doc.shown_image(n, im)) { + (Some(p @ Paint::Solid { .. }), im) if self.doc.image_blob(&im).is_none_or(vectorcraft_doc::ImageBlob::takes_colorize) => { + let im = &*im; if writable(s, im.xf, Rect::new(0.0, 0.0, im.width.max(1).into(), im.height.max(1).into())) { if let Some(colorized) = self.colorized_image(im, p, !n.extras().pixelated) { self.image(s, im, Some(colorized), n.extras().pixelated); @@ -263,7 +264,7 @@ impl Exporter<'_> { self.warn(super::exporter::UNWRITABLE_IMAGE); } } - _ => self.image(s, im, alpha, n.extras().pixelated), + (_, im) => self.image(s, &im, alpha, n.extras().pixelated), }, NodeKind::SymbolInstance { symbol, xf } => { // Within the objects a frame may draw of symbol instances, as on screen: nested @@ -433,14 +434,19 @@ impl Exporter<'_> { /// Is `p` a paint PDF has no paint for when it paints a fill (`fill`) or a stroke, which /// [`Self::area`] draws as art: a pattern swatch or a gradient drawn as pixels /// ([`vectorcraft_color::GradientPaint::draws_as_pixels`]), but not a Perceptual one of spot - /// inks ([`Self::perceptual_spot`]), or a conic gradient that can't be a sweep shading (in - /// PDF/A, or with more than [`super::paint::MAX_SWEEP_STOPS`] stops)? + /// inks ([`Self::perceptual_spot`]), a conic gradient that can't be a sweep shading (in + /// PDF/A, or with more than [`super::paint::MAX_SWEEP_STOPS`] stops), a diamond gradient + /// (four linear gradients, [`Self::diamond`]), or a linear or radial gradient that repeats or + /// reflects (its stops repeated over the area, [`Self::padded`])? pub(super) fn area_paint(&self, p: &Paint, fill: bool) -> bool { match p { Paint::Pattern { pattern, .. } => self.doc.pattern(pattern).is_some(), Paint::Gradient(g) => { let sweep_unwritable = || !self.sweeps || g.gradient.expanded().nth(super::paint::MAX_SWEEP_STOPS).is_some(); - (g.draws_as_pixels(fill) && !self.perceptual_spot(g, fill)) || (g.gradient.kind == GradientKind::Conic && sweep_unwritable()) + (g.draws_as_pixels(fill) && !self.perceptual_spot(g, fill)) + || (g.gradient.kind == GradientKind::Conic && sweep_unwritable()) + || g.gradient.kind == GradientKind::Diamond + || (g.gradient.is_spread() && matches!(g.gradient.kind, GradientKind::Linear | GradientKind::Radial)) } _ => false, } @@ -448,9 +454,11 @@ impl Exporter<'_> { /// Paint the area `clip` (filled by `rule`; bounds `area`) with `p` at `transparency` (opacity, /// blend mode) when it is an [area paint](Self::area_paint) of a fill (`fill`) or a stroke: a - /// pattern's [tiling pattern](Self::tiling) (else its tile instances covering it), or an image - /// of a gradient drawn as pixels placed on `bounds` (the painted object's box, as on the - /// canvas), clipped to it. False (nothing drawn) for other paints. + /// pattern's [tiling pattern](Self::tiling) (else its tile instances covering it), a diamond + /// gradient's four linear gradients, a repeating or reflecting linear or radial gradient's + /// stops repeated over `area`, or an image of a gradient drawn as pixels, placed on + /// `bounds` (the painted object's box, as on the canvas), clipped to it. False (nothing drawn) + /// for other paints. #[allow(clippy::too_many_arguments)] pub(super) fn area( &mut self, @@ -498,7 +506,14 @@ impl Exporter<'_> { } } } - Paint::Gradient(g) => self.field_image(s, g, bounds, area, fill), + Paint::Gradient(g) => { + let pixels = g.draws_as_pixels(fill) && !self.perceptual_spot(g, fill); + // A linear or radial gradient that repeats or reflects is drawn by `padded`. + let drawn = !pixels && self.padded(s, g, bounds, area); + if !drawn && (pixels || g.gradient.kind != GradientKind::Diamond || !self.diamond(s, g, bounds, area)) { + self.field_image(s, g, bounds, area, fill); + } + } _ => {} } } diff --git a/crates/pdf/src/export/paint.rs b/crates/pdf/src/export/paint.rs index 15f3f46637..77815f93b3 100644 --- a/crates/pdf/src/export/paint.rs +++ b/crates/pdf/src/export/paint.rs @@ -236,6 +236,24 @@ impl Exporter<'_> { Paint::Solid { color: c, swatch, tint } => Some(self.solid(c, swatch.as_deref(), *tint).into()), Paint::Gradient(g) => { let geom = g.resolve(bounds); + // A linear or radial gradient that repeats or reflects, where it isn't an area + // paint ([`Self::padded`]): its stops repeated over `bounds`, padding past them. + if matches!(g.gradient.kind, GradientKind::Linear | GradientKind::Radial) && g.gradient.is_spread() { + let paint = match g.gradient.padded_over(&geom, bounds) { + Some(padded) => { + self.warn_capped(padded.capped); + padded_paint(g, padded) + } + // Levels over `bounds` that are not finite (a vector of no length): the + // stops repeated along the vector, padding past it. + None => { + self.warn_capped(true); + let gradient = g.gradient.unrolled().into_owned(); + Paint::Gradient(Box::new(vectorcraft_color::GradientPaint { gradient, ..(**g).clone() })) + } + }; + return self.paint_in(s, &paint, bounds, space); + } let spot = match g.gradient.kind { GradientKind::Freeform => None, _ => self.perceptual_spot_stops(&g.gradient).or_else(|| self.spot_stops(&g.gradient)), @@ -318,30 +336,41 @@ impl Exporter<'_> { } // A function-based shading (ISO 32000-1, 8.7.4.5.2) whose calculator function // turns the angle about the origin into the ramp, once around (0 to 360 - // degrees), carried onto the extent ellipse by its frame. + // degrees), carried onto the extent ellipse by its frame. Stops that repeat + // or reflect `n` times run over 360/`n` degrees, the function repeating or + // reflecting them past it. GradientKind::Conic => { let frame = geom.conic_frame(); if !writable(s, space * frame, Rect::new(-1.0, -1.0, 1.0, 1.0)) { return None; } + let (end_angle, spread_method) = match g.gradient.spread { + _ if !g.gradient.is_spread() => (360.0, SpreadMethod::Pad), + vectorcraft_color::GradientSpread::Reflect => (360.0 / g.gradient.repeat_count() as f32, SpreadMethod::Reflect), + _ => (360.0 / g.gradient.repeat_count() as f32, SpreadMethod::Repeat), + }; Some( SweepGradient { cx: 0.0, cy: 0.0, start_angle: 0.0, - end_angle: 360.0, + end_angle, transform: xf(space * frame), - spread_method: SpreadMethod::Pad, + spread_method, stops, anti_alias: false, } .into(), ) } - // Painted areas get an image of the field ([`Self::area`]); elsewhere (gradient - // slices) the average colour stands in. - GradientKind::Freeform => { - self.warn("freeform gradients are exported as their average colour"); + // Painted areas get an image of the field, or a diamond's four linear gradients + // ([`Self::area`]); elsewhere (gradient slices) the average color stands in. + GradientKind::Freeform | GradientKind::Diamond => { + self.warn(if g.gradient.kind == GradientKind::Diamond { + "diamond gradients in gradient slices are exported as their average color" + } else { + "freeform gradients are exported as their average colour" + }); let n = g.gradient.stops.len().max(1) as f32; let mut acc = [0.0f32; 3]; for s in &g.gradient.stops { @@ -434,7 +463,9 @@ impl Exporter<'_> { /// than an image? pub(super) fn perceptual_spot(&self, g: &vectorcraft_color::GradientPaint, fill: bool) -> bool { let gr = &g.gradient; - !gr.method.is_classic() + // Not one mixed around the hue wheel: its colors between two stops are not tints or + // mixes of the stops' inks, so it stays an image. + gr.method == vectorcraft_color::GradientMethod::Perceptual && gr.kind != GradientKind::Freeform && !(fill && gr.dither) && (self.one_spot_ink(gr).is_some() || self.device_n_inks_only(gr)) @@ -447,7 +478,7 @@ impl Exporter<'_> { /// other gradients, and for an ink too light for lightness to tell its tints apart, which /// [`Self::spot_stops`] then writes with the stops' own tints. fn perceptual_spot_stops(&mut self, g: &vectorcraft_color::Gradient) -> Option> { - if g.method.is_classic() { + if g.method != vectorcraft_color::GradientMethod::Perceptual { return None; } let ink = self.one_spot_ink(g)?; @@ -465,7 +496,7 @@ impl Exporter<'_> { let from_stops = g.gradient.kind != GradientKind::Freeform || !g.has_freeform_points(); if from_stops && self.has_spot_stop(&g.gradient) { self.warn( - "spot colors in gradients exported as images (freeform or dithered gradients, and Perceptual ones with RGB or Lab stops or too many stops) are written in process colors", + "spot colors in gradients exported as images (freeform or dithered gradients, ones mixed around the hue wheel, and Perceptual ones with RGB or Lab stops or too many stops) are written in process colors", ); } } @@ -476,10 +507,100 @@ impl Exporter<'_> { g.stops.iter().any(|s| s.swatch.as_deref().is_some_and(|n| doc.swatch(n).is_some_and(|w| w.spot))) } + /// Draw diamond gradient `g`, placed on `bounds`, over `area` (inside the current clip) as four + /// linear gradients, one for each quadrant of its frame, each equal to the diamond there (PDF + /// has no diamond shading; [`vectorcraft_color::GradientGeom::diamond_quadrants`]). The + /// quadrants overlap so no hairline shows between them, which needs opaque stops. False + /// (nothing drawn) for a diamond with translucent stops or without a frame, for one with a + /// quadrant whose shading or outline PDF can't hold, and for a Perceptual one of spot inks + /// whose ink curve has too many tints once its stops are repeated, which + /// [`Self::field_image`] draws instead. + pub(super) fn diamond(&mut self, s: &mut Surface, g: &vectorcraft_color::GradientPaint, bounds: Rect, area: Rect) -> bool { + if g.gradient.stops.iter().any(|st| st.opacity < 1.0) { + return false; + } + // A diamond that repeats or reflects: its stops repeated over the levels the area reaches + // from the center, then split into quadrants, each of which runs those levels. + let (diamond, geom, capped) = match g.gradient.padded_over(&g.resolve(bounds), area.abs()) { + Some(padded) => (padded.gradient, padded.geom, padded.capped), + None => (g.gradient.clone(), g.resolve(bounds), false), + }; + // A Perceptual one of spot inks whose ink curve no longer fits with its stops repeated. + if !diamond.method.is_classic() && !diamond.fits_ink_tints() { + return false; + } + let Some(quadrants) = geom.diamond_quadrants(area.abs()) else { return false }; + let gradient = vectorcraft_color::Gradient { kind: GradientKind::Linear, ..diamond }; + let mut drawn = Vec::with_capacity(4); + for (outline, geom) in quadrants { + let linear = Paint::Gradient(Box::new(vectorcraft_color::GradientPaint { gradient: gradient.clone(), geom: Some(geom), ..g.clone() })); + let quadrant = kurbo::BezPath::from_vec( + outline + .iter() + .enumerate() + .map(|(i, &p)| if i == 0 { kurbo::PathEl::MoveTo(p) } else { kurbo::PathEl::LineTo(p) }) + .chain([kurbo::PathEl::ClosePath]) + .collect(), + ); + let (Some(paint), Some(path)) = (self.paint(s, &linear, bounds), to_path(s, &quadrant)) else { return false }; + drawn.push((paint, path)); + } + self.warn("diamond gradients are exported as four linear gradients"); + self.warn_capped(capped); + for (paint, path) in drawn { + s.set_stroke(None); + s.set_fill(Some(krilla::paint::Fill { paint, opacity: krilla::num::NormalizedF32::ONE, rule: krilla::paint::FillRule::NonZero })); + s.draw_path(&path); + s.set_fill(None); + } + true + } + + /// Draw linear or radial gradient `g`, placed on `bounds`, that repeats or reflects, over + /// `area` (inside the current clip): PDF's axial and radial shadings pad past their ends, so + /// its stops are repeated as many times as the area needs + /// ([`vectorcraft_color::Gradient::padded_over`]). False (nothing drawn) for another gradient, + /// for one whose shading or area PDF can't hold, and for a Perceptual one of spot inks whose + /// ink curve has too many tints once repeated, which [`Self::field_image`] draws instead. + pub(super) fn padded(&mut self, s: &mut Surface, g: &vectorcraft_color::GradientPaint, bounds: Rect, area: Rect) -> bool { + if !matches!(g.gradient.kind, GradientKind::Linear | GradientKind::Radial) { + return false; + } + let Some(padded) = g.gradient.padded_over(&g.resolve(bounds), area.abs()) else { return false }; + // A Perceptual gradient of spot inks whose ink curve no longer fits once its stops are + // repeated is an image, as one with too many stops is. + if !g.gradient.method.is_classic() && !padded.gradient.fits_ink_tints() { + return false; + } + let capped = padded.capped; + let paint = padded_paint(g, padded); + let (Some(paint), Some(path)) = (self.paint(s, &paint, bounds), to_path(s, &kurbo::Shape::to_path(&area.abs(), 0.1))) else { + return false; + }; + self.warn_capped(capped); + s.set_stroke(None); + s.set_fill(Some(krilla::paint::Fill { paint, opacity: krilla::num::NormalizedF32::ONE, rule: krilla::paint::FillRule::NonZero })); + s.draw_path(&path); + s.set_fill(None); + true + } + + /// Warn when a gradient that repeats or reflects needed more runs of its stops than were + /// written. + fn warn_capped(&mut self, capped: bool) { + if capped { + self.warn(format!( + "gradients that repeat or reflect are exported with at most {} runs of their stops (at most {} stops); they pad past those", + vectorcraft_color::gradient::MAX_SPREAD_RUNS, + vectorcraft_color::gradient::MAX_SPREAD_STOPS + )); + } + } + /// Draw gradient `g`, placed on `bounds`, as an image over `area`, sampled at the document's /// raster effects resolution where it is drawn (`area` as the current transform sizes it, so /// scaled type gets its pixels too): a freeform gradient's colour field (at most - /// [`MAX_FIELD_PX`] a side), or a linear, radial or conic gradient (at most [`MAX_GRADIENT_PX`] a side), + /// [`MAX_FIELD_PX`] a side), or a linear, radial, conic or diamond gradient (at most [`MAX_GRADIENT_PX`] a side), /// with dither's noise when it paints a fill (`fill`). A linear or radial gradient whose stops /// are all CMYK and not linked to a spot swatch is a CMYK image, unless its Perceptual curve /// has too many stops; any other is an RGB image. @@ -504,7 +625,9 @@ impl Exporter<'_> { let field = freeform.then(|| g.freeform_on(b).model_field(spread_scale(b))); let cmyk_doc = self.doc.color_mode == vectorcraft_doc::ColorMode::Cmyk; if g.gradient.kind == GradientKind::Conic { - self.warn("conic gradients drawn as pixels (dithered fills, and Perceptual ones other than spot ink shadings), in a PDF/A file or with more than 97 stops are exported as images"); + self.warn("conic gradients drawn as pixels (dithered fills, ones mixed around the hue wheel, and Perceptual ones other than spot ink shadings), in a PDF/A file or with more than 97 stops are exported as images"); + } else if g.gradient.kind == GradientKind::Diamond { + self.warn("diamond gradients drawn as pixels (dithered fills, ones mixed around the hue wheel, and Perceptual ones other than spot ink shadings), with translucent stops or without an extent are exported as images"); } else if !freeform { self.warn("linear and radial gradients drawn as pixels are exported as images"); } @@ -549,6 +672,12 @@ impl Exporter<'_> { } } +/// `g` written as `padded` gives it: its stops repeated, placed there. +fn padded_paint(g: &vectorcraft_color::GradientPaint, padded: vectorcraft_color::gradient::Padded) -> Paint { + let geom = padded.geom; + Paint::Gradient(Box::new(vectorcraft_color::GradientPaint { gradient: padded.gradient, geom: Some(geom), angle: geom.angle_deg(), ..g.clone() })) +} + /// Is `c` paper white: no ink in CMYK or gray, white in RGB or Lab? fn paper(c: &Color) -> bool { match *c { diff --git a/crates/pdf/src/export/writer.rs b/crates/pdf/src/export/writer.rs index 027025ad2c..9f6d9d6906 100644 --- a/crates/pdf/src/export/writer.rs +++ b/crates/pdf/src/export/writer.rs @@ -26,6 +26,10 @@ pub(crate) struct Writer { images: Vec<(String, Image)>, } +/// What [`Writer::finish`] gives: the file, the warnings of its drawing, and the notes on the +/// output intent asked for ([`crate::ExportReport::setting_notes`]). +pub(crate) type Finished = (Vec, Vec, Vec); + /// One page as [`Writer::page`] draws it: the art placed in a drawing space ([`Self::place`]), /// which [`Self::view`] maps onto the page. pub(crate) struct Sheet<'a> { @@ -252,10 +256,11 @@ impl Writer { } /// The finished file (with the output intent and Trapped entries, and checked against its - /// standard) and the warnings of its drawing. PDF/X-1a spot colours keep their CMYK + /// standard), the warnings of its drawing, and the notes on the output intent asked for + /// ([`crate::ExportReport::setting_notes`]). PDF/X-1a spot colours keep their CMYK /// alternates. When the writer couldn't decode one of the images, its key is added to /// `left_out` ([`leaving_out_undecodable`]) and the writer's error is returned. - pub(crate) fn finish(mut self, left_out: &mut HashSet, display_doc_title: bool) -> Result<(Vec, Vec), PdfError> { + pub(crate) fn finish(mut self, left_out: &mut HashSet, display_doc_title: bool) -> Result { let images = std::mem::take(&mut self.images); let mut bytes = self.pdf.finish().map_err(|e| { if let write::WriteError::Serialization(k) = &e @@ -270,10 +275,9 @@ impl Writer { } let lab = !self.lab_spots.is_empty() && !self.out.standard.cmyk_only(); let bytes = if lab { crate::lab_spot::lab_alternates(bytes, &self.lab_spots) } else { bytes }; - let (bytes, more) = self.out.write_catalog(bytes, display_doc_title)?; - self.warnings.extend(more); + let (bytes, settings) = self.out.write_catalog(bytes, display_doc_title)?; self.warnings.extend(self.rgb_in_cmyk.warning()); - Ok((crate::pdfx::finish(bytes, self.out.standard, self.pdf13)?, self.warnings)) + Ok((crate::pdfx::finish(bytes, self.out.standard, self.pdf13)?, self.warnings, settings)) } } diff --git a/crates/pdf/src/file_info.rs b/crates/pdf/src/file_info.rs index 983a7dcea7..1cb0a45273 100644 --- a/crates/pdf/src/file_info.rs +++ b/crates/pdf/src/file_info.rs @@ -24,6 +24,8 @@ const PDF: &str = "http://ns.adobe.com/pdf/1.3/"; // brand-ok: the XMP namespace /// The File Info fields a PDF gives, each `None` when the file gives none (or only blank text). #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct FileInfo { + /// XMP `dc:title` (its `x-default` item, else its first), else Info `Title`. + pub title: Option, /// XMP `dc:creator` (its names joined with ", "), else Info `Author`. pub author: Option, /// XMP `dc:description` (its `x-default` item, else its first), else Info `Subject`. @@ -53,6 +55,7 @@ pub(crate) fn file_info_in(pdf: &Pdf) -> FileInfo { let mut f = packet(pdf).and_then(|p| xmp(&p)).unwrap_or_default(); let info = pdf.metadata(); let text = |b: &Option>| b.as_deref().map(text_string).map(|s| s.trim().to_string()).filter(|s| !s.is_empty()); + f.title = f.title.or_else(|| text(&info.title)); f.author = f.author.or_else(|| text(&info.author)); f.description = f.description.or_else(|| text(&info.subject)); f.keywords = f.keywords.or_else(|| text(&info.keywords).map(|k| split(&k)).filter(|k| !k.is_empty())); @@ -90,6 +93,7 @@ fn xmp(packet: &[u8]) -> Option { let creators = get(DC, "creator"); let subjects = get(DC, "subject"); Some(FileInfo { + title: first(DC, "title"), author: (!creators.is_empty()).then(|| creators.join(", ")), description: first(DC, "description"), keywords: if subjects.is_empty() { first(PDF, "Keywords").map(|k| split(&k)).filter(|k| !k.is_empty()) } else { Some(subjects) }, diff --git a/crates/pdf/src/import.rs b/crates/pdf/src/import.rs index ffc185a575..d978680d67 100644 --- a/crates/pdf/src/import.rs +++ b/crates/pdf/src/import.rs @@ -35,6 +35,7 @@ mod builder; mod cid; mod device; mod entry; +mod reshaped; mod state; #[cfg(test)] @@ -42,8 +43,8 @@ pub(crate) use cid::{CidText, font_chars, identify_glyph, unify_radical}; #[cfg(any(test, feature = "read-count"))] pub use entry::imports_of; pub use entry::{ - INVISIBLE_TEXT_NOTE, OFF_ARTBOARD_NOTE, OUTLINED_TEXT_NOTE, PAST_PAGE_NOTE, UNMATCHED_GLYPHS_NOTE, UNNAMED_CHARACTERS_NOTE, holds_outlines, - import, import_opened, import_with_report, is_glyph_outlines, is_outlines_note, + INVISIBLE_TEXT_NOTE, OFF_ARTBOARD_NOTE, OUTLINED_TEXT_NOTE, PAST_PAGE_NOTE, RESHAPED_TEXT_NOTE, UNMATCHED_GLYPHS_NOTE, UNNAMED_CHARACTERS_NOTE, + holds_outlines, import, import_opened, import_with_report, is_glyph_outlines, is_outlines_note, }; #[cfg(test)] pub(crate) use entry::{TEST_MAX_OBJECTS, import_with_reader_options, read}; diff --git a/crates/pdf/src/import/actual_text.rs b/crates/pdf/src/import/actual_text.rs index d6d18a7566..aec147f99e 100644 --- a/crates/pdf/src/import/actual_text.rs +++ b/crates/pdf/src/import/actual_text.rs @@ -11,6 +11,9 @@ pub(super) struct ActualText { depth: usize, owner: Option, pending: Option, + /// The owner's replacement is empty: its content has no text, so its glyphs stay art + /// ([`Self::textless`], #6971). + empty: bool, } impl ActualText { @@ -22,6 +25,7 @@ impl ActualText { if self.owner == Some(self.depth) { self.owner = None; self.pending = None; + self.empty = false; } self.depth = self.depth.saturating_sub(1); } @@ -30,6 +34,12 @@ impl ActualText { self.owner.is_some() } + /// Inside a span whose replacement text is empty: the glyphs there are no text, but they + /// still draw, so they come in as outlines rather than as type with no characters (#6971). + pub(super) fn textless(&self) -> bool { + self.owner.is_some() && self.empty + } + pub(super) fn set(&mut self, bytes: &[u8]) -> bool { if self.active() { return true; @@ -39,8 +49,10 @@ impl ActualText { if self.depth == 0 || self.depth > 128 || bytes.len() > 64 * 1024 { return false; } + let text = crate::import_scan::text_string(bytes); self.owner = Some(self.depth); - self.pending = Some(crate::import_scan::text_string(bytes)); + self.empty = text.is_empty(); + self.pending = Some(text); true } } @@ -92,4 +104,35 @@ impl Builder<'_> { } true } + + /// A Type 3 glyph under an active ActualText span. + pub(super) fn actual_type3_glyph(&mut self, key: u128, at: Placement, look: Look, opacity: f32, advance: f64) -> bool { + self.flush_glyphs(); + self.flush_type3(); + if let (Some(stroke), Some(line)) = (&look.stroke, &mut self.text) + && look.fill.is_none() + && line.stroke_actual(key, at, stroke.clone(), look.overprint_stroke) + { + return true; + } + let pending = self.actual.pending.take(); + let content = match pending.as_deref() { + Some(text) if !text.is_empty() => TextContent::Actual(text), + _ => TextContent::Pen, + }; + let place = |line: &mut TextLine| line.push_content(&look, at, opacity, advance, content); + if !self.text.as_mut().is_some_and(place) { + self.flush_text(); + let mut line = TextLine::new(at, opacity); + if !place(&mut line) { + self.actual.pending = pending; + return false; + } + self.text = Some(line); + } + if let Some(line) = &mut self.text { + line.has_type3 = true; + } + true + } } diff --git a/crates/pdf/src/import/builder.rs b/crates/pdf/src/import/builder.rs index 61acbfc8ea..c1be8fba84 100644 --- a/crates/pdf/src/import/builder.rs +++ b/crates/pdf/src/import/builder.rs @@ -1,9 +1,10 @@ use super::cid::{CidText, FontInfo, comparable, font_chars, identify_glyph, matching_face, replacement, unify_radical}; use super::entry::{ - MAX_NESTED, OVERPRINT_UNREAD, OVERPRINT_ZERO_MODE, PATTERN_REUSE, TEXT_OUTLINES, TOO_MANY_OBJECTS, UNMATCHED_GLYPHS_NOTE, + MAX_NESTED, OVERPRINT_UNREAD, OVERPRINT_ZERO_MODE, PATTERN_REUSE, RESHAPED_TEXT_NOTE, TEXT_OUTLINES, TOO_MANY_OBJECTS, UNMATCHED_GLYPHS_NOTE, UNNAMED_CHARACTERS_NOTE, max_objects, }; -use super::state::{Builder, Frame, FrameKind, Saved, bounds, grouped, line_width, mean_scale, paints, round3, stroke_layer}; +use super::reshaped; +use super::state::{Builder, Frame, FrameKind, GlyphRun, Saved, bounds, grouped, line_width, mean_scale, paints, round3, stroke_layer}; use super::{ Affine, Appearance, AppearanceItem, Arc, BezPath, BfString, BlendMode, CacheKey, Color, Colors, Families, FillLayer, FillRule, FunctionBudget, FunctionPaint, HashMap, HashSet, ImageBlob, ImageObject, Knockout, Look, MaskSpec, MaskType, Native, Node, NodeId, NodeKind, OpacityMask, Paint, @@ -11,6 +12,18 @@ use super::{ Upright, Walked, clipped, contains, fold_stop_opacity, function_paint, gradient_shape, is_rectangle, luminance, mask_spec, shading_gradient, }; +fn is_colour_face(face: &vectorcraft_text::FontFace) -> bool { + use skrifa::Tag; + use skrifa::raw::TableProvider; + let Ok(font) = skrifa::FontRef::new(face.file_data()) else { + return false; + }; + font.colr().is_ok() + || font.table_data(Tag::new(b"SVG ")).is_some() + || font.table_data(Tag::new(b"CBDT")).is_some() + || font.table_data(Tag::new(b"sbix")).is_some() +} + impl<'p> Builder<'p> { pub(super) fn new(next: u64, colors: Colors<'p>, text_as: TextAs, route: bool) -> Self { Self { @@ -21,11 +34,14 @@ impl<'p> Builder<'p> { blend: BlendMode::Normal, page: Rect::ZERO, glyphs: None, + type3_run: None, text: None, + text_glyphs: vec![], text_as, actual: Default::default(), images: HashMap::new(), image_keys: HashMap::new(), + raster_scales: HashMap::new(), cmyk_keys: HashSet::new(), separation_paints: HashMap::new(), opaque: HashSet::new(), @@ -99,7 +115,9 @@ impl<'p> Builder<'p> { self.root_groups.clear(); self.blend = BlendMode::Normal; self.glyphs = None; + self.type3_run = None; self.text = None; + self.text_glyphs.clear(); self.mask = None; self.masked.clear(); self.marked.clear(); @@ -217,13 +235,48 @@ impl<'p> Builder<'p> { } } - /// Finish the open glyph runs and the art drawn through the current soft mask. + /// Finish the open glyph runs, type 3 runs and the art drawn through the current soft mask. pub(super) fn flush(&mut self) { self.flush_glyphs(); + self.flush_type3(); self.flush_text(); self.flush_masked(); } + /// Finish the open Type 3 font text run as a named group ``. + pub(super) fn flush_type3(&mut self) { + if let Some(run) = self.type3_run.take() + && !run.nodes.is_empty() + { + let Some(left) = self.objects_left.checked_sub(1) else { + self.warn(super::entry::TOO_MANY_OBJECTS); + return; + }; + self.objects_left = left; + let mut g = Node::group(self.id(), run.nodes); + g.name = Some("".to_string()); + self.emit(Arc::new(g), run.group); + } + } + + /// Add nodes from an interpreted Type 3 glyph to the current Type 3 run. + pub(super) fn push_type3_nodes(&mut self, nodes: Vec>) { + if nodes.is_empty() { + return; + } + let group = self.current_group(); + if let Some(run) = &mut self.type3_run { + if run.group != group { + self.flush_type3(); + self.type3_run = Some(super::state::Type3Run { nodes, group }); + } else { + run.nodes.extend(nodes); + } + } else { + self.type3_run = Some(super::state::Type3Run { nodes, group }); + } + } + /// The art drawn through the graphics state's soft mask so far, as one masked object. fn flush_masked(&mut self) { if self.masked.is_empty() { @@ -375,18 +428,56 @@ impl<'p> Builder<'p> { } pub(super) fn flush_text(&mut self) { - let Some(mut line) = self.text.take() else { return }; + if self.end_text() { + self.flush_glyphs(); + } + } + + /// Finish the open line of type. `true`: it was kept as outlines instead ([`reshaped`]), which + /// are left open as the glyph run for an outline drawn next to join. + pub(super) fn end_text(&mut self) -> bool { + let glyphs = std::mem::take(&mut self.text_glyphs); + let Some(mut line) = self.text.take() else { return false }; let held = std::mem::take(&mut line.held); + // Type the file names itself (ActualText) is in reading order as it stands. + let checked = !glyphs.is_empty() && line.mapped() && !line.has_type3; + let mut outlined = false; if let Some((t, opacity, facts)) = line.finish() { - let mut n = Node::new(self.id(), NodeKind::Text(Box::new(t))); - n.opacity = opacity; - self.lines.insert(n.id, facts); - self.push_node(n); + if checked && reshaped::reshapes(&t.plain_text()) && !reshaped::draws_as(&t, &facts.ink) { + outlined = true; + for g in glyphs { + let same = self.glyphs.as_ref().is_some_and(|r| { + r.paint == g.paint + && r.opacity == g.opacity + && r.overprint == g.overprint + && r.stroke.is_some() == g.stroke.is_some() + && r.stroke.as_ref().map(|s| s.line_width) == g.stroke.as_ref().map(|s| s.line_width) + && (r.scale - g.scale).abs() < 1e-9 + }); + match &mut self.glyphs { + Some(r) if same => r.path.extend(g.path.iter()), + _ => { + self.flush_glyphs(); + self.glyphs = Some(g); + } + } + } + self.warn(RESHAPED_TEXT_NOTE); + } else { + let mut n = Node::new(self.id(), NodeKind::Text(Box::new(t))); + n.opacity = opacity; + self.lines.insert(n.id, facts); + self.push_node(n); + } + } + if outlined && !held.is_empty() { + self.flush_glyphs(); } // The strokes of its glyphs' outlines, right after it ([`import_lines`] makes them its stroke). for n in held { self.push_node(n); } + outlined } /// A stroke of the outline of the glyph just drawn, in the glyph's own paint, while every glyph @@ -467,23 +558,26 @@ impl<'p> Builder<'p> { /// Read a soft mask, pattern cell or type 3 glyph (`read`) on its own: its art, in the /// coordinates `page` has. `None` when nested too deeply. - fn nested(&mut self, page: Rect, read: impl FnOnce(&mut Self)) -> Option>> { + pub(super) fn nested(&mut self, page: Rect, blend: BlendMode, read: impl FnOnce(&mut Self)) -> Option>> { if self.nested >= MAX_NESTED { return None; } + let outer_type3 = self.type3_run.take(); self.flush(); let saved = Saved { stack: std::mem::replace(&mut self.stack, vec![Frame::new(FrameKind::Root)]), root_groups: std::mem::take(&mut self.root_groups), - blend: std::mem::replace(&mut self.blend, BlendMode::Normal), + blend: std::mem::replace(&mut self.blend, blend), mask: self.mask.take(), page: std::mem::replace(&mut self.page, page), + type3_run: outer_type3, }; self.nested += 1; read(self); let art = self.close_frames(); self.nested -= 1; - (self.stack, self.root_groups, self.blend, self.mask, self.page) = (saved.stack, saved.root_groups, saved.blend, saved.mask, saved.page); + (self.stack, self.root_groups, self.blend, self.mask, self.page, self.type3_run) = + (saved.stack, saved.root_groups, saved.blend, saved.mask, saved.page, saved.type3_run); Some(art) } @@ -495,7 +589,7 @@ impl<'p> Builder<'p> { } let page = self.page; let saved = std::mem::replace(&mut self.white_images, m.mask_type() == MaskType::Alpha); - let art = self.nested(page, |b| m.interpret(b)); + let art = self.nested(page, BlendMode::Normal, |b| m.interpret(b)); self.white_images = saved; let spec = match art { Some(art) => { @@ -559,7 +653,7 @@ impl<'p> Builder<'p> { // A swatch is shared with uses outside an alpha mask, and pattern paints keep their // colours there: its images are read as they are. let white = std::mem::take(&mut self.white_images); - let art = self.nested(Rect::ZERO, |b| { + let art = self.nested(Rect::ZERO, BlendMode::Normal, |b| { // A cell whose content can't be decoded is empty. let _ = t.interpret(b, Affine::IDENTITY, stroke); }); @@ -736,8 +830,149 @@ impl<'p> Builder<'p> { n } + /// Glyph `o` of the open line of type, placed by `m` and drawn with `drawn` (its paint, and its + /// stroke when it is stroked), as the outline it is kept as if the line is + /// ([`Self::end_text`]). Nothing for a glyph that shows nothing. + fn keep_glyph( + &mut self, + o: &craft_pdf::interpret::font::OutlineGlyph, + m: Affine, + drawn: Option<(Paint, Option)>, + opacity: f32, + scale: f64, + overprint: bool, + ) { + let Some((paint, stroke)) = drawn else { return }; + let mut path = o.outline(); + if path.elements().is_empty() { + return; + } + path.apply_affine(m); + self.text_glyphs.push(GlyphRun { path, paint, opacity, stroke, scale, overprint }); + } + + fn type3_font_name(&mut self, key: u128) -> FontInfo { + if let Some(n) = self.font_names.get(&key) { + return n.clone(); + } + let name = self.fonts.get(&key).map(|f| f.name.clone()); + let ps = name.as_deref().map(|n| match n.split_once('+') { + Some((tag, rest)) if tag.len() == 6 && tag.chars().all(|c| c.is_ascii_uppercase()) => rest.to_string(), + _ => n.to_string(), + }); + let installed = ps.as_deref().and_then(|ps| vectorcraft_text::FontDb::global().find_postscript(ps)); + let n = match (installed, name) { + (Some(face), _) => FontInfo { family: face.family.clone(), style: face.style.clone(), face: Some(face) }, + (None, Some(name)) => { + let families = self.families.get_or_insert_with(Families::available); + let (family, style, found) = families.resolve(&name, None, false); + if !found && !family.is_empty() && !self.missing_fonts.contains(&family) { + self.missing_fonts.push(family.clone()); + } + let face = vectorcraft_text::FontDb::global().face(&family, &style); + FontInfo { family, style, face } + } + (None, None) => { + let d = vectorcraft_doc::CharStyle::default(); + FontInfo { family: d.font_family, style: d.font_style, face: None } + } + }; + self.font_names.insert(key, n.clone()); + n + } + + /// Type 3 glyph as live type: added to the line being gathered if it has a ToUnicode mapping. + pub(super) fn type_type3_glyph( + &mut self, + t3: &craft_pdf::interpret::font::Type3Glyph<'_>, + m: Affine, + scale: f64, + paint: Option<&craft_pdf::interpret::Paint<'_>>, + stroke: Option<&StrokeProps>, + overprint: bool, + ) -> bool { + if self.text_as != TextAs::Text || self.nested > 0 { + return false; + } + let t3_key = craft_pdf::interpret::CacheKey::cache_key(t3); + let Some(&(font_key, has_to_unicode)) = self.scan.type3_cache_map.get(&t3_key) else { + return false; + }; + let (is_type3, to_unicode, is_colour) = match self.fonts.get(&font_key) { + Some(f) => (f.is_type3, has_to_unicode || f.to_unicode, f.is_colour), + None => (true, has_to_unicode, false), + }; + let authored = self.actual.active(); + if !is_type3 || (!to_unicode && !authored) || is_colour { + return false; + } + let unicode = t3.as_unicode().filter(|u| !super::cid::replacement(u)); + if !authored && unicode.is_none() { + return false; + } + let text: String = match unicode { + Some(BfString::Char(c)) => c.to_string(), + Some(BfString::String(s)) => s, + None => String::new(), + }; + let Some(at) = Placement::of(m) else { return false }; + if !authored && (text.is_empty() || text.chars().any(|c| c.is_control())) { + return false; + } + let width = t3.advance_width().filter(|w| w.is_finite()); + let advance = width.map_or(at.size * 0.5, |w| w as f64 / 1000.0 * at.size * at.h_scale / 100.0); + let info = self.type3_font_name(font_key); + if info.face.as_ref().is_some_and(|f| is_colour_face(f)) { + return false; + } + let (paint, opacity) = match paint { + Some(p) => { + let (paint, opacity) = self.paint(p, stroke.is_some(), self.walked(true)); + (Some(paint), opacity) + } + None => (None, 1.0), + }; + let stroke = stroke.zip(paint.clone()).map(|(p, paint)| (paint, line_width(p, scale))); + let look = Look { + font: font_key, + family: info.family, + style: info.style, + version: None, + size: at.size, + h_scale: at.h_scale, + overprint_fill: stroke.is_none() && overprint, + overprint_stroke: stroke.is_some() && overprint, + fill: if stroke.is_none() { paint } else { None }, + stroke, + }; + if authored { + return self.actual_type3_glyph(font_key, at, look, opacity, advance); + } + let text = visual_glyph_text(text); + let place = |line: &mut TextLine| line.push(&look, at, opacity, advance, &text); + self.flush_glyphs(); + self.flush_type3(); + if let (Some(s), Some(line)) = (&look.stroke, &mut self.text) + && look.fill.is_none() + && line.stroke_last(font_key, at, s.clone(), overprint) + { + return true; + } + if !self.text.as_mut().is_some_and(place) { + self.flush_text(); + let mut line = TextLine::new(at, opacity); + place(&mut line); + self.text = Some(line); + } + if let Some(line) = &mut self.text { + line.has_type3 = true; + } + true + } + /// Glyph `o` as type: added to the line being gathered (or starting one). `false`: it keeps - /// its outline (no Unicode text, mirrored, or not type mode). No `paint`: invisible text, + /// its outline (no Unicode text, mirrored, not type mode, or in a span whose ActualText is + /// empty). No `paint`: invisible text, /// type with neither fill nor stroke. pub(super) fn type_glyph( &mut self, @@ -748,7 +983,7 @@ impl<'p> Builder<'p> { stroke: Option<&StrokeProps>, overprint: bool, ) -> bool { - if self.text_as != TextAs::Text || self.nested > 0 { + if self.text_as != TextAs::Text || self.nested > 0 || self.actual.textless() { return false; } let authored = self.actual.active(); @@ -793,8 +1028,11 @@ impl<'p> Builder<'p> { return false; } let width = o.advance_width().filter(|w| w.is_finite()); - // Set vertically (WMode 1): no horizontal advance. - let upright = width.is_some_and(|w| w.abs() <= 1.0); + // Set vertically (WMode 1): no horizontal advance. Not in a font the file says is written + // horizontally: there a glyph without an advance is a mark over the letter before it (a + // vowel sign, an anusvara), which stays on its line (#5235). + let horizontal = self.fonts.get(&key).is_some_and(|f| f.vertical.is_none()); + let upright = !horizontal && width.is_some_and(|w| w.abs() <= 1.0); let mut info = self.font_name(key, o); // A font the file doesn't carry is drawn with a stand-in: its glyphs can't tell which // style of the installed family it is, so the name decides. @@ -840,6 +1078,8 @@ impl<'p> Builder<'p> { } None => (None, 1.0), }; + // What the glyph is drawn with as an outline, should its line be kept so. + let drawn = paint.clone().map(|p| (p, stroke.cloned())); let stroke = stroke.zip(paint.clone()).map(|(p, paint)| (paint, line_width(p, scale))); let look = Look { font: key, @@ -878,6 +1118,7 @@ impl<'p> Builder<'p> { && look.fill.is_none() && line.stroke_last(key, at, s.clone(), overprint) { + self.keep_glyph(o, m, drawn, opacity, scale, overprint); return true; } if !self.text.as_mut().is_some_and(place) { @@ -888,6 +1129,9 @@ impl<'p> Builder<'p> { } // Its ink: a stroke the file draws as outlines of the glyphs is told by it. let mut ink = o.outline(); + if top.is_none() { + self.keep_glyph(o, m, drawn, opacity, scale, overprint); + } if let Some(line) = &mut self.text && !ink.elements().is_empty() { diff --git a/crates/pdf/src/import/device.rs b/crates/pdf/src/import/device.rs index 2fb6bb9c80..3fcefd7b8e 100644 --- a/crates/pdf/src/import/device.rs +++ b/crates/pdf/src/import/device.rs @@ -33,6 +33,7 @@ impl<'a> Device<'a> for Builder<'_> { fn draw_path(&mut self, path: &BezPath, transform: Affine, paint: &craft_pdf::interpret::Paint<'a>, draw_mode: &PathDrawMode) { self.flush_glyphs(); + self.flush_type3(); let walked = self.walked(false); if self.hold_glyph_stroke(path, transform, paint, draw_mode, walked) { return; @@ -174,7 +175,7 @@ impl<'a> Device<'a> for Builder<'_> { GlyphDrawMode::Invisible => { let typed = match glyph { Glyph::Outline(o) => self.type_glyph(o, transform * glyph_transform, mean_scale(transform), None, None, false), - Glyph::Type3(_) => false, + Glyph::Type3(t3) => self.type_type3_glyph(t3, transform * glyph_transform, mean_scale(transform), None, None, false), }; if !typed { self.warn(INVISIBLE_TEXT_NOTE); @@ -186,12 +187,14 @@ impl<'a> Device<'a> for Builder<'_> { }; match glyph { Glyph::Outline(o) => { + self.flush_type3(); let scale = mean_scale(transform); let overprint = self.glyph_overprint(stroke.is_some()); if self.type_glyph(o, transform * glyph_transform, scale, Some(paint), stroke.as_ref(), overprint) { return; } - self.flush_text(); + // A line kept as outlines leaves them open: this glyph joins them. + self.end_text(); let mut bp = o.outline(); bp.apply_affine(transform * glyph_transform); let (paint, opacity) = self.paint(paint, stroke.is_some(), self.walked(true)); @@ -215,16 +218,26 @@ impl<'a> Device<'a> for Builder<'_> { if self.nested >= MAX_NESTED { return; } - self.flush(); - self.nested += 1; - t3.interpret(self, transform, glyph_transform, paint); - self.nested -= 1; + let scale = mean_scale(transform); + let overprint = self.glyph_overprint(stroke.is_some()); + if self.type_type3_glyph(t3, transform * glyph_transform, scale, Some(paint), stroke.as_ref(), overprint) { + return; + } + self.flush_glyphs(); + self.flush_text(); + let art = self.nested(self.page, self.blend, |b| { + t3.interpret(b, transform, glyph_transform, paint); + }); + if let Some(nodes) = art { + self.push_type3_nodes(nodes); + } } } } fn draw_image(&mut self, image: Image<'a, '_>, transform: Affine) { self.flush_glyphs(); + self.flush_type3(); self.flush_text(); match image { Image::Raster(r) => { @@ -285,6 +298,12 @@ impl<'a> Device<'a> for Builder<'_> { self.add_image(key, || Some((ImageBlob::new("image/jpeg", bytes), w, h)), transform); return; } + // Drawn before: the image is there already, so its pixels aren't converted again. + if let Some(sf) = self.raster_scales.get(&key).copied().filter(|_| self.image_keys.contains_key(&key)) { + let xf = transform * Affine::scale_non_uniform(sf.0 as f64, sf.1 as f64); + self.add_image(key, || None, xf); + return; + } let mut decoded: Option = None; r.with_rgba( |img, alpha| { @@ -303,6 +322,7 @@ impl<'a> Device<'a> for Builder<'_> { self.warn("an image could not be decoded and was skipped"); return; }; + self.raster_scales.insert(key, sf); let xf = transform * Affine::scale_non_uniform(sf.0 as f64, sf.1 as f64); self.add_image(key, || rgba_png(rgba, w, h).map(|png| (ImageBlob::new("image/png", png), w, h)), xf); } diff --git a/crates/pdf/src/import/entry.rs b/crates/pdf/src/import/entry.rs index 38f22689a8..8503b4fb20 100644 --- a/crates/pdf/src/import/entry.rs +++ b/crates/pdf/src/import/entry.rs @@ -171,14 +171,22 @@ pub const INVISIBLE_TEXT_NOTE: &str = "invisible text (such as a scanned page's /// Warning: glyphs that differ from the installed font of their name were kept as outlines. pub const UNMATCHED_GLYPHS_NOTE: &str = "text whose glyphs differ from the installed font of the same name was kept as outlines"; +/// Warning: type in a script whose letters reorder and join (Indic scripts) that, set again from +/// its characters, wouldn't draw the glyphs where the file drew them was kept as outlines (#5235). +pub const RESHAPED_TEXT_NOTE: &str = + "text that would not look as it does in the file if set as type (a script whose letters join) was kept as outlines"; + /// The end of the warning that glyphs whose characters the file doesn't name were kept as /// outlines, after "text in" and the font's name. pub const UNNAMED_CHARACTERS_NOTE: &str = "whose characters the file doesn't name (U+FFFD) was kept as outlines"; /// Is `note` one of the warnings that glyphs were kept as outlines ([`OUTLINED_TEXT_NOTE`], -/// [`UNMATCHED_GLYPHS_NOTE`], [`UNNAMED_CHARACTERS_NOTE`])? +/// [`UNMATCHED_GLYPHS_NOTE`], [`RESHAPED_TEXT_NOTE`], [`UNNAMED_CHARACTERS_NOTE`])? pub fn is_outlines_note(note: &str) -> bool { - note == OUTLINED_TEXT_NOTE || note == UNMATCHED_GLYPHS_NOTE || note.starts_with("text in ") && note.ends_with(UNNAMED_CHARACTERS_NOTE) + note == OUTLINED_TEXT_NOTE + || note == UNMATCHED_GLYPHS_NOTE + || note == RESHAPED_TEXT_NOTE + || note.starts_with("text in ") && note.ends_with(UNNAMED_CHARACTERS_NOTE) } /// Is `n` glyphs kept as outlines (a path the import names ``)? diff --git a/crates/pdf/src/import/reshaped.rs b/crates/pdf/src/import/reshaped.rs new file mode 100644 index 0000000000..77d70dfc1c --- /dev/null +++ b/crates/pdf/src/import/reshaped.rs @@ -0,0 +1,53 @@ +//! Type in a script whose letters reorder and join as they are set (#5235). A PDF draws such text +//! as glyphs already shaped: a vowel sign before the consonant it follows in reading order, a +//! conjunct as one glyph that the file may not name, a mark placed over its base. Read glyph by +//! glyph, the characters don't always make the text that was set, and type made from them draws +//! other glyphs in other places. A line of such type is therefore set again and compared with what +//! the file drew; one that would look different keeps the file's glyphs as outlines. + +use kurbo::{Rect, Shape}; +use vectorcraft_doc::TextObject; + +/// Does `text` have a character of a script whose letters reorder and join into conjuncts: the +/// Brahmic scripts of U+0900 to U+0DFF (Devanagari, Bengali, Gurmukhi, Gujarati, Oriya, Tamil, +/// Telugu, Kannada, Malayalam, Sinhala)? +pub(super) fn reshapes(text: &str) -> bool { + text.chars().any(|c| ('\u{0900}'..='\u{0DFF}').contains(&c)) +} + +/// Would type `t` draw its glyphs where the file drew them (`ink`: each glyph's ink box in +/// document space)? As many glyphs with ink, each within 3 % of the type's size of one of the +/// file's. +pub(super) fn draws_as(t: &TextObject, ink: &[Rect]) -> bool { + let laid = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + let mut set: Vec = + laid.glyphs.iter().filter(|g| !g.outline.elements().is_empty()).map(|g| (t.xf * g.outline.clone()).bounding_box()).collect(); + if set.len() != ink.len() { + return false; + } + let size = t.runs.iter().map(|r| r.style.size).fold(0.0, f64::max); + let tol = size * 0.03; + if !tol.is_finite() || set.iter().chain(ink).any(|r| !(r.x0.is_finite() && r.y0.is_finite() && r.x1.is_finite() && r.y1.is_finite())) { + return false; + } + set.sort_by(|a, b| a.x0.total_cmp(&b.x0)); + let mut used = vec![false; set.len()]; + // Each of the file's glyphs takes one the type draws in its place: looked for among those + // whose left edge is as near. + ink.iter().all(|r| { + let from = set.partition_point(|s| s.x0 < r.x0 - tol); + let found = set + .iter() + .zip(used.iter_mut()) + .skip(from) + .take_while(|(s, _)| s.x0 <= r.x0 + tol) + .find(|(s, used)| !**used && (s.y0 - r.y0).abs() <= tol && (s.x1 - r.x1).abs() <= tol && (s.y1 - r.y1).abs() <= tol); + match found { + Some((_, used)) => { + *used = true; + true + } + None => false, + } + }) +} diff --git a/crates/pdf/src/import/state.rs b/crates/pdf/src/import/state.rs index 93a84ae688..0470d641e2 100644 --- a/crates/pdf/src/import/state.rs +++ b/crates/pdf/src/import/state.rs @@ -62,6 +62,13 @@ pub(super) struct GlyphRun { /// swatch made for it. pub(super) type PatternReadings = (u32, Vec<(Vec, String)>); +/// A run of Type 3 glyph graphics preserved inside a named group. +#[derive(Clone, Debug)] +pub(super) struct Type3Run { + pub(super) nodes: Vec>, + pub(super) group: Option, +} + /// Builder state a nested interpretation (soft mask, pattern cell) starts afresh and gives back. pub(super) struct Saved { pub(super) stack: Vec
\\u0061pp.z \\u{61};\n"); + let members: Vec<&str> = r.members.iter().map(|m| m.name.as_str()).collect(); + assert_eq!(members, ["app.activeDocument"]); + assert_eq!(problems(&r), [("newerSyntax", Some(1), Some("\\u{61}"))]); + assert!(tokens("var x = {this.#\\u0061b};").contains(&(T::Other, "#\\u0061b"))); } #[test] @@ -1585,7 +1739,7 @@ fn include_lines_share_the_folders_of_the_include_path_before_them() { let limits = Limits::default(); let mut acc = report::Acc::new(&limits); let declared = analyze::declarations(&src, &mut acc); - let scan = analyze::scan(&src, &declared, None, std::rc::Rc::from([]), &analyze::Known::default(), &mut acc); + let scan = analyze::scan(&src, &declared, &[], None, std::rc::Rc::from([]), &analyze::Known::default(), &mut acc); let (first, rest) = scan.includes.split_first().unwrap(); assert_eq!((first.paths.len(), rest.len()), (64, 999)); assert!(rest.iter().all(|i| std::rc::Rc::ptr_eq(&i.paths, &first.paths)), "one list of folders, not a copy for each line"); diff --git a/crates/svg/src/css.rs b/crates/svg/src/css.rs index a60b7d4045..f7e067aa30 100644 --- a/crates/svg/src/css.rs +++ b/crates/svg/src/css.rs @@ -7,7 +7,7 @@ use std::collections::{HashMap, HashSet}; use serde::{Deserialize, Serialize}; -use vectorcraft_color::{BlendMode, Color, GradientKind, GradientPaint, Paint}; +use vectorcraft_color::{BlendMode, Color, GradientGeom, GradientKind, GradientPaint, Paint}; use vectorcraft_doc::{AppearanceItem, CharStyle, Document, Justify, LineCap, LiveShape, Node, NodeId, NodeKind, StrokeAlign, StrokeLayer, TextKind}; use vectorcraft_effects::RasterFx; use vectorcraft_geom::shapes::{self, CornerKind}; @@ -177,11 +177,18 @@ pub(crate) fn type_props(st: &CharStyle, len: &dyn Fn(f64) -> String) -> Props { .iter() .map(|t| match t.strip_prefix('-') { Some(off) => (off, 0), - None => (t.as_str(), 1), + // `tag=N` picks the font's alternate N: CSS takes the number as the feature's value. + None => { + let on = t.strip_prefix('+').unwrap_or(t); + match on.split_once('=').map(|(tag, n)| (tag, n.parse::())) { + Some((tag, Ok(n))) => (tag, n), + _ => (on, 1), + } + } }) // A feature tag is four letters or digits: anything else could end the CSS string. .filter(|(tag, _)| tag.len() == 4 && tag.bytes().all(|b| b.is_ascii_alphanumeric())) - .map(|(tag, on)| format!("\"{tag}\" {on}")) + .map(|(tag, value)| format!("\"{tag}\" {value}")) .collect(); // Proportional Metrics: `palt` (SVG writes vertical type as outlines). if st.proportional_metrics { @@ -199,6 +206,14 @@ pub(crate) fn type_props(st: &CharStyle, len: &dyn Fn(f64) -> String) -> Props { p } +/// The decimals, at least `least` and at most 12, for numbers that place a period of length +/// `period` repeated out to `reach` (in the same units): each period then rounds by at most +/// 10^-decimals, and over the `reach / period` periods that adds up to at most a hundredth of one. +fn period_decimals(period: f64, reach: f64, least: u8) -> u8 { + let d = (100.0 * reach / (period * period)).log10().ceil(); + if d.is_nan() || d == f64::INFINITY { 12 } else { d.clamp(f64::from(least), 12.0) as u8 } +} + /// A colour at `opacity`: `#rrggbb` when opaque, else `rgba()`. fn color_css(c: &Color, opacity: f32) -> String { if opacity >= 1.0 { @@ -240,13 +255,22 @@ impl CssUnits { /// `points` in these units (`0` without a unit). fn len(self, points: f64) -> String { - let per_point = match self { + self.len_to(points, 3) + } + + /// One point in these units. + fn per_point(self) -> f64 { + match self { CssUnits::Px | CssUnits::Pt => 1.0, CssUnits::Mm => 25.4 / 72.0, CssUnits::Cm => 2.54 / 72.0, CssUnits::In => 1.0 / 72.0, - }; - match fmt_num(points * per_point, 3) { + } + } + + /// [`Self::len`] with `decimals` decimals. + fn len_to(self, points: f64, decimals: u8) -> String { + match fmt_num(points * self.per_point(), decimals) { zero if zero == "0" => zero, v => format!("{v}{}", self.name()), } @@ -555,13 +579,41 @@ impl Rules<'_> { } } - /// A linear, radial or conic gradient over `b` at `opacity`, with the stops SVG export writes - /// (midpoints as stops of their own). `None` for freeform gradients. + /// A linear, radial, conic or diamond gradient over `b` at `opacity`, with the stops SVG export + /// writes (midpoints as stops of their own). `None` for freeform gradients. fn gradient(&mut self, g: &GradientPaint, b: Rect, opacity: f32) -> Option { let geom = g.resolve(b); - let stops = |pos: &dyn Fn(f32) -> f64| { + // A linear, radial or diamond gradient that repeats or reflects: a repeating gradient of + // one cycle (a run, or a run and its mirror) over that cycle's placement + // (https://www.w3.org/TR/css-images-3/#repeating-gradients). A conic one: its stops + // repeated around the turn. + let kind = g.gradient.kind; + let unrolled = g.gradient.unrolled(); + let (gradient, geom, repeating) = match g.gradient.cycle() { + Some((cycle, runs)) if kind != GradientKind::Conic => { + // CSS radials start at their center: the cycle is scaled about it. + let centered = GradientGeom { focal: None, ..geom }; + let cycle_geom = centered.period(kind, g.gradient.repeat_count()).levels_scaled(kind, f64::from(runs)); + let geom = GradientGeom { focal: geom.focal, ..cycle_geom }; + (std::borrow::Cow::Owned(cycle), geom, "repeating-") + } + _ => (unrolled, geom, ""), + }; + // A repeating gradient's period is the span from its first stop to its last, repeated + // across the box (from 0% to `reach`%): its positions get at least four decimals, and more + // when the box holds so many periods that their rounding would add up to more than a + // hundredth of one ([`period_decimals`]). + let span = gradient.expanded().next().zip(gradient.expanded().last()).map(|(a, z)| (a.0, z.0)); + let decimals = |pos: &dyn Fn(f32) -> f64, reach: f64| match span { + Some((a, z)) if !repeating.is_empty() => { + let (p0, p1) = (pos(a) * 100.0, pos(z) * 100.0); + period_decimals((p1 - p0).abs(), p0.abs().max((reach - p0).abs()), 4) + } + _ => 2, + }; + let stops = |pos: &dyn Fn(f32) -> f64, decimals: u8| { let stops: Vec = - g.gradient.expanded().map(|(t, c, o, _)| format!("{} {}%", color_css(&c, o * opacity), fmt_num(pos(t) * 100.0, 2))).collect(); + gradient.expanded().map(|(t, c, o, _)| format!("{} {}%", color_css(&c, o * opacity), fmt_num(pos(t) * 100.0, decimals))).collect(); stops.join(", ") }; match g.gradient.kind { @@ -578,20 +630,40 @@ impl Rules<'_> { let line = (b.width() * dir.x).abs() + (b.height() * dir.y).abs(); let from = (geom.start - b.center()).dot(dir); let pos = |t: f32| if line > 1e-9 { (from + t as f64 * length) / line + 0.5 } else { t as f64 }; - Some(format!("linear-gradient({}deg, {})", fmt_num(angle, 2), stops(&pos))) + Some(format!("{repeating}linear-gradient({}deg, {})", fmt_num(angle, 2), stops(&pos, decimals(&pos, 100.0)))) } - GradientKind::Radial => { + // CSS has no diamond gradient: the ellipse through the square's corners stands in. + GradientKind::Radial | GradientKind::Diamond => { let r = (geom.end - geom.start).hypot(); - if geom.focal.is_some() { + if g.gradient.kind == GradientKind::Diamond { + self.warn("diamond gradients are written as radial gradients through their corners"); + } else if geom.focal.is_some() { self.warn("radial gradients start at their centre (an off-centre focal point is left out)"); } + // The positions are a share of the radius, and the box reaches out to its farthest + // corner. A repeating gradient's period scales with its radius, so the radius gets + // the decimals that keep the periods in place out to that corner too. + let units = self.opts.units; + let small = r * geom.aspect.abs().min(1.0); + let far = [(b.x0, b.y0), (b.x1, b.y0), (b.x0, b.y1), (b.x1, b.y1)] + .into_iter() + .map(|(x, y)| (Point::new(x, y) - geom.start).hypot()) + .fold(0.0, f64::max); + let reach = if small > 1e-12 { 100.0 * far / small } else { 0.0 }; + let pos = |t: f32| t as f64; + let len = match span { + Some((a, z)) if !repeating.is_empty() => { + period_decimals(small * f64::from(z - a).abs() * units.per_point(), far * units.per_point(), 3) + } + _ => 3, + }; let shape = if (geom.aspect - 1.0).abs() < 1e-9 { - format!("circle {}", self.len(r)) + format!("circle {}", units.len_to(r, len)) } else { - format!("ellipse {} {}", self.len(r), self.len(r * geom.aspect)) + format!("ellipse {} {}", units.len_to(r, len), units.len_to(r * geom.aspect, len)) }; let at = format!("at {} {}", self.len(geom.start.x - b.x0), self.len(geom.start.y - b.y0)); - Some(format!("radial-gradient({shape} {at}, {})", stops(&|t| t as f64))) + Some(format!("{repeating}radial-gradient({shape} {at}, {})", stops(&pos, decimals(&pos, reach)))) } GradientKind::Conic => { // CSS sweeps clockwise from the `from` angle, 0deg straight up @@ -604,7 +676,7 @@ impl Rules<'_> { if (geom.aspect.abs() - 1.0).abs() > 1e-9 && geom.unit_frame().is_some() { self.warn("conic gradients are written circular (an elliptical sweep is left out)"); } - let mut stops: Vec<(f32, Color, f32)> = g.gradient.expanded().map(|(t, c, o, _)| (t, c, o)).collect(); + let mut stops: Vec<(f32, Color, f32)> = gradient.expanded().map(|(t, c, o, _)| (t, c, o)).collect(); if geom.is_mirrored() { stops.reverse(); stops.iter_mut().for_each(|s| s.0 = 1.0 - s.0); diff --git a/crates/svg/src/export.rs b/crates/svg/src/export.rs index eed8ecd335..05107bfb65 100644 --- a/crates/svg/src/export.rs +++ b/crates/svg/src/export.rs @@ -26,6 +26,7 @@ mod nodes; mod output; mod paint; mod text; +mod variables; use nodes::SymbolDef; pub(crate) use nodes::{MASK_FLAGS, Reuse}; @@ -102,6 +103,7 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix: region_boxes: None, art_reach: HashMap::new(), warnings: vec![], + setting_notes: vec![], id_prefix, linked: Vec::new(), instance_xf: Affine::IDENTITY, @@ -117,8 +119,10 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix: layer_nest: 0, non_latin1_names: false, foreign_ns: BTreeMap::new(), + bound: HashMap::new(), }; w.assign_name_ids(); + w.assign_bound_ids(); for layer in &doc.layers { w.count_colorized_images(layer); } @@ -135,9 +139,11 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix: w.line("
"); } + // Include Variable Data, once the body has written the bound objects' ids. + let variables = w.variable_sets(); // XML names cannot use character references. Preserve names that Latin-1 cannot encode. let encoding = if opts.encoding == Encoding::Latin1 && w.non_latin1_names { - w.warn("Unicode data attribute names require UTF-8; SVG was written in UTF-8"); + w.note_setting("Unicode data attribute names require UTF-8; SVG was written in UTF-8"); Encoding::Utf8 } else { opts.encoding @@ -188,7 +194,7 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix: // An artboard exported on its own is named after it (#3544), else after the document. // A name that is blank once the characters XML can't hold are dropped falls back too. let board = opts.artboard.filter(|_| opts.artboard_title).and_then(|i| doc.artboards.get(i)).map(|a| xml_text(&a.name)); - let title = board.filter(|n| !n.trim().is_empty()).unwrap_or_else(|| xml_text(&doc.title)); + let title = board.filter(|n| !n.trim().is_empty()).unwrap_or_else(|| xml_text(doc.info_title())); if !title.is_empty() { out.push_str(&w.indent(1)); out.push_str(&format!("{title}{nl}")); @@ -207,6 +213,7 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix: out.push_str(&w.indent(1)); out.push_str(&format!(""})), + ( + "command.batch", + json!({"label": "B", "commands": [{"command": "object.move", "params": {"dx": 1, "n": {"a": [1, 2.5, {"b": null}]}}}]}), + ), + (STOP_STEP, json!({"message": "Paint it", "allowContinue": false})), + ("object.group", json!({})), + ("object.group", json!([])), + ("object.group", Value::Null), + ]; + for (command, params) in steps { + for first in [true, false] { + let before = if first { vec![] } else { vec![("object.group".to_string(), json!({}))] }; + let mut set = ActionSet::new("Set", vec![Action::new("A", before), Action::new("B", vec![("object.group".into(), json!({}))])]); + let len = files::write_set(&set).len(); + set.actions[0].steps.push((command.to_string(), params.clone())); + let added = files::write_set(&set).len() - len; + let counted = files::step_bytes(command, ¶ms); + let first_bytes = if first { files::FIRST_STEP_BYTES } else { 0 }; + assert_eq!(counted + first_bytes, added, "{command} {params}, first: {first}"); + } + } + let mut set = ActionSet::new("Set", vec![Action::new("A", vec![("object.group".into(), json!({"n": "日本"})); 3])]); + let len = files::write_set(&set).len(); + set.actions[0].excluded_steps = BTreeSet::from([0, 2]); + assert_eq!(files::write_set(&set).len(), len + 2 * files::EXCLUDED_BYTES); + } + + /// The params of `object.move` by 1 as the journal keeps them, which a recording records. + fn recorded_move(app: &mut VectorcraftApp) -> Value { + app.run("object.move", json!({"dx": 1, "dy": 0})).unwrap(); + let moved = app.session.journal.last().unwrap().1.clone(); + app.run("edit.undo", json!({})).unwrap(); + moved + } + + /// An ordinary command recorded as the 10,001st step of an action does not run: the document, + /// the journal and the undo history stay as they were, the recording goes on, and Stop + /// Playing/Recording leaves a set that Load Actions… reads. This holds for Begin Recording's new + /// action and for New Action's recording into an action with steps of its own. + #[test] + fn recorded_commands_keep_an_action_at_10_000_steps() { + for new_action in [false, true] { + let (mut app, x) = app_with_three_moves(); + let moved = recorded_move(&mut app); + let filler = ("object.group".to_string(), json!({})); + if new_action { + app.run(NEW_ACTION, json!({"set": 0, "name": "Long"})).unwrap(); + app.ui.action_sets[0].actions[1].steps = vec![filler; files::MAX_ACTION_STEPS - 1]; + } else { + app.run(START_RECORDING, json!({})).unwrap(); + for _ in 1..files::MAX_ACTION_STEPS { + app.session.journal.push(filler.clone()); + } + } + app.run("object.move", moved.clone()).unwrap(); + assert_eq!(x(&app), 1.0, "the 10,000th step runs"); + let (journal, undo) = (app.session.journal.len(), undo_steps(&app)); + let steps = "the action already has 10,000 steps"; + assert_eq!(app.run("object.move", moved.clone()).unwrap_err(), steps, "new action: {new_action}"); + assert_eq!((x(&app), app.session.journal.len(), undo_steps(&app)), (1.0, journal, undo), "nothing ran"); + assert_eq!(app.ui.status, steps); + assert!(app.ui.recording.is_some(), "the recording goes on"); + assert!(app.run("effect.list", json!({})).is_ok(), "a command that is not recorded still runs"); + let find = |select: bool| json!({"minWidth": 0, "select": select}); + assert_eq!(app.run("document.find", find(true)).unwrap_err(), steps, "Find Objects that selects is recorded"); + assert!(app.run("document.find", find(false)).is_ok()); + let batch = json!({"commands": [{"command": "object.move", "params": moved.clone()}]}); + assert_eq!(app.run("command.batch", batch).unwrap_err(), steps, "a batch is recorded"); + assert_eq!(x(&app), 1.0); + assert_eq!(app.session.journal.len(), journal); + app.run(STOP_RECORDING, json!({})).unwrap(); + assert_eq!(app.ui.action_sets[0].actions[1].steps.len(), files::MAX_ACTION_STEPS); + assert_eq!(app.ui.action_sets[0].actions[1].steps.last(), Some(&("object.move".to_string(), moved))); + let saved = files::write_set(&app.ui.action_sets[0]); + assert_eq!(files::read_set(&saved, "Test").unwrap().actions[1].steps.len(), files::MAX_ACTION_STEPS, "and loads again"); + } + } + + /// An ordinary command whose step would give the set of the action it is recorded into a file + /// larger than 8 MiB does not run, and one that makes the file exactly 8 MiB does. + #[test] + fn recorded_commands_keep_an_action_set_file_within_8_mib() { + let (mut app, x) = app_with_three_moves(); + let moved = recorded_move(&mut app); + let pad = |n: usize| ("object.move".to_string(), json!({"dx": 1, "dy": 0, "pad": "x".repeat(n)})); + app.ui.action_sets[0].actions[0].steps = vec![pad(0)]; + let room = files::MAX_SET_FILE - files::write_set(&app.ui.action_sets[0]).len(); + let added = files::step_bytes("object.move", &moved); + app.ui.action_sets[0].actions[0].steps = vec![pad(room - added)]; + let into = app.ui.action_sets[0].actions[0].id; + app.run(START_RECORDING, json!({})).unwrap(); + app.ui.recording_into = Some(into); + app.run("object.move", moved.clone()).unwrap(); + assert_eq!(x(&app), 1.0, "the step that fills the file runs"); + let (journal, undo) = (app.session.journal.len(), undo_steps(&app)); + let size = "the action set would be larger than 8 MiB"; + assert_eq!(app.run("object.move", moved).unwrap_err(), size); + assert_eq!((x(&app), app.session.journal.len(), undo_steps(&app)), (1.0, journal, undo), "nothing ran"); + assert!(app.ui.recording.is_some(), "the recording goes on"); + app.ui.status.clear(); + app.run(STOP_RECORDING, json!({})).unwrap(); + assert_eq!(app.ui.status, "", "Stop keeps every recorded step"); + let saved = files::write_set(&app.ui.action_sets[0]); + assert_eq!(saved.len(), files::MAX_SET_FILE); + assert_eq!(files::read_set(&saved, "Test").unwrap().actions[0].steps.len(), 2, "and loads again"); + } + + /// A command whose step fits by its params but not with the values it adds to its step as it + /// runs (Scale's Scale Strokes & Effects and Scale Corners) keeps its edit, the status bar names + /// the limit, the next recorded command does not run, and Stop Playing/Recording leaves the step + /// out. + #[test] + fn a_recorded_command_whose_noted_values_do_not_fit_is_left_out() { + let (mut app, x) = app_with_three_moves(); + let scaled = json!({"sx": 200}); + app.run("object.scale", scaled.clone()).unwrap(); + let noted = app.session.journal.last().unwrap().1.clone(); + app.run("edit.undo", json!({})).unwrap(); + assert!(files::step_bytes("object.scale", ¬ed) > files::step_bytes("object.scale", &scaled), "Scale notes values: {noted}"); + let pad = |n: usize| ("object.move".to_string(), json!({"dx": 1, "dy": 0, "pad": "x".repeat(n)})); + app.ui.action_sets[0].actions[0].steps = vec![pad(0)]; + let room = files::MAX_SET_FILE - files::write_set(&app.ui.action_sets[0]).len(); + // Room for the step as given, not for the step as recorded. + app.ui.action_sets[0].actions[0].steps = vec![pad(room - files::step_bytes("object.scale", &scaled))]; + let into = app.ui.action_sets[0].actions[0].id; + app.run(START_RECORDING, json!({})).unwrap(); + app.ui.recording_into = Some(into); + let size = "the action set would be larger than 8 MiB"; + app.run("object.scale", scaled).unwrap(); + assert_eq!(app.ui.status, size); + let scaled_x = x(&app); + assert_ne!(scaled_x, 0.0, "the scale stayed"); + assert_eq!(app.run("object.move", json!({"dx": 1, "dy": 0})).unwrap_err(), size, "no later command runs"); + assert_eq!(x(&app), scaled_x); + assert!(app.ui.recording.is_some(), "the recording goes on"); + app.run(STOP_RECORDING, json!({})).unwrap(); + assert_eq!(app.ui.action_sets[0].actions[0].steps.len(), 1, "the scale's step is left out"); + assert!(files::read_set(&files::write_set(&app.ui.action_sets[0]), "Test").is_ok()); + } + + /// A script that moves the selection twice. + const TWO_MOVES: &str = "vc.run('object.move', {dx: 1, dy: 0}); vc.run('object.move', {dx: 1, dy: 0});"; + + /// Runs `source` to its end: in one call (`frames` false, a run with nobody to ask), or a frame + /// at a time, as the app does. + fn run_script(app: &mut VectorcraftApp, source: &str, frames: bool) { + app.session.script_frames = frames; + app.run("script.run", json!({"source": source, "name": "t.js"})).unwrap(); + for _ in 0..10_000 { + if !app.session.script_running() { + return; + } + crate::script_runs::poll(app); + } + panic!("the script did not end"); + } + + /// Begin Recording with `filler` steps already recorded. + fn recording_with(app: &mut VectorcraftApp, filler: usize) { + app.run(START_RECORDING, json!({})).unwrap(); + for _ in 0..filler { + app.session.journal.push(("object.group".to_string(), json!({}))); + } + } + + /// A script whose commands take a recording past 10,000 steps keeps its edit and the whole + /// journal, the status bar names the limit as the run ends, the next recorded command does not + /// run, and Stop Playing/Recording keeps the 10,000 steps that fit. One that fills the action + /// exactly names no limit. + #[test] + fn script_run_checks_recording_step_limit_on_completion() { + let steps = "the action already has 10,000 steps"; + for frames in [false, true] { + let (mut app, x) = app_with_three_moves(); + recording_with(&mut app, files::MAX_ACTION_STEPS - 1); + app.ui.status.clear(); + run_script(&mut app, TWO_MOVES, frames); + assert_eq!(x(&app), 2.0, "frames {frames}: the script's edit stays"); + let start = recording_start(&app).unwrap(); + assert_eq!(app.session.journal.len() - start, files::MAX_ACTION_STEPS + 1, "frames {frames}: the journal keeps every step"); + assert_eq!(app.ui.status, steps, "frames {frames}: the status bar names the limit now"); + assert!(app.ui.recording.is_some(), "the recording goes on"); + assert_eq!(app.run("object.move", json!({"dx": 1, "dy": 0})).unwrap_err(), steps, "no later command runs"); + assert_eq!(x(&app), 2.0); + app.run(STOP_RECORDING, json!({})).unwrap(); + let recorded = app.ui.action_sets[0].actions.last().unwrap(); + assert_eq!(recorded.steps.len(), files::MAX_ACTION_STEPS); + assert_eq!(recorded.steps.last().map(|(c, _)| c.as_str()), Some("object.move"), "the first move fits"); + let saved = files::write_set(&app.ui.action_sets[0]); + assert_eq!(files::read_set(&saved, "Test").unwrap().actions[1].steps.len(), files::MAX_ACTION_STEPS, "and loads again"); + + let (mut app, _) = app_with_three_moves(); + recording_with(&mut app, files::MAX_ACTION_STEPS - 2); + app.ui.status.clear(); + run_script(&mut app, TWO_MOVES, frames); + let ran = if frames { "Ran t.js" } else { "" }; + assert_eq!(app.ui.status, ran, "frames {frames}: 10,000 steps fit"); + } + } + + /// A script whose commands give the recording's set a file larger than 8 MiB keeps its edit, + /// the status bar names the limit as the run ends, and Stop Playing/Recording keeps the steps + /// that fit in a set that Load Actions… reads. One that fills the file exactly names no limit. + #[test] + fn script_run_checks_recording_byte_limit_on_completion() { + let size = "the action set would be larger than 8 MiB"; + for frames in [false, true] { + for spare in [0, 1] { + let (mut app, x) = app_with_three_moves(); + // The two steps as an action keeps them. + let before = app.session.journal.len(); + run_script(&mut app, TWO_MOVES, false); + let both: usize = app.session.journal_for_action(before).iter().map(|(c, p)| files::step_bytes(c, p)).sum(); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(x(&app), 0.0); + let pad = |n: usize| ("object.move".to_string(), json!({"dx": 1, "dy": 0, "pad": "x".repeat(n)})); + app.ui.action_sets[0].actions[0].steps = vec![pad(0)]; + let room = files::MAX_SET_FILE - files::write_set(&app.ui.action_sets[0]).len(); + // Room for both moves, or for one move and all but a byte of the other. + app.ui.action_sets[0].actions[0].steps = vec![pad(room - both + 1 - spare)]; + let into = app.ui.action_sets[0].actions[0].id; + app.run(START_RECORDING, json!({})).unwrap(); + app.ui.recording_into = Some(into); + app.ui.status.clear(); + run_script(&mut app, TWO_MOVES, frames); + assert_eq!(x(&app), 2.0, "frames {frames}: the script's edit stays"); + let what = format!("frames {frames}, spare {spare}"); + if spare == 1 { + assert_eq!(app.ui.status, if frames { "Ran t.js" } else { "" }, "{what}: the file is exactly 8 MiB"); + continue; + } + assert_eq!(app.ui.status, size, "{what}: the status bar names the limit now"); + assert_eq!(app.session.journal.since(recording_start(&app).unwrap()).len(), 2, "the journal keeps both moves"); + assert_eq!(app.run("object.move", json!({"dx": 1, "dy": 0})).unwrap_err(), size, "no later command runs"); + app.run(STOP_RECORDING, json!({})).unwrap(); + assert_eq!(app.ui.action_sets[0].actions[0].steps.len(), 2, "{what}: the first move fits"); + let saved = files::write_set(&app.ui.action_sets[0]); + assert!(saved.len() <= files::MAX_SET_FILE); + assert!(files::read_set(&saved, "Test").is_ok()); + } + } + } + + /// Presses, drags and releases the active tool from `from` to `to`, as the canvas hands its + /// results on ([`crate::canvas::apply_requests`]). + fn tool_drag(app: &mut VectorcraftApp, from: (f64, f64), to: (f64, f64)) { + use vectorcraft_tools::{PointerEvent, PointerKind}; + let view = app.view_info(); + for (kind, (x, y)) in [(PointerKind::Down, from), (PointerKind::Drag, to), (PointerKind::Up, to)] { + let r = app.session.pointer(&PointerEvent::new(kind, x, y), view); + crate::canvas::apply_requests(app, r); + } + } + + /// A drag with the Selection tool (a committed preview) or the Rectangle tool (a command the + /// tool runs) that takes a recording past 10,000 steps keeps its edit and the journal, the + /// status bar names the limit as the tool ends, and Stop Playing/Recording keeps the 10,000 + /// steps that fit. One that fills the action exactly names no limit. + #[test] + fn tool_commit_checks_recording_step_limit() { + let steps = "the action already has 10,000 steps"; + for tool in ["selection", "rectangle"] { + for filler in [files::MAX_ACTION_STEPS, files::MAX_ACTION_STEPS - 1] { + let (mut app, _) = app_with_three_moves(); + app.select_tool(tool); + recording_with(&mut app, filler); + app.ui.status.clear(); + let (journal, art) = (app.session.journal.len(), app.session.active().unwrap().doc.art_bounds()); + tool_drag(&mut app, (20.0, 20.0), (60.0, 50.0)); + assert_eq!(app.session.journal.len(), journal + 1, "{tool}: the tool journals one step"); + assert_ne!(app.session.active().unwrap().doc.art_bounds(), art, "{tool}: the edit stays"); + if filler < files::MAX_ACTION_STEPS { + assert_eq!(app.ui.status, "", "{tool}: 10,000 steps fit"); + continue; + } + assert_eq!(app.ui.status, steps, "{tool}: the status bar names the limit now"); + assert!(app.ui.recording.is_some(), "the recording goes on"); + app.run(STOP_RECORDING, json!({})).unwrap(); + assert_eq!(app.ui.action_sets[0].actions.last().unwrap().steps.len(), files::MAX_ACTION_STEPS); + } + } + } + + /// A tool's edit whose step gives the recording's set a file larger than 8 MiB keeps its edit, + /// the status bar names the limit as the tool ends, and Stop Playing/Recording leaves the step + /// out of a set that Load Actions… reads. + #[test] + fn tool_commit_checks_recording_byte_limit() { + let size = "the action set would be larger than 8 MiB"; + for tool in ["selection", "rectangle"] { + let (mut app, _) = app_with_three_moves(); + app.select_tool(tool); + app.run(START_RECORDING, json!({})).unwrap(); + let pad = |n: usize| ("object.move".to_string(), json!({"dx": 1, "dy": 0, "pad": "x".repeat(n)})); + app.ui.action_sets[0].actions[0].steps = vec![pad(0)]; + let room = files::MAX_SET_FILE - files::write_set(&app.ui.action_sets[0]).len(); + app.ui.action_sets[0].actions[0].steps = vec![pad(room)]; + app.ui.recording_into = Some(app.ui.action_sets[0].actions[0].id); + app.ui.status.clear(); + let art = app.session.active().unwrap().doc.art_bounds(); + tool_drag(&mut app, (20.0, 20.0), (60.0, 50.0)); + assert_ne!(app.session.active().unwrap().doc.art_bounds(), art, "{tool}: the edit stays"); + assert_eq!(app.ui.status, size, "{tool}: the status bar names the limit now"); + assert_eq!(app.session.journal.since(recording_start(&app).unwrap()).len(), 1, "{tool}: the journal keeps the step"); + app.run(STOP_RECORDING, json!({})).unwrap(); + assert_eq!(app.ui.action_sets[0].actions[0].steps.len(), 1, "{tool}: the step is left out"); + assert!(files::read_set(&files::write_set(&app.ui.action_sets[0]), "Test").is_ok()); + } + } + + /// A step that reaches the journal outside a command, as a panel's or a dialog's commit does, is + /// checked on the app's next frame. A journal rewrite that makes a checked step larger is + /// checked again, and a frame with no new step does not name the limit again. + #[test] + fn a_journal_rewrite_or_a_direct_commit_is_checked_on_the_next_frame() { + let size = "the action set would be larger than 8 MiB"; + let (mut app, _) = app_with_three_moves(); + let small = ("object.move".to_string(), json!({"dx": 1, "dy": 0})); + let pad = |n: usize| ("object.move".to_string(), json!({"dx": 1, "dy": 0, "pad": "x".repeat(n)})); + app.ui.action_sets[0].actions[0].steps = vec![pad(0)]; + let room = files::MAX_SET_FILE - files::write_set(&app.ui.action_sets[0]).len(); + app.ui.action_sets[0].actions[0].steps = vec![pad(room - files::step_bytes(&small.0, &small.1))]; + let into = app.ui.action_sets[0].actions[0].id; + app.run(START_RECORDING, json!({})).unwrap(); + app.ui.recording_into = Some(into); + let ctx = egui::Context::default(); + let frame = |app: &mut VectorcraftApp| { + app.begin_host_iteration(); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| app.tick(ui.ctx())); + out.textures_delta.clear(); + }; + app.session.journal.push(small); + app.ui.status.clear(); + frame(&mut app); + assert_eq!(app.ui.status, "", "a step that fills the file exactly"); + let start = recording_start(&app).unwrap(); + app.session.journal.replace(start, pad(1)); + frame(&mut app); + assert_eq!(app.ui.status, size, "the rewritten step no longer fits"); + app.ui.status.clear(); + frame(&mut app); + assert_eq!(app.ui.status, "", "named once"); + app.run(STOP_RECORDING, json!({})).unwrap(); + assert_eq!(app.ui.action_sets[0].actions[0].steps.len(), 1, "the step is left out"); + } + + /// When the action New Action made for the recording in progress is deleted, Stop + /// Playing/Recording keeps none of its steps, so no limit stops a recorded command, even with + /// the set's file at 8 MiB. + #[test] + fn a_deleted_recording_action_does_not_limit_recorded_commands() { + let (mut app, x) = app_with_three_moves(); + let gone = Action::new("Gone", vec![]); + let id = gone.id; + app.ui.action_sets[0].actions.push(gone); + app.run(START_RECORDING, json!({})).unwrap(); + app.ui.recording_into = Some(id); + app.ui.action_sets[0].actions.retain(|a| a.id != id); + let pad = |n: usize| ("object.move".to_string(), json!({"dx": 1, "dy": 0, "pad": "x".repeat(n)})); + app.ui.action_sets[0].actions[0].steps = vec![pad(0)]; + let room = files::MAX_SET_FILE - files::write_set(&app.ui.action_sets[0]).len(); + app.ui.action_sets[0].actions[0].steps = vec![pad(room)]; + let before = x(&app); + app.run("object.move", json!({"dx": 1, "dy": 0})).unwrap(); + assert_ne!(x(&app), before, "the move ran"); + app.run(STOP_RECORDING, json!({})).unwrap(); + assert_eq!(app.ui.action_sets[0].actions.len(), 1, "no action is added"); + assert!(files::read_set(&files::write_set(&app.ui.action_sets[0]), "Test").is_ok()); + } + + /// A stop that playback reaches while a full action records is not recorded: the status bar shows + /// the reason, and the playback still waits at the stop. + #[test] + fn a_stop_reached_while_recording_a_full_action_is_left_out() { + let (mut app, _) = app_with_a_stop(false); + app.run(START_RECORDING, json!({})).unwrap(); + for _ in 1..files::MAX_ACTION_STEPS { + app.session.journal.push(("object.group".to_string(), json!({}))); + } + play(&mut app, 0, 0).unwrap(); + assert!(waiting_at_stop(&app)); + assert_eq!(app.ui.status, "the action already has 10,000 steps"); + app.run(STOP_RECORDING, json!({})).unwrap(); + let recorded = app.ui.action_sets[0].actions.last().unwrap(); + assert_eq!(recorded.steps.len(), files::MAX_ACTION_STEPS); + assert_eq!(recorded.steps.last().map(|(c, _)| c.as_str()), Some("command.batch")); + } + + /// Steps that reach the journal without a command's check are left out by Stop Playing/Recording + /// past either limit, and the status bar names the limit. + #[test] + fn stop_leaves_out_recorded_steps_past_the_limits() { + let (mut app, _) = app_with_three_moves(); + app.run(START_RECORDING, json!({})).unwrap(); + for _ in 0..files::MAX_ACTION_STEPS + 5 { + app.session.journal.push(("object.group".to_string(), json!({}))); + } + app.run(STOP_RECORDING, json!({})).unwrap(); + assert_eq!(app.ui.status, "the action already has 10,000 steps"); + assert_eq!(app.ui.action_sets[0].actions.last().unwrap().steps.len(), files::MAX_ACTION_STEPS); + + let (mut app, _) = app_with_three_moves(); + let pad = |n: usize| ("object.move".to_string(), json!({"dx": 1, "dy": 0, "pad": "x".repeat(n)})); + app.run(START_RECORDING, json!({})).unwrap(); + app.session.journal.push(pad(files::MAX_SET_FILE / 2)); + app.session.journal.push(pad(files::MAX_SET_FILE / 2)); + app.session.journal.push(pad(0)); + app.run(STOP_RECORDING, json!({})).unwrap(); + assert_eq!(app.ui.status, "the action set would be larger than 8 MiB"); + assert_eq!(app.ui.action_sets[0].actions.last().unwrap().steps.len(), 1); + assert!(files::read_set(&files::write_set(&app.ui.action_sets[0]), "Test").is_ok()); + } + + /// An exclusion that would give a set a file larger than 8 MiB is refused for a set, an action, + /// a step and the other steps of an action, and leaves every exclusion as it was. One that + /// fills the file exactly, one that changes nothing and an inclusion still work, also in a set + /// that is already larger than 8 MiB. + #[test] + fn excluding_steps_keeps_an_action_set_file_within_8_mib() { + let (mut app, _) = app_with_three_moves(); + let pad = |n: usize| ("object.move".to_string(), json!({"dx": 1, "dy": 0, "pad": "x".repeat(n)})); + app.ui.action_sets[0].actions.push(Action::new("Pad", vec![pad(0)])); + let room = files::MAX_SET_FILE - files::write_set(&app.ui.action_sets[0]).len(); + // Room for two more excluded steps. + app.ui.action_sets[0].actions[1].steps = vec![pad(room - 2 * files::EXCLUDED_BYTES)]; + let size = "the action set would be larger than 8 MiB"; + let include = |app: &mut VectorcraftApp, p: Value| app.run(INCLUDE_STEPS, p); + let excluded = |app: &VectorcraftApp| app.ui.action_sets[0].actions.iter().map(|a| a.excluded_steps.clone()).collect::>(); + let none = vec![BTreeSet::new(), BTreeSet::new()]; + assert_eq!(include(&mut app, json!({"set": 0, "included": false})).unwrap_err(), size); + assert_eq!(include(&mut app, json!({"set": 0, "action": 0, "included": false})).unwrap_err(), size); + assert_eq!(excluded(&app), none, "nothing changed"); + // Two steps fill the file to 8 MiB. + include(&mut app, json!({"set": 0, "action": 0, "step": 0, "included": false, "others": true})).unwrap(); + assert_eq!(excluded(&app), [BTreeSet::from([1, 2]), BTreeSet::new()]); + assert_eq!(files::write_set(&app.ui.action_sets[0]).len(), files::MAX_SET_FILE); + assert_eq!(include(&mut app, json!({"set": 0, "action": 0, "step": 0, "included": false})).unwrap_err(), size); + assert_eq!(include(&mut app, json!({"set": 0, "action": 1, "step": 0, "included": false})).unwrap_err(), size); + assert!(include(&mut app, json!({"set": 0, "action": 0, "step": 1, "included": false})).is_ok(), "no change"); + include(&mut app, json!({"set": 0, "action": 0, "step": 1, "included": true})).unwrap(); + include(&mut app, json!({"set": 0, "action": 0, "step": 0, "included": false})).unwrap(); + assert_eq!(excluded(&app), [BTreeSet::from([0, 2]), BTreeSet::new()]); + assert!(files::read_set(&files::write_set(&app.ui.action_sets[0]), "Test").is_ok()); + + // A set already larger than 8 MiB can still include its steps. + app.ui.action_sets[0].actions[1].steps[0] = pad(room); + assert_eq!(include(&mut app, json!({"set": 0, "action": 0, "step": 1, "included": false})).unwrap_err(), size); + include(&mut app, json!({"set": 0, "included": true})).unwrap(); + assert_eq!(excluded(&app), none); + + // The steps a recording adds to the set count too. + let (mut app, _) = app_with_three_moves(); + let room = files::MAX_SET_FILE - files::write_set(&app.ui.action_sets[0]).len(); + app.run(START_RECORDING, json!({})).unwrap(); + app.session.journal.push(pad(room - files::step_bytes("object.move", &pad(0).1))); + assert_eq!(include(&mut app, json!({"set": 0, "included": false})).unwrap_err(), size); + assert!(app.ui.action_sets[0].actions[0].excluded_steps.is_empty()); + } + + /// Adds an action to set `set` whose step makes the set's file `short` bytes short of 8 MiB. + fn pad_set_to(app: &mut VectorcraftApp, set: usize, short: usize) { + let pad = |n: usize| ("object.move".to_string(), json!({"pad": "x".repeat(n)})); + let s = &mut app.ui.action_sets[set]; + s.actions.push(Action::new("Pad", vec![pad(0)])); + let room = files::MAX_SET_FILE - files::write_set(s).len(); + s.actions.last_mut().unwrap().steps[0] = pad(room - short); + assert_eq!(files::write_set(s).len(), files::MAX_SET_FILE - short); + } + + /// `n` actions with no steps, named A0, A1 … + fn empty_actions(n: usize) -> Vec { + (0..n).map(|i| Action::new(format!("A{i}"), vec![])).collect() + } + + /// A recorded batch that edits another document, and whose values make its step too large only + /// as it runs, keeps its edits in both documents: the status bar names the limit, the next + /// recorded command does not run, and Stop Playing/Recording leaves the batch's step out. + #[test] + fn a_recorded_batch_that_edits_another_document_is_left_out_when_it_grows() { + // Three moves' document, a move as recorded there, and a second document that is active. + let two_documents = || { + let (mut app, x) = app_with_three_moves(); + let moved = recorded_move(&mut app); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + (app, x, moved) + }; + let batch = json!({"commands": [ + {"command": "document.activate", "params": {"index": 0}}, + {"command": "object.scale", "params": {"sx": 200}}, + ]}); + let (mut app, _, _) = two_documents(); + app.run("command.batch", batch.clone()).unwrap(); + let noted = app.session.journal.last().unwrap().1.clone(); + // The batch as the app runs it (with the active artboard) before the scale notes its values. + let mut sent = noted.clone(); + sent["commands"][1]["params"] = json!({"sx": 200}); + let given = files::step_bytes("command.batch", &sent); + assert!(files::step_bytes("command.batch", ¬ed) > given, "the scale notes values: {noted}"); + + let (mut app, x, moved) = two_documents(); + pad_set_to(&mut app, 0, given); + let into = app.ui.action_sets[0].actions.last().unwrap().id; + app.run(START_RECORDING, json!({"set": 0})).unwrap(); + app.ui.recording_into = Some(into); + app.run("command.batch", batch).unwrap(); + let size = "the action set would be larger than 8 MiB"; + assert_eq!(app.ui.status, size); + let scaled = x(&app); + assert_ne!(scaled, 0.0, "the scale stayed"); + assert_eq!(app.run("object.move", moved).unwrap_err(), size, "no later command runs"); + assert_eq!(x(&app), scaled); + let pad = app.ui.action_sets[0].actions.last().unwrap().steps.len(); + app.run(STOP_RECORDING, json!({})).unwrap(); + assert_eq!(app.ui.action_sets[0].actions.last().unwrap().steps.len(), pad, "the batch's step is left out"); + assert!(files::read_set(&files::write_set(&app.ui.action_sets[0]), "Test").is_ok()); + } + + /// Set Options… renaming the set that an action records into has the next recorded command + /// measure the set's file again: a step that fit before the longer name does not run after it. + #[test] + fn a_set_renamed_while_it_records_is_measured_again() { + let (mut app, x) = app_with_three_moves(); + let moved = recorded_move(&mut app); + let added = files::step_bytes("object.move", &moved); + pad_set_to(&mut app, 0, 2 * added + 3); + let into = app.ui.action_sets[0].actions.last().unwrap().id; + app.run(START_RECORDING, json!({"set": 0})).unwrap(); + app.ui.recording_into = Some(into); + app.run("object.move", moved.clone()).unwrap(); + crate::dialogs::action_set_options::open(&mut app, 0); + let longer = format!("{} 1234", app.ui.action_sets[0].name); + app.ui.dialog.as_mut().unwrap().fields.insert("name".into(), json!(longer)); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(app.ui.action_sets[0].name, longer); + assert_eq!(app.run("object.move", moved).unwrap_err(), "the action set would be larger than 8 MiB"); + assert_eq!(x(&app), 1.0, "only the first move ran"); + app.run(STOP_RECORDING, json!({})).unwrap(); + assert!(files::read_set(&files::write_set(&app.ui.action_sets[0]), "Test").is_ok()); + } + + /// Steps recorded into an action are included in playback, also when the action holds an + /// exclusion past its last step, as saved preferences can; the set's file stays within 8 MiB. + #[test] + fn steps_recorded_after_an_exclusion_past_the_last_step_are_included() { + let (mut app, _) = app_with_three_moves(); + let moved = recorded_move(&mut app); + let added = files::step_bytes("object.move", &moved); + pad_set_to(&mut app, 0, added); + let pad = app.ui.action_sets[0].actions.last_mut().unwrap(); + pad.excluded_steps.insert(1); + let into = pad.id; + app.run(START_RECORDING, json!({"set": 0})).unwrap(); + app.ui.recording_into = Some(into); + app.run("object.move", moved).unwrap(); + app.run(STOP_RECORDING, json!({})).unwrap(); + let pad = app.ui.action_sets[0].actions.last().unwrap(); + assert_eq!((pad.steps.len(), pad.excluded_steps.len()), (2, 0), "the recorded step is included"); + assert_eq!(files::write_set(&app.ui.action_sets[0]).len(), files::MAX_SET_FILE); + } + + /// Duplicate copies no action or set when the copy would give a file larger than 8 MiB or a set + /// of more than 1,000 actions, and still copies one that fits. + #[test] + fn duplicate_keeps_action_set_files_within_their_limits() { + let mut app = app_with_sets(); + pad_set_to(&mut app, 1, 0); + let size = "the action set would be larger than 8 MiB"; + let names = set_names(&app); + assert_eq!(app.run(DUPLICATE, json!({"set": 1, "action": 0})).unwrap_err(), size); + assert_eq!(app.run(DUPLICATE, json!({"set": 1})).unwrap_err(), size, "the copy's name is longer"); + assert_eq!((set_names(&app), app.ui.action_sets[1].actions.len()), (names, 3), "nothing was copied"); + app.ui.action_sets[2].actions = empty_actions(1000); + let many = "the action set file holds more than 1,000 actions"; + assert_eq!(app.run(DUPLICATE, json!({"set": 2, "action": 0})).unwrap_err(), many); + assert_eq!(app.ui.action_sets[2].actions.len(), 1000); + app.ui.action_sets[2].actions.pop(); + app.run(DUPLICATE, json!({"set": 2, "action": 0})).unwrap(); + app.run(DUPLICATE, json!({"set": 2})).unwrap(); + assert_eq!((app.ui.action_sets[2].actions.len(), app.ui.action_sets[3].actions.len()), (1000, 1000)); + } + + /// New Action and Begin Recording add no action and start no recording when the action would + /// give its set more than 1,000 actions or a file larger than 8 MiB, and New Action adds one that + /// fits. + #[test] + fn new_action_keeps_an_action_set_file_within_its_limits() { + let mut app = app_with_sets(); + app.ui.action_sets[2].actions = empty_actions(1000); + let many = "the action set file holds more than 1,000 actions"; + assert_eq!(app.run(NEW_ACTION, json!({"set": 2, "name": "More"})).unwrap_err(), many); + assert_eq!(app.run(START_RECORDING, json!({"set": 2})).unwrap_err(), many, "Begin Recording too"); + pad_set_to(&mut app, 1, 200); + let size = "the action set would be larger than 8 MiB"; + assert_eq!(app.run(NEW_ACTION, json!({"set": 1, "name": "x".repeat(300)})).unwrap_err(), size); + assert!(app.ui.recording.is_none(), "no recording started"); + assert_eq!((app.ui.action_sets[1].actions.len(), app.ui.action_sets[2].actions.len()), (3, 1000)); + app.run(NEW_ACTION, json!({"set": 1, "name": "More"})).unwrap(); + app.run(STOP_RECORDING, json!({})).unwrap(); + assert_eq!(app.ui.action_sets[1].actions.len(), 4); + assert!(files::write_set(&app.ui.action_sets[1]).len() <= files::MAX_SET_FILE); + } + + /// Renaming an action, Action Options and Set Options change nothing when the change would give + /// the set a file larger than 8 MiB, with the steps a recording adds to the set; a change that + /// fills the file exactly, or that makes a set already past 8 MiB smaller, is made. New Set adds + /// no set whose file would be larger than 8 MiB. + #[test] + fn renaming_keeps_an_action_set_file_within_8_mib() { + let mut app = app_with_sets(); + pad_set_to(&mut app, 1, 2); + let size = "the action set would be larger than 8 MiB"; + assert_eq!(app.run(RENAME_ACTION, json!({"set": 1, "action": 0, "name": "Nudge Far"})).unwrap_err(), size); + assert_eq!(app.run(ACTION_OPTIONS, json!({"set": 1, "action": 0, "color": "red"})).unwrap_err(), size); + assert_eq!(app.run(ACTION_OPTIONS, json!({"set": 1, "action": 0, "key": 2})).unwrap_err(), size); + let nudge = &app.ui.action_sets[1].actions[0]; + assert_eq!((nudge.name.as_str(), nudge.key, nudge.color.as_deref()), ("Nudge", None, None), "nothing changed"); + crate::dialogs::action_set_options::open(&mut app, 1); + app.ui.dialog.as_mut().unwrap().fields.insert("name".into(), json!("Mine and More")); + assert_eq!(crate::dialogs::confirm(&mut app).unwrap_err(), size); + assert!(app.ui.dialog.is_some(), "Set Options stays open"); + assert_eq!(app.ui.action_sets[1].name, "Mine"); + app.ui.dialog = None; + app.run(RENAME_ACTION, json!({"set": 1, "action": 0, "name": "Nudge++"})).unwrap(); + assert_eq!(files::write_set(&app.ui.action_sets[1]).len(), files::MAX_SET_FILE, "the file is exactly 8 MiB"); + app.ui.action_sets[1].actions[1].name = "x".repeat(100); + app.run(RENAME_ACTION, json!({"set": 1, "action": 1, "name": "Nudge Again"})).unwrap(); + assert_eq!(app.ui.action_sets[1].actions[1].name, "Nudge Again", "a set past 8 MiB gets smaller"); + + crate::dialogs::action_set_options::open_new(&mut app); + app.ui.dialog.as_mut().unwrap().fields.insert("name".into(), json!("x".repeat(files::MAX_SET_FILE))); + assert_eq!(crate::dialogs::confirm(&mut app).unwrap_err(), size); + assert_eq!(app.ui.action_sets.len(), 3, "no set was added"); + app.ui.dialog = None; + + // The steps a recording adds to the set count too. + let mut app = app_with_sets(); + pad_set_to(&mut app, 1, 1000); + app.run(START_RECORDING, json!({"set": 1})).unwrap(); + app.session.journal.push(("object.move".to_string(), json!({"pad": "x".repeat(1000)}))); + assert_eq!(app.run(RENAME_ACTION, json!({"set": 1, "action": 0, "name": "Nudge+"})).unwrap_err(), size); + app.run(RENAME_ACTION, json!({"set": 1, "action": 0, "name": "Nudg"})).unwrap(); + } + + /// Load Actions… adds no set that Save Actions… would write as a file larger than 8 MiB: a file + /// with less white space, a file whose set name gets a number, and another app's action set whose + /// names take more bytes in the file. + #[test] + fn load_actions_refuses_a_set_that_would_save_larger_than_8_mib() { + let mut app = app_with_sets(); + let size = "the action set would be larger than 8 MiB"; + let wide = ActionSet::new("Wide", vec![Action::new("Zeros", vec![("object.move".into(), json!({"p": vec![0; 600_000]}))])]); + let saved = files::write_set(&wide); + let packed = serde_json::to_string(&serde_json::from_str::(&saved).unwrap()).unwrap(); + assert!(packed.len() <= files::MAX_SET_FILE && saved.len() > files::MAX_SET_FILE); + assert_eq!(app.run(LOAD_SET, json!({ "data": packed })).unwrap_err(), size); + + let mut full = app_with_sets(); + full.ui.action_sets[1].actions.clear(); + pad_set_to(&mut full, 1, 0); + let mine = files::write_set(&full.ui.action_sets[1]); + assert_eq!(app.run(LOAD_SET, json!({ "data": mine })).unwrap_err(), size, "Mine 2 is longer"); + let yours = mine.replacen("\"Mine\"", "\"Your\"", 1); + assert_eq!(app.run(LOAD_SET, json!({ "data": yours })).unwrap()["name"], "Your"); + + let name = "\u{1}".repeat(1024); + let steps = [("Group", true); 40]; + let text = aia_text("Names", &vec![(name.as_str(), steps.as_slice()); 1000]); + assert!(text.len() <= files::MAX_SET_FILE); + assert_eq!(app.run(LOAD_SET, json!({ "data": text })).unwrap_err(), size); + assert_eq!(set_names(&app), ["Default Actions", "Mine", "Other", "Your"]); + } + + /// A step inserted from the menu saves and loads as the command and params it holds, with its + /// place and exclusion. + #[test] + fn an_inserted_menu_item_saves_and_loads() { + let (mut app, _) = app_with_three_moves(); + app.run(INSERT_MENU_ITEM, json!({"set": 0, "action": 0, "step": 1, "command": "type.changeCase", "params": {"case": "title"}})).unwrap(); + app.ui.action_sets[0].actions[0].excluded_steps = BTreeSet::from([2]); + let loaded = files::read_set(&files::write_set(&app.ui.action_sets[0]), "Test").unwrap(); + let action = &loaded.actions[0]; + assert_eq!(action.steps, app.ui.action_sets[0].actions[0].steps); + assert_eq!(action.steps[2], ("type.changeCase".to_string(), json!({"case": "title"}))); + assert_eq!(action.excluded_steps, BTreeSet::from([2])); + } + #[test] fn delete_step_removes_one_step_and_moves_the_exclusions_up() { let (mut app, _) = app_with_a_stop(false); @@ -4004,6 +6140,366 @@ mod tests { assert_eq!(open_kind(&app), None, "deleting its step closes it"); } + /// The steps of action `action` in set `set`: each command, with its `dx` when it has one. + fn step_names(app: &VectorcraftApp, set: usize, action: usize) -> Vec { + app.ui.action_sets[set].actions[action] + .steps + .iter() + .map(|(c, p)| match p.get("dx") { + Some(dx) => format!("{c} {dx}"), + None => c.clone(), + }) + .collect() + } + + /// The bottom bar's Stop and Begin Recording buttons, as drawn last. + fn stop_and_record(ctx: &egui::Context, app: &mut VectorcraftApp) -> (egui::Pos2, egui::Pos2) { + super::super::tests_appearance::frame_events(ctx, app, vec![], show); + let mut bar = crate::toolbar::tests::widget_rects(ctx, egui::vec2(24.0, 24.0)); + bar.sort_by(|a, b| a.left().total_cmp(&b.left())); + let [stop, record, ..] = bar[..] else { panic!("the bottom bar: {bar:?}") }; + (stop.center(), record.center()) + } + + #[test] + fn begin_recording_selected_action_adds_steps_without_new_action() { + use super::super::tests_appearance::{click, frame_events, text_rect}; + let (mut app, _) = app_with_three_moves(); + app.ui.action_set = Some(0); + let ctx = egui::Context::default(); + app.ui_ctx = Some(ctx.clone()); + let texts = frame_events(&ctx, &mut app, vec![], show); + click(&ctx, &mut app, text_rect(&texts, "Three Moves").center(), show); + let (stop, record) = stop_and_record(&ctx, &mut app); + click(&ctx, &mut app, record, show); + app.run("object.move", json!({"dx": 8, "dy": 0})).unwrap(); + click(&ctx, &mut app, stop, show); + assert_eq!(app.ui.action_sets[0].actions.len(), 1, "no new action"); + assert_eq!(step_names(&app, 0, 0), ["object.move 1", "object.move 2", "object.move 4", "object.move 8"], "added at the end"); + + // With a step selected, the recorded steps go after it. + click_first_step(&ctx, &mut app); + // The steps shown move the bottom bar down. + let (stop, record) = stop_and_record(&ctx, &mut app); + click(&ctx, &mut app, record, show); + app.run("object.move", json!({"dx": 16, "dy": 0})).unwrap(); + click(&ctx, &mut app, stop, show); + assert_eq!(step_names(&app, 0, 0), ["object.move 1", "object.move 16", "object.move 2", "object.move 4", "object.move 8"]); + + // With no action selected, Begin Recording still adds a new action. + let texts = frame_events(&ctx, &mut app, vec![], show); + click(&ctx, &mut app, text_rect(&texts, "▾ Moves").center(), show); + let (stop, record) = stop_and_record(&ctx, &mut app); + click(&ctx, &mut app, record, show); + app.run("object.move", json!({"dx": 32, "dy": 0})).unwrap(); + click(&ctx, &mut app, stop, show); + let names: Vec<&str> = app.ui.action_sets[0].actions.iter().map(|a| a.name.as_str()).collect(); + assert_eq!(names, ["Three Moves", "Action 2"]); + assert_eq!(step_names(&app, 0, 1), ["object.move 32"]); + } + + #[test] + fn begin_recording_after_selected_step_preserves_order_and_exclusions() { + let (mut app, _) = app_with_three_moves(); + app.ui.action_sets[0].actions[0].excluded_steps = BTreeSet::from([0, 2]); + for (params, want) in [ + (json!({"action": 0}), "no such action"), + (json!({"set": 0, "after": 0}), "no such action"), + (json!({"set": 1, "action": 0}), "no such action"), + (json!({"set": 0, "action": 1}), "no such action"), + (json!({"set": 0, "action": "0"}), "no such action"), + (json!({"set": 0, "action": 0, "after": 3}), "no such action step"), + (json!({"set": 0, "action": 0, "after": null}), "no such action step"), + (json!({"set": 0, "action": 0, "after": -1}), "no such action step"), + ] { + assert_eq!(app.run(START_RECORDING, params.clone()).unwrap_err(), want, "{params}"); + assert!(app.ui.recording.is_none(), "{params}"); + } + assert_eq!( + app.run(START_RECORDING, json!({"set": 0, "action": 0, "after": 0})).unwrap(), + json!({"set": 0, "action": 0, "name": "Three Moves"}) + ); + app.run("object.move", json!({"dx": 8, "dy": 0})).unwrap(); + app.run("object.move", json!({"dx": 16, "dy": 0})).unwrap(); + app.run(STOP_RECORDING, json!({})).unwrap(); + assert_eq!(app.ui.action_sets[0].actions.len(), 1, "no new action"); + assert_eq!(step_names(&app, 0, 0), ["object.move 1", "object.move 8", "object.move 16", "object.move 2", "object.move 4"]); + assert_eq!(app.ui.action_sets[0].actions[0].excluded_steps, BTreeSet::from([0, 4]), "the steps keep whether they are excluded"); + } + + #[test] + fn steps_recorded_into_the_middle_of_an_action_keep_the_selected_step_and_dialog_on_their_steps() { + let (mut app, _) = app_with_three_moves(); + let ctx = egui::Context::default(); + app.ui_ctx = Some(ctx.clone()); + let id = app.ui.action_sets[0].actions[0].id; + app.run(START_RECORDING, json!({"set": 0, "action": 0, "after": 0})).unwrap(); + app.run("object.move", json!({"dx": 8, "dy": 0})).unwrap(); + app.run("object.move", json!({"dx": 16, "dy": 0})).unwrap(); + set_pstate::>(&ctx, SELECTED_STEP, Some((id, 2))); + crate::dialogs::action_stop::open_record(&mut app, Some((0, 0)), Some(1)); + app.run(STOP_RECORDING, json!({})).unwrap(); + assert_eq!(step_names(&app, 0, 0), ["object.move 1", "object.move 8", "object.move 16", "object.move 2", "object.move 4"]); + assert_eq!(pstate::>(&ctx, SELECTED_STEP), Some((id, 4)), "the move by 4 stays selected"); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["step"], json!(3), "Record Stop stays after the move by 2"); + } + + #[test] + fn step_edits_while_recording_into_an_action_keep_the_recording_in_place() { + let (mut app, _) = app_with_three_moves(); + // The recording goes between the moves by 2 and 4. + app.run(START_RECORDING, json!({"set": 0, "action": 0, "after": 1})).unwrap(); + app.run("object.move", json!({"dx": 8, "dy": 0})).unwrap(); + app.run(DELETE_STEP, json!({"set": 0, "action": 0, "step": 0})).unwrap(); + app.run(INSERT_STOP, json!({"set": 0, "action": 0, "step": 0})).unwrap(); + app.run(MOVE_STEP, json!({"set": 0, "action": 0, "step": 2, "before": 0})).unwrap(); + app.run(STOP_RECORDING, json!({})).unwrap(); + assert_eq!(step_names(&app, 0, 0), ["object.move 4", "object.move 2", STOP_STEP, "object.move 8"]); + + let (mut app, _) = app_with_three_moves(); + app.run(START_RECORDING, json!({"set": 0, "action": 0, "after": 1})).unwrap(); + app.run("object.move", json!({"dx": 8, "dy": 0})).unwrap(); + app.run(DELETE_STEP, json!({"set": 0, "action": 0, "step": 0})).unwrap(); + app.run(STOP_RECORDING, json!({})).unwrap(); + assert_eq!(step_names(&app, 0, 0), ["object.move 2", "object.move 8", "object.move 4"], "a step deleted before the place"); + } + + #[test] + fn move_step_within_action_updates_order_exclusions_and_selection() { + let (mut app, _) = app_with_three_moves(); + app.ui.action_sets[0].actions[0].steps.push(("object.move".into(), json!({"dx": 8, "dy": 0}))); + app.ui.action_sets[0].actions[0].excluded_steps = BTreeSet::from([1]); + let ctx = egui::Context::default(); + app.ui_ctx = Some(ctx.clone()); + let id = app.ui.action_sets[0].actions[0].id; + set_pstate::>(&ctx, SELECTED_STEP, Some((id, 3))); + let selected_step = |ctx: &egui::Context| pstate::>(ctx, SELECTED_STEP); + assert_eq!( + app.run(MOVE_STEP, json!({"set": 0, "action": 0, "step": 1, "before": 4})).unwrap(), + json!({"set": 0, "action": 0, "step": 3, "moved": true}) + ); + assert_eq!(step_names(&app, 0, 0), ["object.move 1", "object.move 4", "object.move 8", "object.move 2"]); + assert_eq!(app.ui.action_sets[0].actions[0].excluded_steps, BTreeSet::from([3]), "the moved step stays excluded"); + assert_eq!(selected_step(&ctx), Some((id, 2)), "the selected step stays selected"); + assert_eq!( + app.run(MOVE_STEP, json!({"set": 0, "action": 0, "step": 2, "before": 0})).unwrap(), + json!({"set": 0, "action": 0, "step": 0, "moved": true}) + ); + assert_eq!(step_names(&app, 0, 0), ["object.move 8", "object.move 1", "object.move 4", "object.move 2"]); + assert_eq!(app.ui.action_sets[0].actions[0].excluded_steps, BTreeSet::from([3])); + assert_eq!(selected_step(&ctx), Some((id, 0)), "the moved selected step is selected where it went"); + for before in [1, 2] { + assert_eq!( + app.run(MOVE_STEP, json!({"set": 0, "action": 0, "step": 1, "before": before})).unwrap(), + json!({"set": 0, "action": 0, "step": 1, "moved": false}) + ); + } + assert_eq!(step_names(&app, 0, 0), ["object.move 8", "object.move 1", "object.move 4", "object.move 2"], "a drop on itself moves nothing"); + crate::dialogs::action_stop::open_record(&mut app, Some((0, 0)), Some(3)); + app.run(MOVE_STEP, json!({"set": 0, "action": 0, "step": 3, "before": 0})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["step"], json!(0), "an open Record Stop follows its step"); + } + + #[test] + fn move_step_between_actions_and_sets_keeps_file_roundtrip() { + let (mut app, _) = app_with_three_moves(); + app.ui.action_sets[0].actions[0].excluded_steps = BTreeSet::from([2]); + let rotate = ("object.rotate".to_string(), json!({"angle": 5})); + app.ui.action_sets.push(ActionSet::new("Other", vec![Action::new("Empty", vec![]), Action::new("One", vec![rotate])])); + app.ui.action_set = Some(0); + let ctx = egui::Context::default(); + app.ui_ctx = Some(ctx.clone()); + let (id, empty) = (app.ui.action_sets[0].actions[0].id, app.ui.action_sets[1].actions[0].id); + set_pstate::>(&ctx, "actions-selected", Some((0, 0))); + set_pstate::>(&ctx, SELECTED_STEP, Some((id, 2))); + assert_eq!( + app.run(MOVE_STEP, json!({"set": 0, "action": 0, "step": 2, "toSet": 1, "toAction": 0, "before": 0})).unwrap(), + json!({"set": 1, "action": 0, "step": 0, "moved": true}) + ); + assert_eq!(step_names(&app, 0, 0), ["object.move 1", "object.move 2"]); + assert!(app.ui.action_sets[0].actions[0].excluded_steps.is_empty()); + assert_eq!(step_names(&app, 1, 0), ["object.move 4"], "an empty action takes a step"); + assert_eq!(app.ui.action_sets[1].actions[0].excluded_steps, BTreeSet::from([0]), "the moved step stays excluded"); + assert_eq!(pstate::>(&ctx, SELECTED_STEP), Some((empty, 0))); + assert_eq!(pstate::>(&ctx, "actions-selected"), Some((1, 0))); + assert_eq!((app.ui.action_set, app.ui.action_sets_selected.as_slice()), (Some(1), &[1][..])); + assert!(pstate::>(&ctx, "actions-expanded").contains(&empty), "the step's new action shows its steps"); + app.run(MOVE_STEP, json!({"set": 0, "action": 0, "step": 0, "toSet": 1, "toAction": 1, "before": 0})).unwrap(); + assert_eq!(step_names(&app, 1, 1), ["object.move 1", "object.rotate"]); + assert_eq!(pstate::>(&ctx, SELECTED_STEP), Some((empty, 0)), "an unmoved selected step stays"); + let loaded = files::read_set(&files::write_set(&app.ui.action_sets[1]), "Other").unwrap(); + for (a, b) in loaded.actions.iter().zip(&app.ui.action_sets[1].actions) { + assert_eq!((&a.name, &a.steps, &a.excluded_steps), (&b.name, &b.steps, &b.excluded_steps)); + } + } + + #[test] + fn move_step_rejects_invalid_and_oversize_destinations_without_changes() { + let (mut app, _) = app_with_three_moves(); + let full = Action::new("Full", vec![("object.move".to_string(), json!({"dx": 0})); files::MAX_ACTION_STEPS]); + let big = |text: String| ActionSet::new("Big", vec![Action::new("Big", vec![("document.note".to_string(), json!({ "s": text }))])]); + let room = files::MAX_SET_FILE - files::write_set(&big(String::new())).len() - 4; + app.ui.action_sets.push(ActionSet::new("Full", vec![full])); + app.ui.action_sets.push(big("x".repeat(room))); + assert!(files::write_set(&app.ui.action_sets[2]).len() <= files::MAX_SET_FILE); + let before: Vec = app.ui.action_sets.iter().map(files::write_set).collect(); + for (params, want) in [ + (json!({}), "no such action"), + (json!({"set": 0, "action": 1, "step": 0, "before": 0}), "no such action"), + (json!({"set": 3, "action": 0, "step": 0, "before": 0}), "no such action"), + (json!({"set": 0, "action": 0, "step": 3, "before": 0}), "no such action step"), + (json!({"set": 0, "action": 0, "before": 0}), "no such action step"), + (json!({"set": 0, "action": 0, "step": 0}), "no such action step"), + (json!({"set": 0, "action": 0, "step": 0, "before": 4}), "no such action step"), + (json!({"set": 0, "action": 0, "step": 0, "before": "1"}), "no such action step"), + (json!({"set": 0, "action": 0, "step": 0, "toSet": 3, "before": 0}), "no such action set"), + (json!({"set": 0, "action": 0, "step": 0, "toSet": null, "before": 0}), "no such action set"), + (json!({"set": 0, "action": 0, "step": 0, "toSet": 1, "toAction": 1, "before": 0}), "no such action"), + (json!({"set": 0, "action": 0, "step": 0, "toSet": 1, "toAction": 0, "before": 0}), "the action already has 10,000 steps"), + (json!({"set": 0, "action": 0, "step": 0, "toSet": 2, "toAction": 0, "before": 1}), "the action set would be larger than 8 MiB"), + ] { + assert_eq!(app.run(MOVE_STEP, params.clone()).unwrap_err(), want, "{params}"); + assert_eq!(app.ui.action_sets.iter().map(files::write_set).collect::>(), before, "{params}"); + } + } + + #[test] + fn drag_step_shows_insertion_line_and_moves_once() { + use egui::{Event, PointerButton}; + let (mut app, _) = app_with_three_moves(); + app.ui.action_set = Some(0); + let ctx = egui::Context::default(); + app.ui_ctx = Some(ctx.clone()); + set_pstate(&ctx, "actions-expanded", BTreeSet::from([app.ui.action_sets[0].actions[0].id])); + let texts = super::super::tests_appearance::frame_events(&ctx, &mut app, vec![], show); + let mut rows: Vec = texts.iter().filter(|(s, _)| s == "object.move").map(|(_, r)| *r).collect(); + rows.sort_by(|a, b| a.top().total_cmp(&b.top())); + let (from, to) = (rows[0].center(), egui::pos2(rows[0].center().x, rows[2].center().y + 4.0)); + let accent = Tokens::get(&ctx).accent; + // Whether a frame with `events` draws the insertion line. + let frame = |app: &mut VectorcraftApp, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + fn line(s: &egui::Shape, accent: egui::Color32) -> bool { + match s { + egui::Shape::LineSegment { stroke, .. } => stroke.width == 2.0 && stroke.color == accent, + egui::Shape::Vec(v) => v.iter().any(|s| line(s, accent)), + _ => false, + } + } + out.shapes.iter().any(|c| line(&c.shape, accent)) + }; + let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + assert!(!frame(&mut app, vec![Event::PointerMoved(from)]), "no line before a drag"); + frame(&mut app, vec![button(from, true)]); + frame(&mut app, vec![Event::PointerMoved(from + egui::vec2(0.0, 12.0))]); + assert!(frame(&mut app, vec![Event::PointerMoved(to)]), "the line shows where the step goes"); + assert_eq!(step_names(&app, 0, 0), ["object.move 1", "object.move 2", "object.move 4"], "nothing moves while dragging"); + frame(&mut app, vec![button(to, false)]); + assert_eq!(step_names(&app, 0, 0), ["object.move 2", "object.move 4", "object.move 1"], "the release moves the step"); + for _ in 0..3 { + assert!(!frame(&mut app, vec![]), "no line after the drop"); + } + assert_eq!(step_names(&app, 0, 0), ["object.move 2", "object.move 4", "object.move 1"], "the step moves once"); + } + + #[test] + fn drag_step_released_off_the_rows_leaves_it_in_place_without_an_undo_step() { + use egui::{Event, PointerButton}; + let (mut app, _) = app_with_three_moves(); + app.ui.action_set = Some(0); + let ctx = egui::Context::default(); + app.ui_ctx = Some(ctx.clone()); + set_pstate(&ctx, "actions-expanded", BTreeSet::from([app.ui.action_sets[0].actions[0].id])); + let texts = super::super::tests_appearance::frame_events(&ctx, &mut app, vec![], show); + let mut rows: Vec = texts.iter().filter(|(s, _)| s == "object.move").map(|(_, r)| *r).collect(); + rows.sort_by(|a, b| a.top().total_cmp(&b.top())); + let from = rows[0].center(); + let over = egui::pos2(from.x, rows[2].center().y + 4.0); + let off = egui::pos2(from.x, rows[2].bottom() + 2_000.0); + let undo = undo_steps(&app); + let frame = |app: &mut VectorcraftApp, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + }; + let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(&mut app, vec![button(from, true)]); + frame(&mut app, vec![Event::PointerMoved(from + egui::vec2(0.0, 12.0))]); + frame(&mut app, vec![Event::PointerMoved(over)]); + frame(&mut app, vec![Event::PointerMoved(off)]); + frame(&mut app, vec![button(off, false)]); + for _ in 0..3 { + frame(&mut app, vec![]); + } + assert_eq!(step_names(&app, 0, 0), ["object.move 1", "object.move 2", "object.move 4"], "the step stays where it was"); + assert_eq!(undo_steps(&app), undo, "no undo step"); + assert_eq!(pstate::>(&ctx, DRAGGED_STEP), None, "the drag ends"); + } + + #[test] + fn drag_step_ends_without_a_move_when_a_command_changes_its_action() { + use egui::{Event, PointerButton}; + let (mut app, _) = app_with_three_moves(); + let rotate = |angle: u32| ("object.rotate".to_string(), json!({"angle": angle})); + app.ui.action_sets[0].actions.push(Action::new("Turns", vec![rotate(5), rotate(6)])); + app.ui.action_set = Some(0); + let ctx = egui::Context::default(); + app.ui_ctx = Some(ctx.clone()); + set_pstate(&ctx, "actions-expanded", BTreeSet::from([app.ui.action_sets[0].actions[0].id])); + let texts = super::super::tests_appearance::frame_events(&ctx, &mut app, vec![], show); + let mut rows: Vec = texts.iter().filter(|(s, _)| s == "object.move").map(|(_, r)| *r).collect(); + rows.sort_by(|a, b| a.top().total_cmp(&b.top())); + let (from, to) = (rows[0].center(), egui::pos2(rows[0].center().x, rows[1].center().y + 4.0)); + let frame = |app: &mut VectorcraftApp, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + }; + let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + let start_drag = |app: &mut VectorcraftApp| { + frame(app, vec![button(from, true)]); + frame(app, vec![Event::PointerMoved(from + egui::vec2(0.0, 12.0))]); + }; + // A command on another action leaves the drag as it is. + start_drag(&mut app); + app.run(DELETE_STEP, json!({"set": 0, "action": 1, "step": 0})).unwrap(); + frame(&mut app, vec![Event::PointerMoved(to)]); + frame(&mut app, vec![button(to, false)]); + assert_eq!(step_names(&app, 0, 0), ["object.move 2", "object.move 1", "object.move 4"], "the dragged step moves"); + // A command that deletes the dragged step's action's first step puts another step at the + // dragged index. + start_drag(&mut app); + app.run(DELETE_STEP, json!({"set": 0, "action": 0, "step": 0})).unwrap(); + frame(&mut app, vec![Event::PointerMoved(to)]); + assert_eq!(pstate::>(&ctx, DRAGGED_STEP), None, "the drag ends"); + frame(&mut app, vec![button(to, false)]); + assert_eq!(step_names(&app, 0, 0), ["object.move 1", "object.move 4"], "no other step moves"); + // Two equal steps, one excluded, that change places put the other one at the dragged index. + let same = ("object.move".to_string(), json!({"dx": 1, "dy": 0})); + app.ui.action_sets[0].actions[0].steps = vec![same.clone(), same]; + app.ui.action_sets[0].actions[0].excluded_steps = BTreeSet::from([1]); + start_drag(&mut app); + app.run(MOVE_STEP, json!({"set": 0, "action": 0, "step": 1, "before": 0})).unwrap(); + frame(&mut app, vec![Event::PointerMoved(to)]); + frame(&mut app, vec![button(to, false)]); + assert_eq!(app.ui.action_sets[0].actions[0].excluded_steps, BTreeSet::from([0]), "the excluded step stays first"); + } + + #[test] + fn step_and_set_edits_keep_an_open_insert_menu_item_on_its_place() { + let (mut app, _) = app_with_three_moves(); + app.ui.action_sets[0].actions.insert(0, Action::new("First", vec![])); + crate::dialogs::action_insert_menu_item::open(&mut app, Some((0, 1)), Some(2)); + app.run(DUPLICATE, json!({"set": 0, "action": 0})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["action"], json!(2), "a copied action above moves it down"); + app.run(DELETE_STEP, json!({"set": 0, "action": 2, "step": 0})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["step"], json!(1), "a deleted step above moves it up"); + app.run(DELETE_STEP, json!({"set": 0, "action": 2, "step": 1})).unwrap(); + assert_eq!(open_kind(&app), None, "deleting its step closes it"); + crate::dialogs::action_insert_menu_item::open(&mut app, Some((0, 0)), None); + app.run(DELETE_SETS, json!({"sets": [0]})).unwrap(); + assert_eq!(open_kind(&app), None, "deleting its set closes it"); + } + /// Selects the first step of "Three Moves" by clicking its row, with the action open. fn click_first_step(ctx: &egui::Context, app: &mut VectorcraftApp) { use super::super::tests_appearance::{click, frame_events}; @@ -4393,7 +6889,7 @@ mod tests { json!({"format": "vcactions", "version": version, "name": "Old", "actions": [{"name": "A", "steps": [{"command": "object.move"}]}]}); assert_eq!(files::read_set(&old.to_string(), "Test").unwrap().actions[0].steps.len(), 1, "version {version}"); } - let later = json!({"format": "vcactions", "version": 4, "name": "New", "actions": []}); + let later = json!({"format": "vcactions", "version": 7, "name": "New", "actions": []}); assert_eq!(files::read_set(&later.to_string(), "Test").unwrap_err(), "the action set file needs a later version of VectorCraft"); for params in [json!({"message": 5}), json!({"allowContinue": "yes"}), json!(42)] { let stop = json!({"command": "action.stop", "params": params}); @@ -4474,6 +6970,58 @@ mod tests { assert_eq!(app.ui.action_sets[0].actions[0].steps.len(), 3); } + /// The panel menu's Insert Menu Item… after the selected step: Find narrows the list, a click on + /// a row picks the item and runs nothing, Cancel inserts nothing, and OK inserts the pick after + /// the step. With nothing selected and nothing recording, the item is off. + #[test] + fn insert_menu_item_in_the_menu_picks_from_the_list_and_inserts_on_ok() { + use super::super::tests_appearance::{click, frame_events, text_rect}; + let (mut app, _) = app_with_three_moves(); + app.ui.action_set = Some(0); + let ctx = egui::Context::default(); + app.ui_ctx = Some(ctx.clone()); + let open = |ctx: &egui::Context, app: &mut VectorcraftApp| { + let texts = frame_events(ctx, app, vec![], menu); + let item = texts.iter().find(|(s, _)| s.trim() == "Insert Menu Item…").map(|(_, r)| *r).expect("Insert Menu Item… in the menu"); + click(ctx, app, item.center(), menu); + }; + open(&ctx, &mut app); + assert_eq!(open_kind(&app), None, "nothing selected and nothing recording: the item is off"); + + click_first_step(&ctx, &mut app); + open(&ctx, &mut app); + let d = app.ui.dialog.as_ref().expect("Insert Menu Item… opens its dialog"); + assert_eq!(d.kind, crate::dialogs::action_insert_menu_item::KIND); + assert_eq!((&d.fields["set"], &d.fields["action"], &d.fields["step"]), (&json!(0), &json!(0), &json!(0))); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("find".into(), json!("object.ungroup")); + } + let draw = |app: &mut VectorcraftApp, ui: &mut egui::Ui| crate::dialogs::show(app, ui.ctx()); + let mut texts = vec![]; + for _ in 0..3 { + texts = frame_events(&ctx, &mut app, vec![], draw); + } + assert!(!texts.iter().any(|(s, _)| s == "Object › Group"), "Find narrows the list: {texts:?}"); + let doc = app.session.active().unwrap().doc.clone(); + click(&ctx, &mut app, text_rect(&texts, "Object › Ungroup").center(), draw); + let d = app.ui.dialog.as_ref().expect("a pick keeps the dialog open"); + assert_eq!((d.str("command"), &d.fields["params"]), ("object.ungroup".to_string(), &json!({}))); + assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, &doc), "a pick runs nothing"); + + crate::dialogs::cancel(&mut app); + assert_eq!(app.ui.action_sets[0].actions[0].steps.len(), 3, "Cancel inserts nothing"); + + open(&ctx, &mut app); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("command".into(), json!("object.ungroup")); + } + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(open_kind(&app), None, "OK closes the dialog"); + let ids: Vec = app.ui.action_sets[0].actions[0].steps.iter().map(|(c, _)| c.clone()).collect(); + assert_eq!(ids, ["object.move", "object.ungroup", "object.move", "object.move"], "the pick goes after the selected step"); + assert_eq!(pstate::>(&ctx, SELECTED_STEP), Some((app.ui.action_sets[0].actions[0].id, 1)), "and is selected"); + } + #[test] fn set_edits_keep_an_open_record_stop_on_its_action() { let mut app = app_with_sets(); @@ -4485,4 +7033,182 @@ mod tests { app.run(DELETE_SETS, json!({"sets": [1]})).unwrap(); assert_eq!(open_kind(&app), None, "deleting its set closes it"); } + + /// [`app_with_three_moves`] with a second rectangle whose Attributes note is "Badge front" → + /// (the app, the first rectangle's x offset, the second rectangle's x offset). + #[allow(clippy::type_complexity)] + fn app_with_a_noted_rect() -> (VectorcraftApp, Box f64>, Box f64>) { + let (mut app, x) = app_with_three_moves(); + let first = app.session.active().unwrap().selection.objects.clone(); + let id = vectorcraft_doc::NodeId( + app.run("shape.rectangle", json!({"x": 100, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(), + ); + app.run("attributes.set", json!({"ids": [id.0], "note": "Badge front"})).unwrap(); + app.run("select.set", json!({"ids": first.iter().map(|i| i.0).collect::>()})).unwrap(); + let noted = move |app: &VectorcraftApp| app.session.active().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap().x0 - 100.0; + (app, Box::new(x), Box::new(noted)) + } + + /// A Select Object step goes after the given step, or at the action's end, runs nothing when it + /// goes in, and plays as `select.byNote`: the steps after it act on the objects it selects. + #[test] + fn insert_select_object_goes_after_the_given_step_and_plays_as_a_selection_by_note() { + let (mut app, x, noted) = app_with_a_noted_rect(); + let selection = app.session.active().unwrap().selection.clone(); + let r = app.run(INSERT_SELECT_OBJECT, json!({"set": 0, "action": 0, "step": 0, "note": " badge "})).unwrap(); + assert_eq!(r, json!({"set": 0, "action": 0, "step": 1})); + assert_eq!(app.session.active().unwrap().selection, selection, "inserting runs nothing"); + let action = &app.ui.action_sets[0].actions[0]; + assert_eq!(action.steps[1], (SELECT_OBJECT_STEP.to_string(), json!({"note": "badge", "caseSensitive": false, "wholeWord": false}))); + app.run(INSERT_SELECT_OBJECT, json!({"set": 0, "action": 0, "note": "Badge", "caseSensitive": true, "wholeWord": true})).unwrap(); + assert_eq!(app.ui.action_sets[0].actions[0].steps[4].1, json!({"note": "Badge", "caseSensitive": true, "wholeWord": true})); + play(&mut app, 0, 0).unwrap(); + assert_eq!((x(&app), noted(&app)), (1.0, 6.0), "the moves after the step move the object with the note"); + let ids = &app.session.active().unwrap().selection.objects; + assert_eq!(ids.len(), 1); + } + + /// A playback whose Select Object step finds no object stops there with the step's error, at + /// every speed, and runs none of the steps after it. + #[test] + fn a_select_object_step_that_finds_nothing_stops_the_playback() { + for speed in ["accelerated", "step"] { + let (mut app, x, noted) = app_with_a_noted_rect(); + app.run(PLAYBACK_OPTIONS, json!({"speed": speed})).unwrap(); + app.ui.action_sets[0].actions[0].insert_step(0, (SELECT_OBJECT_STEP.into(), json!({"note": "missing"}))); + let selection = app.session.active().unwrap().selection.clone(); + let e = play(&mut app, 0, 0).unwrap_err(); + assert!(e.contains("no object that can be selected has a note matching “missing”"), "{speed}: {e}"); + play_out(&mut app); + assert_eq!((x(&app), noted(&app)), (0.0, 0.0), "{speed}: nothing after it runs"); + assert_eq!(app.session.active().unwrap().selection, selection, "{speed}: the selection stays"); + assert!(app.ui.action_playing.is_none(), "{speed}"); + } + } + + #[test] + fn insert_select_object_refuses_bad_params_and_changes_nothing() { + let (mut app, _, _) = app_with_a_noted_rect(); + let place = |extra: Value| { + let mut p = json!({"set": 0, "action": 0}); + if let (Some(p), Some(extra)) = (p.as_object_mut(), extra.as_object()) { + p.extend(extra.clone()); + } + p + }; + for (params, want) in [ + (place(json!({})), "the note is empty"), + (place(json!({"note": " \t "})), "the note is empty"), + (place(json!({"note": 5})), "`note` must be a string"), + (place(json!({"note": "x".repeat(1025)})), "the note is longer than 1,024 bytes"), + (place(json!({"note": "x", "caseSensitive": "yes"})), "`caseSensitive` must be true or false"), + (place(json!({"note": "x", "wholeWord": 0})), "`wholeWord` must be true or false"), + (place(json!({"note": "x", "action": 5})), "no such action"), + (place(json!({"note": "x", "step": 9})), "no such action step"), + (json!({"note": "x"}), "no such action"), + (json!(["note"]), "`params` must be an object"), + ] { + assert_eq!(app.run(INSERT_SELECT_OBJECT, params.clone()).unwrap_err(), want, "{params}"); + assert_eq!(app.ui.action_sets[0].actions[0].steps.len(), 3, "{params}"); + } + assert!(app.run(INSERT_SELECT_OBJECT, place(json!({"note": "x".repeat(1024)}))).is_ok(), "1,024 bytes goes in"); + } + + /// A saved Select Object step loads back as it was, in a version 4 file that older builds refuse; + /// a file whose Select Object step has bad params is refused, also inside a recorded batch. + #[test] + fn a_saved_select_object_step_survives_and_bad_ones_are_refused() { + let (mut app, _, _) = app_with_a_noted_rect(); + app.run(INSERT_SELECT_OBJECT, json!({"set": 0, "action": 0, "note": "Badge", "wholeWord": true})).unwrap(); + let saved = files::write_set(&app.ui.action_sets[0]); + let file: Value = serde_json::from_str(&saved).unwrap(); + assert_eq!(file["version"], json!(4), "older builds must refuse a Select Object step"); + assert_eq!( + file["actions"][0]["steps"][3], + json!({"command": "select.byNote", "params": {"note": "Badge", "caseSensitive": false, "wholeWord": true}}) + ); + let loaded = files::read_set(&saved, "Test").unwrap(); + assert_eq!(loaded.actions[0].steps, app.ui.action_sets[0].actions[0].steps); + app.ui.action_sets[0].actions[0].steps.push(("action.stop".into(), json!({"message": ""}))); + let file: Value = serde_json::from_str(&files::write_set(&app.ui.action_sets[0])).unwrap(); + assert_eq!(file["version"], json!(4), "with a stop too"); + for params in [json!({}), json!({"note": " "}), json!({"note": 5}), json!({"note": "a", "caseSensitive": 1}), json!(null), json!(42)] { + let step = json!({"command": "select.byNote", "params": params}); + for step in [step.clone(), json!({"command": "command.batch", "params": {"commands": [step]}})] { + let bad = json!({"format": "vcactions", "version": 4, "name": "Bad", "actions": [{"name": "A", "steps": [step]}]}); + assert_eq!(files::read_set(&bad.to_string(), "Test").unwrap_err(), "not an action set file", "{step}"); + } + } + let nested = json!({"commands": [{"command": "select.byNote", "params": {"note": "Inner"}}]}); + let set = ActionSet::new("Nested", vec![Action::new("A", vec![("command.batch".into(), nested)])]); + assert_eq!(serde_json::from_str::(&files::write_set(&set)).unwrap()["version"], json!(4), "a step in a recorded batch counts"); + } + + /// The panel menu's Select Object… opens Set Selection on the selected step's place, with an + /// empty note and both options off; Cancel inserts nothing, and OK inserts the step after the + /// selected step, whose row shows the note. While recording, the step goes into the recording. + /// With nothing selected and nothing recording, the item is off. + #[test] + fn select_object_in_the_menu_opens_set_selection_and_inserts_on_ok() { + use super::super::tests_appearance::{click, frame_events}; + let (mut app, _, _) = app_with_a_noted_rect(); + app.ui.action_set = Some(0); + let ctx = egui::Context::default(); + app.ui_ctx = Some(ctx.clone()); + let open = |ctx: &egui::Context, app: &mut VectorcraftApp| { + let texts = frame_events(ctx, app, vec![], menu); + let item = texts.iter().find(|(s, _)| s.trim() == "Select Object…").map(|(_, r)| *r).expect("Select Object… in the menu"); + click(ctx, app, item.center(), menu); + }; + open(&ctx, &mut app); + assert_eq!(open_kind(&app), None, "nothing selected and nothing recording: the item is off"); + + click_first_step(&ctx, &mut app); + open(&ctx, &mut app); + let d = app.ui.dialog.as_ref().expect("Select Object… opens Set Selection"); + assert_eq!(d.kind, crate::dialogs::action_select_object::KIND); + assert_eq!((&d.fields["set"], &d.fields["action"], &d.fields["step"]), (&json!(0), &json!(0), &json!(0))); + assert_eq!((d.str("note"), d.bool("caseSensitive"), d.bool("wholeWord")), (String::new(), false, false)); + crate::dialogs::cancel(&mut app); + assert_eq!(app.ui.action_sets[0].actions[0].steps.len(), 3, "Cancel inserts nothing"); + + open(&ctx, &mut app); + // A field of another type (set through ui.dialog.set) is an error, and the dialog stays. + for (key, value) in [("note", json!(5)), ("caseSensitive", json!("yes")), ("wholeWord", json!(1))] { + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("note".into(), json!("Badge")); + d.fields.insert("caseSensitive".into(), json!(false)); + d.fields.insert("wholeWord".into(), json!(false)); + d.fields.insert(key.into(), value.clone()); + } + assert!(crate::dialogs::confirm(&mut app).is_err(), "`{key}`: {value} is an error"); + assert_eq!(open_kind(&app), Some(crate::dialogs::action_select_object::KIND), "`{key}`: the dialog stays open"); + assert_eq!(app.ui.action_sets[0].actions[0].steps.len(), 3, "`{key}`: nothing is inserted"); + } + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("note".into(), json!("Badge")); + d.fields.insert("caseSensitive".into(), json!(true)); + d.fields.insert("wholeWord".into(), json!(false)); + } + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(open_kind(&app), None, "OK closes Set Selection"); + let action = &app.ui.action_sets[0].actions[0]; + assert_eq!(action.steps[1], (SELECT_OBJECT_STEP.to_string(), json!({"note": "Badge", "caseSensitive": true, "wholeWord": false}))); + let texts = frame_events(&ctx, &mut app, vec![], show); + assert!(texts.iter().any(|(s, _)| s == "Select Object: Badge"), "the step's row shows the note: {texts:?}"); + + app.run(START_RECORDING, json!({})).unwrap(); + open(&ctx, &mut app); + assert!(!app.ui.dialog.as_ref().is_some_and(|d| d.fields.contains_key("set")), "while recording it goes into the recording"); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("note".into(), json!("While recording")); + } + crate::dialogs::confirm(&mut app).unwrap(); + app.run(STOP_RECORDING, json!({})).unwrap(); + let recorded = app.ui.action_sets[0].actions.last().unwrap(); + assert_eq!( + recorded.steps, + [(SELECT_OBJECT_STEP.to_string(), json!({"note": "While recording", "caseSensitive": false, "wholeWord": false}))] + ); + } } diff --git a/crates/ui-egui/src/panels/actions/files.rs b/crates/ui-egui/src/panels/actions/files.rs index f7df78ee9b..a8ae79e713 100644 --- a/crates/ui-egui/src/panels/actions/files.rs +++ b/crates/ui-egui/src/panels/actions/files.rs @@ -1,14 +1,19 @@ //! Action set files: the Actions panel menu's Save Actions… and Load Actions…. //! -//! An action set file (`.vcactions`) is JSON: `{"format": "vcactions", "version": 1, 2 or 3, "name", +//! An action set file (`.vcactions`) is JSON: `{"format": "vcactions", "version": 1 to 6, "name", //! "actions": [{"name", "steps": [{"command", "params", "excluded"?}], "key"?, "color"?}]}`. Each step is a //! command id and its params, as `command.batch` takes them, or a stop: the command `action.stop` -//! with `{"message", "allowContinue"}`. `key` is the action's function key +//! with `{"message", "allowContinue"}`. A Select Object step is the command `select.byNote` with +//! `{"note", "caseSensitive", "wholeWord"}`, and a Select Path step is the command `select.storedPath` +//! with `{"id", "fingerprint"}`. `key` is the action's function key //! (`{"key": 1 to 15, "cmd", "shift"}`) and `color` its Button Mode color; an action without them, //! or with a value that is not one, has none. `excluded: true` keeps a step but skips it during //! playback. Sets with exclusions use version 2 so older builds refuse them rather than replay -//! excluded steps, and sets with stops use version 3 so older builds refuse them rather than fail -//! at a stop. Other sets use version 1, and earlier version 1 and 2 files still work. +//! excluded steps, sets with stops use version 3 so older builds refuse them rather than fail at a +//! stop, sets with Select Object steps use version 4, sets with Select Path steps use version 5 and +//! sets with View menu steps ([`crate::menus::plays_in_app`]), whose params are an object, use +//! version 6 so older builds refuse them rather than fail at that step. Other sets use version 1, and +//! earlier version 1 to 5 files still work. //! Load Actions… also reads the action sets another app saves as text (`.aia`, through //! `actionSet.read`). @@ -31,10 +36,10 @@ pub const ACTIONS_EXT: &str = "vcactions"; pub(super) const MAX_SET_FILE: usize = 8 << 20; /// The most actions [`read_set`] reads from one file. -const MAX_SET_ACTIONS: usize = 1000; +pub(super) const MAX_SET_ACTIONS: usize = 1000; /// The most steps [`read_set`] reads in one action. -const MAX_ACTION_STEPS: usize = 10_000; +pub(super) const MAX_ACTION_STEPS: usize = 10_000; /// The most left-out steps that Load Actions… lists for an action set another app saved. const MAX_SKIPPED: usize = 1000; @@ -74,17 +79,94 @@ fn is_false(value: &bool) -> bool { !value } +/// A step as [`write_set`] writes it when it is included: [`FileStep`] without `excluded`. +#[derive(Serialize)] +struct IncludedStep<'a> { + command: &'a str, + params: &'a Value, +} + +/// The bytes that excluding one step adds to the text [`write_set`] writes: a comma, a line +/// break, the indent and `"excluded": true`. +pub(super) const EXCLUDED_BYTES: usize = 28; + +/// The bytes more that a step adds to the text [`write_set`] writes as an action's first step than +/// [`step_bytes`] counts: a line break on each side of the step and the indent of the closing +/// bracket, in place of a comma and a line break. +pub(super) const FIRST_STEP_BYTES: usize = 6; + +/// The bytes that the included step `(command, params)` adds to the text [`write_set`] writes when +/// it goes after the last step of an action. As the action's first step it adds +/// [`FIRST_STEP_BYTES`] more. +pub(super) fn step_bytes(command: &str, params: &Value) -> usize { + /// Counts the bytes and the line breaks written to it. + #[derive(Default)] + struct Count { + bytes: usize, + breaks: usize, + } + impl std::io::Write for Count { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.bytes += buf.len(); + self.breaks += buf.iter().filter(|&&b| b == b'\n').count(); + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + let mut count = Count::default(); + if serde_json::to_writer_pretty(&mut count, &IncludedStep { command, params }).is_err() { + return MAX_SET_FILE + 1; + } + // In the file every line of the step is indented by 8 more spaces, and a comma and a line break + // come before it. + count.bytes + 8 * (count.breaks + 1) + 2 +} + /// The params of the stops in a step: a stop's own, or those of the stops a `command.batch` step /// holds, which playback runs as its own steps. fn stops_in<'a>(command: &str, params: &'a Value) -> Vec<&'a Value> { - if command == super::STOP_STEP { + steps_in(super::STOP_STEP, command, params) +} + +/// The params of the Select Object steps in a step, as [`stops_in`] finds stops. +fn select_objects_in<'a>(command: &str, params: &'a Value) -> Vec<&'a Value> { + steps_in(super::SELECT_OBJECT_STEP, command, params) +} + +/// The params of the steps that run command `kind` in a step: the step's own, or those of the +/// steps a `command.batch` step holds, which playback runs as its own steps. +fn steps_in<'a>(kind: &str, command: &str, params: &'a Value) -> Vec<&'a Value> { + if command == kind { return vec![params]; } if command != "command.batch" { return vec![]; } let steps = params.get("commands").and_then(Value::as_array).into_iter().flatten(); - steps.filter(|step| super::is_stop(step)).map(|step| step.get("params").unwrap_or(&Value::Null)).collect() + steps.filter(|step| step.get("command").and_then(Value::as_str) == Some(kind)).map(|step| step.get("params").unwrap_or(&Value::Null)).collect() +} + +/// The params of the Select Path steps in a step, as [`stops_in`] finds stops. +fn select_paths_in<'a>(command: &str, params: &'a Value) -> Vec<&'a Value> { + steps_in(super::SELECT_PATH_STEP, command, params) +} + +/// The params of the View menu steps ([`crate::menus::plays_in_app`]) in a step, as [`stops_in`] +/// finds stops. +fn ui_steps_in<'a>(command: &str, params: &'a Value) -> Vec<&'a Value> { + if crate::menus::plays_in_app(command) { + return vec![params]; + } + if command != "command.batch" { + return vec![]; + } + let steps = params.get("commands").and_then(Value::as_array).into_iter().flatten(); + steps + .filter(|step| step.get("command").and_then(Value::as_str).is_some_and(crate::menus::plays_in_app)) + .map(|step| step.get("params").unwrap_or(&Value::Null)) + .collect() } /// `set` as the text of an action set file. @@ -104,11 +186,18 @@ pub fn write_set(set: &ActionSet) -> String { color: a.color.clone(), }) .collect(); - let has_stop = set.actions.iter().flat_map(|a| &a.steps).any(|(command, params)| !stops_in(command, params).is_empty()); - let version = match (has_stop, set.actions.iter().any(|a| !a.excluded_steps.is_empty())) { - (true, _) => 3, - (false, true) => 2, - (false, false) => 1, + let steps = || set.actions.iter().flat_map(|a| &a.steps); + let has_select_object = steps().any(|(command, params)| !select_objects_in(command, params).is_empty()); + let has_select_path = steps().any(|(command, params)| !select_paths_in(command, params).is_empty()); + let has_stop = steps().any(|(command, params)| !stops_in(command, params).is_empty()); + let has_ui_step = steps().any(|(command, params)| !ui_steps_in(command, params).is_empty()); + let version = match (has_select_path, has_select_object, has_stop, set.actions.iter().any(|a| !a.excluded_steps.is_empty())) { + _ if has_ui_step => 6, + (true, ..) => 5, + (false, true, ..) => 4, + (false, false, true, _) => 3, + (false, false, false, true) => 2, + (false, false, false, false) => 1, }; let file = SetFile { format: ACTIONS_EXT.into(), version, name: set.name.clone(), actions }; serde_json::to_string_pretty(&file).unwrap_or_default() @@ -123,7 +212,7 @@ pub fn read_set(text: &str, name: &str) -> Result { if f.format != ACTIONS_EXT { return Err("not an action set file".into()); } - if !matches!(f.version, 1..=3) { + if !matches!(f.version, 1..=6) { return Err("the action set file needs a later version of VectorCraft".into()); } if f.actions.len() > MAX_SET_ACTIONS { @@ -136,6 +225,18 @@ pub fn read_set(text: &str, name: &str) -> Result { if stops.any(|p| super::stop_params(p).is_err()) { return Err("not an action set file".into()); } + let mut select_paths = f.actions.iter().flat_map(|a| &a.steps).flat_map(|s| select_paths_in(&s.command, &s.params)); + if select_paths.any(|p| vectorcraft_engine::stored_path_params(p).is_err()) { + return Err("not an action set file".into()); + } + let mut select_objects = f.actions.iter().flat_map(|a| &a.steps).flat_map(|s| select_objects_in(&s.command, &s.params)); + if select_objects.any(|p| super::select_object_params(p).is_err()) { + return Err("not an action set file".into()); + } + let mut ui_steps = f.actions.iter().flat_map(|a| &a.steps).flat_map(|s| ui_steps_in(&s.command, &s.params)); + if ui_steps.any(|p| !p.is_object()) { + return Err("not an action set file".into()); + } let actions = f .actions .into_iter() @@ -329,6 +430,8 @@ fn load_aia(app: &mut VectorcraftApp, params: Value) -> Result { } let AiaLoad { mut set, skipped, left_out } = aia_set(&read, "Actions"); set.name = free_set_name(&app.ui.action_sets, &set.name); + // The set must save as a file that Load Actions… reads, which can be larger than the file read. + super::edit_keeps_set_loadable(app, None, &set)?; let (name, actions) = (set.name.clone(), set.actions.len()); app.ui.action_sets.push(set); if left_out > 0 { @@ -350,14 +453,17 @@ fn load_aia(app: &mut VectorcraftApp, params: Value) -> Result { /// same name as one in the panel gets the next free number (`Print 2`). Loaded actions keep their /// function keys. The current set and the other sets stay as they are → /// `{set: index, name, actions: n}`. Where the host can read part of a file (the desktop), a file -/// larger than 8 MiB is refused after its first 8 MiB and one byte are read. +/// larger than 8 MiB is refused after its first 8 MiB and one byte are read. A set that Save +/// Actions… would write as a file Load Actions… refuses (larger than 8 MiB, as a file with less +/// white space or a name that gets a number can give) is refused too, and no set is added. /// /// An action set another app saved as text (`.aia`, read with `actionSet.read`) comes in with its /// actions and the steps that stand for a VectorCraft command ([`step_name`], [`step_commands`]), /// with no params; a step that is off in the file is excluded from playback. A set with no name is /// called after the file, else `Actions`. The other steps are left out and listed, and the status /// bar says how many → `{set, name, actions, skipped: [{action, step}] (at most 1,000), leftOut: n}`. -/// Such a file that `actionSet.read` marks `truncated` is refused, and no set is added. +/// Such a file that `actionSet.read` marks `truncated` is refused, and so is one whose set Save +/// Actions… would write larger than 8 MiB; then no set is added. pub fn load_set(app: &mut VectorcraftApp, p: &Value) -> Result { let (text, stem) = match p.get("data") { Some(Value::String(data)) => { @@ -398,6 +504,8 @@ pub fn load_set(app: &mut VectorcraftApp, p: &Value) -> Result { }; let mut set = read_set(&text, if stem.is_empty() { "Actions" } else { &stem })?; set.name = free_set_name(&app.ui.action_sets, &set.name); + // A number added to the name can make a file at the limit larger than it. + super::edit_keeps_set_loadable(app, None, &set)?; let (name, actions) = (set.name.clone(), set.actions.len()); app.ui.action_sets.push(set); Ok(json!({ "set": app.ui.action_sets.len() - 1, "name": name, "actions": actions })) diff --git a/crates/ui-egui/src/panels/align.rs b/crates/ui-egui/src/panels/align.rs index e1076145d3..02c7969be2 100644 --- a/crates/ui-egui/src/panels/align.rs +++ b/crates/ui-egui/src/panels/align.rs @@ -1,6 +1,7 @@ //! Align panel: Align Objects, Distribute Objects and Distribute Spacing (both with the spacing //! value when aligning to a key object or a key guide) and Align To (selection / key object / -//! artboard). +//! artboard). With the Artboard tool chosen, the buttons align and distribute the artboards the +//! tool has selected. use egui::Ui; use serde::Serialize; @@ -59,6 +60,13 @@ pub fn with_align_to(app: &VectorcraftApp, base: Value) -> Value { align_params(base, align_to(app), objects_aligned(app)) } +/// The params that an Object → Align menu item with params `p` sends: [`with_align_to`] unless `p` +/// names `to` or anchor points are selected (Direct Selection), when `p` goes unchanged and the +/// points align to their own bounds. Insert Menu Item stores the same params as the item's step. +pub fn menu_align_params(app: &VectorcraftApp, p: Value) -> Value { + if p.as_object().is_some_and(|o| !o.contains_key("to")) && !has_anchors(app) { with_align_to(app, p) } else { p } +} + /// The selected objects that Align aligns as objects: none while anchor points are selected /// (Direct Selection), since the points align and a single path's points must not go to the /// artboard as a single object does (#1636). @@ -104,7 +112,7 @@ pub enum Button { } impl Button { - /// The engine command the button runs. + /// The engine command the button runs on the selected objects. pub(crate) fn command(self) -> &'static str { match self { Button::Align(..) | Button::AlignCenters => "object.align", @@ -112,6 +120,59 @@ impl Button { Button::Spacing(_) => "object.distributeSpacing", } } + + /// The engine command the button runs on the selected artboards ([`on_artboards`]). + fn artboard_command(self) -> &'static str { + match self { + Button::Align(..) | Button::AlignCenters => "artboard.align", + Button::Distribute(..) => "artboard.distribute", + Button::Spacing(_) => "artboard.distributeSpacing", + } + } + + /// The engine command a click on the button runs now: the artboard command with the Artboard + /// tool chosen, else the object command. + pub(crate) fn command_now(self, app: &VectorcraftApp) -> &'static str { + if on_artboards(app) { self.artboard_command() } else { self.command() } + } +} + +/// Whether the Align panel's buttons, and the Control bar's, align and distribute artboards: the +/// Artboard tool is chosen. They then act on the artboards the tool has selected. +pub(crate) fn on_artboards(app: &VectorcraftApp) -> bool { + app.session.tool_id() == "artboard" +} + +/// The number of artboards the Artboard tool has selected ([`super::artboards::picked`]). +pub(crate) fn artboards_selected(app: &VectorcraftApp) -> usize { + let n = app.session.active().map_or(0, |d| d.doc.artboards.len()); + if n == 0 { 0 } else { super::artboards::picked(app, n).len() } +} + +/// With the Artboard tool chosen, whether the Distribute buttons of the Align panel and the Control +/// bar can space the selected artboards: two or more with Align to Artboard, whose spacing places +/// the second from the active one (the Artboard tool's selection always holds its active artboard), +/// else three or more, since the first and the last stay where they are. +pub(crate) fn artboards_distribute(app: &VectorcraftApp) -> bool { + artboards_selected(app) >= if app.ui.align_to == AlignTo::Artboard { 2 } else { 3 } +} + +/// Runs what a click on button `b` runs with the Artboard tool chosen: the artboard command on +/// the artboards the tool has selected. With Align to Artboard chosen, it sends `to: "artboard"`, +/// which keeps the tool's active artboard in place, and the Distribute buttons send the +/// Distribute Spacing value. With Align to Selection chosen, it sends `to: "selection"`. +fn run_on_artboards(app: &mut VectorcraftApp, b: Button) -> Result { + let to_artboard = app.ui.align_to == AlignTo::Artboard; + let mut p = match b { + Button::Align(axis, v) | Button::Distribute(axis, v) => json!({axis: v}), + Button::AlignCenters => json!({"horizontal": "center", "vertical": "center"}), + Button::Spacing(axis) => json!({"axis": axis}), + }; + p["to"] = json!(if to_artboard { "artboard" } else { "selection" }); + if to_artboard && matches!(b, Button::Distribute(..) | Button::Spacing(_)) { + p["spacing"] = json!(app.ui.align_spacing); + } + app.run(b.artboard_command(), p) } /// The Align panel's buttons as UI commands ([`crate::menus::UI_COMMANDS`]), in the panel's order: @@ -143,8 +204,12 @@ pub(crate) fn button(id: &str) -> Option